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(aio): drop the two orphaned v1 dataset tables (#93072)

posthog[bot]b144e42e3ffc
diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.py
index 916ddf80ce13..2e03ddec1f2c 100644
--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py
+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py
@@ -799,6 +799,168 @@ class TestDropTableValidation:
assert migration_risk.level == RiskLevel.NEEDS_REVIEW
assert migration_risk.max_score == 2
+ def test_drop_table_resolves_deleted_model_with_custom_db_table(self):
+ """
+ Valid pattern: the dropped table has a custom db_table, so its name does not match
+ <app_label>_<model> and the model is gone from the registry. The migration history
+ still records which model created the table.
+ """
+ create_op = create_mock_operation(
+ migrations.CreateModel,
+ name="Dataset",
+ options={"db_table": "llm_analytics_dataset"},
+ )
+ create_migration = MagicMock()
+ create_migration.app_label = "ai_observability"
+ create_migration.name = "0001_adopt"
+ create_migration.operations = [create_op]
+ create_migration.dependencies = []
+
+ delete_model_op = create_mock_operation(migrations.DeleteModel, name="Dataset")
+ separate_op = create_mock_operation(
+ migrations.SeparateDatabaseAndState,
+ state_operations=[delete_model_op],
+ database_operations=[],
+ )
+ state_removal_migration = MagicMock()
+ state_removal_migration.app_label = "ai_observability"
+ state_removal_migration.name = "0032_dataset_versioning"
+ state_removal_migration.operations = [separate_op]
+ state_removal_migration.dependencies = [("ai_observability", "0001_adopt")]
+
+ drop_migration = MagicMock()
+ drop_migration.app_label = "ai_observability"
+ drop_migration.name = "0033_drop_legacy_dataset"
+ drop_migration.dependencies = [("ai_observability", "0032_dataset_versioning")]
+ drop_migration.operations = [
+ create_mock_operation(migrations.RunSQL, sql="DROP TABLE IF EXISTS llm_analytics_dataset;")
+ ]
+
+ mock_loader = MagicMock()
+ mock_loader.disk_migrations = {
+ ("ai_observability", "0001_adopt"): create_migration,
+ ("ai_observability", "0032_dataset_versioning"): state_removal_migration,
+ ("ai_observability", "0033_drop_legacy_dataset"): drop_migration,
+ }
+
+ migration_risk = self.analyzer.analyze_migration_with_context(
+ drop_migration,
+ "products/ai_observability/backend/migrations/0033_drop_legacy_dataset.py",
+ mock_loader,
+ )
+
+ assert migration_risk.level == RiskLevel.NEEDS_REVIEW
+ assert migration_risk.max_score == 2
+
+ def test_drop_table_still_owned_by_live_model_in_another_app_stays_blocked(self):
+ """Unsafe pattern: the origin app created the model, then released it from state to another
+ app that kept the same db_table. The live table is now owned elsewhere. A DROP written in
+ the origin app must stay BLOCKED, not be validated by the stale CreateModel/DeleteModel pair
+ left in the origin app's history.
+
+ Uses llm_analytics_llmskill: ai_observability created it, migration 0005 released it from
+ state, and the live skills.LLMSkill model still maps to the table.
+ """
+ create_op = create_mock_operation(
+ migrations.CreateModel,
+ name="LLMSkill",
+ options={"db_table": "llm_analytics_llmskill"},
+ )
+ create_migration = MagicMock()
+ create_migration.app_label = "ai_observability"
+ create_migration.name = "0001_adopt"
+ create_migration.operations = [create_op]
+ create_migration.dependencies = []
+
+ delete_model_op = create_mock_operation(migrations.DeleteModel, name="LLMSkill")
+ separate_op = create_mock_operation(
+ migrations.SeparateDatabaseAndState,
+ state_operations=[delete_model_op],
+ database_operations=[],
+ )
+ state_removal_migration = MagicMock()
+ state_removal_migration.app_label = "ai_observability"
+ state_removal_migration.name = "0005_release_skills_to_skills_app"
+ state_removal_migration.operations = [separate_op]
+ state_removal_migration.dependencies = [("ai_observability", "0001_adopt")]
+
+ drop_migration = MagicMock()
+ drop_migration.app_label = "ai_observability"
+ drop_migration.name = "0043_drop_legacy_llmskill"
+ drop_migration.dependencies = [("ai_observability", "0005_release_skills_to_skills_app")]
+ drop_migration.operations = [
+ create_mock_operation(migrations.RunSQL, sql="DROP TABLE IF EXISTS llm_analytics_llmskill;")
+ ]
+
+ mock_loader = MagicMock()
+ mock_loader.disk_migrations = {
+ ("ai_observability", "0001_adopt"): create_migration,
+ ("ai_observability", "0005_release_skills_to_skills_app"): state_removal_migration,
+ ("ai_observability", "0043_drop_legacy_llmskill"): drop_migration,
+ }
+
+ migration_risk = self.analyzer.analyze_migration_with_context(
+ drop_migration,
+ "products/ai_observability/backend/migrations/0043_drop_legacy_llmskill.py",
+ mock_loader,
+ )
+
+ assert migration_risk.level == RiskLevel.BLOCKED
+ assert migration_risk.max_score == 5
+
+ def test_drop_table_resolves_the_most_recent_owner_of_a_reused_db_table(self):
+ """Unsafe pattern: a second model took over the db_table when the first was deleted from
+ state, and no migration ever removed that second model. Resolving the table to the first,
+ long-deleted model would pair the drop with an obsolete DeleteModel and pass it."""
+ legacy_create_op = create_mock_operation(
+ migrations.CreateModel,
+ name="Legacy",
+ options={"db_table": "shared_table"},
+ )
+ create_migration = MagicMock()
+ create_migration.app_label = "myapp"
+ create_migration.name = "0001_create_legacy"
+ create_migration.operations = [legacy_create_op]
+ create_migration.dependencies = []
+
+ successor_create_op = create_mock_operation(
+ migrations.CreateModel,
+ name="Successor",
+ options={"db_table": "shared_table"},
+ )
+ handover_op = create_mock_operation(
+ migrations.SeparateDatabaseAndState,
+ state_operations=[create_mock_operation(migrations.DeleteModel, name="Legacy"), successor_create_op],
+ database_operations=[],
+ )
+ handover_migration = MagicMock()
+ handover_migration.app_label = "myapp"
+ handover_migration.name = "0002_successor_takes_over_table"
+ handover_migration.operations = [handover_op]
+ handover_migration.dependencies = [("myapp", "0001_create_legacy")]
+
+ drop_migration = MagicMock()
+ drop_migration.app_label = "myapp"
+ drop_migration.name = "0003_drop_shared_table"
+ drop_migration.dependencies = [("myapp", "0002_successor_takes_over_table")]
+ drop_migration.operations = [create_mock_operation(migrations.RunSQL, sql="DROP TABLE IF EXISTS shared_table;")]
+
+ mock_loader = MagicMock()
+ mock_loader.disk_migrations = {
+ ("myapp", "0001_create_legacy"): create_migration,
+ ("myapp", "0002_successor_takes_over_table"): handover_migration,
+ ("myapp", "0003_drop_shared_table"): drop_migration,
+ }
+
+ migration_risk = self.analyzer.analyze_migration_with_context(
+ drop_migration,
+ "myapp/migrations/0003_drop_shared_table.py",
+ mock_loader,
+ )
+
+ assert migration_risk.level == RiskLevel.BLOCKED
+ assert migration_risk.max_score == 5
+
def test_drop_table_with_gap_between_state_removal_and_drop(self):
"""
Valid pattern: State removal several migrations before drop.
diff --git a/posthog/management/migration_analysis/utils.py b/posthog/management/migration_analysis/utils.py
index e425d12c0056..f3668f15d537 100644
--- a/posthog/management/migration_analysis/utils.py
+++ b/posthog/management/migration_analysis/utils.py
@@ -166,6 +166,13 @@ def check_drop_properly_staged(
- For "table": SeparateDatabaseAndState with DeleteModel for the model
- For "column": SeparateDatabaseAndState with RemoveField for the model+field
"""
+ # A table a live model still owns is not an orphaned table: the model moved to another app or
+ # the name was reused there. This app's history still holds the old CreateModel and a later
+ # DeleteModel, so the staged-drop walk below would match a stale mapping and validate a drop of
+ # a live, in-use table. Refuse it here so the drop stays BLOCKED.
+ if target_type == "table" and _table_owned_by_live_model(table_name):
+ return False
+
if not loader or not hasattr(loader, "disk_migrations"):
return False
@@ -173,7 +180,11 @@ def check_drop_properly_staged(
# posthog_namedquery -> NamedQuery
# llm_analytics_evaluation (app=llm_analytics) -> Evaluation
app_label = getattr(migration, "app_label", None)
- model_name = _model_name_for_table(app_label, table_name) or _extract_model_name_from_table(table_name, app_label)
+ model_name = (
+ _model_name_for_table(app_label, table_name)
+ or _model_name_from_history(app_label, table_name, loader)
+ or _extract_model_name_from_table(table_name, app_label)
+ )
if not model_name:
return False
@@ -209,11 +220,24 @@ def check_drop_properly_staged(
return False
+def _table_owned_by_live_model(table_name: str) -> bool:
+ """True if any app's live model currently maps to this table.
+
+ The staged-drop check resolves a dropped table back to the model that created it and looks for a
+ prior DeleteModel. That mapping goes stale when a table is moved to another app (or reused under
+ the same name) while keeping its db_table, because the origin app still has both the CreateModel
+ and a DeleteModel in its history. Scanning every app's live models catches the table that is
+ still owned, so a drop of it is not mistaken for a retired-table cleanup. Auto-created
+ many-to-many through tables count as owned: no model class declares them, but an M2M field does.
+ """
+ return any(model._meta.db_table == table_name for model in apps.get_models(include_auto_created=True))
+
+
def _model_name_for_table(app_label: Optional[str], table_name: str) -> Optional[str]:
"""Resolve the model whose db_table matches via the app registry. Handles custom db_table
names the string heuristic can't (e.g. legacy llm_analytics_* tables owned by the
ai_observability app). Returns None for models no longer in the registry (deleted models);
- callers fall back to the string heuristic."""
+ callers fall back to the migration history."""
if not app_label:
return None
try:
@@ -226,6 +250,42 @@ def _model_name_for_table(app_label: Optional[str], table_name: str) -> Optional
return None
+def _model_name_from_history(app_label: Optional[str], table_name: str, loader: Any) -> Optional[str]:
+ """Resolve the model that created a table from the app's migration history.
+
+ The registry lookup only sees live models, so a model that was deleted, or one that moved to
+ a new db_table, leaves its old table unresolvable there. The CreateModel that declared the
+ table still records the mapping.
+
+ `disk_migrations` has no order, so walk it by migration name and keep the last match. A table
+ name that two models used over time then resolves to the more recent one, deterministically.
+ """
+ if not app_label or not loader or not hasattr(loader, "disk_migrations"):
+ return None
+
+ latest_owner: Optional[str] = None
+ for key, historical_migration in sorted(loader.disk_migrations.items(), key=lambda item: item[0]):
+ if key[0] != app_label:
+ continue
+ for op in _create_model_operations(getattr(historical_migration, "operations", [])):
+ name = getattr(op, "name", "")
+ created_table = (getattr(op, "options", None) or {}).get("db_table") or f"{app_label}_{name.lower()}"
+ if created_table == table_name:
+ latest_owner = name
+ return latest_owner
+
+
+def _create_model_operations(operations: Any) -> list[Any]:
+ """Collect CreateModel operations, including those staged inside SeparateDatabaseAndState."""
+ found = []
+ for op in operations:
+ if op.__class__.__name__ == "SeparateDatabaseAndState":
+ found.extend(_create_model_operations(getattr(op, "state_operations", [])))
+ elif op.__class__.__name__ == "CreateModel":
+ found.append(op)
+ return found
+
+
def _extract_model_name_from_table(table_name: str, app_label: Optional[str] = None) -> Optional[str]:
"""
Extract Django model name from table name.
diff --git a/products/ai_observability/backend/migrations/0043_drop_legacy_dataset_tables.py b/products/ai_observability/backend/migrations/0043_drop_legacy_dataset_tables.py
new file mode 100644
index 000000000000..42b975cdf9a3
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0043_drop_legacy_dataset_tables.py
@@ -0,0 +1,27 @@
+# Phase 2 of the staged drop. Migration 0032 (#75748, on master since 2026-08-03) removed the v1
+# Dataset and DatasetItem models from Django state and moved the live models to the _v2 tables.
+# Nothing has read or written the v1 tables since.
+#
+# Migration 0032 copied no v1 rows into the _v2 tables, so this drop destroys whatever the v1 tables
+# still hold. The reverse is a no-op, because a CREATE TABLE would only fake a recovery.
+#
+# Drop the item table first, because the v1 child still holds a foreign key to the v1 parent.
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0042_aiobservabilitychecklistitemstate"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ sql="DROP TABLE IF EXISTS llm_analytics_datasetitem;",
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ migrations.RunSQL(
+ sql="DROP TABLE IF EXISTS llm_analytics_dataset;",
+ reverse_sql=migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index 692ea7ca14cc..ee998cb2575a 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0042_aiobservabilitychecklistitemstate
+0043_drop_legacy_dataset_tables