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(insights): retire the last production callers of filter_to_query (#99774)

Thomas Obermüller50d06cc7c760
diff --git a/posthog/management/commands/migrate_experiments.py b/posthog/management/commands/migrate_experiments.py
deleted file mode 100644
index e18eb8a28f53..000000000000
--- a/posthog/management/commands/migrate_experiments.py
+++ /dev/null
@@ -1,78 +0,0 @@
-import logging
-from datetime import datetime
-
-from django.core.management.base import BaseCommand
-
-from posthog.schema import ExperimentFunnelsQuery, ExperimentTrendsQuery
-
-from posthog.exceptions_capture import capture_exception
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-
-from products.experiments.backend.models.experiment import Experiment
-
-logger = logging.getLogger(__name__)
-logger.setLevel(logging.INFO)
-
-
-class Command(BaseCommand):
- help = "Migrate experiment metrics to new schema"
-
- def handle(self, *args, **options):
- logger.info("Starting experiments migration")
-
- experiments = Experiment.objects.iterator(chunk_size=100)
- for experiment in experiments:
- try:
- # Check for valid insight type
- if not experiment.filters.get("insight"):
- logger.warning(f"Skipping experiment {experiment.id}: 'insight' type is missing or invalid")
- continue
-
- # Update main metric
- main_experiment_query = self.create_experiment_query(
- filters=experiment.filters,
- custom_exposure_filter=(
- experiment.parameters.get("custom_exposure_filter") if experiment.parameters else None
- ),
- )
- experiment.metrics = [main_experiment_query.model_dump()]
-
- # Update secondary metrics
- experiment.metrics_secondary = []
- for secondary_metric in experiment.secondary_metrics or []:
- secondary_query = self.create_experiment_query(
- filters=secondary_metric["filters"],
- name=secondary_metric["name"],
- )
- experiment.metrics_secondary.append(secondary_query.model_dump())
-
- experiment.filters["migrated_at"] = str(datetime.now())
-
- experiment.save()
- logger.info(f"ID: {experiment.id} updated")
- except Exception as e:
- capture_exception(e)
- logger.exception(f"Error migrating experiment {experiment.id}")
-
- logger.info("Experiment migration completed")
-
- def create_experiment_query(self, filters, custom_exposure_filter=None, name=None):
- filters["explicit_date"] = True
-
- if filters.get("insight") == "TRENDS":
- count_query = filter_to_query(filters)
- exposure_query = None
- if custom_exposure_filter:
- exposure_query = filter_to_query(custom_exposure_filter)
- return ExperimentTrendsQuery(
- count_query=count_query,
- exposure_query=exposure_query,
- name=name,
- )
- elif filters.get("insight") == "FUNNELS":
- funnels_query = filter_to_query(filters)
- return ExperimentFunnelsQuery(
- funnels_query=funnels_query,
- name=name,
- )
- raise ValueError(f"Unsupported or missing insight type: {filters.get('insight')}")
diff --git a/posthog/migrations/0530_convert_dashboard_templates_to_queries.py b/posthog/migrations/0530_convert_dashboard_templates_to_queries.py
index 927b939379e2..d06a51cdf5b0 100644
--- a/posthog/migrations/0530_convert_dashboard_templates_to_queries.py
+++ b/posthog/migrations/0530_convert_dashboard_templates_to_queries.py
@@ -1,32 +1,35 @@
# Generated by Django 4.2.15 on 2024-11-04 11:24
+import logging
from django.db import migrations
-from posthog.schema import InsightVizNode
+logger = logging.getLogger(__name__)
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-
-def update_filters_to_queries(apps, schema_editor):
+def warn_on_unconverted_templates(apps, schema_editor):
DashboardTemplate = apps.get_model("posthog", "DashboardTemplate")
-
- for template in DashboardTemplate.objects.all():
- for tile in template.tiles:
- if "filters" in tile:
- source = filter_to_query(tile["filters"], allow_variables=True)
- query = InsightVizNode(source=source)
- tile["query"] = query.model_dump(exclude_none=True)
- del tile["filters"]
- template.save()
-
-
-def revert_queries_to_filters(apps, schema_editor):
- pass
+ unconverted = sum(
+ 1
+ for template in DashboardTemplate.objects.all().iterator(chunk_size=100)
+ if any("filters" in tile for tile in (template.tiles or []))
+ )
+ if unconverted:
+ logger.warning(
+ "%s dashboard template(s) hold tiles in the legacy `filters` shape and were not converted "
+ "to `query`. A dashboard created from such a template gets insights with no definition.",
+ unconverted,
+ )
class Migration(migrations.Migration):
dependencies = [("posthog", "0529_hog_function_mappings")]
+ # This migration no longer converts, because the conversion needed `filter_to_query` and that
+ # converter is retired. `0001_squash_2026_09_07_initial` replaces this migration, so a fresh
+ # database never reaches it, and `ensure_migration_defaults` seeds the global templates in
+ # query shape. Django keeps the original chain when a squash is only partly applied, so a
+ # database that stopped inside the replaced range does still reach this migration. Re-seeding
+ # does not cover the templates a team created for itself, so this reports what it skipped.
operations = [
- migrations.RunPython(update_filters_to_queries, revert_queries_to_filters),
+ migrations.RunPython(warn_on_unconverted_templates, migrations.RunPython.noop),
]
diff --git a/posthog/migrations/0545_insight_filters_to_query.py b/posthog/migrations/0545_insight_filters_to_query.py
index 6f797977620b..b22c694a27bd 100644
--- a/posthog/migrations/0545_insight_filters_to_query.py
+++ b/posthog/migrations/0545_insight_filters_to_query.py
@@ -1,49 +1,33 @@
# Generated by Django 4.2.14 on 2024-08-22 12:23
import logging
-from datetime import datetime
-from django.db import connection, migrations
+from django.db import migrations
from django.db.models import Q
-from posthog.schema import InsightVizNode
-
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-
logger = logging.getLogger(__name__)
-def migrate_insight_filters_to_query(apps, schema_editor):
+def warn_on_unconverted_insights(apps, schema_editor):
Insight = apps.get_model("posthog", "Insight")
- insights = Insight.objects.filter(Q(filters__insight__isnull=False) & Q(query__kind__isnull=True))
- migrated_at = datetime.now()
-
- for insight in insights.iterator(chunk_size=100):
- try:
- source = filter_to_query(insight.filters)
- query = InsightVizNode(source=source)
- insight.query = query.model_dump(exclude_none=True)
-
- # add a migrated_at as filter, so that we can find migrated insights for rolling back
- insight.filters["migrated_at"] = str(migrated_at)
- insight.save()
- except Exception:
- logger.error(f"Error converting insight with id {insight.pk}") # noqa: TRY400
-
-
-def rollback_insight_filters_to_query(apps, schema_editor):
- with connection.cursor() as cursor:
- cursor.execute(
- """
- UPDATE posthog_dashboarditem
- SET query = NULL, filters = filters - 'migrated_at'
- WHERE filters->>'migrated_at' IS NOT NULL
- """
+ # The predicate the conversion used, so the count names the rows it would have rewritten.
+ unconverted = Insight.objects.filter(Q(filters__insight__isnull=False) & Q(query__kind__isnull=True)).count()
+ if unconverted:
+ logger.warning(
+ "%s insight(s) hold only legacy `filters` and were not converted to `query`. "
+ "Their `filters` are intact, but each insight renders blank until someone opens and saves it.",
+ unconverted,
)
class Migration(migrations.Migration):
dependencies = [("posthog", "0544_team_flags_persistence_default")]
+ # This migration no longer converts, because the conversion needed `filter_to_query` and that
+ # converter is retired. `0001_squash_2026_09_07_initial` replaces this migration, so a fresh
+ # database never reaches it, and a database that already applied it keeps its converted
+ # insights. Django keeps the original chain when a squash is only partly applied, so a
+ # database that stopped inside the replaced range does still reach this migration. There it
+ # reports what it skipped instead of recording itself complete in silence.
operations = [
- migrations.RunPython(migrate_insight_filters_to_query, rollback_insight_filters_to_query),
+ migrations.RunPython(warn_on_unconverted_insights, migrations.RunPython.noop),
]
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index e678becb42a1..78b79341ebeb 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -1002,6 +1002,6 @@ web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.ap
web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight_metadata drives(TrendsQuery) 5
web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight_query drives(TrendsQuery) 4
web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_paths_v2 drives(TrendsQuery) 1
-web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.test_insight_write_validation drives(TrendsQuery) 6
+web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.test_insight_write_validation drives(TrendsQuery) 4
web_analytics:backend/hogql_queries/ products.signals.backend.test.test_scout_report_api drives(TrendsQuery) 1
web_analytics:backend/hogql_queries/ products.tasks.backend.tests.test_api drives(TrendsQuery) 3
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 3a8a3f4b5cc3..ff280bf733ea 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -680,10 +680,6 @@ class InsightSerializer(InsightBasicSerializer):
validate_insight_write(
query=query,
- # No write reaches the stored filters, so only the query needs judging.
- filters=None,
- # A write that omits `query` keeps the stored one, which is still what renders.
- unchanged_query=None if "query" in attrs else getattr(self.instance, "query", None),
team=self.context["get_team"](),
user=self.context["request"].user,
request=self.context["request"],
diff --git a/products/product_analytics/backend/presentation/insight_write_validation.py b/products/product_analytics/backend/presentation/insight_write_validation.py
index 058070bad537..a46a76ffc783 100644
--- a/products/product_analytics/backend/presentation/insight_write_validation.py
+++ b/products/product_analytics/backend/presentation/insight_write_validation.py
@@ -11,7 +11,7 @@ shows which saves the rules would refuse before any save starts to fail.
"""
import logging
-from typing import Any, Literal
+from typing import Any
from django.contrib.auth.models import AnonymousUser
@@ -22,7 +22,6 @@ from rest_framework.request import Request
from posthog.dataclasses import frozen
from posthog.event_usage import report_user_action
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
from posthog.hogql_queries.query_runner import QueryRunner, get_query_runner_or_none
from posthog.models import Team, User
from posthog.ph_client import feature_enabled_or_false
@@ -34,13 +33,11 @@ INSIGHT_WRITE_VALIDATION_ENFORCED_FLAG = "insight-write-validation-enforced"
INSIGHT_WRITE_VALIDATION_COUNTER = Counter(
"posthog_insight_write_validation_rejected_total",
- "Insight writes holding a query the runner's validation rules reject, by rule, query kind "
- "and which field carried the query. Writes counted in shadow mode were still saved.",
- labelnames=["rule_code", "query_kind", "write_source", "mode"],
+ "Insight writes holding a query the runner's validation rules reject, by rule and query "
+ "kind. Writes counted in shadow mode were still saved.",
+ labelnames=["rule_code", "query_kind", "mode"],
)
-WriteSource = Literal["query", "filters"]
-
Writer = User | AnonymousUser | SyntheticUser
@@ -49,7 +46,6 @@ class InsightWriteRejection:
rule_code: str
message: str
query_kind: str
- write_source: WriteSource
@frozen
@@ -61,20 +57,12 @@ class _RuleError:
def validate_insight_write(
*,
query: dict[str, Any] | None,
- filters: dict[str, Any] | None,
- unchanged_query: dict[str, Any] | None = None,
team: Team,
user: Writer,
request: Request | None = None,
) -> None:
"""Record, and once enforced reject, an insight write that no runner could execute."""
- rejection = find_insight_write_rejection(
- query=query,
- filters=filters,
- unchanged_query=unchanged_query,
- team=team,
- user=user,
- )
+ rejection = find_insight_write_rejection(query=query, team=team, user=user)
if rejection is None:
return
@@ -84,37 +72,19 @@ def validate_insight_write(
return
raise ValidationError(
- {rejection.write_source: ErrorDetail(rejection.message, code=rejection.rule_code)},
+ {"query": ErrorDetail(rejection.message, code=rejection.rule_code)},
)
def find_insight_write_rejection(
*,
query: dict[str, Any] | None,
- filters: dict[str, Any] | None,
- unchanged_query: dict[str, Any] | None = None,
team: Team,
user: Writer,
) -> InsightWriteRejection | None:
- """The first validation rule the written query breaks, or None if every rule passes.
-
- An insight renders from `query` whenever it has one, and falls back to `filters` only
- when it does not. So a written query is what the rules must judge, and written filters
- matter only when no query remains on the insight after this write. `unchanged_query` is
- the stored query this write leaves in place, which keeps a filters write from being
- judged on a field that nothing renders.
- """
+ """The first validation rule the written query breaks, or None if every rule passes."""
if query:
- return _rejection_for(query, write_source="query", team=team, user=user)
-
- if filters and not unchanged_query:
- try:
- source = filter_to_query(filters)
- except Exception:
- # Filters this side can't convert never reach a runner here, and the app converts
- # them again in the browser, so we have nothing to say about them.
- return None
- return _rejection_for(source, write_source="filters", team=team, user=user)
+ return _rejection_for(query, team=team, user=user)
return None
@@ -142,7 +112,6 @@ def is_insight_write_validation_enforced(user: Writer, team: Team) -> bool:
def _rejection_for(
query: dict[str, Any] | BaseModel,
*,
- write_source: WriteSource,
team: Team,
user: Writer,
) -> InsightWriteRejection | None:
@@ -158,7 +127,6 @@ def _rejection_for(
rule_code=rule_error.code,
message=rule_error.message,
query_kind=str(getattr(runner.query, "kind", "unknown")),
- write_source=write_source,
)
except Exception:
# Only a rule saying "this can never run" is worth a 400. Anything else a rule throws
@@ -199,7 +167,6 @@ def _record(
INSIGHT_WRITE_VALIDATION_COUNTER.labels(
rule_code=rejection.rule_code,
query_kind=rejection.query_kind,
- write_source=rejection.write_source,
mode=mode,
).inc()
@@ -210,7 +177,6 @@ def _record(
{
"rule_code": rejection.rule_code,
"query_kind": rejection.query_kind,
- "write_source": rejection.write_source,
"mode": mode,
},
team=team,
diff --git a/products/product_analytics/backend/tests/test_insight_write_validation.py b/products/product_analytics/backend/tests/test_insight_write_validation.py
index d02835ed52d7..c0be3ace2c24 100644
--- a/products/product_analytics/backend/tests/test_insight_write_validation.py
+++ b/products/product_analytics/backend/tests/test_insight_write_validation.py
@@ -10,111 +10,53 @@ from products.product_analytics.backend.presentation.insight_write_validation im
)
PAGEVIEW_SERIES = [{"kind": "EventsNode", "event": "$pageview"}]
-PAGEVIEW_FILTER_EVENTS = [{"id": "$pageview", "type": "events"}]
class TestInsightWriteValidation(BaseTest):
- def _find(
- self,
- *,
- query: dict[str, Any] | None = None,
- filters: dict[str, Any] | None = None,
- unchanged_query: dict[str, Any] | None = None,
- ) -> InsightWriteRejection | None:
- return find_insight_write_rejection(
- query=query,
- filters=filters,
- unchanged_query=unchanged_query,
- team=self.team,
- user=self.user,
- )
+ def _find(self, *, query: dict[str, Any] | None = None) -> InsightWriteRejection | None:
+ return find_insight_write_rejection(query=query, team=self.team, user=self.user)
@parameterized.expand(
[
(
"empty trends series",
{"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": []}},
- None,
"insight_requires_at_least_one_series",
- "query",
),
(
"empty trends series, unwrapped",
{"kind": "TrendsQuery", "series": []},
- None,
"insight_requires_at_least_one_series",
- "query",
),
(
"empty lifecycle series",
{"kind": "InsightVizNode", "source": {"kind": "LifecycleQuery", "series": []}},
- None,
"insight_requires_at_least_one_series",
- "query",
),
(
"funnel with a single step",
{"kind": "InsightVizNode", "source": {"kind": "FunnelsQuery", "series": PAGEVIEW_SERIES}},
- None,
"funnels_require_at_least_two_steps",
- "query",
- ),
- (
- "legacy filters that convert to an empty series",
- None,
- {"insight": "TRENDS", "events": []},
- "insight_requires_at_least_one_series",
- "filters",
),
]
)
- def test_rejects_a_query_no_runner_can_execute(
- self,
- _name: str,
- query: dict | None,
- filters: dict | None,
- expected_code: str,
- expected_source: str,
- ) -> None:
- rejection = self._find(query=query, filters=filters)
+ def test_rejects_a_query_no_runner_can_execute(self, _name: str, query: dict, expected_code: str) -> None:
+ rejection = self._find(query=query)
assert rejection is not None
assert rejection.rule_code == expected_code
- assert rejection.write_source == expected_source
@parameterized.expand(
[
(
"trends with a series",
{"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": PAGEVIEW_SERIES}},
- None,
- None,
- ),
- (
- "hogql",
- {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},
- None,
- None,
- ),
- ("a kind no runner owns", {"kind": "SomeQueryWeDoNotHave", "series": []}, None, None),
- ("a payload no runner can parse", {"kind": "TrendsQuery", "series": [{"nope": True}]}, None, None),
- ("legacy filters with an event", None, {"insight": "TRENDS", "events": PAGEVIEW_FILTER_EVENTS}, None),
- (
- "a query that renders, alongside filters that would not",
- {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": PAGEVIEW_SERIES}},
- {"insight": "TRENDS", "events": []},
- None,
- ),
- (
- "filters the rules refuse, on an insight whose stored query renders",
- None,
- {"insight": "TRENDS", "events": []},
- {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": PAGEVIEW_SERIES}},
),
- ("nothing written", None, None, None),
+ ("hogql", {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}}),
+ ("a kind no runner owns", {"kind": "SomeQueryWeDoNotHave", "series": []}),
+ ("a payload no runner can parse", {"kind": "TrendsQuery", "series": [{"nope": True}]}),
+ ("nothing written", None),
]
)
- def test_accepts_everything_the_rules_do_not_refuse(
- self, _name: str, query: dict | None, filters: dict | None, unchanged_query: dict | None
- ) -> None:
- assert self._find(query=query, filters=filters, unchanged_query=unchanged_query) is None
+ def test_accepts_everything_the_rules_do_not_refuse(self, _name: str, query: dict | None) -> None:
+ assert self._find(query=query) is None