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): refuse an update that removes an insight's query (#96058)

Thomas Obermüllerca2a9f32f89b
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 121edc618483..5d592eb7986c 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -722,12 +722,22 @@ class InsightSerializer(InsightBasicSerializer):
"Send a query object instead. See https://posthog.com/docs/api/insights"
)
- if self.instance is None and query in (None, {}):
- raise ValidationError(
- {
- "query": "Creating an insight needs a query. See https://posthog.com/docs/api/insights",
- }
- )
+ if query in (None, {}):
+ if self.instance is None:
+ raise ValidationError(
+ {
+ "query": "Creating an insight needs a query. See https://posthog.com/docs/api/insights",
+ }
+ )
+ if "query" in attrs:
+ # Writing the empty query would erase the stored definition, and nothing renders
+ # an insight without one, so the write is refused instead.
+ raise ValidationError(
+ {
+ "query": "An insight needs a query. To keep the stored one, leave query out of the "
+ "request. See https://posthog.com/docs/api/insights",
+ }
+ )
validate_insight_write(
query=query,
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index d94bbcfee06b..d0f4bfdcf6af 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -143,6 +143,21 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["attr"], "query")
+ def test_updating_an_insight_to_remove_its_query_is_rejected(self) -> None:
+ # An explicit null used to be written, which erased the stored definition.
+ insight = Insight.objects.create(
+ team=self.team,
+ name="Query insight",
+ query=default_pageview_query(),
+ )
+ stored_query = Insight.objects.get(pk=insight.pk).query
+
+ response = self.client.patch(f"/api/projects/{self.team.id}/insights/{insight.id}/", {"query": None})
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], "query")
+ self.assertEqual(Insight.objects.get(pk=insight.pk).query, stored_query)
+
def test_creating_query_insight_is_allowed(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.id}/insights/",