Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Binary file not shown.
Binary file not shown.
109 changes: 109 additions & 0 deletions scripts/ci/migration_safety.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Fail when a new migration drops, renames or retypes a column or table that the release still serving reads.

ArgoCD runs migrations before the rollout, so for some seconds the previous release's pods serve against the new
schema. On 4 Dec 2026 a migration dropped organizations.setup_dismissed_at while those pods still selected it: every
request that loaded an organization answered 500 for about 20 s, a new user's first build among them. So a migration
must work with the code before it (expand, then contract): add the new column and copy the data in one release, stop
reading the old one, and drop it in a later release, once the code on main no longer names it.

Usage: migration_safety.py <base-ref> (the commit the release serving was built from: a pull request's base, or the
previous main). Checks the migrations added since <base-ref> under app/database/migrations against app/src at
<base-ref>. A name the old code uses for something else can be let through with a line in the migration:
`-- contract: <name>: <why the release serving doesn't read it>`.
"""

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: <name>: <why>` 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]))
63 changes: 63 additions & 0 deletions scripts/ci/test_migration_safety.py
Original file line number Diff line number Diff line change
@@ -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()
Loading