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
-
cargo xtask migrations-lint(xtask/src/cmd/migrations_lint.rs; the blockingmigrations-lintstage ofcargo xtask validate) runs three checks over every.sqlunder themigrationsandoutbox-migrationsdirectories ofservices/andcrates/:-
v7 primary keys (#1173): no migration versioned at or after
V4_FREE_FROM_VERSION(20260808000001) may default a column togen_random_uuid()oruuid_generate_v4()— primary keys are app-supplied UUID v7. Earlier history is grandfathered by version. -
Global DDL (#1392): every
services//migrations/.sqlis classified by thecanopy_test_lib::global_ddllexer — 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’senqueued_at, which needs an entry inDATABASE_OWNED_STAMPSwith its reason. Earlier history is grandfathered by version, and the banner counts its clock defaults.
-
-
cargo xtask outbox-migrations --check(ADR-039; theoutbox-migrationsstage): a service’sevent_outboxmigrations are generated copies of canopy-mq’s canonical source. Edit the source and run--write; never edit the copy. -
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 inpublic, 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 conformingCREATE EXTENSION IF NOT EXISTS … WITH SCHEMA public, anypublic.<name>target, an unguardedCREATE 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: roleALTERand membership grants,GRANT … ON DATABASE,COMMENT/SECURITY LABELon a role, database or schema (they write the cluster-sharedpg_shdescription/pg_shseclabel), session advisory locks. -
The fast path — a conforming
CREATE EXTENSION IF NOT EXISTSis 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 anEXECUTE(aCREATE FUNCTIONbody 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 unguardedCREATE ROLE, whose guard is written literally around theEXECUTEand 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_withapplies the service’s embedded migrator (sqlx::migrate!("./migrations")) during boot, onmigration_database_urlwhen a deployment splits the schema-owning login from the runtime login (#1456;ServiceSettingsincrates/canopy-common/src/settings.rs), otherwise ondatabase_url. -
Job-owned (
MigrationMode::JobOwned). WithCANOPY_<SVC>SKIP_MIGRATIONS=truebootstrap applies nothing; the deploy job runscanopy-manage migrate apply --service <canopy-svc>with the URL inCANOPY_MIGRATEDATABASE_URL(#1246 — the posture the withdrawn #1279 cutover was to adopt for the chain services). InCANOPY_ENV=developmentthe skip is refused unlessCANOPY_<SVC>__MIGRATIONS_JOB_CONFIGUREDis also set (nothing in the devstack compose sets either variable today; the dormantchain-migration-splitprofile is the rehearsal path), so a developer cannot strand a schema —decide_migration_modeincrates/canopy-api/src/bootstrap.rs. -
The per-service
idempotency_keystables 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 |
|
New migration: |
Default value is wrong |
Edit the up, force-rerun |
New migration: |
CHECK constraint was too strict |
Drop and re-add manually |
New migration: |
Index was on the wrong column |
Edit the up |
New migration: |
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:
-
Expand (
_add_new_column.sql): add the new column; old and new code paths both see a valid schema. -
Code: deploy an app that writes both columns and reads the old.
-
Backfill (
_backfill_new_column.sql): copy historical values. -
Code: deploy an app that writes both and reads the new.
-
Code: deploy an app that writes only the new column.
-
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 |
|---|---|
|
SHA-256 hash chain over |
|
Wildcard-subscribed event log with its own hash chain. |
|
JWS-signed column shape verified by cross-service consumers. ADR-002 |
|
24-hour TTL; single-flight execution — an atomic claim elects one winner per key (fresh-insert / TTL-recover / hash-fenced steal) holding a |
|
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
-
cargo xtask Subcommand Catalog —
migrate,migrations-lintandoutbox-migrationsflags. -
Testing › Ephemeral schemas — how the replay exercises every migration.