Skip to content

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.

  1. 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
          • …
  2. Apply the migration

    Terminal window
    alembic -c api/alembic.ini upgrade head
  3. (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.

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:

Terminal window
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.sql

uv 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.

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.

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 NULL on 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).

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.

# bad
count = 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 offline
op.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 $$;
""")

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 A
def upgrade() -> None:
op.create_foreign_key("usage_router_id_fkey", "usage", "router", ["router_id"], ["id"], postgresql_not_valid=True)
# revision B, down_revision = A
def 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, inside autocommit_block(). A failed CREATE INDEX CONCURRENTLY leaves an invalid index behind, so drop it first with if_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 NULL on a large table through a CHECK (col IS NOT NULL) NOT VALID constraint, validated, then SET NOT NULL, which Postgres then accepts without a scan.

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 NULL gets 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 by downgrade(): drop_table leaves 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 of b7e4c1a90f23 deletes the revoked keys before dropping token.revoked, since the column gone would make them valid again.

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 from read_configuration_file_without_validating_it(), interpolates it with interpolate_variables, and keeps its own default, since the schema’s default may change. For example, 4a8f3b3aed3a reads the bootstrap admin credentials this way.