Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(migrations): block migration file deletion (#66817)

Raúl Negrón-Oterodbe773ee170b
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.md
index 4cc2abaf7960..bea91313d43c 100644
--- a/.agents/skills/django-migrations/SKILL.md
+++ b/.agents/skills/django-migrations/SKILL.md
@@ -14,6 +14,20 @@ Read these files first, before writing or editing a migration:
If the task is a ClickHouse migration, use `clickhouse-migrations` instead.
+## Never delete a migration file
+
+Adding migrations is fine. **Deleting a historical one — any `*/migrations/NNNN_*.py` already on master, even an app's `0001_initial.py`, even to "undo" a schema change — is not.** Deleting the file undoes nothing: the table and its constraints stay in every database where the migration ran, fresh databases never recreate them, and the "Migration Risk Analysis" CI job re-flags the file as a phantom new migration on every open PR that predates the deletion. The deleted-migration check in the `repo-checks` CI job (the `hogli lint:migration-deletions` command) blocks this. Genuinely intentional, reviewed deletions — a product/app move, a revert, a squash — are acknowledged in `.github/scripts/migration-deletion-allowlist.txt`, never by disabling the guard.
+
+**If a task asks you to delete a migration file, stop and flag it instead.**
+
+To retire a model/table:
+
+1. Remove all usage and the model class. `makemigrations`, then wrap the generated `DeleteModel` in `migrations.SeparateDatabaseAndState(state_operations=[...])` (state only, no DB change). KEEP this file. Keep the app in `INSTALLED_APPS`.
+2. Deploy, wait at least one full deploy cycle.
+3. Optionally `DROP TABLE` later in a NEW `RunSQL` migration — never by deleting old files.
+
+Full guide: `safe-django-migrations.md` (`## Dropping Tables`, `### Removing a whole product or app`). Deleting a migration your branch added but never merged to master is allowed (regenerating).
+
## Workflow
1. **Classify** the change as additive (new nullable column, new table) or risky (drop/rename, `NOT NULL`, indexes, constraints, large data updates, model moves). A change is also risky if it touches a [hot table](#hot-table-hazard), regardless of how additive it looks. See also the [cross-language `NOT NULL` hazard](#cross-language-not-null-hazard) below.
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index c03ee5ad0708..61c0b2234370 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -177,6 +177,7 @@ jobs:
backend_files: ${{ steps.filter.outputs.backend_files }}
migrations: ${{ steps.filter.outputs.migrations || 'true' }}
migrations_files: ${{ steps.filter.outputs.migrations_files }}
+ migrations_any: ${{ steps.filter.outputs.migrations_any || 'true' }}
tasks_temporal: ${{ steps.filter.outputs.tasks_temporal || 'true' }}
openapi_types: ${{ steps.filter.outputs.openapi_types || 'true' }}
legacy: ${{ steps.filter.outputs.legacy || 'true' }}
@@ -333,6 +334,11 @@ jobs:
# depot strips canonical's separate persons-migration job
- 'rust/persons_migrations/*.sql'
- 'rust/bin/migrate-persons'
+ # Any migration file in any app (broader than `migrations` above,
+ # which omits ee/ and posthog sub-package dirs). Gates the
+ # deleted-migration check in repo-checks.
+ migrations_any:
+ - '**/migrations/*.py'
tasks_temporal:
- 'products/tasks/backend/temporal/**/*'
product_yamls:
@@ -860,6 +866,9 @@ jobs:
needs: [changes]
if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'
timeout-minutes: 10
+ permissions:
+ contents: read
+ pull-requests: read # list PR files for the deleted-migration check
name: Repo checks (depot-ubuntu-latest)
runs-on: depot-ubuntu-latest
steps:
@@ -888,6 +897,15 @@ jobs:
run: tach check --dependencies --interfaces
- name: Check product facade enforcement (import-linter)
run: lint-imports
+ # Block deleting historical migration files (see safe-django-migrations.md).
+ # GITHUB_ACTIONS=false suppresses the command's PR annotations on the shadow.
+ - name: Check deleted migrations
+ if: github.event_name == 'pull_request' && needs.changes.outputs.migrations_any == 'true'
+ env:
+ GITHUB_ACTIONS: 'false'
+ REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ run: .github/scripts/list-removed-renamed-paths.sh | ./bin/hogli lint:migration-deletions
validate-product-yamls:
needs: [changes]
diff --git a/.github/scripts/list-removed-renamed-paths.sh b/.github/scripts/list-removed-renamed-paths.sh
new file mode 100755
index 000000000000..8aab1ae4de26
--- /dev/null
+++ b/.github/scripts/list-removed-renamed-paths.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+# Print the PR's removed/renamed file paths (one per line) from the GitHub PR-files API.
+# "removed"/"renamed" files existed on the PR base, so they are historical (renames carry
+# the old path in previous_filename). Consumers filter these for deleted Django migrations
+# (hogli lint:migration-deletions). Retries transient gh-api errors. Requires REPO,
+# PR_NUMBER, and an authenticated gh (GH_TOKEN or ambient token).
+set -euo pipefail
+
+for attempt in 1 2 3; do
+ if removed=$(gh api --paginate "repos/${REPO}/pulls/${PR_NUMBER}/files?per_page=100" \
+ --jq '.[] | select(.status == "removed" or .status == "renamed") | .previous_filename // .filename'); then
+ printf '%s\n' "$removed"
+ exit 0
+ fi
+ if [ "$attempt" = 3 ]; then
+ echo "could not list PR files after 3 attempts" >&2
+ exit 1
+ fi
+ echo "gh api attempt ${attempt} failed; retrying" >&2
+ sleep $((attempt * 5))
+done
diff --git a/.github/scripts/migration-deletion-allowlist.txt b/.github/scripts/migration-deletion-allowlist.txt
new file mode 100644
index 000000000000..5bc6d8c65cd1
--- /dev/null
+++ b/.github/scripts/migration-deletion-allowlist.txt
@@ -0,0 +1,12 @@
+# Migration files whose deletion is intentional and reviewed — listed here to pass the
+# deleted-migration guard in repo-checks (hogli lint:migration-deletions). Deleting a migration
+# that exists on master diverges fresh DBs from deployed ones; see
+# docs/published/handbook/engineering/safe-django-migrations.md.
+#
+# Add a path ONLY when the deletion is genuinely safe and reviewed (a product move, a
+# revert of a not-yet-deployed migration, a squash). One entry per line; a directory entry
+# allowlists everything under it (trailing slash optional). Remove stale entries once merged.
+#
+# Examples (commented out, not active):
+# products/old_product/backend/migrations/ # whole-product move
+# posthog/migrations/0500_oops.py # single revert
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 8d5edfc83252..21ba786e0100 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -82,6 +82,7 @@ jobs:
backend_files: ${{ steps.filter.outputs.backend_files }}
migrations: ${{ steps.filter.outputs.migrations || 'true' }}
migrations_files: ${{ steps.filter.outputs.migrations_files }}
+ migrations_any: ${{ steps.filter.outputs.migrations_any || 'true' }}
persons_sql: ${{ steps.filter.outputs.persons_sql || 'true' }}
tasks_temporal: ${{ steps.filter.outputs.tasks_temporal || 'true' }}
openapi_types: ${{ steps.filter.outputs.openapi_types || 'true' }}
@@ -244,6 +245,11 @@ jobs:
- 'posthog/migrations/*.py'
- 'products/*/backend/migrations/*.py'
- 'products/*/migrations/*.py' # Legacy structure
+ # Any migration file in any app (broader than `migrations` above,
+ # which omits ee/ and posthog sub-package dirs). Gates the
+ # deleted-migration check in repo-checks.
+ migrations_any:
+ - '**/migrations/*.py'
persons_sql:
- 'rust/persons_migrations/*.sql'
- 'rust/bin/migrate-persons'
@@ -896,6 +902,7 @@ jobs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
permissions:
contents: read
+ pull-requests: read # list PR files for the deleted-migration check
name: Repo checks (depot-ubuntu-latest)
runs-on: depot-ubuntu-latest
steps:
@@ -925,6 +932,17 @@ jobs:
- name: Install Python dependencies
run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev
+ # Above the boundary: a gh-api flake here is retryable setup, not a
+ # run-cancelling deterministic failure. The classifier runs below.
+ - name: Fetch deleted migration paths
+ id: fetch-deleted-migrations
+ if: github.event_name == 'pull_request' && needs.changes.outputs.migrations_any == 'true'
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ run: .github/scripts/list-removed-renamed-paths.sh > "$RUNNER_TEMP/deleted-migration-paths.txt"
+
# Boundary between network-dependent setup and the deterministic
# checks below. The "Flag deterministic failure" step keys off this
# step's outcome so a transient setup failure doesn't cancel the run.
@@ -932,6 +950,13 @@ jobs:
id: setup-complete
run: echo "Setup complete — any failure below is a deterministic check failure"
+ # Below the boundary so a real deletion trips the early-cancel gate (see
+ # safe-django-migrations.md). Gated on the fetch outcome so a skipped fetch
+ # skips this too, rather than reading a file it never wrote.
+ - name: Check deleted migrations
+ if: steps.fetch-deleted-migrations.outcome == 'success'
+ run: ./bin/hogli lint:migration-deletions < "$RUNNER_TEMP/deleted-migration-paths.txt"
+
- name: Bootstrap scaffold product
run: ./bin/hogli product:bootstrap spline_reticulator --non-interactive
diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.md
index faf3a7b6152e..0e6e3b78f433 100644
--- a/docs/published/handbook/engineering/safe-django-migrations.md
+++ b/docs/published/handbook/engineering/safe-django-migrations.md
@@ -212,7 +212,7 @@ class Migration(migrations.Migration):
Removing a product (`products/<name>/`) is the phased table drop above — once per model — plus app teardown. It is **not** a folder delete.
-**Do not "remove" a table by deleting its migration file.** Deleting the file drops nothing:
+**Do not "remove" a table by deleting its migration file.** The deleted-migration check in the `repo-checks` CI job (the `hogli lint:migration-deletions` command) blocks deleting any migration that exists on master; genuinely intentional, reviewed deletions (a product move, a revert, a squash) are acknowledged in `.github/scripts/migration-deletion-allowlist.txt`. Deleting the file drops nothing:
- The table and its FK constraints stay in every database where the migration already ran.
- The `django_migrations` rows linger as orphans — harmless (Django ignores migrations for apps not in `INSTALLED_APPS`) but never cleaned up.
diff --git a/hogli.yaml b/hogli.yaml
index c89533b89108..9c742426eb4f 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -821,6 +821,9 @@ quality:
lint:workflows:
click: hogli_commands.workflow_lint.cli:cmd_lint_workflows
description: Lint .github/workflows/** for repo conventions
+ lint:migration-deletions:
+ click: hogli_commands.migration_deletions:cmd_lint_migration_deletions
+ description: Block deleting historical Django migration files
format:mcp:
cmd: pnpm run --filter @posthog/mcp format
description: Format MCP files
diff --git a/tools/hogli-commands/hogli_commands/migration_deletions.py b/tools/hogli-commands/hogli_commands/migration_deletions.py
new file mode 100644
index 000000000000..5f03e045433a
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/migration_deletions.py
@@ -0,0 +1,106 @@
+"""hogli lint:migration-deletions — fail when a PR deletes a historical Django migration.
+
+Reads removed/renamed paths from stdin (the repo-checks CI job feeds them
+from the GitHub PR-files API) and fails on any Django migration the allowlist doesn't
+acknowledge. Those paths are removed relative to the PR base, so each already-existing
+migration among them is historical. See _GUIDANCE and
+docs/published/handbook/engineering/safe-django-migrations.md for the why.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path, PurePosixPath
+
+import click
+from hogli.manifest import REPO_ROOT
+
+ALLOWLIST_PATH = REPO_ROOT / ".github" / "scripts" / "migration-deletion-allowlist.txt"
+
+# ClickHouse and async migrations are separate systems, excluded by grandparent dir name.
+_NON_DJANGO_PARENTS = {"clickhouse", "async_migrations"}
+
+_IN_GH_ACTIONS = os.environ.get("GITHUB_ACTIONS") == "true"
+
+_GUIDANCE = """\
+Deleting a migration that exists on master does NOT undo a schema change. The table
+and its constraints stay in every database where the migration ran, fresh databases
+never recreate them, and the Migration Risk Analysis job re-flags it as a phantom new
+migration on every open PR that predates the deletion.
+
+To retire a model/table instead:
+ 1. Remove all usage and the model class. Run makemigrations, then wrap the generated
+ DeleteModel in migrations.SeparateDatabaseAndState(state_operations=[...]) so it
+ changes Django state only. KEEP this file. Keep the app in INSTALLED_APPS.
+ 2. Deploy and wait at least one full deploy cycle.
+ 3. Optionally DROP TABLE later in a NEW RunSQL migration — never by deleting old files.
+
+Full guide: docs/published/handbook/engineering/safe-django-migrations.md
+("Dropping Tables", "Removing a whole product or app").
+
+If this deletion is genuinely intentional and reviewed (a product/app move, a revert,
+or a squash), acknowledge it by adding the path(s) to
+.github/scripts/migration-deletion-allowlist.txt — never by disabling this guard."""
+
+
+def is_django_migration(path: str) -> bool:
+ """True for a numbered Django migration file, e.g. posthog/migrations/0001_initial.py.
+
+ Require the NNNN_ prefix: it excludes __init__.py and, crucially, the standalone data
+ scripts that also live in a migrations/ dir (e.g. posthog/rbac/migrations/rbac_*.py),
+ which are not Django ORM migrations. Also excludes the ClickHouse/async systems.
+ """
+ p = PurePosixPath(path)
+ if p.parent.name != "migrations" or p.suffix != ".py" or not p.name[:1].isdigit():
+ return False
+ return p.parent.parent.name not in _NON_DJANGO_PARENTS
+
+
+def load_allowlist(allowlist_path: Path) -> list[str]:
+ """Allowlist entries (one path per line; '#' comments, blanks, and a missing file ignored)."""
+ if not allowlist_path.exists():
+ return []
+ entries = []
+ for line in allowlist_path.read_text().splitlines():
+ entry = line.split("#", 1)[0].strip()
+ if entry:
+ entries.append(entry)
+ return entries
+
+
+def is_allowlisted(path: str, allowlist: list[str]) -> bool:
+ """True if path matches an allowlist entry exactly, or sits under a directory entry
+ (trailing slash optional, so `products/x/migrations` and `.../migrations/` both work)."""
+ for entry in allowlist:
+ prefix = entry.rstrip("/")
+ if path == prefix or path.startswith(prefix + "/"):
+ return True
+ return False
+
+
+def guarded_deletions(paths: list[str], allowlist: list[str]) -> list[str]:
+ """The subset of deleted paths that are Django migrations and not allowlisted."""
+ return [p for p in paths if is_django_migration(p) and not is_allowlisted(p, allowlist)]
+
+
[email protected](name="lint:migration-deletions", help="Block deleting historical Django migration files")
+def cmd_lint_migration_deletions() -> None:
+ """Read removed file paths from stdin and fail on any historical Django migration."""
+ removed = sys.stdin.read().splitlines()
+ violations = guarded_deletions(removed, load_allowlist(ALLOWLIST_PATH))
+
+ if not violations:
+ click.echo("No historical migration files deleted.")
+ return
+
+ if _IN_GH_ACTIONS:
+ for path in violations:
+ click.echo(
+ f"::error file={path} title=lint:migration-deletions::Deleting a historical Django migration is not allowed (see safe-django-migrations.md)"
+ )
+ click.echo("\nERROR: refusing to delete historical Django migration file(s):\n", err=True)
+ for path in violations:
+ click.echo(f" - {path}", err=True)
+ click.echo(f"\n{_GUIDANCE}", err=True)
+ raise SystemExit(1)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_migration_deletions.py b/tools/hogli-commands/hogli_commands/tests/test_migration_deletions.py
new file mode 100644
index 000000000000..5754d1d2a295
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_migration_deletions.py
@@ -0,0 +1,90 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+import hogli_commands.migration_deletions as md
+from click.testing import CliRunner
+
+
+ "path,expected",
+ [
+ ("posthog/migrations/0001_initial.py", True),
+ ("ee/migrations/0042_thing.py", True),
+ ("products/tasks/backend/migrations/0003_x.py", True),
+ ("posthog/session/migrations/0001_initial.py", True), # real Django sub-package app
+ ("posthog/migrations/__init__.py", False),
+ ("posthog/migrations/manual_fix.py", False), # non-numbered -> not a flagged migration
+ ("posthog/rbac/migrations/rbac_team_migration.py", False), # standalone RBAC data script, not ORM
+ ("posthog/clickhouse/migrations/0099_x.py", False),
+ ("posthog/async_migrations/migrations/0005_y.py", False),
+ ("posthog/migrations/0001_initial.txt", False),
+ ("products/tasks/backend/views.py", False),
+ ],
+)
+def test_is_django_migration(path: str, expected: bool) -> None:
+ assert md.is_django_migration(path) is expected
+
+
+def test_load_allowlist_ignores_comments_and_blanks(tmp_path: Path) -> None:
+ f = tmp_path / "allow.txt"
+ f.write_text(
+ "# header\n\nposthog/migrations/0500_oops.py # trailing comment\n products/old/backend/migrations/ \n"
+ )
+ assert md.load_allowlist(f) == ["posthog/migrations/0500_oops.py", "products/old/backend/migrations/"]
+
+
+def test_load_allowlist_missing_file_is_empty(tmp_path: Path) -> None:
+ assert md.load_allowlist(tmp_path / "nope.txt") == []
+
+
+ "path,allowlist,expected",
+ [
+ ("posthog/migrations/0500_oops.py", ["posthog/migrations/0500_oops.py"], True),
+ ("products/old/backend/migrations/0001_initial.py", ["products/old/backend/migrations/"], True),
+ (
+ "products/old/backend/migrations/0001_initial.py",
+ ["products/old/backend/migrations"],
+ True,
+ ), # trailing slash optional
+ ("products/old_v2/backend/migrations/0001_initial.py", ["products/old/backend/migrations/"], False),
+ ("posthog/migrations/0500_oops.py", [], False),
+ ],
+)
+def test_is_allowlisted(path: str, allowlist: list[str], expected: bool) -> None:
+ assert md.is_allowlisted(path, allowlist) is expected
+
+
+def test_guarded_deletions_filters_and_respects_allowlist() -> None:
+ paths = [
+ "posthog/migrations/0001_initial.py",
+ "posthog/migrations/__init__.py",
+ "posthog/clickhouse/migrations/0099_x.py",
+ "products/old/backend/migrations/0001_x.py",
+ "frontend/app.ts",
+ ]
+ assert md.guarded_deletions(paths, ["products/old/backend/migrations/"]) == ["posthog/migrations/0001_initial.py"]
+
+
+ "stdin,allowlist,expected_exit",
+ [
+ ("posthog/migrations/0001_initial.py\nfrontend/x.ts\n", "", 1), # historical deletion -> block
+ ("posthog/migrations/__init__.py\nfrontend/app.ts\n", "", 0), # only non-migrations -> pass
+ # historical migration deleted but acknowledged in the allowlist -> pass
+ ("products/old/backend/migrations/0001_x.py\n", "products/old/backend/migrations/\n", 0),
+ ],
+)
+def test_command(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, stdin: str, allowlist: str, expected_exit: int
+) -> None:
+ allow = tmp_path / "allow.txt"
+ allow.write_text(allowlist)
+ monkeypatch.setattr(md, "ALLOWLIST_PATH", allow)
+ result = CliRunner().invoke(md.cmd_lint_migration_deletions, input=stdin)
+ # A crash also exits non-zero — assert the exit is a real verdict, not a trapped exception.
+ assert not isinstance(result.exception, Exception)
+ assert result.exit_code == expected_exit