Migrations¶
Forward-only SQL migration runner.
migrate ¶
Migration runner.
Forward-only by design. The runner:
- Discovers
*.sqlfiles under :mod:taskq.migrationsin lexicographic order, the naming convention is{ver}_{nn}_{pre|post}_{description}.sql. - Substitutes the
{schema}placeholder with the configured schema name. - Applies migrations not already recorded in
{schema}.schema_migrations, recording a SHA-256 checksum of the rendered SQL after each successful apply.
There is no down operation. To revert, restore from a database backup.
Published variants¶
An applied migration's ledger checksum must match the bundled file or the
runner refuses (checksum drift, fail-closed). The one exception: a file
whose bytes were amended after first shipping may exist in more than one
published version, and databases that applied the earlier bytes keep
that checksum forever. The _variants/ directory inside
:mod:taskq.migrations carries the published history (one file per
vintage, named for the commit that published it); the drift check accepts
a ledger checksum matching the current file OR any bundled variant, each
rendered with the checking database's own schema. A checksum nothing
bundled produced is still drift. Variants are code: reviewed, bundled,
versioned — adding one is a PR, never a runtime knob.
Non-transactional migrations¶
By default each migration file runs inside its own transaction, so a failure
rolls the whole file back. Postgres forbids some statements inside a
transaction block, CREATE INDEX CONCURRENTLY, DROP INDEX
CONCURRENTLY, several ALTER TYPE/VACUUM forms, which makes them
inexpressible under the default wrapper. A migration can opt out by placing
the header directive -- taskq:no-transaction in its leading comment
block (-- line comments only, before the first SQL token); the runner
then executes the file statement by statement with no wrapping transaction
(Alembic's autocommit-block semantics). Two rules keep that safe:
- The migration must be idempotent and re-runnable, nothing rolls back, so a mid-file failure leaves earlier statements in place and the migration is re-executed on the next run. The ledger records completion only after every statement succeeds.
-
An interrupted
CREATE INDEX CONCURRENTLYleaves anINVALIDindex behind; the standard remedy is drop-and-rebuild, written into the migration itself::-- taskq:no-transaction -- NOT redundant with IF NOT EXISTS below: an interrupted CREATE INDEX -- CONCURRENTLY leaves an INVALID index that IF NOT EXISTS alone would -- silently skip rebuilding, so drop the debris first. DROP INDEX CONCURRENTLY IF EXISTS "{schema}".jobs_foo_idx; CREATE INDEX CONCURRENTLY IF NOT EXISTS jobs_foo_idx ON "{schema}".jobs (foo);
Transaction-control statements (BEGIN/COMMIT/ROLLBACK/...) are
rejected in non-transactional files, they would silently re-open a
transaction and, on failure, poison the caller's connection. Statement
splitting assumes standard_conforming_strings=on (the Postgres default
since 9.1).
The ledger column schema_migrations.use_transaction records how each
migration ran (false = outside a transaction) so operators can see which
migrations were/are safe to run online; the runner adds the column on first
use, so pre-upgrade ledgers need no dedicated migration.
__all__
module-attribute
¶
__all__ = [
"ApplyFailureDiagnosis",
"ChecksumDrift",
"ChecksumDriftError",
"Migration",
"MigrationLockTimeoutError",
"Phase",
"apply_pending",
"apply_pending_locked",
"checksum_drifts",
"diagnose_apply_failure",
"discover",
"list_applied",
"list_invalid_indexes",
"migration_advisory_lock",
"migration_lock_name",
"render",
"render_apply_failure_lines",
"split_statements",
]
DEFAULT_MIGRATION_DDL_LOCK_TIMEOUT
module-attribute
¶
Migration
dataclass
¶
Migration(
version: str,
phase: Phase,
description: str,
filename: str,
sql_template: str,
use_transaction: bool = True,
)
A single SQL migration file.
use_transaction
class-attribute
instance-attribute
¶
When False (-- taskq:no-transaction header directive), apply the
file statement by statement with no wrapping transaction. Postgres
requires this for CREATE INDEX CONCURRENTLY and friends, but nothing
rolls back on failure, so such migrations must be idempotent.
render ¶
MigrationLockTimeoutError ¶
Bases: RuntimeError
A migration run's DDL waited ddl_lock_timeout for a table lock and
gave up; its transaction rolled back and nothing was applied.
migration is the transactional migration whose DDL timed out, or
None when the wait was the runner's own upgrade of the
schema_migrations ledger (an ALTER TABLE that runs before the
first migration of a run, or after a -- taskq:no-transaction file's
statements). Raised in place of the driver's LockNotAvailableError
(kept as the cause) so the report names what waited, the bound that
expired, and the remedy, the holder must be found and ended, or the
bound raised, rather than the bare canceling statement due to lock
timeout.
Source code in src/taskq/migrate.py
ChecksumDrift
dataclass
¶
One applied migration whose ledger checksum differs from the file.
key is the ledger identity ({version}:{phase}), stored is
the checksum recorded when the migration ran, current is the
checksum the bundled file renders to now.
ChecksumDriftError ¶
Bases: RuntimeError
An APPLIED migration's ledger checksum differs from the bundled file.
The ledger checksum is the SHA-256 of the SQL as it ran; a mismatch means the file no longer matches the schema the database actually has. Applying further migrations on top would build on an unverified premise (the recorded schema may not be what the current files produce, so the next file's assumptions can be silently wrong), which is why the runner refuses by default instead of warning and continuing. NOT-YET-APPLIED files cannot drift: nothing is recorded for them yet.
Remedies: restore the migration file to the version that actually ran
(editing an already-applied migration is never picked up, forward-only
by design), or, after verifying the edited file is exactly what the
database already has (or that the edit is safe to build on), pass
allow_checksum_drift=True (the CLI's --allow-checksum-drift)
to proceed past the refusal. The drift is still logged as a warning
either way, the ledger keeps the stored checksum.
Source code in src/taskq/migrate.py
ApplyFailureDiagnosis
dataclass
¶
ApplyFailureDiagnosis(
headline: str,
failed_filename: str | None,
use_transaction: bool | None,
invalid_indexes: tuple[str, ...],
schema: str,
guard_rejected: bool = False,
)
Self-diagnosis of a failed migration apply, gathered on the still-open
connection by :func:diagnose_apply_failure and rendered by
:func:render_apply_failure_lines.
headline
instance-attribute
¶
First line of the original error (asyncpg messages can be multiline).
failed_filename
instance-attribute
¶
Filename of the migration that failed, taken from the exception's
taskq_failed_migration tag when :func:apply_pending attached one,
else the first unrecorded migration in discover() order (a heuristic
that misattributes under --phase); None when it could not be
determined.
use_transaction
instance-attribute
¶
Migration.use_transaction of the failed migration; None when
the failed migration could not be determined.
invalid_indexes
instance-attribute
¶
INVALID indexes in the schema, debris of an interrupted CREATE
INDEX CONCURRENTLY; only gathered for no-transaction failures.
guard_rejected
class-attribute
instance-attribute
¶
True when the failure was the transaction-control guard refusing the
file (:func:_reject_transaction_control) rather than a statement
failing mid-file, read from the exception's taskq_guard_rejection
tag. The report then says nothing was executed and that the fix is
removing the statement, instead of the generic no-transaction wording
("statements before the failure remain applied", "re-run, the
migration is idempotent"), both false for a guard rejection.
__post_init__ ¶
Source code in src/taskq/migrate.py
discover ¶
Return all bundled migrations sorted by version, then pre before post.
Raises :class:ValueError when two bundled files map to one ledger
identity (see :func:_refuse_duplicate_ledger_keys).
Source code in src/taskq/migrate.py
render ¶
Substitute {schema} in a SQL template.
SQL files escape literal curly braces by doubling them ({{ → {)
because :func:str.format is the substitution engine.
Source code in src/taskq/migrate.py
split_statements ¶
Split a SQL script into individual statements, without their ;.
Non-transactional migrations are executed statement by statement: a
multi-statement string sent through Postgres' simple query protocol runs
as ONE implicit transaction, which would defeat the point (CREATE
INDEX CONCURRENTLY would still be "inside a transaction block").
Splitting understands single-quoted strings (including E'...'
backslash escapes and '' doubling), "..."-quoted identifiers,
-- line comments, nested /* ... */ block comments, and
dollar-quoted bodies ($$...$$ / $tag$...$tag$). Leading comments
stay attached to the statement that follows them; comment-only chunks
are dropped. Unterminated constructs yield one trailing chunk, leaving
the syntax error to Postgres, same as executing the file whole.
Source code in src/taskq/migrate.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | |
list_applied
async
¶
Return {version}:{phase} keys recorded in schema_migrations.
Returns an empty set if the schema or table does not yet exist, a
fresh database is the common case on first migrate up.
Source code in src/taskq/migrate.py
checksum_drifts
async
¶
Compare the ledger's recorded checksums against the bundled files.
Returns one :class:ChecksumDrift per APPLIED migration whose stored
checksum differs from what its file renders to now, keyed by the
migration key, empty when the ledger and the files agree (or when no
ledger exists yet). Shared by migrate up's fail-closed refusal
(:func:apply_pending) and migrate status's drift report, so both
surfaces answer with the same comparison.
A drifted checksum means the file no longer matches the SQL that built the schema: the file was edited after it ran, or the ledger was tampered with. Neither is recoverable by applying more migrations, which is why callers should surface the result prominently rather than bury it among pending entries.
Source code in src/taskq/migrate.py
list_invalid_indexes
async
¶
Return the names of INVALID indexes in schema, sorted by name.
An interrupted CREATE INDEX CONCURRENTLY leaves an INVALID index
behind: the query planner ignores it, but writers still maintain it, so
it is pure overhead (and blocks the re-run's IF NOT EXISTS). The CLI
surfaces these in its failure report so users never have to query the
catalogs by hand.
Source code in src/taskq/migrate.py
apply_pending
async
¶
apply_pending(
conn: Connection,
*,
schema: str,
phase: Phase | None = None,
target: str | None = None,
max_steps: int | None = None,
ddl_lock_timeout: float = DEFAULT_MIGRATION_DDL_LOCK_TIMEOUT,
allow_checksum_drift: bool = False,
) -> list[Migration]
Apply pending migrations.
Each migration runs in its own transaction so a failure in one file does
not leave a half-applied schema, unless the file carries the
-- taskq:no-transaction header directive (:attr:Migration.use_transaction),
in which case it is executed statement by statement with no wrapping
transaction. That unlocks CREATE INDEX CONCURRENTLY and friends, but
nothing rolls back on failure: prior statements stay applied, the
migration is NOT recorded in the ledger, and it will be re-executed on
the next run, so non-transactional migrations must be idempotent.
:param phase: restrict to pre or post migrations only.
:param target: stop after applying this version (inclusive). Must
name a version in the discovered set: an unknown target, a
deleted or renumbered migration, raises ValueError rather
than silently applying every pending migration.
:param max_steps: stop after this many applies.
:param ddl_lock_timeout: seconds a transactional migration may wait for
a table lock (:data:DEFAULT_MIGRATION_DDL_LOCK_TIMEOUT); applied
as SET LOCAL lock_timeout inside each migration's own
transaction, so it never outlives the migration, and never applied
to -- taskq:no-transaction files, whose CONCURRENTLY waits
are heavyweight-lock waits by design. A wait that outlives it
raises :class:MigrationLockTimeoutError; 0 waits indefinitely
(stated explicitly, so a session-level lock_timeout default
cannot bound the wait either); negative, non-finite, and
sub-millisecond values are refused with ValueError.
:param allow_checksum_drift: proceed past :class:ChecksumDriftError
when an APPLIED migration's ledger checksum differs from the
bundled file. The drift is still logged as a warning. NOT-YET-
APPLIED files cannot drift (nothing is recorded for them yet), so
this flag never changes which migrations run, only whether a
drifted ledger refuses the run.
:returns: migrations that were applied (in order).
:raises ChecksumDriftError: when an applied migration's stored checksum
differs from the file and allow_checksum_drift is False.
Raised BEFORE anything is applied: a ledger that no longer matches
the files means the schema's provenance is unverified, and further
migrations must not build on it.
Source code in src/taskq/migrate.py
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 | |
migration_lock_name ¶
Schema-qualified migration advisory-lock name: taskq:migrate:{schema}.
Advisory locks live in a per-database namespace, so the pre-qualification
fixed bigint key was shared by every schema in the database: two
deployments sharing one database serialized their migrations on one
lock, and the loser of a cross-deployment race, a schema with
nothing to migrate, burned its bounded startup wait and SystemExited
while an unrelated schema's long DDL ran. Qualifying with the schema
gives each schema its own lock; same-schema replicas still serialize
(the reason the lock exists, a virgin schema's bare CREATE TABLE
races two concurrent appliers).
Deliberately the same taskq:{purpose}:{schema} shape as
:func:taskq.constants.schema_lock_name (built from it). That helper
is how every purpose lock in the system derives its key, one lock
per schema and purpose (maintenance_leader, prune, archive_expiry,
cron, migrate). Keyed locks, which must distinguish a resource
within a schema, embed the schema before their key instead: the
sliding-window bucket lock taskq:{schema}:sw:{name} (mirroring
the bucket's Redis key) and the enqueue unique-for lock
taskq:unique_for:{schema}:{actor}:{identity_key}. Both
conventions qualify with the schema; they differ only in where the
distinguishing key segments sit.
Upgrade discipline: the qualified key replaces the unqualified bigint outright, a mixed old/new fleet holds different keys, so an old and a new replica can apply migrations to the SAME schema concurrently during the deploy window. Adopt by restarting the fleet onto the new release rather than rolling it; the window is the deploy, not the steady state. (Same caveat as the schema-qualified leader locks.)
Source code in src/taskq/migrate.py
diagnose_apply_failure
async
¶
Gather a self-diagnosis of a failed apply on the still-open conn.
Both apply paths leave the connection reusable (a transactional failure
rolls back; the no-transaction path never opened one), so the same conn
can report what failed and what state the schema is in. Diagnosis must
NEVER mask the original error: every read is individually suppressed,
and whatever could not be gathered degrades to the generic report
(failed_filename=None).
Source code in src/taskq/migrate.py
render_apply_failure_lines ¶
Render a diagnosis as report lines (CLI stderr / startup SystemExit).
startup=False reproduces the migrate up CLI report verbatim;
startup=True swaps only the action line for the restart-safe
variant (:data:_STARTUP_ACTION_LINE), except for guard rejections,
where neither action line is truthful (nothing executed, and re-run or
restart fails identically until the statement is removed), so the
guard branch renders the same remove-and-rerun guidance either way.
Source code in src/taskq/migrate.py
migration_advisory_lock
async
¶
migration_advisory_lock(
conn: Connection,
lock_timeout: float = DEFAULT_MIGRATION_LOCK_TIMEOUT,
*,
schema: str,
) -> AsyncGenerator[None]
Hold schema's migration advisory lock on conn, with a bounded wait.
Extracted so the CLI and :func:apply_pending_locked serialize on the SAME
lock without duplicating the acquire/reset/release protocol. The CLI cannot
delegate to apply_pending_locked: it owns the connection so it
can run _report_up_failure diagnostics on it after a failure, and
apply_pending_locked converts failures to SystemExit before that
could run.
The lock key is :func:migration_lock_name, schema-qualified, because
advisory locks are database-scoped and an unqualified key serializes
every schema in the database (see that function's docstring for the
cross-deployment failure mode and the mixed-fleet adopt note).
schema is required, not defaulted: a silent default would point at
one fixed schema while the caller's settings name another, the same
defect class the qualification itself fixes.
lock_timeout bounds only the WAIT for the advisory lock, via
Postgres' lock_timeout GUC. It is reset to unlimited before the body
runs: the session-wide value must not bound the -- taskq:no-transaction
files, whose CONCURRENTLY phases wait on heavyweight locks by design,
while each transactional migration bounds its own table-lock wait with
SET LOCAL (see :func:apply_pending's ddl_lock_timeout). Neither
bound can interrupt a statement that already holds its lock, a long
index build is governed by statement_timeout, widened below. 0
waits indefinitely (stated explicitly, so a session-level
lock_timeout default cannot bound the acquire either); negative,
non-finite, and sub-millisecond values are refused with ValueError,
the same rule ddl_lock_timeout follows. If the reset fails (a
wedged caller-owned connection), the failure is logged as a warning
naming the connection and the lock flow proceeds, that connection keeps
the wait bound as its session-wide lock_timeout until it is closed.
statement_timeout is widened to unlimited immediately after the
lock is acquired, once, for the whole apply phase, and NEVER on the
contention path: a caller-owned connection that merely lost the race
gets SystemExit above and returns to its owner, which must not
silently gain a session-wide unlimited statement_timeout from losing
a lock race. A session statement_timeout (server_settings on the
connection, a role/database default, a DSN options clause) would
abort a long DDL statement, an index build over a large table ,
mid-statement, and identically on every retry, since the runner
re-executes the same migration after a failure. Like the
lock_timeout doctrine, the widened state is deliberately NOT
restored on exit: the unlock must not trade a GUC restore for a
failed migration run, and a failed widening is logged as a warning
naming the connection while the apply proceeds, that connection
keeps its session statement_timeout.
Raises :class:SystemExit on contention rather than blocking until the
container platform kills the process.
Source code in src/taskq/migrate.py
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 | |
apply_pending_locked
async
¶
apply_pending_locked(
dsn: str | None = None,
*,
schema: str,
phase: Phase | None = "pre",
target: str | None = None,
max_steps: int | None = None,
conn: Connection | None = None,
conn_factory: Callable[[], Awaitable[Connection]]
| None = None,
lock_timeout: float = DEFAULT_MIGRATION_LOCK_TIMEOUT,
ddl_lock_timeout: float = DEFAULT_MIGRATION_DDL_LOCK_TIMEOUT,
allow_checksum_drift: bool = False,
) -> list[Migration]
Apply pending migrations under a session-level advisory lock.
Acquires pg_advisory_lock to prevent concurrent startup races,
applies pending migrations, and releases the lock.
lock_timeout bounds only the wait for the advisory lock, via
Postgres' lock_timeout GUC. It is reset to unlimited before the
migrations run; each transactional migration then bounds its own
table-lock waits with ddl_lock_timeout (see :func:apply_pending),
which cannot interrupt a statement that already holds its lock. Pass
0 to wait indefinitely (the old behaviour).
The session's statement_timeout is widened to unlimited for the
apply phase for the same reason, a caller-supplied session default
must not abort a long DDL statement mid-build (it would fail
identically on every retry).
Losing the race raises :class:SystemExit naming the contention, rather
than hanging until the platform kills the container.
allow_checksum_drift passes through to :func:apply_pending: a
ledger checksum that no longer matches the bundled files refuses the
run (as :class:ChecksumDriftError, converted to SystemExit by
this wrapper's failure handling) unless the flag is set. Startup
callers (--migrate, TASKQ_MIGRATE_ON_START) should leave it
False: a drifted ledger is exactly the state a fleet must not start
on.
Connection sources (mutually exclusive):
* conn, pre-constructed, caller-owned; NOT closed here.
* conn_factory, zero-arg async factory; closed in finally.
* dsn, asyncpg.connect(dsn); closed in finally.
Raises :class:SystemExit on failure so the calling process aborts
cleanly. This is the recommended entry point for CLI --migrate
and admin sidecar TASKQ_MIGRATE_ON_START paths.
phase defaults to "pre" because this entry point fires on
process lifecycle events nobody sequences, a pod restart, a rollout,
an autoscale event, not on an operator's decision. A post-phase
migration exists precisely to be withheld until the whole fleet is
confirmed upgraded, and no single process can know that, so applying
one here would let a restart close a rolling-deploy overlap window
mid-rollout. Dropping the old single-column idempotency index while
the not-yet-upgraded half of the fleet is still issuing
ON CONFLICT (idempotency_key) takes that half's ENTIRE enqueue
path down: the arbiter index is resolved at plan time, so every
enqueue fails regardless of row values. The post phase stays behind
the operator's explicit taskq migrate up --phase post; pass
phase=None to apply every phase from a context that has that
knowledge.
Source code in src/taskq/migrate.py
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 | |