Edit SQL models
If you modify API database tables in api/infrastructure/postgres/models.py, use Alembic to generate and apply a migration, and write it by the rules below.
-
Generate a migration
Terminal window alembic -c api/alembic.ini revision --autogenerate -m "message"If the change needs to migrate data, edit the revision file.
Directoryapi/
Directoryalembic/
- alembic.ini Alembic configuration file
- env.py
- script.py.mako
Directoryversions/ Generated migrations files
- …
-
Apply the migration
Terminal window alembic -c api/alembic.ini upgrade head -
(Optional) Revert the last migration
Terminal window alembic -c api/alembic.ini downgrade -1
The CI runs every migration on each pull request: it checks that there is a single head, that the migrations match the models, and that downgrade then upgrade work on a database holding a row in every table.
Lint the migrations with Squawk
Section titled “Lint the migrations with Squawk”On each pull request, the CI also renders the SQL of the migrations the pull request adds, and lints it with Squawk. The findings appear in the summary of the “Lint the migrations” job; they do not fail it, but the pull request description answers each of them. A migration that cannot be rendered (rule 2 below) fails the job.
To run the same lint locally, render the migrations after a revision, here a9c2e7b41d35, then lint the file:
CONFIG_FILE=./config.example.yml .venv/bin/alembic -c api/alembic.ini upgrade a9c2e7b41d35:head --sql > migrations.sql.venv/bin/squawk --config .squawk.toml migrations.sqluv run alembic -c api/alembic.ini history lists the revisions, newest first: start from the one before your first migration. Call the binaries of .venv directly: under uv run, a redirected output stays empty.
Squawk’s advice to add concurrently does not apply as is: Alembic runs the migrations in a transaction, where CREATE INDEX CONCURRENTLY fails. Follow rule 3 instead.
Write a migration that is safe to deploy
Section titled “Write a migration that is safe to deploy”Each rule below comes from a bug or a risk found in the existing migrations, which predate them. Squawk reports breaches of rules 1 and 3, and the render fails on a breach of rule 2; the others are checked in review.
1. Expand, then contract
Section titled “1. Expand, then contract”During a rolling deployment the previous release keeps serving traffic on the new schema. A migration either expands the schema or contracts it, never both:
- Expand: create a table, add a column that is nullable or has a default, add an enum value, add an index. It ships with the code that uses it.
- Contract: drop or rename a table, a column, a type or a constraint, change a column type, set
NOT NULLon an existing column. It ships in a later release than the code that stopped using the old shape.
A rename is an expand (add the new column, write both, copy), then a contract (drop the old one).
2. No data read from Python
Section titled “2. No data read from Python”A migration does not read rows or the schema through op.get_bind() to decide what to do next: that needs a live connection and breaks alembic upgrade --sql. Put the decision in SQL. Writing through op.get_bind() or op.execute() is fine.
# badcount = op.get_bind().execute(sa.text("SELECT count(*) FROM provider WHERE model_total_params IS NULL")).scalar()if count > 0: raise ValueError("...")
# good: Postgres takes the decision, online and offlineop.execute(""" DO $$ BEGIN IF EXISTS (SELECT 1 FROM provider WHERE model_total_params IS NULL) THEN RAISE EXCEPTION 'provider.model_total_params holds NULL values'; END IF; END $$;""")3. No long lock on a large table
Section titled “3. No long lock on a large table”The usage table takes a write on every inference request. On it, and on any table that can grow, a statement must not hold a lock for the time of a full scan.
Alembic runs every pending migration in one transaction, so splitting the work across two migrations does not release the locks in between. op.get_context().autocommit_block() does: it commits the transaction in progress and runs its statements in autocommit. But the revision is only stamped at the end of upgrade(), so a block that fails leaves half a migration behind, and the rerun fails (constraint "…" already exists). An autocommit_block() is therefore the whole upgrade() of its own migration, and the work it depends on goes in the migration before it:
# revision Adef upgrade() -> None: op.create_foreign_key("usage_router_id_fkey", "usage", "router", ["router_id"], ["id"], postgresql_not_valid=True)
# revision B, down_revision = Adef upgrade() -> None: # Outside a transaction, VALIDATE does not keep the lock ADD CONSTRAINT took: writes go on during the scan. with op.get_context().autocommit_block(): op.execute("ALTER TABLE usage VALIDATE CONSTRAINT usage_router_id_fkey")If VALIDATE fails, the database stays at revision A with the constraint not validated: fix the rows and rerun.
- Create and drop an index
CONCURRENTLY(postgresql_concurrently=True), in its own migration, insideautocommit_block(). A failedCREATE INDEX CONCURRENTLYleaves an invalid index behind, so drop it first withif_exists=True. - Add a foreign key or a check constraint
NOT VALID(postgresql_not_valid=True), then validate it in the next migration, as above. - Set
NOT NULLon a large table through aCHECK (col IS NOT NULL) NOT VALIDconstraint, validated, thenSET NOT NULL, which Postgres then accepts without a scan.
4. Named constraints
Section titled “4. Named constraints”Every constraint has a name, so that downgrade() can drop it. The naming convention of the SQLAlchemy metadata names the single-column ones; give a constraint on several columns an explicit name (unique_rate_limit_per_role).
5. Downgrades that run, and say what they lose
Section titled “5. Downgrades that run, and say what they lose”- A column put back
NOT NULLgets a value first. When the column that replaced it holds the same data, rename it back (op.alter_column(..., new_column_name=...)) instead of adding and copying. - A type created by
upgrade()is dropped bydowngrade():drop_tableleaves enum types behind. - A
downgrade()that loses data, or restores a state with a security meaning (revocation, permissions, expiry), says so in its docstring. For example, the downgrade ofb7e4c1a90f23deletes the revoked keys before droppingtoken.revoked, since the column gone would make them valid again.
6. No validated configuration
Section titled “6. No validated configuration”A migration never calls get_configuration(). Its code is frozen, but it runs with the configuration file of another release. upgrade() would validate the file against the schema of the image running it, so the first required field added later breaks a revision that never reads it. A rollback runs alembic downgrade with the configuration file of the target release, a schema it was not written for.
downgrade()reads nothing but the database.- An
upgrade()that needs a value reads that key alone fromread_configuration_file_without_validating_it(), interpolates it withinterpolate_variables, and keeps its own default, since the schema’s default may change. For example,4a8f3b3aed3areads the bootstrap admin credentials this way.