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): auto-wrap bare query sources saved via the REST API (#73333)

Thomas Obermüllera9f6638fa7b3
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index d68216be16e1..31fd5b038117 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -548,6 +548,22 @@ class QueryFieldSerializer(serializers.Serializer):
return data
+# Bare query sources that only render inside an InsightVizNode. The UI (Query.tsx) routes
+# wrapper nodes and a few standalone kinds (e.g. WebOverviewQuery) to real renderers; the
+# kinds below have no bare renderer and fall through to a JSON-dump fallback that paints
+# ~0px inside a dashboard tile, so they are safe (and necessary) to auto-wrap on save.
+AUTO_WRAPPED_INSIGHT_QUERY_KINDS = frozenset(
+ {
+ "TrendsQuery",
+ "FunnelsQuery",
+ "RetentionQuery",
+ "PathsQuery",
+ "StickinessQuery",
+ "LifecycleQuery",
+ }
+)
+
+
class InsightFilterOverrideContext(BaseModel):
dashboard: schema.DashboardFilter | None = PydanticField(
default=None, description="Dashboard filters that remain active after applying tile precedence."
@@ -713,6 +729,30 @@ class InsightSerializer(InsightBasicSerializer):
return super().validate(attrs)
+ def validate_query(self, value: dict[str, Any] | None) -> dict[str, Any] | None:
+ """Auto-wrap bare query sources in the wrapper node the UI renders.
+
+ Bare sources save and execute fine, but the UI only routes wrapper nodes to chart
+ renderers, so unwrapped queries show up as blank tiles. Everything else passes
+ through untouched: already-wrapped nodes must round-trip verbatim, and payloads we
+ don't positively recognize keep today's accept-as-is behavior — hard rejection
+ stays MCP-only (see MCPInsightSerializer).
+ """
+ if not value:
+ return value
+ try:
+ if value.get("kind") == "HogQLQuery":
+ return schema.DataVisualizationNode(source=schema.HogQLQuery.model_validate(value)).model_dump(
+ exclude_none=True, mode="json"
+ )
+ if value.get("kind") in AUTO_WRAPPED_INSIGHT_QUERY_KINDS:
+ return schema.InsightVizNode.model_validate({"kind": "InsightVizNode", "source": value}).model_dump(
+ exclude_none=True, mode="json"
+ )
+ except PydanticValidationError:
+ pass
+ return value
+
@monitor(feature=Feature.INSIGHT, endpoint="insight", method="POST")
def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> Insight:
request = self.context["request"]
@@ -1438,7 +1478,7 @@ class MCPInsightSerializer(InsightSerializer):
raise serializers.ValidationError({"query": "This field is required."})
return super().validate(attrs)
- def validate_query(self, value: dict[str, Any]) -> dict[str, Any]:
+ def validate_query(self, value: dict[str, Any] | None) -> dict[str, Any]:
# Raw HogQL → DataVisualizationNode
try:
return schema.DataVisualizationNode(source=schema.HogQLQuery.model_validate(value)).model_dump(
diff --git a/products/product_analytics/backend/api/test/test_insight_query.py b/products/product_analytics/backend/api/test/test_insight_query.py
index 58dbc0f198f7..9bb0ef53fdd9 100644
--- a/products/product_analytics/backend/api/test/test_insight_query.py
+++ b/products/product_analytics/backend/api/test/test_insight_query.py
@@ -201,6 +201,104 @@ class TestInsight(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest, QueryMatc
listed_insights = self.dashboard_api.list_insights()
assert listed_insights["count"] == 2
+ @parameterized.expand(
+ [
+ (
+ "bare_trends_query",
+ {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "name": "$pageview"}],
+ "dateRange": {"date_from": "-7d"},
+ "interval": "day",
+ },
+ "InsightVizNode",
+ "TrendsQuery",
+ ),
+ (
+ "bare_hogql_query",
+ {"kind": "HogQLQuery", "query": "select event from events limit 1"},
+ "DataVisualizationNode",
+ "HogQLQuery",
+ ),
+ ]
+ )
+ def test_create_wraps_bare_query_sources(self, _name, query, expected_kind, expected_source_kind) -> None:
+ insight_id, insight_json = self.dashboard_api.create_insight({"name": "Bare query insight", "query": query})
+
+ assert insight_json["query"]["kind"] == expected_kind
+ stored_query = Insight.objects.get(pk=insight_id).query
+ assert stored_query is not None
+ assert stored_query["kind"] == expected_kind
+ assert stored_query["source"]["kind"] == expected_source_kind
+
+ @parameterized.expand(
+ [
+ (
+ "already_wrapped_insight_viz_node",
+ {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "name": "$pageview"}],
+ "dateRange": {"date_from": "-7d"},
+ "interval": "day",
+ },
+ "showTable": True,
+ },
+ ),
+ (
+ "bare_web_overview_query_rendered_unwrapped_by_the_ui",
+ {"kind": "WebOverviewQuery", "properties": [], "dateRange": {"date_from": "-7d"}},
+ ),
+ (
+ "query_kind_without_an_insight_renderer",
+ {
+ "kind": "ErrorTrackingQuery",
+ "dateRange": {"date_from": "-7d"},
+ "orderBy": "last_seen",
+ "volumeResolution": 60,
+ },
+ ),
+ ]
+ )
+ def test_create_stores_non_bare_queries_verbatim(self, _name, query) -> None:
+ insight_id, _ = self.dashboard_api.create_insight({"name": "Verbatim query insight", "query": query})
+
+ assert Insight.objects.get(pk=insight_id).query == query
+
+ def test_update_wraps_bare_query_sources(self) -> None:
+ insight_id, _ = self.dashboard_api.create_insight(
+ {
+ "name": "Insight to update",
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "name": "$pageview"}],
+ },
+ },
+ }
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/insights/{insight_id}",
+ {
+ "query": {
+ "kind": "FunnelsQuery",
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview", "name": "$pageview"},
+ {"kind": "EventsNode", "event": "$pageleave", "name": "$pageleave"},
+ ],
+ }
+ },
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ stored_query = Insight.objects.get(pk=insight_id).query
+ assert stored_query is not None
+ assert stored_query["kind"] == "InsightVizNode"
+ assert stored_query["source"]["kind"] == "FunnelsQuery"
+
@parameterized.expand(
[
(