: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ci): keep the restored schema's migration history consistent (#97123)
Rafael Audibert8f6e8b64037c
diff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.pyindex 25c7074ab13b..f75ec2d3093e 100644--- a/tools/hogli-commands/hogli_commands/db_schema.py+++ b/tools/hogli-commands/hogli_commands/db_schema.py@@ -35,7 +35,7 @@ DOCKER_COMPOSE = ["docker", "compose", "-f", "docker-compose.dev.yml"]DB_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")PRODUCT_DB_ROUTING_PATH = Path("products/db_routing.yaml")APP_LABEL_RE = re.compile(r"^[a-z][a-z0-9_]*$")-SQUASH_SCHEMA_ADDONS_NAME_PATTERN = r"%\_squash\_%\_schema\_addons"+SQUASH_SCHEMA_ADDONS_NAME_RE = re.compile(r".*_squash_.*_schema_addons$")T = TypeVar("T")@@ -172,13 +172,68 @@ def _recreate_database(target_db: str) -> None:_psql_admin(f"CREATE DATABASE {target_db};")-def _ensure_migration_defaults(target_db: str) -> None:+def _manage(target_db: str, *args: str) -> None:+ """Run a management command against target_db."""_run(- ["python", "manage.py", "ensure_migration_defaults"],+ ["python", "manage.py", *args],env={"DATABASE_URL": f"postgres://posthog:posthog@localhost:5432/{target_db}"},)+def _ensure_migration_defaults(target_db: str) -> None:+ _manage(target_db, "ensure_migration_defaults")+++def _psql_write(target_db: str, sql: str) -> None:+ """Run a one-shot statement against target_db."""+ _run(+ [+ *DOCKER_COMPOSE,+ "exec",+ "-T",+ "db",+ "psql",+ "-q",+ "-v",+ "ON_ERROR_STOP=1",+ "-U",+ "posthog",+ target_db,+ "-c",+ sql,+ ]+ )+++def _psql_rows(target_db: str, sql: str) -> list[list[str]]:+ """Run a query against target_db and return its rows as lists of column values."""+ result = subprocess.run(+ [+ *DOCKER_COMPOSE,+ "exec",+ "-T",+ "db",+ "psql",+ "-At",+ "-F",+ "\t",+ "-v",+ "ON_ERROR_STOP=1",+ "-U",+ "posthog",+ target_db,+ "-c",+ sql,+ ],+ cwd=REPO_ROOT,+ env=os.environ.copy(),+ check=True,+ capture_output=True,+ text=True,+ )+ return [line.split("\t") for line in result.stdout.splitlines() if line]++def _product_routed_app_labels() -> list[str]:"""App labels whose tables live in their own database, per products/db_routing.yaml."""config_path = _resolve_repo_path(PRODUCT_DB_ROUTING_PATH)@@ -189,44 +244,91 @@ def _product_routed_app_labels() -> list[str]:return sorted(label for label in labels if APP_LABEL_RE.fullmatch(label))-def _forget_product_app_migrations(target_db: str) -> None:- """Drop the dump's claim that product-routed apps are migrated in this database.+@dataclass(frozen=True)+class MigrationRecordPlan:+ """What a restore does to the django_migrations rows the dump carries."""- The dump is taken from a CI database that routes those apps elsewhere, so `migrate` skipped+ forget: tuple[tuple[str, str], ...]+ replay: tuple[tuple[str, str], ...]+ refake: tuple[tuple[str, str], ...]+++def plan_migration_records(+ recorded: Iterable[tuple[str, str]], product_app_labels: Iterable[str]+) -> MigrationRecordPlan:+ """Decide which of the dump's migration records to forget, replay for real, and re-record.++ The dump is taken from a CI database that routes product apps elsewhere, so `migrate` skippedevery operation in their migrations there while Django recorded them as applied anyway (itrecords whatever the router decides). Restored verbatim, that leaves a database assertingstamphog and visual_review are migrated without a single one of their tables — and anenvironment that configures no product database then applies their NEXT migration for real- and dies on the missing table. Clearing the rows lets each consumer replay them under its own- routing: a no-op where the app is routed away, real tables where it isn't.+ and dies on the missing table. Forgetting the rows lets each consumer replay them under its+ own routing: a no-op where the app is routed away, real tables where it isn't.The squash schema-addons migrations go with them. Each one depends on the leaf squash of everysquashed app, the product-routed apps included, so a database that keeps an addons row whileits dependency row is gone fails Django's consistency check before `migrate` does anything.- Replay is cheap: the addons operations probe the schema and skip what is already there.+ Replaying one is cheap: its operations probe the schema and skip what is already there.++ Everything an app records after its addons migration depends on that addons migration, so it+ fails the same check for the same reason and has to be forgotten too. Those migrations are+ already in the restored schema though, so replaying one would add a column that exists. They+ are re-recorded with `--fake` instead. The repo keeps one migration line per app, so a name+ that sorts after the addons migration is a descendant of it, and faking up to the last one+ re-records the whole run.+ """+ routed = set(product_app_labels)+ by_app: dict[str, list[str]] = {}+ for app, name in recorded:+ by_app.setdefault(app, []).append(name)++ forget: list[tuple[str, str]] = []+ replay: list[tuple[str, str]] = []+ refake: list[tuple[str, str]] = []+ for app, recorded_names in sorted(by_app.items()):+ names = sorted(recorded_names)+ if app in routed:+ forget.extend((app, name) for name in names)+ continue+ addons = next((name for name in names if SQUASH_SCHEMA_ADDONS_NAME_RE.fullmatch(name)), None)+ if addons is None:+ continue+ trailing = [name for name in names if name > addons]+ forget.append((app, addons))+ forget.extend((app, name) for name in trailing)+ replay.append((app, addons))+ if trailing:+ refake.append((app, trailing[-1]))++ return MigrationRecordPlan(forget=tuple(forget), replay=tuple(replay), refake=tuple(refake))+++def _sql_string(value: str) -> str:+ escaped = value.replace("'", "''")+ return f"'{escaped}'"+++def _forget_product_app_migrations(target_db: str) -> None:+ """Re-record the dump's migrations the way this database can honor them.++ See `plan_migration_records` for what moves and why."""app_labels = _product_routed_app_labels()if not app_labels:return- in_list = ", ".join(f"'{label}'" for label in app_labels)- _run(- [- *DOCKER_COMPOSE,- "exec",- "-T",- "db",- "psql",- "-q",- "-v",- "ON_ERROR_STOP=1",- "-U",- "posthog",- target_db,- "-c",- f"DELETE FROM django_migrations WHERE app IN ({in_list}) "- f"OR name LIKE '{SQUASH_SCHEMA_ADDONS_NAME_PATTERN}';",- ]- )+ recorded = [(row[0], row[1]) for row in _psql_rows(target_db, "SELECT app, name FROM django_migrations;")]+ plan = plan_migration_records(recorded, app_labels)+ if not plan.forget:+ return++ pairs = ", ".join(f"({_sql_string(app)}, {_sql_string(name)})" for app, name in plan.forget)+ _psql_write(target_db, f"DELETE FROM django_migrations WHERE (app, name) IN ({pairs});")++ for app, name in plan.replay:+ _manage(target_db, "migrate", app, name, "--noinput")+ for app, name in plan.refake:+ _manage(target_db, "migrate", app, name, "--noinput", "--fake")def restore_schema_dump(diff --git a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py b/tools/hogli-commands/hogli_commands/tests/test_db_schema.pyindex 0f1983c3bedd..2c7c959ecbcf 100644--- a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py@@ -295,6 +295,7 @@ def test_restore_schema_dump_recreate_drops_and_creates(tmp_path: Path, monkeypalambda gzip_path, target_db: restored.append((gzip_path, target_db)),)monkeypatch.setattr(db_schema, "_ensure_migration_defaults", lambda target_db: defaults.append(target_db))+ monkeypatch.setattr(db_schema, "_psql_rows", lambda target_db, sql: [])db_schema.restore_schema_dump(target_db="test_posthog", recreate=True, schema_path=schema_path)@@ -304,12 +305,46 @@ def test_restore_schema_dump_recreate_drops_and_creates(tmp_path: Path, monkeypaassert defaults == ["test_posthog"]+_RECORDED = [+ ("stamphog", "0001_squash_2026_09_07_initial"),+ ("stamphog", "0002_later"),+ ("posthog", "0001_squash_2026_09_07_initial"),+ ("posthog", "1345_squash_2026_09_07_schema_addons"),+ ("posthog", "1346_untrack_organization_is_hipaa"),+ ("posthog", "1347_add_a_column"),+ ("cdp", "0005_no_addons_migration_here"),+]+++ "attribute,expected",+ [+ (+ "forget",+ (+ # A product-routed app is replayed in full under the consumer's own routing.+ ("posthog", "1345_squash_2026_09_07_schema_addons"),+ ("posthog", "1346_untrack_organization_is_hipaa"),+ ("posthog", "1347_add_a_column"),+ ("stamphog", "0001_squash_2026_09_07_initial"),+ ("stamphog", "0002_later"),+ ),+ ),+ # The addons migration probes the schema, so replaying it for real is safe.+ ("replay", (("posthog", "1345_squash_2026_09_07_schema_addons"),)),+ # Its descendants are already in the restored schema, so they are re-recorded, not re-run.+ ("refake", (("posthog", "1347_add_a_column"),)),+ ],+)+def test_plan_migration_records(attribute: str, expected: tuple[tuple[str, str], ...]) -> None:+ plan = db_schema.plan_migration_records(_RECORDED, ["stamphog"])++ assert getattr(plan, attribute) == expected++def test_restore_schema_dump_forgets_product_app_migrations(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- # The dump comes from a database that routes product apps elsewhere, so it records their- # migrations as applied without ever creating their tables. Left in place, the next product- # migration is applied for real here and fails on the missing table. The squash schema-addons- # rows must go too: they depend on the product apps' leaf squashes, so keeping them while the- # product rows are gone fails Django's migration consistency check.+ # Every migration the plan forgets has to leave the table, or the restored database asserts a+ # migration applied before its dependency and Django refuses to migrate at all.schema_path = tmp_path / "schema.sql.gz"_write_schema(schema_path)commands: list[list[str]] = []@@ -317,16 +352,20 @@ def test_restore_schema_dump_forgets_product_app_migrations(tmp_path: Path, monkmonkeypatch.setattr(db_schema, "_run", lambda command, env=None: commands.append(command))monkeypatch.setattr(db_schema, "_run_psql_with_gzip_input", lambda gzip_path, target_db: None)monkeypatch.setattr(db_schema, "_ensure_migration_defaults", lambda target_db: None)+ monkeypatch.setattr(db_schema, "_product_routed_app_labels", lambda: ["stamphog"])+ monkeypatch.setattr(db_schema, "_psql_rows", lambda target_db, sql: [list(row) for row in _RECORDED])db_schema.restore_schema_dump(target_db="test_posthog", recreate=False, schema_path=schema_path)deletes = [command[-1] for command in commands if "DELETE FROM django_migrations" in command[-1]]assert len(deletes) == 1- app_labels = db_schema._product_routed_app_labels()- assert app_labels, "expected products/db_routing.yaml to route at least one app"- for app_label in app_labels:- assert f"'{app_label}'" in deletes[0]- assert r"name LIKE '%\_squash\_%\_schema\_addons'" in deletes[0]+ for app, name in db_schema.plan_migration_records(_RECORDED, ["stamphog"]).forget:+ assert f"('{app}', '{name}')" in deletes[0]+ migrates = [command for command in commands if command[:3] == ["python", "manage.py", "migrate"]]+ assert migrates == [+ ["python", "manage.py", "migrate", "posthog", "1345_squash_2026_09_07_schema_addons", "--noinput"],+ ["python", "manage.py", "migrate", "posthog", "1347_add_a_column", "--noinput", "--fake"],+ ]def test_restore_schema_dump_recreate_cleans_up_after_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -372,6 +411,7 @@ def test_restore_schema_dump_without_recreate_does_not_drop(tmp_path: Path, monkmonkeypatch.setattr(db_schema, "_run", lambda command, env=None: commands.append(command))monkeypatch.setattr(db_schema, "_run_psql_with_gzip_input", lambda gzip_path, target_db: None)monkeypatch.setattr(db_schema, "_ensure_migration_defaults", lambda target_db: None)+ monkeypatch.setattr(db_schema, "_psql_rows", lambda target_db, sql: [])db_schema.restore_schema_dump(target_db="posthog", recreate=False, schema_path=schema_path)