Database Migrations

For a contributor writing a schema migration: canopy is forward-only for application-level schema migrations. The rationale is ADR-016; this page is the how-to — write it, pass the gates, know how it runs, recover locally. The migrator’s database inventory lives in the deployment guide; the variables that select the run mode in the configuration reference; column and table conventions in Coding Conventions › Database patterns.

TL;DR

  • Write forward SQL only. There is no down.sql.

  • If your migration is wrong, write a new forward migration that fixes it.

  • For destructive changes (rename, drop, retype), use the expand-contract pattern below.

  • Broke your local dev DB? cargo xtask migrate rollback (Devstack Migration Snapshot & Rollback).

  • Broke production? PITR — Database Backup & Restore.

Writing a migration

Migration files live under each service’s migrations/ directory:

services/canopy-snap/migrations/
  20260326000000_create_snap_tables.sql
  20260329000000_create_abawd_tables.sql
  ...

Filename format: <UTC timestamp>_<descriptive_name>.sql. The timestamp orders execution; the name is for humans. Each file contains forward DDL only:

-- 20260502120000_add_quality_review_flag.sql

ALTER TABLE caps_authorizations
    ADD COLUMN quality_review_required BOOLEAN NOT NULL DEFAULT false;

CREATE INDEX idx_caps_authorizations_qa
    ON caps_authorizations (quality_review_required)
    WHERE quality_review_required = true;

Run it locally with cargo xtask dev refresh — it picks up new migrations and keeps the data (dev restart wipes it).

Gates a new migration must pass

  1. cargo xtask migrations-lint (xtask/src/cmd/migrations_lint.rs; the blocking migrations-lint stage of cargo xtask validate) runs three checks over every .sql under the migrations and outbox-migrations directories of services/ and crates/:

    • v7 primary keys (#1173): no migration versioned at or after V4_FREE_FROM_VERSION (20260808000001) may default a column to gen_random_uuid() or uuid_generate_v4() — primary keys are app-supplied UUID v7. Earlier history is grandfathered by version.

    • Global DDL (#1392): every services//migrations/.sql is classified by the canopy_test_lib::global_ddl lexer — the contract in the next section.

    • Clock defaults (#2589): no migration versioned at or after CLOCK_DEFAULT_FREE_FROM_VERSION (20270209000000) may default a column to the database clock (now(), CURRENT_TIMESTAMP, CURRENT_DATE, clock_timestamp() and their kin). A writer binds its own instant (ADR-033 §5), so such a default could only stamp a row written past that code, from the wrong clock. The exception is a stamp the database owns, such as the outbox’s enqueued_at, which needs an entry in DATABASE_OWNED_STAMPS with its reason. Earlier history is grandfathered by version, and the banner counts its clock defaults.

  2. cargo xtask outbox-migrations --check (ADR-039; the outbox-migrations stage): a service’s event_outbox migrations are generated copies of canopy-mq’s canonical source. Edit the source and run --write; never edit the copy.

  3. The ephemeral-schema replay: every infra test replays the service’s full migration set into a fresh schema on search_path=<schema>,public (testing.adoc#ephemeral-schemas). A migration that only works in public, or that needs a cluster-global lock it does not declare, fails the lane.

All three run in the battery, which the merge train's car runs (#3354), so that is where a migration is exercised (Testing › CI vs local).

The global DDL contract

The replay is per schema, so a migration may only contain statements search_path can isolate. canopy_test_lib::global_ddl::scan classifies each file; cargo xtask migrations-lint enforces the verdict, and the replay reads the same report for its per-migration lock policy (#1808), so the lint and the lock cannot drift apart.

  • Forbidden outright — cluster-global statements the per-schema replay cannot isolate: role DROP / REASSIGN OWNED / DROP OWNED, database or schema mutation, extension mutation other than a conforming CREATE EXTENSION IF NOT EXISTS … WITH SCHEMA public, any public.<name> target, an unguarded CREATE ROLE.

  • Marker-required — allowed only with an opt-in -- global-ddl: <reason> line anywhere in the file, which also puts the migration on the locked replay path: role ALTER and membership grants, GRANT … ON DATABASE, COMMENT / SECURITY LABEL on a role, database or schema (they write the cluster-shared pg_shdescription / pg_shseclabel), session advisory locks.

  • The fast path — a conforming CREATE EXTENSION IF NOT EXISTS is idempotent and its target is checkable, so the replay locks only while the extension is still absent (LockPolicy::IfExtensionAbsent).

  • Dynamic SQL — the SQL a statement carries as data is shadow-scanned one level deep: string literals and the $tag$…$tag$ body of an EXECUTE (a CREATE FUNCTION body is not; it runs at call time). EXECUTE format('GRANT CONNECT ON DATABASE %I …') is therefore classified as the statement it builds. The scan cannot evaluate what it reads, so it over-includes on purpose and softens a dynamic site from forbidden to marker-required — except an unguarded CREATE ROLE, whose guard is written literally around the EXECUTE and stays decidable.

  • Grandfathering — the files that already carried global DDL are exempt from the marker requirement only, by exact path in GRANDFATHERED_GLOBAL_DDL_FILES (applied migrations are immutable); a forbidden statement fails whether or not a file is listed, and the list only shrinks.

How migrations run

  • In-process — the default (MigrationMode::Run). canopy_api::bootstrap_with applies the service’s embedded migrator (sqlx::migrate!("./migrations")) during boot, on migration_database_url when a deployment splits the schema-owning login from the runtime login (#1456; ServiceSettings in crates/canopy-common/src/settings.rs), otherwise on database_url.

  • Job-owned (MigrationMode::JobOwned). With CANOPY_<SVC>SKIP_MIGRATIONS=true bootstrap applies nothing; the deploy job runs canopy-manage migrate apply --service <canopy-svc> with the URL in CANOPY_MIGRATEDATABASE_URL (#1246 — the posture the withdrawn #1279 cutover was to adopt for the chain services). In CANOPY_ENV=development the skip is refused unless CANOPY_<SVC>__MIGRATIONS_JOB_CONFIGURED is also set (nothing in the devstack compose sets either variable today; the dormant chain-migration-split profile is the rehearsal path), so a developer cannot strand a schema — decide_migration_mode in crates/canopy-api/src/bootstrap.rs.

  • The per-service idempotency_keys tables are created by the migration phase in both modes (canopy_db::ensure_idempotency_schema, #1463), never by the runtime.

When a migration is wrong

The fix is a new migration that corrects it forward, not a down:

Bug Wrong fix Right fix

Column was misnamed

db:rollback, edit the up, re-apply

New migration: ALTER TABLE … RENAME COLUMN

Default value is wrong

Edit the up, force-rerun

New migration: ALTER TABLE … ALTER COLUMN … SET DEFAULT

CHECK constraint was too strict

Drop and re-add manually

New migration: ALTER TABLE … DROP CONSTRAINT, ADD CONSTRAINT

Index was on the wrong column

Edit the up

New migration: DROP INDEX, CREATE INDEX

Migration shipped to prod but data is bad

Application-level rollback

New migration backfills correct values; PITR if data is unrecoverable

Once a migration has merged to main, it is history. Don’t edit it.

Expand-contract for destructive changes

A schema change is destructive if it removes a column, table, index or constraint that existing code reads; renames a column or table; changes a column’s type incompatibly (TEXT → INTEGER); or tightens a NOT NULL / CHECK against rows that don’t yet satisfy it. For these, split the change into separate forward migrations. The classic shape — a column rename:

  1. Expand (_add_new_column.sql): add the new column; old and new code paths both see a valid schema.

  2. Code: deploy an app that writes both columns and reads the old.

  3. Backfill (_backfill_new_column.sql): copy historical values.

  4. Code: deploy an app that writes both and reads the new.

  5. Code: deploy an app that writes only the new column.

  6. Contract (_drop_old_column.sql): drop the old column once nothing reads it.

Each step is independently deployable and rollback-safe: at any point you can revert the application deploy without touching the database, because the schema satisfies both N-1 and N. More files than a one-shot RENAME COLUMN; none of them can break a running deploy in flight. Trivial additive changes — a new nullable or defaulted column, a table no code reads yet, a new index — ship as one forward migration.

Audit-sensitive tables

Some tables carry compliance-critical invariants that no migration should casually disturb:

Table Invariant

fti_audit_log (canopy-tanf, canopy-medicaid)

SHA-256 hash chain over previous_hash / event_hash. Break = Pub 1075 §9 reportable to IRS. ADR-014

audit_events (canopy-security)

Wildcard-subscribed event log with its own hash chain.

*_determinations (signed) tables

JWS-signed column shape verified by cross-service consumers. ADR-002

idempotency_keys (per service)

24-hour TTL; single-flight execution — an atomic claim elects one winner per key (fresh-insert / TTL-recover / hash-fenced steal) holding a claim_id-fenced, renewed lease, so each key’s handler runs once per key across concurrent requests and replicas (epic #1003). Evolved via additive, forward-only expand/contract columns (state, request_hash, claim_id, lease_expires_at, response_headers, replayable; nullable response_*) with state-invariant CHECKs. DDL is owned by the migration path (#1463): canopy_db::ensure_idempotency_schema, run by bootstrap’s migration phase and by canopy-manage migrate apply — never by the runtime.

fti_chain_verifications (canopy-security)

Daily verify-job results; restoring from a stale snapshot would re-emit historical breach events.

Migrations against these tables get an explicit pre-merge review pass for hash-chain compatibility. If you’re touching column shapes a hash includes, the migration must extend the chain forward, not break it.

Recovery paths

Local dev DB — snapshot before a risky migration, roll back if it breaks (xtask/src/cmd/migrate.rs; the full procedure is Devstack Migration Snapshot & Rollback):

cargo xtask migrate snapshot                                       # pg_dump every database into .devstack/snapshots/<timestamp>/
cargo xtask migrate rollback [--id <timestamp>] [--db <name>]...   # latest snapshot unless --id; --db restricts to listed databases

CI — every merge-request pipeline applies migrations as its test jobs bring their stacks up (#3248). A bad migration fails there; push the corrective migration.

Production — PITR (pg_basebackup + WAL replay) per Database Backup & Restore. If the schema is wrong but the data is intact, the right move is usually a forward migration that corrects the schema, deployed under a feature flag; reach for PITR only when data has been corrupted or destroyed, since PITR rolls back unrelated work too.

Why no down.sql

Short version: ADR-016. Long version: down migrations create more problems than they solve at canopy’s compliance and operational posture; forward-only forces every fix through the same review and test gates the original went through.

See also

Edit this page · default