Skip to main content

alembic-autoseq 🛡️

CI PyPI version Python versions License: MIT

Alembic AutoSeq automatically reconciles sequential migration numbers, resolves duplicate revision IDs, and heals multi-head branch conflicts for teams developing with SQLAlchemy and Alembic in parallel.


⚡ The Problem: Alembic Migration Conflicts in Parallel Development

When multiple developers work on different Git feature branches off the same base migration:

  1. Duplicate Sequence Numbers: Developer A creates 0004_add_orders.py and Developer B creates 0004_add_inventory.py. Both files share sequence number 0004 and point to down_revision = '0003'.
  2. Multiple Heads Crash: Running alembic upgrade head crashes with:
    alembic.util.exc.CommandError: Multiple head revisions are present for given argument 'head'; please specify a revision or 'heads'
    
  3. Missing Revision Crash on Shared DBs: When testing on a shared dev/staging database, Developer A applies their migration. When Developer B pulls or switches branches, Alembic crashes with:
    alembic.util.exc.CommandError: Can't locate revision identified by '0004_add_orders'
    
  4. The "Silent Skip" Hazard: If both developers use the same revision string (e.g. '0004'), Alembic thinks the migration has already run and silently skips creating the new tables, causing unexpected runtime SQL errors.

⚖️ Comparison: alembic merge vs. alembic-autoseq

Alembic provides a native command alembic merge heads, but its behavior is often undesirable for teams using human-readable sequential migrations:

Feature / Behavior Standard alembic merge alembic-autoseq
Migration History Graph Creates diamond merge nodes (merge_heads_rev.py) that clutter migration history Maintains a clean, 100% linear chain (0001 -> 0002 -> 0003 -> 0004 -> 0005)
Sequential File Renaming ❌ No. Keeps duplicate prefixes like two 0004_ files ✅ Yes. Automatically renames 0004_ to 0005_ on disk
Revision ID Updating ❌ Leaves duplicate revision IDs intact ✅ Safely updates revision and down_revision variables via AST
Shared Database Desync ❌ Crashes with Can't locate revision ✅ Auto-reconciles DB stamp to highest common ancestor
Developer Overhead Requires manual developer intervention and extra merge commits Zero overhead: automatically runs via a single line in env.py

⚠️ When NOT to use alembic-autoseq

  • Historical / Production Migrations: Never use AutoSeq to renumber migrations that have already been applied to production. AutoSeq is strictly designed to reconcile active, unmerged branch migrations before they hit main or production.
  • Complex Multi-Database Branches: If your architecture intentionally relies on complex non-linear DAG branching across separate database clusters, use Alembic's native multi-head tracking.

🚀 Quick Start (1-Line Integration)

1. Install via pip

pip install alembic-autoseq

2. Add to your alembic/env.py

In your alembic/env.py, add alembic_autoseq.guard() inside run_migrations_online():

import alembic_autoseq

def run_migrations_online():
    connectable = engine_from_config(...)

    with connectable.connect() as connection:
        # Automatically detects conflicts and heals branch revision links before Alembic runs
        alembic_autoseq.guard(connection=connection, auto_heal=True)

        context.configure(connection=connection, target_metadata=target_metadata)
        with context.begin_transaction():
            context.run_migrations()
        connection.commit()

Now, whenever you run alembic upgrade head, any parallel branch collisions are automatically linearized and applied without crashing.


🛠️ CLI Usage & CI/CD Guard

alembic-autoseq comes with a CLI for local validation and automated CI checks:

1. Pre-Merge CI Validation (check)

Fails with exit code 1 if any duplicate sequence numbers or multiple heads are present. Perfect for GitHub Actions or pre-commit hooks:

alembic-autoseq check

Output when conflict exists:

❌ Found 3 conflict(s):
  • [DUPLICATE_REVISION_ID] Duplicate revision ID '0004' found across 2 files: ['0004_add_inventory.py', '0004_add_orders.py']
  • [DUPLICATE_SEQUENCE_NUMBER] Duplicate sequence number '4' found across files: ['0004_add_inventory.py', '0004_add_orders.py']
  • [MULTIPLE_HEADS] Multiple heads detected (2 heads): ['0004 (0004_add_inventory.py)', '0004 (0004_add_orders.py)']

2. Auto-Rebase (rebase)

Automatically re-links the active branch migration to the latest upstream head and increments sequence numbers:

alembic-autoseq rebase

3. Migration DAG Tree Visualizer (tree)

Prints an ASCII tree of the migration DAG directly in your terminal:

alembic-autoseq tree
📂 Versions Directory: /path/to/alembic/versions
Total Migrations: 5 | Heads: 1

└── [0001] 0001 -> 0001_initial_tables.py
    └── [0002] 0002 -> 0002_add_roles.py
        └── [0003] 0003 -> 0003_add_departments.py
            └── [0004] 0004 -> 0004_add_orders.py
                └── [0005] 0005 -> 0005_add_inventory.py (HEAD)

✨ DAG is clean and linear.

🤖 GitHub Actions CI Workflow

Add this step to your GitHub Actions .github/workflows/ci.yml to prevent broken migration chains from being merged into main:

name: Migrations Guard
on: [pull_request]

jobs:
  check-migrations:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"
      - name: Install alembic-autoseq
        run: pip install alembic-autoseq
      - name: Verify migration linearity
        run: alembic-autoseq check

🪝 Pre-Commit Hook Integration

Add to your .pre-commit-config.yaml:

repos:
  - repo: https://github.com/jagadeesh88705/alembic_autoseq
    rev: v0.1.1
    hooks:
      - id: alembic-autoseq-check

🏗️ Architecture & Mechanics

📖 Under the Hood: For a detailed breakdown of how AST parsing, SQLite/PostgreSQL savepoints, and in-memory revision map reloading work, read UNDER_THE_HOOD.md.

                      alembic_autoseq.guard()
                                │
        ┌───────────────────────┴───────────────────────┐
        ▼                                               ▼
1. Scan Migration Files                         2. Inspect Database
   • Python AST metadata parsing                   • Reads alembic_version table
   • Sequence number & digit width detection       • Detects orphan DB stamps
        │                                               │
        └───────────────────────┬───────────────────────┘
                                ▼
                     3. DAG Conflict Detection
                        ┌──────────────────────────────┐
                        │ Are there multiple heads?    │
                        │ Are sequence IDs duplicated? │
                        │ Are down_revisions broken?   │
                        └──────────────┬───────────────┘
                                       │
                   ┌───────────────────┴───────────────────┐
             No Conflicts                             Conflicts Found
                   │                                       │
                   ▼                                       ▼
           Proceed normally                       4. Automatic Rebase Engine
                                                     • Detects active branch migration
                                                     • Auto-increments sequence ID (0004 -> 0005)
                                                     • Updates down_revision to upstream head
                                                     • Atomically updates file & in-memory map
                                                           │
                                                           ▼
                                                  Proceed with Alembic Upgrade!

🧪 Running the Test Suite

git clone https://github.com/jagadeesh88705/alembic_autoseq.git
cd alembic_autoseq
python -m venv .venv
source .venv/bin/activate  # On Windows: .\.venv\Scripts\activate
pip install -e .[dev]
pytest -v

📄 License

This project is licensed under the MIT License.

Metadata

Release files for alembic-autoseq 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for alembic-autoseq 0.1.1
File Size Uploaded Provenance Actions
alembic_autoseq-0.1.1.tar.gz 22.4 kB With provenance Details for alembic_autoseq-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for alembic-autoseq 0.1.1
File Interpreter ABI Platform Actions
alembic_autoseq-0.1.1-py3-none-any.whl Python 3 none any Details for alembic_autoseq-0.1.1-py3-none-any.whl

Total release size: 40.8 kB

Release files / alembic_autoseq-0.1.1.tar.gz

Download URL alembic_autoseq-0.1.1.tar.gz
Size 22.4 kB
Tags Source
SHA-256 checksum
How to use checksums
b9a6b815315b009c9337d45ee8ad702076b3570eece30d8433519594e5555ca0
BLAKE2b-256 checksum
How to use checksums
bd0cd35e9a725cce68e529c8185710ded4ac8ef2f479df57324d89bd317edd42
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Release files / alembic_autoseq-0.1.1-py3-none-any.whl

Download URL alembic_autoseq-0.1.1-py3-none-any.whl
Size 18.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cfa30a47cf46a6215b2bd22532594be427a54a7c1d00929e451e06ccdbd06d4d
BLAKE2b-256 checksum
How to use checksums
a58ec45852d064fce4ddcc4dd4408763d6676be41cba6219b246f40c7ecf445b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Security for alembic-autoseq 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for alembic_autoseq-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page