A one-line lock file stops Alembic migration heads from splitting
The author, an LLM engineer at Nowcast, describes a team using Alembic[1] whose migrations failed on dev after pull requests were merged into main. The team's env.py gives each new revision the next number after the current maximum. Two PRs made from the same main both got number 123, both passed CI, and both were merged, so the head[2] split into two. The same thing happened with revision 124 the following day. Pushes to main automatically deploy to dev and run alembic upgrade head, so the dev migration failed two days in a row.
The team had turned off the GitHub setting "Require branches to be up to date before merging", and merge queue[3] was not available on their plan for a private repo. Requiring up to date for every PR meant repeated Update branch runs as main kept moving, and deploying only after CI passed did not stop the split on main. The fix borrows from django-linear-migrations: a migrations/HEAD file holds the current head's file name on one line, so two branches that each add a migration change the same line and Git reports a conflict before merge. The file name is used instead of the number because two PRs with the same number would make an identical change and would not conflict.
An entry in alembic.ini runs a post_write_hooks[4] script that rewrites HEAD each time a revision is generated. A small test that needs no database checks that HEAD matches the single head, and it is a required CI check, because Alembic ignores hook failures. If a conflict is resolved wrongly, the test fails on the latest main.
Repository Alembic github.com
Database migrations tool for SQLAlchemy, used to version and apply schema changes to a database.
Sources
-
JPZenn JA
1 行のロックファイルで Alembic の head の分岐を防ぐ


