Skip to content

πŸ™Œ OpenHands: AI-Driven Development

PLTF-2895: add enterprise migration integrity check (#14689)

aivong-openhands5399cb13c1c9
diff --git a/.github/workflows/enterprise-apply-migrations-test-db.yml b/.github/workflows/enterprise-apply-migrations-test-db.yml
deleted file mode 100644
index a19fca65bd..0000000000
--- a/.github/workflows/enterprise-apply-migrations-test-db.yml
+++ /dev/null
@@ -1,98 +0,0 @@
-name: Enterprise Apply Migrations on Test DB
-
-# Applies the full enterprise migration chain against a throwaway test Postgres, using the
-# SAME driver as production (pg8000) and the real migrations/env.py harness
-# (advisory lock + transaction wrapping). This catches migration bugs before
-# merge/deploy instead of in the staging migrate-db init container β€” e.g. a
-# CREATE INDEX CONCURRENTLY in an autocommit_block, which crashes under env.py.
-
-on:
- pull_request:
- paths:
- - 'enterprise/migrations/**'
- - 'enterprise/alembic.ini'
- - '.github/workflows/enterprise-apply-migrations-test-db.yml'
-
-# Group is per-PR-branch, so this only cancels a superseded run of the SAME PR
-# (e.g. after a new push) β€” never another PR. cancel-in-progress is safe here
-# because each run uses its own throwaway Postgres service that is destroyed with
-# the runner: cancelling mid-migration leaves no shared/persistent state behind.
-concurrency:
- group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
- cancel-in-progress: true
-
-jobs:
- apply-migrations:
- name: Apply migrations on test DB
- runs-on: ubuntu-24.04
- strategy:
- matrix:
- # Test both the production driver (pg8000) and the psycopg2 fallback.
- # The CLOUD_SQL_POSTGRES_VERSION env var holds the canonical Cloud SQL
- # major version β€” update this job's image tag whenever that variable
- # changes in the deploy repo. If CLOUD_SQL_POSTGRES_VERSION is unset,
- # postgres:16 is used as a reasonable fallback (check deploy repo for
- # the current cloudsql-postgres image tag and keep them in sync).
- db-driver: [pg8000, ""] # [production driver, psycopg2 fallback]
- # Safety timeout: large schemas with many indexes/tables can take 15+ minutes
- # to migrate. Adjust if schema growth outpaces this estimate.
- timeout-minutes: 30
- services:
- postgres:
- image: postgres:16
- env:
- POSTGRES_USER: openhands
- POSTGRES_PASSWORD: openhands
- POSTGRES_DB: openhands
- ports:
- - 5432:5432
- options: >-
- --health-cmd "pg_isready -U openhands"
- --health-interval 5s
- --health-timeout 5s
- --health-retries 10
- env:
- DB_HOST: localhost
- DB_PORT: "5432"
- DB_USER: openhands
- DB_PASS: openhands
- DB_NAME: openhands
- DB_DRIVER: ${{ matrix.db-driver }} # pg8000 for prod parity, "" for psycopg2
- steps:
- - uses: actions/checkout@v6
- - name: Install poetry via pipx
- run: pipx install poetry
- - name: Set up Python
- uses: actions/setup-python@v6
- with:
- python-version: "3.12"
- cache: "poetry"
- - name: Install Python dependencies using Poetry
- working-directory: ./enterprise
- run: poetry install --with dev,test
- - name: Show migration history
- working-directory: ./enterprise
- run: poetry run alembic history --verbose
- - name: Apply full migration chain (upgrade head)
- working-directory: ./enterprise
- run: |
- echo "::group::alembic upgrade head (from empty DB)"
- START=$(date +%s)
- poetry run alembic upgrade head
- echo "upgrade head took $(( $(date +%s) - START ))s"
- echo "::endgroup::"
- poetry run alembic current
- - name: Round-trip the newest migration (downgrade -1, upgrade head)
- working-directory: ./enterprise
- # Fail fast if downgrade fails. The database is throwaway, and the
- # final reporting step still prints the current revision for debugging.
- run: |
- echo "::group::downgrade -1 then re-upgrade"
- poetry run alembic downgrade -1
- poetry run alembic upgrade head
- echo "::endgroup::"
- poetry run alembic current
- - name: Report migration state
- if: always()
- working-directory: ./enterprise
- run: poetry run alembic current || true
diff --git a/.github/workflows/enterprise-check-migrations.yml b/.github/workflows/enterprise-check-migrations.yml
index 739f04702f..5ec57b0e7e 100644
--- a/.github/workflows/enterprise-check-migrations.yml
+++ b/.github/workflows/enterprise-check-migrations.yml
@@ -4,6 +4,15 @@ on:
pull_request:
paths:
- 'enterprise/migrations/**'
+ - 'enterprise/alembic.ini'
+ - 'scripts/check_enterprise_migration_integrity.py'
+ - '.github/workflows/enterprise-check-migrations.yml'
+
+# Group is per-PR-branch, so this only cancels a superseded run of the SAME PR
+# (e.g. after a new push) β€” never another PR.
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+ cancel-in-progress: true
jobs:
check-sync:
@@ -15,6 +24,8 @@ jobs:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
+ - name: Check migration static integrity
+ run: python3 scripts/check_enterprise_migration_integrity.py
- name: Fetch base branch
env:
@@ -55,3 +66,79 @@ jobs:
edit-mode: replace
body: |
⚠️ This PR contains **migrations**. Please synchronize before merging to prevent conflicts.
+
+ apply-migrations:
+ name: Apply migrations on test DB
+ runs-on: ubuntu-24.04
+ needs: [check-sync]
+ strategy:
+ matrix:
+ # Test both the production driver (pg8000) and the psycopg2 fallback.
+ # The CLOUD_SQL_POSTGRES_VERSION env var holds the canonical Cloud SQL
+ # major version β€” update this job's image tag whenever that variable
+ # changes in the deploy repo. If CLOUD_SQL_POSTGRES_VERSION is unset,
+ # postgres:16 is used as a reasonable fallback (check deploy repo for
+ # the current cloudsql-postgres image tag and keep them in sync).
+ db-driver: [pg8000, ""] # [production driver, psycopg2 fallback]
+ # Safety timeout: large schemas with many indexes/tables can take 15+ minutes
+ # to migrate. Adjust if schema growth outpaces this estimate.
+ timeout-minutes: 30
+ services:
+ postgres:
+ image: postgres:16
+ env:
+ POSTGRES_USER: openhands
+ POSTGRES_PASSWORD: openhands
+ POSTGRES_DB: openhands
+ ports:
+ - 5432:5432
+ options: >-
+ --health-cmd "pg_isready -U openhands"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 10
+ env:
+ DB_HOST: localhost
+ DB_PORT: "5432"
+ DB_USER: openhands
+ DB_PASS: openhands
+ DB_NAME: openhands
+ DB_DRIVER: ${{ matrix.db-driver }} # pg8000 for prod parity, "" for psycopg2
+ steps:
+ - uses: actions/checkout@v6
+ - name: Install poetry via pipx
+ run: pipx install poetry
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.12"
+ cache: "poetry"
+ - name: Install Python dependencies using Poetry
+ working-directory: ./enterprise
+ run: poetry install --with dev,test
+ - name: Show migration history
+ working-directory: ./enterprise
+ run: poetry run alembic history --verbose
+ - name: Apply full migration chain (upgrade head)
+ working-directory: ./enterprise
+ run: |
+ echo "::group::alembic upgrade head (from empty DB)"
+ START=$(date +%s)
+ poetry run alembic upgrade head
+ echo "upgrade head took $(( $(date +%s) - START ))s"
+ echo "::endgroup::"
+ poetry run alembic current
+ - name: Round-trip the newest migration (downgrade -1, upgrade head)
+ working-directory: ./enterprise
+ # Fail fast if downgrade fails. The database is throwaway, and the
+ # final reporting step still prints the current revision for debugging.
+ run: |
+ echo "::group::downgrade -1 then re-upgrade"
+ poetry run alembic downgrade -1
+ poetry run alembic upgrade head
+ echo "::endgroup::"
+ poetry run alembic current
+ - name: Report migration state
+ if: always()
+ working-directory: ./enterprise
+ run: poetry run alembic current || true
diff --git a/scripts/check_enterprise_migration_integrity.py b/scripts/check_enterprise_migration_integrity.py
new file mode 100644
index 0000000000..6765f4f8ff
--- /dev/null
+++ b/scripts/check_enterprise_migration_integrity.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import argparse
+import ast
+import re
+import sys
+from collections import defaultdict
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[1]
+DEFAULT_VERSIONS_DIR = ROOT / 'enterprise' / 'migrations' / 'versions'
+MIGRATION_FILENAME_RE = re.compile(r'^(?P<prefix>\d+)_.+\.py$')
+MISSING = object()
+
+
+def _literal_assignment(module: ast.Module, name: str) -> Any:
+ for node in module.body:
+ if isinstance(node, ast.Assign):
+ targets = node.targets
+ elif isinstance(node, ast.AnnAssign):
+ targets = [node.target]
+ else:
+ continue
+
+ if any(
+ isinstance(target, ast.Name) and target.id == name for target in targets
+ ):
+ return ast.literal_eval(node.value)
+
+ return MISSING
+
+
+def _format_paths(paths: list[Path]) -> str:
+ return ', '.join(path.name for path in sorted(paths))
+
+
+def _down_revisions(value: Any, path: Path, errors: list[str]) -> list[str]:
+ if value is MISSING:
+ errors.append(f'{path.name}: missing down_revision assignment')
+ return []
+ if value is None:
+ return []
+ if isinstance(value, str):
+ return [value]
+ if isinstance(value, (list, tuple)):
+ if all(isinstance(item, str) for item in value):
+ return list(value)
+
+ errors.append(
+ f'{path.name}: down_revision must be None, a string, or a sequence of strings'
+ )
+ return []
+
+
+def check_migration_integrity(versions_dir: Path = DEFAULT_VERSIONS_DIR) -> list[str]:
+ errors: list[str] = []
+ migrations: list[dict[str, Any]] = []
+ prefixes: defaultdict[str, list[Path]] = defaultdict(list)
+ revisions: defaultdict[str, list[Path]] = defaultdict(list)
+ referenced_revisions: set[str] = set()
+
+ if not versions_dir.exists():
+ return [f'Migration versions directory does not exist: {versions_dir}']
+
+ for path in sorted(versions_dir.glob('*.py')):
+ if path.name == '__init__.py':
+ continue
+
+ match = MIGRATION_FILENAME_RE.match(path.name)
+ prefix = match.group('prefix') if match else None
+ if prefix is None:
+ errors.append(
+ f'{path.name}: migration filename must start with a numeric prefix'
+ )
+ else:
+ prefixes[prefix].append(path)
+
+ try:
+ module = ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
+ except SyntaxError as exc:
+ errors.append(f'{path.name}: cannot parse migration: {exc}')
+ continue
+
+ revision = _literal_assignment(module, 'revision')
+ if not isinstance(revision, str):
+ errors.append(f'{path.name}: revision must be a string')
+ continue
+
+ revisions[revision].append(path)
+ if prefix is not None and prefix != revision:
+ errors.append(
+ f'{path.name}: Filename prefix {prefix} does not match revision {revision}'
+ )
+
+ down_revision = _literal_assignment(module, 'down_revision')
+ down_revisions = _down_revisions(down_revision, path, errors)
+ referenced_revisions.update(down_revisions)
+ migrations.append(
+ {
+ 'path': path,
+ 'revision': revision,
+ 'down_revisions': down_revisions,
+ }
+ )
+
+ for prefix, paths in sorted(prefixes.items()):
+ if len(paths) > 1:
+ errors.append(
+ f'Duplicate migration filename prefix {prefix}: {_format_paths(paths)}'
+ )
+
+ for revision, paths in sorted(revisions.items()):
+ if len(paths) > 1:
+ errors.append(
+ f'Duplicate migration revision {revision}: {_format_paths(paths)}'
+ )
+
+ known_revisions = set(revisions)
+ for migration in migrations:
+ for down_revision in migration['down_revisions']:
+ if down_revision not in known_revisions:
+ errors.append(
+ f'{migration["path"].name}: references missing down_revision '
+ f'{down_revision}'
+ )
+
+ heads = sorted(known_revisions - referenced_revisions)
+ if migrations and len(heads) != 1:
+ errors.append(
+ f'Expected exactly one migration head, found {len(heads)}: '
+ f'{", ".join(heads) if heads else "<none>"}'
+ )
+
+ return errors
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description='Check enterprise Alembic migration static integrity.'
+ )
+ parser.add_argument(
+ '--versions-dir',
+ type=Path,
+ default=DEFAULT_VERSIONS_DIR,
+ help='Path to the enterprise Alembic versions directory.',
+ )
+ return parser.parse_args()
+
+
+def main() -> int:
+ args = parse_args()
+ errors = check_migration_integrity(args.versions_dir)
+ if errors:
+ print('Enterprise migration integrity check failed:', file=sys.stderr)
+ for error in errors:
+ print(f' - {error}', file=sys.stderr)
+ return 1
+
+ print('Enterprise migration integrity checks passed.')
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/tests/unit/test_enterprise_migration_integrity.py b/tests/unit/test_enterprise_migration_integrity.py
new file mode 100644
index 0000000000..ac4042f075
--- /dev/null
+++ b/tests/unit/test_enterprise_migration_integrity.py
@@ -0,0 +1,285 @@
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[2]
+MODULE_NAME = 'check_enterprise_migration_integrity'
+_saved_spec = None
+
+
+def load_module():
+ global _saved_spec
+ if _saved_spec is not None:
+ module = importlib.util.module_from_spec(_saved_spec)
+ spec_loader = _saved_spec.loader
+ spec_loader.exec_module(module)
+ sys.modules[MODULE_NAME] = module
+ return module
+ path = ROOT / 'scripts' / 'check_enterprise_migration_integrity.py'
+ spec = importlib.util.spec_from_file_location(MODULE_NAME, path)
+ if spec is None or spec.loader is None:
+ raise AssertionError(f'Unable to load module from {path}')
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ _saved_spec = spec
+ sys.modules[MODULE_NAME] = module
+ return module
+
+
+def write_migration(
+ versions_dir: Path,
+ filename: str,
+ *,
+ revision: str,
+ down_revision: str | None,
+) -> None:
+ down_revision_value = repr(down_revision) if down_revision is not None else 'None'
+ (versions_dir / filename).write_text(
+ '\n'.join(
+ [
+ '"""Test migration."""',
+ '',
+ f'revision = {revision!r}',
+ f'down_revision = {down_revision_value}',
+ 'branch_labels = None',
+ 'depends_on = None',
+ '',
+ 'def upgrade():',
+ ' pass',
+ '',
+ 'def downgrade():',
+ ' pass',
+ '',
+ ]
+ )
+ )
+
+
+def versions_dir(tmp_path: Path) -> Path:
+ path = tmp_path / 'versions'
+ path.mkdir()
+ return path
+
+
+def test_valid_linear_migrations_pass(versions_dir: Path):
+ module = load_module()
+ write_migration(
+ versions_dir,
+ '001_create_users.py',
+ revision='001',
+ down_revision=None,
+ )
+ write_migration(
+ versions_dir,
+ '002_add_user_email.py',
+ revision='002',
+ down_revision='001',
+ )
+
+ assert module.check_migration_integrity(versions_dir) == []
+
+
+def test_duplicate_filename_prefix_fails(versions_dir: Path):
+ module = load_module()
+ write_migration(
+ versions_dir,
+ '001_create_users.py',
+ revision='001',
+ down_revision=None,
+ )
+ write_migration(
+ versions_dir,
+ '001_add_user_email.py',
+ revision='002',
+ down_revision='001',
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any('Duplicate migration filename prefix 001' in error for error in errors)
+
+
+def test_duplicate_revision_fails(versions_dir: Path):
+ module = load_module()
+ write_migration(
+ versions_dir,
+ '001_create_users.py',
+ revision='001',
+ down_revision=None,
+ )
+ write_migration(
+ versions_dir,
+ '002_add_user_email.py',
+ revision='001',
+ down_revision='001',
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any('Duplicate migration revision 001' in error for error in errors)
+
+
+def test_filename_prefix_must_match_revision(versions_dir: Path):
+ module = load_module()
+ write_migration(
+ versions_dir,
+ '001_create_users.py',
+ revision='002',
+ down_revision=None,
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any(
+ 'Filename prefix 001 does not match revision 002' in error for error in errors
+ )
+
+
+def test_missing_down_revision_fails(versions_dir: Path):
+ module = load_module()
+ write_migration(
+ versions_dir,
+ '001_create_users.py',
+ revision='001',
+ down_revision=None,
+ )
+ write_migration(
+ versions_dir,
+ '002_add_user_email.py',
+ revision='002',
+ down_revision='999',
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any('references missing down_revision 999' in error for error in errors)
+
+
+def test_missing_down_revision_assignment_fails(versions_dir: Path):
+ """Test when down_revision is completely absent from the file."""
+ module = load_module()
+ (versions_dir / '001_create_users.py').write_text(
+ '\n'.join(
+ [
+ '"""Test migration."""',
+ '',
+ "revision = '001'",
+ 'branch_labels = None',
+ 'depends_on = None',
+ '',
+ 'def upgrade():',
+ ' pass',
+ '',
+ 'def downgrade():',
+ ' pass',
+ '',
+ ]
+ )
+ )
+ write_migration(
+ versions_dir,
+ '002_add_user_email.py',
+ revision='002',
+ down_revision='001',
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any('missing down_revision assignment' in error for error in errors)
+
+
+def test_multiple_heads_fail(versions_dir: Path):
+ module = load_module()
+ write_migration(
+ versions_dir,
+ '001_create_users.py',
+ revision='001',
+ down_revision=None,
+ )
+ write_migration(
+ versions_dir,
+ '002_add_user_email.py',
+ revision='002',
+ down_revision='001',
+ )
+ write_migration(
+ versions_dir,
+ '003_add_user_name.py',
+ revision='003',
+ down_revision='001',
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any('Expected exactly one migration head' in error for error in errors)
+
+
+def test_revision_must_be_string(versions_dir: Path):
+ module = load_module()
+ (versions_dir / '001_create_users.py').write_text(
+ '\n'.join(
+ [
+ '"""Test migration with non-string revision."""',
+ '',
+ 'revision = 123',
+ 'down_revision = None',
+ 'branch_labels = None',
+ 'depends_on = None',
+ '',
+ 'def upgrade():',
+ ' pass',
+ '',
+ 'def downgrade():',
+ ' pass',
+ '',
+ ]
+ )
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any(
+ '001_create_users.py: revision must be a string' in error for error in errors
+ )
+
+
+def test_invalid_down_revision_type_fails(versions_dir: Path):
+ module = load_module()
+ write_migration(
+ versions_dir,
+ '001_create_users.py',
+ revision='001',
+ down_revision=None,
+ )
+ # Write a migration with an invalid down_revision type (integer instead of string)
+ (versions_dir / '002_add_user_email.py').write_text(
+ '\n'.join(
+ [
+ '"""Test migration."""',
+ '',
+ "revision = '002'",
+ 'down_revision = 123', # invalid type: must be None, string, or sequence
+ 'branch_labels = None',
+ 'depends_on = None',
+ '',
+ 'def upgrade():',
+ ' pass',
+ '',
+ 'def downgrade():',
+ ' pass',
+ '',
+ ]
+ )
+ )
+
+ errors = module.check_migration_integrity(versions_dir)
+
+ assert any(
+ 'down_revision must be None, a string, or a sequence of strings' in error
+ for error in errors
+ )