DEV Community

Libme
Libme

Posted on

Alembic "Multiple head revisions are present": Merge or Rebase the Migration? (Plus a CI Guard)

Short answer: Alembic refuses to run because two migration files both claim the same parent, so your history has forked into two heads. If neither migration has been applied to a shared database, change one file's down_revision to point at the other (a rebase). If either has already run somewhere you can't reset, create a merge revision with alembic merge. Either way, add a CI check so a fork fails the pull request instead of the deploy.

What does the error actually look like?

FAILED: Multiple head revisions are present for given argument 'head';
please specify a specific target revision, '<branchname>@head' to narrow
to a specific head, or 'heads' for all heads
Enter fullscreen mode Exit fullscreen mode

It usually appears right after merging two feature branches that each added a migration. Each was created while main pointed at the same latest revision, so each file says down_revision = "abc123". Alembic stores migrations as a graph, not a numbered list. Two children of one parent means two tips, and alembic upgrade head (singular) cannot pick one.

Confirm it first:

alembic heads
# 3f9a1c2b7d10 (head)
# 8e44b0a9c5d2 (head)
Enter fullscreen mode Exit fullscreen mode

Two lines ending in (head) is the diagnosis. alembic history --verbose shows where the fork starts.

Takeaway: the error is not a bug in either migration; it is a graph with two tips, and you have to decide what order they apply in.

Dead ends developers usually try first

  • alembic upgrade heads (plural). It works, and it applies both branches. It also leaves the fork in place, so the next person to run alembic revision --autogenerate hits the same problem, and the relative order of the two branches is undefined. Fine as a one-time unblock, not as a fix.
  • Deleting one migration file. If that migration already ran on any database, its revision id sits in that database's alembic_version table and Alembic will complain it can't locate the revision.
  • Editing alembic_version by hand. Possible in a throwaway dev database. In anything shared, you are lying to the migration tool about which schema changes were applied.

Should I merge or rebase the migration?

The deciding question is whether either migration has already been applied somewhere you can't casually reset.

Situation Best option Why
Both migrations only exist on unmerged or just-merged branches; no shared DB has run them Rebase: edit one down_revision Keeps history linear and readable
One or both already ran on staging or production Merge revision (alembic merge) Rewriting a parent for an applied migration desyncs alembic_version
The two migrations touch the same table or column Rebase, and read both files A merge revision does not check for semantic conflicts
You just need a dev database working today alembic upgrade heads Temporary; fix the graph afterwards

Option A: rebase

Suppose the fork is 3f9a1c2b7d10 (yours) and 8e44b0a9c5d2 (the other branch, already on main). In your file, change the parent:

# before
down_revision = "abc123"
# after
down_revision = "8e44b0a9c5d2"
Enter fullscreen mode Exit fullscreen mode

Run alembic heads again; it should show one line. If you had already applied your migration to your local database, downgrade it before editing, or reset the local database, since its stored parent relationship no longer matches the file.

Option B: merge revision

alembic merge -m "merge add_invoices and add_user_flags" 3f9a1c2b7d10 8e44b0a9c5d2
Enter fullscreen mode Exit fullscreen mode

This generates a near-empty migration whose down_revision is a tuple of both parents:

revision = "c71d5e08aa31"
down_revision = ("3f9a1c2b7d10", "8e44b0a9c5d2")

def upgrade() -> None:
    pass

def downgrade() -> None:
    pass
Enter fullscreen mode Exit fullscreen mode

Databases that applied one branch will pick up the other, then the merge, on the next alembic upgrade head. alembic merge heads -m "..." is a shortcut when there are exactly the heads you want to join.

The part people skip: a merge revision only reconciles the graph. If branch A drops a column that branch B's new index depends on, Alembic will happily apply them in an arbitrary order. Read both upgrade functions before choosing the merge, and put any reconciling statements in the merge file's upgrade().

Takeaway: merge when history is already shared, rebase when it isn't, and never trust a merge revision to catch a semantic conflict.

How do I stop this from happening again?

The fork is invisible in each pull request on its own, because each branch has exactly one head. It only appears after both land. The cheapest guard is a CI step that counts heads on the merged result. This uses Alembic's own API rather than parsing CLI output:

# scripts/check_alembic_heads.py
import sys
from alembic.config import Config
from alembic.script import ScriptDirectory

script = ScriptDirectory.from_config(Config("alembic.ini"))
heads = script.get_heads()

if len(heads) != 1:
    print(f"Expected 1 Alembic head, found {len(heads)}: {', '.join(heads)}")
    print("Run `alembic merge` or rebase one migration's down_revision.")
    sys.exit(1)
print(f"OK: single head {heads[0]}")
Enter fullscreen mode Exit fullscreen mode

Run it on pull requests with a GitHub Actions step:

- name: Check for forked migration history
  run: python scripts/check_alembic_heads.py
Enter fullscreen mode Exit fullscreen mode

For this to catch the race, the check needs to run against the merge result. GitHub's pull_request event checks out a merge of your branch with the base by default, so two PRs that each pass alone will fail the second one after the first merges, if the second is re-run or rebased. Pair it with a branch protection rule that requires branches to be up to date before merging, otherwise the stale green check can still let a fork through. That setting trades some merge friction for correctness, and on a busy repo it gets annoying.

Another way to avoid the whole class: Django solves the same problem with makemigrations --merge and an explicit "Conflicting migrations detected" error, so if you use Django the workflow is analogous but the command names differ.

Takeaway: a one-line head count in CI turns a deploy-time surprise into a failed pull request.

FAQ

How do I fix "Multiple head revisions are present for given argument 'head'" in Alembic?

Run alembic heads to see both tips, then either run alembic merge -m "merge" <rev1> <rev2> to create a merge revision or edit one migration's down_revision to point at the other. Re-run alembic heads and confirm it prints a single head.

Is alembic upgrade heads safe to use instead of merging?

It applies every branch, so it unblocks you, but it leaves the history forked and does not define the order the branches apply in. Use it as a temporary measure, then merge or rebase.

Can I change down_revision after a migration has been applied?

Only if you can reset every database that applied it. On a shared database the stored alembic_version no longer matches the file, so create a merge revision instead.

Bottom line

If you hit this on a feature branch before anything is deployed, rebase your migration onto the other head and move on. If production or staging has already run either migration, write a merge revision and read both upgrade functions for conflicts. In every project with more than one person touching the schema, add the head-count script to CI. It takes a few minutes to set up and removes this error from your release day.

Related reading

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The decision table is the part I would steal — merge when the branch is already out in the wild, rebase when it is still local. That one line would have saved my team an argument. The CI guard is the real win though: catching two heads before they reach main, with the exact fix command in the PR comment, turns a red check into a 30-second fix instead of a 30-minute dig through migration files.

One gap I am curious about: your guard counts heads, and your own warning says a merge revision only reconciles the graph — if branch A drops a column that branch B's upgrade() still expects, the merge succeeds and the deploy fails. Do you have a second tripwire for that kind of semantic conflict, like running the migration against a staging snapshot in CI, or is that the one case where you still rely on a human reading both files before approving the merge?