From e2226d45b564caf30b6b942e24039e5dbd3ce163 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 05:36:08 +0000 Subject: [PATCH 1/4] CI: migrations named by timestamp, never renamed once on main, and new ones sort after main's (sc-9611) --- .github/workflows/ci.yml | 4 +++ AGENTS.md | 4 +++ scripts/ci/check_migrations.sh | 46 ++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100755 scripts/ci/check_migrations.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 35c3f1e4..43c29f09 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,12 +144,16 @@ jobs: # Migrations run before the rollout, so the release still serving must work with the new schema: a new migration # mustn't drop, rename or retype what main's code reads (4 Dec 2026: a dropped column failed requests for ~20 s). - run: python3 -m unittest scripts/ci/test_migration_safety.py + # Migrations run in file-name order and are recorded by name, so one already on main is never renamed and a new + # one sorts after all of main's (two branches that each add one: the second to merge takes a later timestamp). - env: BASE: ${{ github.event.pull_request.base.sha || github.event.before }} run: | if [ -z "$BASE" ] || [ "$BASE" = 0000000000000000000000000000000000000000 ]; then echo "No earlier commit to compare with." + scripts/ci/check_migrations.sh "" else + scripts/ci/check_migrations.sh "$BASE" python3 scripts/ci/migration_safety.py "$BASE" fi diff --git a/AGENTS.md b/AGENTS.md index be1727ba..2c81db99 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,6 +100,10 @@ design is in `docs/design.md`; read it before changing the architecture, and upd anything main's code still names. This is deploy safety, not backwards compatibility: the old column still goes, one release later. (4 Dec 2026, a dropped organizations column failed every request for ~20 s, a new user's first build among them.) +- Migrations run in file-name order and the database records each by name. Name a new one + `YYYY_MM_DD_HHMMSS_snake_case.rs` with a timestamp after every migration on main, and never rename or delete one that + is on main. If another branch's migration merged first with a later timestamp, rename yours to a newer one before + merging. scripts/ci/check_migrations.sh checks all three in the same job. - The server connects with sqlx's prepared-statement cache off (`config::without_statement_cache`): a migration that adds a column makes Postgres refuse an old pod's cached `SELECT table.*` ("cached plan must not change result type"). Keep it off. `tests/rollouts.rs` fails if it comes back on. (4 Dec 2026, #178's rollout.) diff --git a/scripts/ci/check_migrations.sh b/scripts/ci/check_migrations.sh new file mode 100755 index 00000000..7efc2792 --- /dev/null +++ b/scripts/ci/check_migrations.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# app/'s migrations, checked before they reach a deployed database (ported from fleetlayer's scripts/check-migrations, +# sc-9611). Migrations run in name order and a database records each one by name, so: +# - each is named YYYY_MM_DD_HHMMSS_snake_case.rs; +# - against a base commit (CI gives the push's or the pull request's base; default origin/main): every migration the +# base has is still there under the same name (deployed databases have applied it), and every new one sorts after +# all of them. Two sessions that each add a migration on their own branch: whoever rebases second renames theirs to +# a later timestamp, or it would run before one production already applied. +# +# scripts/ci/check_migrations.sh [] +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +dir=app/database/migrations +base=${1-origin/main} +pattern='^[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{6}_[a-z0-9_]+\.rs$' + +now=$(find "$dir" -maxdepth 1 -type f -name '*.rs' -printf '%f\n' | LC_ALL=C sort) +bad=$(grep -vE "$pattern" <<<"$now" || true) +if [ -n "$bad" ]; then + echo "check_migrations: not named YYYY_MM_DD_HHMMSS_snake_case.rs: $bad" >&2 + exit 1 +fi + +if [ -z "$base" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then + echo "check_migrations: $(wc -l <<<"$now") migrations, all named right (no base to compare with)." + exit 0 +fi +before=$(git ls-tree --name-only "$base" "$dir/" | xargs -rn1 basename | grep -E "$pattern" | LC_ALL=C sort || true) +while IFS= read -r f; do + [ -n "$f" ] || continue + if ! grep -qxF "$f" <<<"$now"; then + echo "check_migrations: $f is on $base already, so deployed databases may have applied it: never rename or remove it" >&2 + exit 1 + fi +done <<<"$before" +last=$(tail -n1 <<<"$before") +new=0 +while IFS= read -r f; do + grep -qxF "$f" <<<"$before" && continue + new=$((new + 1)) + if [ -n "$last" ] && [[ ! "$f" > "$last" ]]; then + echo "check_migrations: $f is new, but $base already has $last, which sorts after it: give it a later timestamp" >&2 + exit 1 + fi +done <<<"$now" +echo "check_migrations: $(wc -l <<<"$now") migrations, named right; $new new since $base, all after its last ($last)." From ab2d7abf37d2f01318ab1cd1616d1f8965934396 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 05:49:24 +0000 Subject: [PATCH 2/4] Migrations: own required-to-be job, byte-order compare, edits to applied migrations fail, unreachable base warns (review) --- .github/workflows/ci.yml | 20 ++++++++++++++++---- AGENTS.md | 5 +++-- scripts/ci/check_migrations.sh | 10 +++++++++- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 43c29f09..b3912a45 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -141,16 +141,28 @@ jobs: persist-credentials: false fetch-depth: 0 - run: scripts/ci/cli_version.sh + + # The migrations a change adds, against its base (a required check: main's ruleset makes a pull request up to date + # with main first, so two branches' migrations are always checked against each other). + migrations: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + fetch-depth: 0 # Migrations run before the rollout, so the release still serving must work with the new schema: a new migration # mustn't drop, rename or retype what main's code reads (4 Dec 2026: a dropped column failed requests for ~20 s). - run: python3 -m unittest scripts/ci/test_migration_safety.py - # Migrations run in file-name order and are recorded by name, so one already on main is never renamed and a new - # one sorts after all of main's (two branches that each add one: the second to merge takes a later timestamp). + # Migrations run in file-name order and are recorded by name, so one already on main is never renamed or edited, + # and a new one sorts after all of main's (two branches that each add one: the second to merge takes a later + # timestamp). With no base it can reach (a new branch, a force-push), only the names are checked. - env: BASE: ${{ github.event.pull_request.base.sha || github.event.before }} run: | - if [ -z "$BASE" ] || [ "$BASE" = 0000000000000000000000000000000000000000 ]; then - echo "No earlier commit to compare with." + if [ -z "$BASE" ] || [ "$BASE" = 0000000000000000000000000000000000000000 ] || ! git cat-file -e "$BASE^{commit}" 2>/dev/null; then + echo "::warning::No earlier commit to compare the migrations with (${BASE:-none}): only their names are checked." scripts/ci/check_migrations.sh "" else scripts/ci/check_migrations.sh "$BASE" diff --git a/AGENTS.md b/AGENTS.md index 2c81db99..5f794b30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,14 +96,15 @@ design is in `docs/design.md`; read it before changing the architecture, and upd - Migrations run before the rollout, so for a few seconds the previous release serves against the new schema. A migration must work with the code before it: add the new column and copy the data in one change, stop reading the old one in the same change, and drop or rename it in a later change. A required column gets a default. CI's - `cli-version` job runs scripts/ci/migration_safety.py, which fails a new migration that drops, renames or retypes + `migrations` job runs scripts/ci/migration_safety.py, which fails a new migration that drops, renames or retypes anything main's code still names. This is deploy safety, not backwards compatibility: the old column still goes, one release later. (4 Dec 2026, a dropped organizations column failed every request for ~20 s, a new user's first build among them.) - Migrations run in file-name order and the database records each by name. Name a new one `YYYY_MM_DD_HHMMSS_snake_case.rs` with a timestamp after every migration on main, and never rename or delete one that is on main. If another branch's migration merged first with a later timestamp, rename yours to a newer one before - merging. scripts/ci/check_migrations.sh checks all three in the same job. + merging. A migration on main is never edited either (deployed databases won't run it again): fix it with a new one. + scripts/ci/check_migrations.sh checks all of this in CI's `migrations` job. - The server connects with sqlx's prepared-statement cache off (`config::without_statement_cache`): a migration that adds a column makes Postgres refuse an old pod's cached `SELECT table.*` ("cached plan must not change result type"). Keep it off. `tests/rollouts.rs` fails if it comes back on. (4 Dec 2026, #178's rollout.) diff --git a/scripts/ci/check_migrations.sh b/scripts/ci/check_migrations.sh index 7efc2792..b059f61b 100755 --- a/scripts/ci/check_migrations.sh +++ b/scripts/ci/check_migrations.sh @@ -3,12 +3,15 @@ # sc-9611). Migrations run in name order and a database records each one by name, so: # - each is named YYYY_MM_DD_HHMMSS_snake_case.rs; # - against a base commit (CI gives the push's or the pull request's base; default origin/main): every migration the -# base has is still there under the same name (deployed databases have applied it), and every new one sorts after +# base has is still there under the same name and unchanged (deployed databases have applied it, and never run it +# again: a fix is a new migration), and every new one sorts after # all of them. Two sessions that each add a migration on their own branch: whoever rebases second renames theirs to # a later timestamp, or it would run before one production already applied. # # scripts/ci/check_migrations.sh [] set -euo pipefail +# Byte order, as the migrations macro sorts them (a locale's collation can order `_ab` and `_a_c` the other way). +export LC_ALL=C cd "$(git rev-parse --show-toplevel)" dir=app/database/migrations base=${1-origin/main} @@ -33,6 +36,11 @@ while IFS= read -r f; do exit 1 fi done <<<"$before" +changed=$(git diff --name-only --diff-filter=M "$base" -- "$dir/" | xargs -rn1 basename) +if [ -n "$changed" ]; then + echo "check_migrations: changed since $base, which deployed databases already ran and won't run again: $changed. Put the change in a new migration." >&2 + exit 1 +fi last=$(tail -n1 <<<"$before") new=0 while IFS= read -r f; do From a4ccad5c451440fafb96c1bb9144a0ebaebc2335 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 08:30:04 +0000 Subject: [PATCH 3/4] Migration safety: read the SQL from the migration's Rust string literals (sql_of), since splitting the whole file on ';' matched nothing in a real migration Found and fixed by the fleetlayer cloud session (fleetlayer/fleetlayer-cloud#41); plain strings' line continuations are joined here too. Replayed over every migration: 2026_12_06's DROP COLUMN setup_dismissed_at (#172) is now caught against its parent, which still read it. --- scripts/ci/migration_safety.py | 17 ++++++++++++- scripts/ci/test_migration_safety.py | 39 ++++++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/scripts/ci/migration_safety.py b/scripts/ci/migration_safety.py index f6215a28..637c6dd3 100644 --- a/scripts/ci/migration_safety.py +++ b/scripts/ci/migration_safety.py @@ -23,6 +23,21 @@ IDENT = r'"?([A-Za-z_][A-Za-z0-9_]*)"?' +def sql_of(source): + """The SQL in a migration: its Rust string literals (raw `r#"…"#` and plain `"…"`), one statement list. Splitting + the whole file on `;` would start every statement with Rust code (`const SCHEMA …`, `pub async fn …`), and no + statement would match.""" + literals = [m.group(2) for m in re.finditer(r'r(#*)"(.*?)"\1', source, flags=re.S)] + rest = re.sub(r'r(#*)".*?"\1', " ", source, flags=re.S) + rest = re.sub(r"//[^\n]*", " ", rest) + # A plain string's `\` line continuation drops the newline and the next line's indentation, as Rust does. + literals += [ + re.sub(r"\\\n\s*", "", m.group(1)).replace('\\"', '"') + for m in re.finditer(r'"((?:[^"\\]|\\.)*)"', rest, flags=re.S) + ] + return ";\n".join(literals) + + def strip_comments(sql): sql = re.sub(r"/\*.*?\*/", " ", sql, flags=re.S) return re.sub(r"--[^\n]*", " ", sql) @@ -85,7 +100,7 @@ def main(base): for path in added: source = open(path).read() ok = allowed(source) - for kind, name, statement in removed_names(source): + for kind, name, statement in removed_names(sql_of(source)): if name in ok or not still_read(base, name): continue problems.append(f"{path}: drops or changes {kind} `{name}`, which {CODE} still reads at {base[:12]}:\n {statement}") diff --git a/scripts/ci/test_migration_safety.py b/scripts/ci/test_migration_safety.py index bd640722..6f06c9a7 100644 --- a/scripts/ci/test_migration_safety.py +++ b/scripts/ci/test_migration_safety.py @@ -5,7 +5,7 @@ import unittest sys.path.insert(0, os.path.dirname(__file__)) -from migration_safety import allowed, removed_names # noqa: E402 +from migration_safety import allowed, removed_names, sql_of # noqa: E402 def names(sql): @@ -61,3 +61,40 @@ def test_a_contract_line_lets_a_name_through(self): if __name__ == "__main__": unittest.main() + + +class SqlOf(unittest.TestCase): + """Migrations are Rust files: the SQL has to come out of their string literals first.""" + + def test_a_raw_string_constant(self): + source = '''//! Drops a column; the comment's semicolon doesn't matter. +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r#" +ALTER TABLE planes ADD COLUMN sent_at TIMESTAMPTZ, DROP COLUMN address; +"#; +''' + self.assertEqual(names(sql_of(source)), [("column", "address")]) + + def test_a_plain_string_in_the_call(self): + source = '''use laravel::db::AnyTransaction; +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query("ALTER TABLE diffs DROP COLUMN \\"comment_images\\"").unprepared().await?; + Ok(()) +} +''' + self.assertEqual(names(sql_of(source)), [("column", "comment_images")]) + + def test_a_plain_string_with_line_continuations(self): + source = 'pub async fn migrate() {\n tx.query("ALTER TABLE diffs \\\n DROP COLUMN old_images").unprepared().await?;\n}\n' + self.assertEqual(names(sql_of(source)), [("column", "old_images")]) + + def test_the_whole_file_unextracted_finds_nothing(self): + source = 'pub async fn migrate() { tx.query("ALTER TABLE t DROP COLUMN c").unprepared().await?; }' + self.assertEqual(names(source), []) + From ddd6ac6a95f6070633fea2be2babdbb104208ce4 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Sat, 5 Dec 2026 08:31:30 +0000 Subject: [PATCH 4/4] Migration safety tests: the whole script on a repository shaped like #172, a DROP first in its string (the shape the old whole-file split missed), and a continuation between COLUMN and the name --- scripts/ci/test_migration_safety.py | 78 ++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/scripts/ci/test_migration_safety.py b/scripts/ci/test_migration_safety.py index 6f06c9a7..0682a56a 100644 --- a/scripts/ci/test_migration_safety.py +++ b/scripts/ci/test_migration_safety.py @@ -1,7 +1,9 @@ """Tests for migration_safety.py: python3 -m unittest scripts/ci/test_migration_safety.py""" import os +import subprocess import sys +import tempfile import unittest sys.path.insert(0, os.path.dirname(__file__)) @@ -91,10 +93,84 @@ def test_a_plain_string_in_the_call(self): self.assertEqual(names(sql_of(source)), [("column", "comment_images")]) def test_a_plain_string_with_line_continuations(self): - source = 'pub async fn migrate() {\n tx.query("ALTER TABLE diffs \\\n DROP COLUMN old_images").unprepared().await?;\n}\n' + # The break between COLUMN and the name: unjoined, the parser would read the column as `COLUMN`. + source = 'pub async fn migrate() {\n tx.query("ALTER TABLE diffs DROP COLUMN \\\n old_images").unprepared().await?;\n}\n' self.assertEqual(names(sql_of(source)), [("column", "old_images")]) def test_the_whole_file_unextracted_finds_nothing(self): source = 'pub async fn migrate() { tx.query("ALTER TABLE t DROP COLUMN c").unprepared().await?; }' self.assertEqual(names(source), []) + + +# The 4 Dec migration's file as it merged (#172): its SQL is in a raw string constant, past the Rust code. (Its DROP is +# the literal's third statement, so even the old whole-file split found it; DROP_FIRST below is the shape it missed.) +MIGRATION_4_DEC = """//! The organization's settings page. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r#" +ALTER TABLE organizations ADD COLUMN setup_shown BOOLEAN; +UPDATE organizations SET setup_shown = false WHERE setup_dismissed_at IS NOT NULL; +ALTER TABLE organizations DROP COLUMN setup_dismissed_at; +%s +ALTER TABLE organizations + ADD COLUMN project_threshold DOUBLE PRECISION NOT NULL DEFAULT 0 + CHECK (project_threshold >= 0 AND project_threshold <= 1), + ADD COLUMN project_comment_when_unchanged BOOLEAN NOT NULL DEFAULT false; +"#; +""" + +DROP_FIRST = """use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query("ALTER TABLE organizations DROP COLUMN setup_dismissed_at").unprepared().await?; + Ok(()) +} +""" + + +class TheScriptOnARepository(unittest.TestCase): + """The whole script, run in a repository shaped like #172: the base's code reads the column, the change adds the + migration that drops it.""" + + SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "migration_safety.py") + + def check(self, migration): + with tempfile.TemporaryDirectory() as repo: + def git(*args): + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=repo, check=True, + capture_output=True) + + git("init", "-q", "-b", "main") + os.makedirs(os.path.join(repo, "app/src/models")) + os.makedirs(os.path.join(repo, "app/database/migrations")) + with open(os.path.join(repo, "app/src/models/organizations.rs"), "w") as f: + f.write("pub struct Organization {\n pub setup_dismissed_at: Option,\n}\n") + git("add", "-A") + git("commit", "-q", "-m", "base") + with open(os.path.join(repo, "app/database/migrations/2026_12_06_000000_organization_settings.rs"), "w") as f: + f.write(migration) + git("add", "-A") + git("commit", "-q", "-m", "the migration") + return subprocess.run([sys.executable, "-I", self.SCRIPT, "HEAD~1"], cwd=repo, capture_output=True, text=True) + + def test_the_4_dec_migration_fails(self): + result = self.check(MIGRATION_4_DEC % "") + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("`setup_dismissed_at`", result.stderr) + + def test_a_drop_first_in_its_string_fails(self): + # Split on `;` without sql_of, this statement started with `use laravel…pub async fn…`, and nothing matched. + result = self.check(DROP_FIRST) + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("`setup_dismissed_at`", result.stderr) + + def test_a_contract_line_lets_it_through(self): + result = self.check(MIGRATION_4_DEC % "-- contract: setup_dismissed_at: a test of the escape hatch") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr)