From 0fa629b49497458ef3dda29718858800339d319d Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 20:30:08 +1300 Subject: [PATCH] CI: a new migration mustn't drop, rename or retype what the release still serving reads, or add a required column with no default; AGENTS.md says why (the 4 Dec first-build 500) --- .github/workflows/ci.yml | 11 ++ AGENTS.md | 7 ++ .../migration_safety.cpython-313.pyc | Bin 0 -> 7829 bytes .../test_migration_safety.cpython-313.pyc | Bin 0 -> 4177 bytes scripts/ci/migration_safety.py | 109 ++++++++++++++++++ scripts/ci/test_migration_safety.py | 63 ++++++++++ 6 files changed, 190 insertions(+) create mode 100644 scripts/ci/__pycache__/migration_safety.cpython-313.pyc create mode 100644 scripts/ci/__pycache__/test_migration_safety.cpython-313.pyc create mode 100644 scripts/ci/migration_safety.py create mode 100644 scripts/ci/test_migration_safety.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ecd7c8c3..3d8f676a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -120,6 +120,17 @@ jobs: with: fetch-depth: 0 - run: scripts/ci/cli_version.sh + # 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 + - 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." + else + python3 scripts/ci/migration_safety.py "$BASE" + fi # The CircleCI orb's scripts (clients/circleci-orb), rendered and linted: validating it with CircleCI needs a token. orb: diff --git a/AGENTS.md b/AGENTS.md index 11ea07ba..467a3091 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,6 +63,13 @@ design is in `docs/design.md`; read it before changing the architecture, and upd - A test never skips quietly. When a service it needs (the blob store, Postgres, a forge stub) is missing, it fails with a message naming the service: a test that returns early passes in CI. (3 Dec 2026: the server tests that need blobs returned early in CI's `test` job, which runs no S3, and passed without checking anything.) +- 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 + 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.) - Every background process (workers, renderers, scheduled jobs) ships with a health check or heartbeat that checks the work is done, not just that the process is up, in the same change. - Production reads its secrets from 1Password through the cluster's ExternalSecrets (talira-ai/infra, diff --git a/scripts/ci/__pycache__/migration_safety.cpython-313.pyc b/scripts/ci/__pycache__/migration_safety.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9917678da0c525b86e0546b23c5c5d479570508 GIT binary patch literal 7829 zcmc&(U2NM{mL?_2k|@bPu@wI#)6hwpScxUaO`IR+ud1!YPW_XJQX0o@6k4QYCK9QT zl%1&EUGEGqW2cL?({5oc_F>bR0h(Y2XkG>g76WV-n1?*{fvU2x%Nl60+n2t%aWUB0 zr#+Vx<)7He3^2f6K$lm%f9HJX+;h)4T=95F49fD&Z8v{ck756f{+Okz+*tV^Xnc&( zn1s9z+^a?5+!IV zce2oAsDzl#Wd!t2VaC!NrHnHQR2&RRbBxSUvcjj+l*~yJypV#o3@ZmoG9;zM?jB0Y z3G(VjGBw5}MF}ke^Tl*p%qeY@EK=|i9vN7SONat1>jSb9H^GZJ+1zQrOl3vrLtAka zlVW&5Hb?<(NI5aiWtbo}Bv41F9xg$>ap;YsK>vC!vm6Voq!@wE>#WN`nNxDvILpf! zUY0pF4%|(S^E#s)x+rdflkSibcPq!~M8LGP$gt4MAh1?O%owl@J)*G2^(-l|z7PP59nF%73-fK|SgmJvIY7HS^{ zTh%TwU<-wIB)awqUd}P;1Rnq?AkA%;6B3_Q@=`-b_QY4Q|buYO*vq$e9ojZ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b+ zrrBA3hA%iu)h)lZB5(Ce$6LYpm{TjQrNKe~MhR*G>`NI`&W5o>y6L z|8w#+yyp2^Fq+1nJB-?jw>)<@;hyE=7~!7Im#j@+*~#g{v&UzS|LkuHc*)+h=y1(C s?mFfgo;sQq3HvX4f7&|}o!c|tdat$6aqnQs^V)wByO!-3(X5mDe~yjZ`~Uy| literal 0 HcmV?d00001 diff --git a/scripts/ci/__pycache__/test_migration_safety.cpython-313.pyc b/scripts/ci/__pycache__/test_migration_safety.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..856ad6bad4b0f25612d7d9c2193debe9ce8bc527 GIT binary patch literal 4177 zcmbuC-*4N-9l(#2WK*(TyY{lV!I0h3{IFWvs*@P)oL`nDx>h1fo+xD*>W!r&O5!Y$ z&K=d%#kRmAJO@RpfD-w}^LnO2+ z79_t}@GT4kc|WHJtHPnOL%u}tUG1M0+`n1T{bHs;=%#cdN}@MnBnJQClZXtAqti%< zoJ30BYN#+C^x)@aLvD@?tv;pn&)r5y8$}3YPx%tT_cWUIelV(wbulh&-YV+UrnqJi z+%oD!vkl8ssaDhNjp_A`IlR7MH!Slao@(K?Y1lSMV_G4`x=j-mBfvG+ zr(bI}t-E^F86tYidQGpYrqhpjK0#Xcwx)_A2;S3>?OjiFn@E%8=}h7*X2 zV`wRgP#fB;k6JS&@shYAE`vn|5Jog?hD^~E&VXF-S3_|j7Z*qvMu>-<5WUlM!fS?E zb;3*^M^GuN!tgkYiH6nE6Q*W2G&51Ls(RuzgSNG1#h8Mrvc*X}#u7LYK2yR-VJ|%o z$vyP>^yR;&9!<~h3?%`>8(p|XCF+@KO9JIhm+qt8c1?wwnolM6=>6W z{B_yC07dVjRRpvmMk)y@BCrxxLXbu{H+_s5(y#PEDk=RWT9@KcXRzQJA;)a+16R>V?{3Zw7QCG zT9fMdS4(n1_G+pIZ5fmTdYX+h3eM$=I9JMMgRYNOE?vm4^lI1LThIfL-dC}j?Uw0` zy0hq(`&e`aG|+(9@*Uua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(the commit the release serving was built from: a pull request's base, or the +previous main). Checks the migrations added since under app/database/migrations against app/src at +. A name the old code uses for something else can be let through with a line in the migration: +`-- contract: : `. +""" + +import re +import subprocess +import sys + +MIGRATIONS = "app/database/migrations/" +CODE = "app/src" + +IDENT = r'"?([A-Za-z_][A-Za-z0-9_]*)"?' + + +def strip_comments(sql): + sql = re.sub(r"/\*.*?\*/", " ", sql, flags=re.S) + return re.sub(r"--[^\n]*", " ", sql) + + +def removed_names(source): + """(kind, name, statement) for each column or table the migration drops, renames or retypes.""" + out = [] + for statement in strip_comments(source).split(";"): + s = " ".join(statement.split()) + table = re.match(r"(?i)ALTER TABLE (?:IF EXISTS )?(?:ONLY )?" + IDENT, s) + if table: + for m in re.finditer(r"(?i)\bDROP (?:COLUMN )?(?:IF EXISTS )?" + IDENT, s): + if m.group(1).upper() in ("CONSTRAINT", "DEFAULT", "NOT", "INDEX"): + continue + out.append(("column", m.group(1), s)) + for m in re.finditer(r"(?i)\bRENAME (?:COLUMN )?" + IDENT + r" TO\b", s): + if m.group(1).upper() in ("CONSTRAINT", "TO"): + continue + out.append(("column", m.group(1), s)) + for m in re.finditer(r"(?i)\bALTER (?:COLUMN )?" + IDENT + r" (?:SET DATA )?TYPE\b", s): + out.append(("column", m.group(1), s)) + if re.search(r"(?i)\bRENAME TO\b", s): + out.append(("table", table.group(1), s)) + # A required column with no default: the old release's inserts into the table leave it out and fail. + for m in re.finditer(r"(?i)\bADD (?:COLUMN )?(?:IF NOT EXISTS )?" + IDENT + r"([^,]*)", s): + spec = m.group(2).upper() + if re.search(r"\bNOT NULL\b", spec) and not re.search(r"\bDEFAULT\b|\bGENERATED\b", spec): + out.append(("table (a required column with no default added to it)", table.group(1), s)) + drop = re.match(r"(?i)DROP TABLE (?:IF EXISTS )?(.+?)(?: CASCADE| RESTRICT)?$", s) + if drop: + for name in drop.group(1).split(","): + m = re.fullmatch(IDENT, name.strip()) + if m: + out.append(("table", m.group(1), s)) + return out + + +def allowed(source): + return {m.group(1) for m in re.finditer(r"--\s*contract:\s*" + IDENT, source)} + + +def run(*args): + return subprocess.run(args, check=True, capture_output=True, text=True).stdout + + +def still_read(base, name): + """Whether app/src at `base` names `name` as a whole word.""" + found = subprocess.run(["git", "grep", "-q", "-w", "-e", name, base, "--", CODE], capture_output=True) + return found.returncode == 0 + + +def main(base): + added = [ + line.split("\t", 1)[1] + for line in run("git", "diff", "--name-status", "--diff-filter=A", f"{base}...HEAD", "--", MIGRATIONS).splitlines() + if line.endswith(".rs") + ] + problems = [] + for path in added: + source = open(path).read() + ok = allowed(source) + for kind, name, statement in removed_names(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}") + if problems: + print("\n".join(problems), file=sys.stderr) + print( + "\nMigrations run before the rollout, so the release serving must still work afterwards. Add the new\n" + "column and copy the data now, stop reading the old one in this change, and drop it in a later change\n" + "(once main's code doesn't name it). If the old code uses the name for something else, add\n" + "`-- contract: : ` to the migration.", + file=sys.stderr, + ) + return 1 + print(f"{len(added)} new migration(s); none drops or changes anything the release serving reads.") + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit(__doc__) + sys.exit(main(sys.argv[1])) diff --git a/scripts/ci/test_migration_safety.py b/scripts/ci/test_migration_safety.py new file mode 100644 index 00000000..bd640722 --- /dev/null +++ b/scripts/ci/test_migration_safety.py @@ -0,0 +1,63 @@ +"""Tests for migration_safety.py: python3 -m unittest scripts/ci/test_migration_safety.py""" + +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(__file__)) +from migration_safety import allowed, removed_names # noqa: E402 + + +def names(sql): + return [(kind, name) for kind, name, _ in removed_names(sql)] + + +class RemovedNames(unittest.TestCase): + def test_the_4_dec_migration_drops_the_column_the_old_release_read(self): + sql = """ + 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; + """ + self.assertEqual(names(sql), [("column", "setup_dismissed_at")]) + + def test_drops_renames_and_retypes(self): + sql = """ + ALTER TABLE builds DROP COLUMN IF EXISTS a, DROP COLUMN "b"; + ALTER TABLE builds RENAME COLUMN c TO d; + ALTER TABLE builds RENAME e TO f; + ALTER TABLE builds ALTER COLUMN g TYPE BIGINT, ALTER h SET DATA TYPE TEXT; + ALTER TABLE old_things RENAME TO new_things; + DROP TABLE IF EXISTS t1, t2 CASCADE; + """ + self.assertEqual( + names(sql), + [("column", "a"), ("column", "b"), ("column", "c"), ("column", "e"), ("column", "g"), ("column", "h"), + ("table", "old_things"), ("table", "t1"), ("table", "t2")], + ) + + def test_additions_constraints_defaults_and_comments_are_safe(self): + sql = """ + -- ALTER TABLE x DROP COLUMN y; + /* DROP TABLE z; */ + ALTER TABLE builds ADD COLUMN base_branch TEXT; + ALTER TABLE builds DROP CONSTRAINT builds_check, ALTER COLUMN x DROP DEFAULT, ALTER COLUMN y DROP NOT NULL; + ALTER TABLE builds RENAME CONSTRAINT a TO b; + CREATE INDEX i ON builds (x); + DROP INDEX IF EXISTS i; + """ + self.assertEqual(names(sql), []) + + def test_a_required_column_without_a_default_breaks_the_old_inserts(self): + sql = """ + ALTER TABLE builds ADD COLUMN a TEXT NOT NULL, ADD COLUMN b INT NOT NULL DEFAULT 0, ADD COLUMN c TEXT; + ALTER TABLE organizations ADD COLUMN t DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (t >= 0 AND t <= 1); + """ + self.assertEqual(names(sql), [("table (a required column with no default added to it)", "builds")]) + + def test_a_contract_line_lets_a_name_through(self): + self.assertEqual(allowed("-- contract: state: the old code's `state` is builds.state, not this table's\n"), {"state"}) + + +if __name__ == "__main__": + unittest.main()