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(insights): run the query validation rules when an insight is saved (#89477)

Thomas Obermüllerfeedf7179921
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 61fc08b3335e..83a0a06771b0 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -188,6 +188,7 @@ from products.product_analytics.backend.presentation.insight_suggestions import
get_insight_analysis,
get_insight_suggestions,
)
+from products.product_analytics.backend.presentation.insight_write_validation import validate_insight_write
from common.hogvm.python.utils import HogVMException
@@ -736,6 +737,16 @@ class InsightSerializer(InsightBasicSerializer):
):
raise PermissionDenied("Creating or updating insights with legacy filters is not available for this user.")
+ validate_insight_write(
+ query=query,
+ filters=attrs.get("filters"),
+ # 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"],
+ )
+
new_dashboard_ids = attrs.get("dashboards")
if new_dashboard_ids is not None:
team = self.context["get_team"]()
diff --git a/products/product_analytics/backend/presentation/insight_write_validation.py b/products/product_analytics/backend/presentation/insight_write_validation.py
new file mode 100644
index 000000000000..058070bad537
--- /dev/null
+++ b/products/product_analytics/backend/presentation/insight_write_validation.py
@@ -0,0 +1,221 @@
+"""Run the query runners' validation rules when an insight is written, not only when it runs.
+
+The rules in `posthog/hogql_queries/validation` fire from `QueryRunner.calculate()`, so they
+only see a query on the read path. An insight whose query no runner can execute saves
+cleanly and then fails on every render, so a dashboard can hold a tile that has never drawn.
+This module runs the same rule objects against the query that is being written, which
+reports the problem once instead of on every read.
+
+A rejection is recorded but not raised until the enforcement flag is on for the team. That
+shows which saves the rules would refuse before any save starts to fail.
+"""
+
+import logging
+from typing import Any, Literal
+
+from django.contrib.auth.models import AnonymousUser
+
+from prometheus_client import Counter
+from pydantic import BaseModel
+from rest_framework.exceptions import ErrorDetail, ValidationError
+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
+from posthog.synthetic_user import SyntheticUser
+
+logger = logging.getLogger(__name__)
+
+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"],
+)
+
+WriteSource = Literal["query", "filters"]
+
+Writer = User | AnonymousUser | SyntheticUser
+
+
+@frozen
+class InsightWriteRejection:
+ rule_code: str
+ message: str
+ query_kind: str
+ write_source: WriteSource
+
+
+@frozen
+class _RuleError:
+ message: str
+ code: str
+
+
+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,
+ )
+ if rejection is None:
+ return
+
+ enforced = is_insight_write_validation_enforced(user, team)
+ _record(rejection, enforced=enforced, team=team, user=user, request=request)
+ if not enforced:
+ return
+
+ raise ValidationError(
+ {rejection.write_source: 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.
+ """
+ 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 None
+
+
+def is_insight_write_validation_enforced(user: Writer, team: Team) -> bool:
+ distinct_id = getattr(user, "distinct_id", None)
+ if not distinct_id:
+ return False
+
+ return feature_enabled_or_false(
+ INSIGHT_WRITE_VALIDATION_ENFORCED_FLAG,
+ str(distinct_id),
+ groups={
+ "organization": str(team.organization_id),
+ "project": str(team.id),
+ },
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ send_feature_flag_events=False,
+ )
+
+
+def _rejection_for(
+ query: dict[str, Any] | BaseModel,
+ *,
+ write_source: WriteSource,
+ team: Team,
+ user: Writer,
+) -> InsightWriteRejection | None:
+ runner = _runner_or_none(query, team=team, user=user)
+ if runner is None:
+ return None
+
+ try:
+ runner.validate()
+ except ValidationError as error:
+ rule_error = _first_error(error)
+ return InsightWriteRejection(
+ 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
+ # is our bug, and failing the save on it would block writes the read path accepts.
+ logger.exception("Insight write validation rule failed")
+ return None
+
+ return None
+
+
+def _runner_or_none(query: dict[str, Any] | BaseModel, *, team: Team, user: Writer) -> QueryRunner | None:
+ try:
+ return get_query_runner_or_none(query, team, user=user if isinstance(user, User) else None)
+ except Exception:
+ # A payload no runner can be built for is one the read path already handles its own
+ # way. Rejecting it here would turn every shape we don't recognize into a 400.
+ return None
+
+
+def _first_error(error: ValidationError) -> _RuleError:
+ detail: Any = error.detail
+ if isinstance(detail, dict):
+ detail = next(iter(detail.values()), "")
+ if isinstance(detail, list):
+ detail = detail[0] if detail else ""
+ return _RuleError(message=str(detail), code=str(getattr(detail, "code", "invalid")))
+
+
+def _record(
+ rejection: InsightWriteRejection,
+ *,
+ enforced: bool,
+ team: Team,
+ user: Writer,
+ request: Request | None,
+) -> None:
+ mode = "enforced" if enforced else "shadow"
+ INSIGHT_WRITE_VALIDATION_COUNTER.labels(
+ rule_code=rejection.rule_code,
+ query_kind=rejection.query_kind,
+ write_source=rejection.write_source,
+ mode=mode,
+ ).inc()
+
+ try:
+ report_user_action(
+ user,
+ "insight write validation rejected",
+ {
+ "rule_code": rejection.rule_code,
+ "query_kind": rejection.query_kind,
+ "write_source": rejection.write_source,
+ "mode": mode,
+ },
+ team=team,
+ organization=team.organization,
+ request=request,
+ )
+ except Exception:
+ logger.exception("Failed to report an insight write validation rejection")
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index 17d46f5c097e..017f23c3892b 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -34,7 +34,7 @@
e.`$window_id` AS `$window_id`,
if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
+ ([e__person.properties___fish] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,6 +44,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -111,7 +121,17 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -168,8 +188,8 @@
e.uuid AS uuid,
e.`$session_id` AS `$session_id`,
e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,
+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -178,6 +198,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -294,7 +324,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -326,7 +373,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
diff --git a/products/product_analytics/backend/tests/api/test_insight_query.py b/products/product_analytics/backend/tests/api/test_insight_query.py
index 4dfbcb1f03d5..8705200ce73a 100644
--- a/products/product_analytics/backend/tests/api/test_insight_query.py
+++ b/products/product_analytics/backend/tests/api/test_insight_query.py
@@ -1,6 +1,7 @@
-from typing import get_args
+from typing import Any, get_args
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
+from unittest.mock import patch
from django.test import SimpleTestCase
@@ -204,6 +205,55 @@ class TestInsight(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest, QueryMatc
expected_status=status.HTTP_201_CREATED,
)
+ @patch("products.product_analytics.backend.presentation.insight_write_validation.report_user_action")
+ def test_saves_a_query_the_rules_reject_while_enforcement_is_off(self, mock_report: Any) -> None:
+ insight_id, _ = self.dashboard_api.create_insight(
+ {"name": "Empty series", "query": {"kind": "StickinessQuery", "series": []}},
+ expected_status=status.HTTP_201_CREATED,
+ )
+
+ assert Insight.objects.filter(pk=insight_id).exists()
+ reported = [call for call in mock_report.call_args_list if call[0][1] == "insight write validation rejected"]
+ assert len(reported) == 1
+ assert reported[0][0][2]["rule_code"] == "insight_requires_at_least_one_series"
+ assert reported[0][0][2]["mode"] == "shadow"
+
+ @patch(
+ "products.product_analytics.backend.presentation.insight_write_validation.feature_enabled_or_false",
+ return_value=True,
+ )
+ def test_rejects_a_query_the_rules_reject_once_enforced(self, _flag: Any) -> None:
+ insight_count_before = Insight.objects.count()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/insights/",
+ {"name": "Empty series", "query": {"kind": "StickinessQuery", "series": []}},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "insight_requires_at_least_one_series"
+ assert response.json()["attr"] == "query"
+ assert Insight.objects.count() == insight_count_before
+
+ @patch(
+ "products.product_analytics.backend.presentation.insight_write_validation.feature_enabled_or_false",
+ return_value=True,
+ )
+ def test_accepts_filters_the_rules_reject_when_the_stored_query_still_renders(self, _flag: Any) -> None:
+ insight_id, _ = self.dashboard_api.create_insight(
+ {
+ "name": "Insight with a query",
+ "query": {"kind": "StickinessQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},
+ }
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{insight_id}",
+ {"filters": {"insight": "TRENDS", "events": []}},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+
def test_can_list_insights_including_those_with_only_queries(self) -> None:
self.dashboard_api.create_insight({"name": "Insight with filters"})
self.dashboard_api.create_insight(
diff --git a/products/product_analytics/backend/tests/test_insight_write_validation.py b/products/product_analytics/backend/tests/test_insight_write_validation.py
new file mode 100644
index 000000000000..d02835ed52d7
--- /dev/null
+++ b/products/product_analytics/backend/tests/test_insight_write_validation.py
@@ -0,0 +1,120 @@
+from typing import Any
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from products.product_analytics.backend.presentation.insight_write_validation import (
+ InsightWriteRejection,
+ find_insight_write_rejection,
+)
+
+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,
+ )
+
+ @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)
+
+ 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),
+ ]
+ )
+ 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