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.

fix(devex): keep schema addons migrations off the product database apps (#97170)

Julian Bez8d0a8cd198a2
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.md
index 345823c13b35..0886e2df8b41 100644
--- a/.agents/skills/django-migrations/SKILL.md
+++ b/.agents/skills/django-migrations/SKILL.md
@@ -104,6 +104,10 @@ A `ForeignKey` _targeting_ a hot table is the same hazard from the other side, a
- **`db_constraint=False` on the `ForeignKey`** — emits no FK constraint and takes **no** lock on the parent at all (app-level enforcement only). This is the only truly lock-free path.
- **A real DB constraint, two-phase** — declare the FK `db_constraint=False`, then add it back as a DB constraint with `AddForeignKeyNotValid`, and `ValidateForeignKey` in a later migration. Be honest: `ADD CONSTRAINT ... NOT VALID` still takes a _brief_ `SHARE ROW EXCLUSIVE` lock on the parent for the metadata add — it skips the row scan, so it shrinks the lock window but does not eliminate it. `VALIDATE` then runs lock-free on the parent.
+## Product database boundaries
+
+Apps listed in `products/db_routing.yaml` migrate on their own database and nowhere else. A migration may only depend on migrations that apply to a database it applies to itself, so never add a dependency from another app onto one of those apps, and never the reverse. No foreign key or index can cross databases, so the edge buys nothing, and the CI schema restore relies on its absence: it forgets the routed apps' `django_migrations` rows so each job applies them under its own routing, and a dependant of a forgotten row makes Django refuse to migrate. `posthog/test/repo_invariants/test_migration_dependencies_share_a_database.py` blocks the edge.
+
## Cross-language `NOT NULL` hazard
`posthog_user`, `posthog_team`, and other core tables in the main Postgres database are written by Django **and** by `nodejs/` (plugin-server tests via `insertRow`), `rust/` services, and Temporal workers. Those non-Django writers issue raw `INSERT`s that only list the columns they care about, so any new `NOT NULL` column without a Postgres-level `DEFAULT` will break them with `null value in column "<col>" violates not-null constraint`.
diff --git a/docs/internal/ci-things-already-tried.md b/docs/internal/ci-things-already-tried.md
index 546969c3ce69..d1ba5b13c18c 100644
--- a/docs/internal/ci-things-already-tried.md
+++ b/docs/internal/ci-things-already-tried.md
@@ -505,7 +505,7 @@ uv run --with git+https://github.com/PostHog/django-nextgensquash python -m next
uv run --with git+https://github.com/PostHog/django-nextgensquash python -m nextgensquash install --settings posthog.settings --input-dir /tmp/squash
```
-The generated finalize files import `posthog/migration_helpers/squash_idempotent.py`, so the package is a dev-only tool and not a dependency of this repo. The emit gate refuses young migrations that touch deferred foreign-key fields; bump the cutoff past them. Keep the window between cutoff and merge short: every migration that lands on master in that window sits before `finalize_fks` on a fresh database, and one that touches a deferred column forces a re-squash. A dedicated migration test (`TestMigrations` with `migrate_from`) that targets a folded migration fails with "not a valid node", because the loader drops replaced nodes; delete those tests, since a folded migration has been applied everywhere by definition.
+The generated finalize files import `posthog/migration_helpers/squash_idempotent.py`, so the package is a dev-only tool and not a dependency of this repo. The emit gate refuses young migrations that touch deferred foreign-key fields; bump the cutoff past them. Keep the window between cutoff and merge short: every migration that lands on master in that window sits before `finalize_fks` on a fresh database, and one that touches a deferred column forces a re-squash. A dedicated migration test (`TestMigrations` with `migrate_from`) that targets a folded migration fails with "not a valid node", because the loader drops replaced nodes; delete those tests, since a folded migration has been applied everywhere by definition. A `schema_addons` file must not depend on an app routed to another database (`products/db_routing.yaml`): the CI schema restore forgets those apps' `django_migrations` rows so each environment applies them under its own routing, and a dependant of a forgotten row makes Django refuse to migrate at all. The tool skips apps on another database, and `posthog/test/repo_invariants/test_migration_dependencies_share_a_database.py` blocks the edge in review; forgetting more rows on restore is the wrong fix, because the caller's `migrate` then re-applies DDL the dump already holds.
_Also asked as:_ squash the migrations, compress the migration history, why are there so many migrations, speed up the migration replay, nextgensquash
diff --git a/ee/migrations/0062_squash_2026_09_07_schema_addons.py b/ee/migrations/0062_squash_2026_09_07_schema_addons.py
index b07ea47b9fa7..e015c9d0149f 100644
--- a/ee/migrations/0062_squash_2026_09_07_schema_addons.py
+++ b/ee/migrations/0062_squash_2026_09_07_schema_addons.py
@@ -67,13 +67,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/posthog/migrations/1345_squash_2026_09_07_schema_addons.py b/posthog/migrations/1345_squash_2026_09_07_schema_addons.py
index 996cb9d5319a..dfc7b7271718 100644
--- a/posthog/migrations/1345_squash_2026_09_07_schema_addons.py
+++ b/posthog/migrations/1345_squash_2026_09_07_schema_addons.py
@@ -70,13 +70,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/posthog/test/repo_invariants/test_migration_dependencies_share_a_database.py b/posthog/test/repo_invariants/test_migration_dependencies_share_a_database.py
new file mode 100644
index 000000000000..bc20aec34a01
--- /dev/null
+++ b/posthog/test/repo_invariants/test_migration_dependencies_share_a_database.py
@@ -0,0 +1,35 @@
+"""A migration may only depend on migrations that apply to every database it applies to itself.
+
+Apps listed in `products/db_routing.yaml` migrate on their own database aliases and nowhere else.
+A dependency edge across that boundary is meaningless for schema (no index or foreign key reaches
+another database), and it breaks every consumer of the CI schema dump: `hogli db:restore-*`
+deletes the routed apps' `django_migrations` rows from the restored default database so each
+environment can apply them under its own routing, and Django's `check_consistent_history` then
+refuses to migrate any database that still records a dependant of those rows.
+"""
+
+from django.db import connections, router
+from django.db.migrations.loader import MigrationLoader
+
+
+def _migration_aliases(app_label: str) -> frozenset[str]:
+ return frozenset(alias for alias in connections if router.allow_migrate(alias, app_label))
+
+
+def test_migration_dependencies_share_a_database_with_their_dependants() -> None:
+ graph = MigrationLoader(connection=None, ignore_no_migrations=True).graph
+ aliases = {app: _migration_aliases(app) for app in {app for app, _ in graph.nodes}}
+
+ # The resolved graph carries `run_before` edges as parents too; the declared
+ # `dependencies` list alone would miss them.
+ crossings = sorted(
+ f"{app}.{name} -> {parent.key[0]}.{parent.key[1]}"
+ for (app, name), node in graph.node_map.items()
+ for parent in node.parents
+ if parent.key[0] != app and not aliases[app] <= aliases[parent.key[0]]
+ )
+ assert not crossings, (
+ "These migrations depend on a migration that never applies to any of their own databases. "
+ "Drop the dependency; a routed product app cannot be referenced from another database.\n "
+ + "\n ".join(crossings)
+ )
diff --git a/products/ai_observability/backend/migrations/0045_squash_2026_09_07_schema_addons.py b/products/ai_observability/backend/migrations/0045_squash_2026_09_07_schema_addons.py
index 55d5d7f76d90..b8f19b38738d 100644
--- a/products/ai_observability/backend/migrations/0045_squash_2026_09_07_schema_addons.py
+++ b/products/ai_observability/backend/migrations/0045_squash_2026_09_07_schema_addons.py
@@ -70,13 +70,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/conversations/backend/migrations/0066_squash_2026_09_07_schema_addons.py b/products/conversations/backend/migrations/0066_squash_2026_09_07_schema_addons.py
index c4bcabe37495..125e0e6804b6 100644
--- a/products/conversations/backend/migrations/0066_squash_2026_09_07_schema_addons.py
+++ b/products/conversations/backend/migrations/0066_squash_2026_09_07_schema_addons.py
@@ -69,13 +69,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/customer_analytics/backend/migrations/0051_squash_2026_09_07_schema_addons.py b/products/customer_analytics/backend/migrations/0051_squash_2026_09_07_schema_addons.py
index 8399bfbdaafa..664ffb4e9e79 100644
--- a/products/customer_analytics/backend/migrations/0051_squash_2026_09_07_schema_addons.py
+++ b/products/customer_analytics/backend/migrations/0051_squash_2026_09_07_schema_addons.py
@@ -69,13 +69,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/dashboards/backend/migrations/0018_squash_2026_09_07_schema_addons.py b/products/dashboards/backend/migrations/0018_squash_2026_09_07_schema_addons.py
index 0c914978d651..06676bdf2aa5 100644
--- a/products/dashboards/backend/migrations/0018_squash_2026_09_07_schema_addons.py
+++ b/products/dashboards/backend/migrations/0018_squash_2026_09_07_schema_addons.py
@@ -67,13 +67,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/data_modeling/backend/migrations/0035_squash_2026_09_07_schema_addons.py b/products/data_modeling/backend/migrations/0035_squash_2026_09_07_schema_addons.py
index a3cbb6abf484..fc46a93cafc3 100644
--- a/products/data_modeling/backend/migrations/0035_squash_2026_09_07_schema_addons.py
+++ b/products/data_modeling/backend/migrations/0035_squash_2026_09_07_schema_addons.py
@@ -67,13 +67,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/error_tracking/backend/migrations/0033_squash_2026_09_07_schema_addons.py b/products/error_tracking/backend/migrations/0033_squash_2026_09_07_schema_addons.py
index 621840855ae3..d54f833a0394 100644
--- a/products/error_tracking/backend/migrations/0033_squash_2026_09_07_schema_addons.py
+++ b/products/error_tracking/backend/migrations/0033_squash_2026_09_07_schema_addons.py
@@ -67,13 +67,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/feature_flags/backend/migrations/0019_squash_2026_09_07_schema_addons.py b/products/feature_flags/backend/migrations/0019_squash_2026_09_07_schema_addons.py
index 4ba8dcacc088..37ae2b8b91b8 100644
--- a/products/feature_flags/backend/migrations/0019_squash_2026_09_07_schema_addons.py
+++ b/products/feature_flags/backend/migrations/0019_squash_2026_09_07_schema_addons.py
@@ -69,13 +69,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/notebooks/backend/migrations/0019_squash_2026_09_07_schema_addons.py b/products/notebooks/backend/migrations/0019_squash_2026_09_07_schema_addons.py
index 08874791d2d6..dad658c2c0f8 100644
--- a/products/notebooks/backend/migrations/0019_squash_2026_09_07_schema_addons.py
+++ b/products/notebooks/backend/migrations/0019_squash_2026_09_07_schema_addons.py
@@ -67,13 +67,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/replay_vision/backend/migrations/0091_squash_2026_09_07_schema_addons.py b/products/replay_vision/backend/migrations/0091_squash_2026_09_07_schema_addons.py
index fb37892a9c24..39f932fcd458 100644
--- a/products/replay_vision/backend/migrations/0091_squash_2026_09_07_schema_addons.py
+++ b/products/replay_vision/backend/migrations/0091_squash_2026_09_07_schema_addons.py
@@ -69,13 +69,11 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/signals/backend/migrations/0119_squash_2026_09_07_schema_addons.py b/products/signals/backend/migrations/0119_squash_2026_09_07_schema_addons.py
index 7e64770708ba..e35b3cdffe54 100644
--- a/products/signals/backend/migrations/0119_squash_2026_09_07_schema_addons.py
+++ b/products/signals/backend/migrations/0119_squash_2026_09_07_schema_addons.py
@@ -69,13 +69,11 @@ class Migration(migrations.Migration):
("signals", "0117_drop_signalscoutconfig_team_id_fk_idx"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/products/tracing/backend/migrations/0004_squash_2026_09_07_schema_addons.py b/products/tracing/backend/migrations/0004_squash_2026_09_07_schema_addons.py
index d21cdd7d6391..5d1978ceb3b5 100644
--- a/products/tracing/backend/migrations/0004_squash_2026_09_07_schema_addons.py
+++ b/products/tracing/backend/migrations/0004_squash_2026_09_07_schema_addons.py
@@ -68,14 +68,12 @@ class Migration(migrations.Migration):
("signals", "0001_squash_2026_09_07_initial"),
("skills", "0001_squash_2026_09_07_initial"),
("slack_app", "0001_squash_2026_09_07_initial"),
- ("stamphog", "0001_squash_2026_09_07_initial"),
("streamlit_apps", "0004_squash_2026_09_07_finalize_fks"),
("surveys", "0001_squash_2026_09_07_initial"),
("tasks", "0121_squash_2026_09_07_finalize_fks"),
("tracing", "0001_squash_2026_09_07_initial"),
("tracing", "0002_teamtracingconfig"),
("user_interviews", "0001_squash_2026_09_07_initial"),
- ("visual_review", "0001_squash_2026_09_07_initial"),
("warehouse_sources", "0001_squash_2026_09_07_initial"),
("web_analytics", "0001_squash_2026_09_07_initial"),
("wizard", "0001_squash_2026_09_07_initial"),
diff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.py
index 784d3637fa7b..99ea1ee1a912 100644
--- a/tools/hogli-commands/hogli_commands/db_schema.py
+++ b/tools/hogli-commands/hogli_commands/db_schema.py
@@ -35,7 +35,6 @@ 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_RE = re.compile(r".*_squash_.*_schema_addons$")
T = TypeVar("T")
@@ -205,35 +204,6 @@ def _psql_write(target_db: str, sql: str) -> None:
)
-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)
@@ -244,81 +214,27 @@ def _product_routed_app_labels() -> list[str]:
return sorted(label for label in labels if APP_LABEL_RE.fullmatch(label))
-@dataclass(frozen=True, kw_only=True)
-class MigrationRecord:
- """One row of django_migrations."""
-
- app: str
- name: str
-
-
-def migrations_to_forget(
- recorded: Iterable[MigrationRecord], product_app_labels: Iterable[str]
-) -> tuple[MigrationRecord, ...]:
- """Pick the dump's migration records this database cannot honor.
+def _forget_product_app_migrations(target_db: str) -> None:
+ """Drop the dump's claim that product-routed apps are migrated in this database.
- The dump is taken from a CI database that routes product apps elsewhere, so `migrate` skipped
+ The dump is taken from a CI database that routes those apps elsewhere, so `migrate` skipped
every operation in their migrations there while Django recorded them as applied anyway (it
records whatever the router decides). Restored verbatim, that leaves a database asserting
stamphog and visual_review are migrated without a single one of their tables — and an
environment that configures no product database then applies their NEXT migration for real
- and dies on the missing table. Forgetting the rows lets each consumer apply them under its own
+ 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.
- The squash schema-addons migrations go with them. Each one depends on the leaf squash of every
- squashed app, the product-routed apps included, so a database that keeps an addons row while
- its dependency row is gone fails Django's consistency check before `migrate` does anything.
- Re-applying 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. The repo keeps one
- migration line per app, so a name that sorts after the addons migration is a descendant of it.
-
- Nothing is re-recorded here. The caller's own `migrate` applies every forgotten migration
- against the restored schema, which is the only pass that sees this database's routing.
- """
- routed = set(product_app_labels)
- by_app: dict[str, list[str]] = {}
- for record in recorded:
- by_app.setdefault(record.app, []).append(record.name)
-
- forget: list[MigrationRecord] = []
- for app, recorded_names in sorted(by_app.items()):
- names = sorted(recorded_names)
- if app in routed:
- forget.extend(MigrationRecord(app=app, name=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
- forget.extend(MigrationRecord(app=app, name=name) for name in names if name >= addons)
-
- return tuple(forget)
-
-
-def _sql_string(value: str) -> str:
- escaped = value.replace("'", "''")
- return f"'{escaped}'"
-
-
-def _forget_product_app_migrations(target_db: str) -> None:
- """Drop the dump's migration records this database cannot honor.
-
- See `migrations_to_forget` for what goes and why.
+ Only these rows go. Every other row stays, so the caller's `migrate` never re-applies schema
+ the dump already holds. That holds as long as no migration outside a routed app depends on
+ one inside it; `posthog/test/repo_invariants/test_migration_dependencies_share_a_database.py`
+ keeps it that way.
"""
app_labels = _product_routed_app_labels()
if not app_labels:
return
- recorded = [
- MigrationRecord(app=row[0], name=row[1])
- for row in _psql_rows(target_db, "SELECT app, name FROM django_migrations;")
- ]
- forget = migrations_to_forget(recorded, app_labels)
- if not forget:
- return
-
- pairs = ", ".join(f"({_sql_string(r.app)}, {_sql_string(r.name)})" for r in forget)
- _psql_write(target_db, f"DELETE FROM django_migrations WHERE (app, name) IN ({pairs});")
+ in_list = ", ".join(f"'{label}'" for label in app_labels)
+ _psql_write(target_db, f"DELETE FROM django_migrations WHERE app IN ({in_list});")
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.py
index e8e209668bda..28cff74a6423 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py
@@ -295,7 +295,6 @@ def test_restore_schema_dump_recreate_drops_and_creates(tmp_path: Path, monkeypa
lambda 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)
@@ -305,37 +304,11 @@ def test_restore_schema_dump_recreate_drops_and_creates(tmp_path: Path, monkeypa
assert defaults == ["test_posthog"]
-def _record(app: str, name: str) -> db_schema.MigrationRecord:
- return db_schema.MigrationRecord(app=app, name=name)
-
-
-_RECORDED = [
- _record("stamphog", "0001_squash_2026_09_07_initial"),
- _record("stamphog", "0002_later"),
- _record("posthog", "0001_squash_2026_09_07_initial"),
- _record("posthog", "1345_squash_2026_09_07_schema_addons"),
- _record("posthog", "1346_untrack_organization_is_hipaa"),
- _record("posthog", "1347_add_a_column"),
- _record("cdp", "0005_no_addons_migration_here"),
-]
-
-
-def test_migrations_to_forget() -> None:
- # A product-routed app goes in full. Elsewhere the addons migration and everything recorded
- # after it go, because each of those depends on a row that is about to disappear.
- assert db_schema.migrations_to_forget(_RECORDED, ["stamphog"]) == (
- _record("posthog", "1345_squash_2026_09_07_schema_addons"),
- _record("posthog", "1346_untrack_organization_is_hipaa"),
- _record("posthog", "1347_add_a_column"),
- _record("stamphog", "0001_squash_2026_09_07_initial"),
- _record("stamphog", "0002_later"),
- )
-
-
def test_restore_schema_dump_forgets_product_app_migrations(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
- # Two regressions live here. Leaving a forgotten migration's descendant behind makes Django
- # refuse to migrate at all. Re-recording any of them here marks a product app migrated on a
- # database that never got its tables, which breaks its next migration instead.
+ # 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. Nothing else may go: a
+ # forgotten row outside those apps makes the caller's migrate re-run DDL the dump already holds.
schema_path = tmp_path / "schema.sql.gz"
_write_schema(schema_path)
commands: list[list[str]] = []
@@ -343,15 +316,12 @@ def test_restore_schema_dump_forgets_product_app_migrations(tmp_path: Path, monk
monkeypatch.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: [[r.app, r.name] for r in _RECORDED])
+ monkeypatch.setattr(db_schema, "_product_routed_app_labels", lambda: ["stamphog", "visual_review"])
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
- for record in db_schema.migrations_to_forget(_RECORDED, ["stamphog"]):
- assert f"('{record.app}', '{record.name}')" in deletes[0]
+ assert deletes == ["DELETE FROM django_migrations WHERE app IN ('stamphog', 'visual_review');"]
assert not [command for command in commands if command[:3] == ["python", "manage.py", "migrate"]]
@@ -398,7 +368,6 @@ def test_restore_schema_dump_without_recreate_does_not_drop(tmp_path: Path, monk
monkeypatch.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)