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.

feat(product-analytics): add insight_type and source to insight usage events (#62800)

Mike Warren33545a924c48
diff --git a/ee/hogai/tools/upsert_dashboard/tool.py b/ee/hogai/tools/upsert_dashboard/tool.py
index 90c2cb65f6f6..24b4a3de96f5 100644
--- a/ee/hogai/tools/upsert_dashboard/tool.py
+++ b/ee/hogai/tools/upsert_dashboard/tool.py
@@ -279,6 +279,8 @@ class UpsertDashboardTool(MaxTool):
"insight created",
{
"insight_id": insight.short_id,
+ **insight.get_analytics_query_kinds(),
+ **insight.get_analytics_query_metadata(),
"source": EventSource.POSTHOG_AI,
},
team=self._team,
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 328d23dbef0e..31dc0fe2102d 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -349,7 +349,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
// insights
reportInsightMetadataAiGenerated: (queryKind: NodeKind) => ({ queryKind }),
reportInsightMetadataAiGenerationFailed: (queryKind: NodeKind) => ({ queryKind }),
- reportInsightCreated: (query: Node | null) => ({ query }),
+ reportInsightStarted: (query: Node | null) => ({ query }),
reportInsightSaved: (
insight: Partial<QueryBasedInsightModel> | null,
query: Node | null,
@@ -1211,11 +1211,12 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
total_properties: totalProperties,
})
},
- reportInsightCreated: async ({ query }, breakpoint) => {
- // "insight created" essentially means that the user clicked "New insight"
+ reportInsightStarted: async ({ query }, breakpoint) => {
+ // "insight started" means the user opened a blank insight editor (intent — it may never be
+ // persisted). The actual creation is tracked server-side as "insight created".
await breakpoint(500) // Debounce to avoid multiple quick "New insight" clicks being reported
- posthog.capture('insight created', { ...sanitizeQuery(query), source: 'web' })
+ posthog.capture('insight started', { ...sanitizeQuery(query), source: 'web' })
},
reportInsightMetadataAiGenerated: async ({ queryKind }) => {
posthog.capture('insight metadata ai generated', { query_kind: queryKind })
@@ -1249,6 +1250,15 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
...sanitizeQuery(query),
}
+ // The view path passes a bare source node, so sanitizeQuery's `query_kind`/`query_source_kind`
+ // describe the source rather than the wrapper. Override them from the full stored query so
+ // `query_kind` consistently means the top-level node, matching every other insight event.
+ const modelQuery = insightModel.query as Node | null | undefined
+ if (modelQuery) {
+ payload.query_kind = modelQuery.kind
+ payload.query_source_kind = isNodeWithSource(modelQuery) ? modelQuery.source.kind : undefined
+ }
+
const eventName = delay ? 'insight analyzed' : 'insight viewed'
posthog.capture(eventName, objectClean({ ...payload, source: 'web' }))
},
diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsx
index 703677345462..942e5a52c3ed 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.tsx
+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx
@@ -593,7 +593,7 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
actions.setFreshQuery(true)
}
- eventUsageLogic.actions.reportInsightCreated(query)
+ eventUsageLogic.actions.reportInsightStarted(query)
}
}
},
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 7222bf7437ba..cf194115a3ee 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -94,6 +94,31 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
dashboard_names,
)
+ @patch("products.dashboards.backend.api.dashboard.report_user_action")
+ def test_non_web_retrieve_fires_dashboard_read_event(self, mock_report_user_action: mock.Mock) -> None:
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "test"})
+ mock_report_user_action.reset_mock()
+
+ self.client.get(f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/", HTTP_X_POSTHOG_CLIENT="mcp")
+
+ mock_report_user_action.assert_any_call(
+ self.user,
+ "dashboard read",
+ {"dashboard_id": dashboard_id, "creation_mode": "default"},
+ team=ANY,
+ request=ANY,
+ )
+
+ @patch("products.dashboards.backend.api.dashboard.report_user_action")
+ def test_web_retrieve_does_not_fire_dashboard_read_event(self, mock_report_user_action: mock.Mock) -> None:
+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "test"})
+ mock_report_user_action.reset_mock()
+
+ self.client.get(f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/")
+
+ read_calls = [c for c in mock_report_user_action.call_args_list if c.args[1:2] == ("dashboard read",)]
+ self.assertEqual(read_calls, [])
+
def test_retrieve_dashboard_list_includes_other_environments(self):
other_team_in_project = Team.objects.create(organization=self.organization, project=self.project)
_, team_in_other_project = Project.objects.create_with_team(
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index e415cd85204e..09e777d7ebe4 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -871,6 +871,8 @@
'filters_hash',
'funnel',
'generate_query_metadata',
+ 'get_analytics_query_kinds',
+ 'get_analytics_query_metadata',
'get_effective_query',
'get_file_system_representation',
'get_file_system_unfiled',
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index d2107b72768e..b59ce27946ef 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -45,7 +45,7 @@ from posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSet
from posthog.api.utils import action
from posthog.clickhouse.client.async_task_chain import task_chain_context
from posthog.constants import GENERATED_DASHBOARD_PREFIX
-from posthog.event_usage import report_user_action
+from posthog.event_usage import EventSource, get_event_source, report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers import create_dashboard_from_template
from posthog.helpers.dashboard_templates import create_from_template, dashboard_template_from_creation_payload
@@ -2063,6 +2063,18 @@ class DashboardsViewSet(
data = serializer.data
response = Response(data)
+
+ # Track non-web reads (API/MCP/wizard/…) as a distinct event so programmatic
+ # reads are measurable without inflating the web-only `dashboard viewed` metric.
+ if get_event_source(request) != EventSource.WEB:
+ report_user_action(
+ request.user,
+ "dashboard read",
+ {"dashboard_id": dashboard.id, "creation_mode": dashboard.creation_mode},
+ team=self.team,
+ request=request,
+ )
+
return response
# ******************************************
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 71e53bff842a..59c2e0abdb16 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -61,7 +61,7 @@ from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import AccessMethod, tags_context
from posthog.constants import INSIGHT
from posthog.errors import ExposedCHQueryError
-from posthog.event_usage import get_request_analytics_properties, report_user_action
+from posthog.event_usage import EventSource, get_event_source, get_request_analytics_properties, report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.helpers.multi_property_breakdown import protect_old_clients_from_multi_property_default
from posthog.helpers.trigram_search import (
@@ -149,13 +149,11 @@ EXPORT_QUERY_CACHE_MISS = Counter(
def _get_insight_type(insight: Insight) -> str:
- """Return a normalized lowercase insight type string for analytics."""
+ """Return a normalized lowercase insight type string for analytics (used by the dashboard tile event)."""
if insight.query:
- # New query-based insight — source kind looks like "TrendsQuery", "FunnelsQuery", etc.
source = insight.query.get("source", insight.query)
- kind = source.get("kind", "")
+ kind = source.get("kind", "") if isinstance(source, dict) else ""
return kind.replace("Query", "").lower() if kind else "json"
- # Legacy filter-based insight
return str(insight.filters.get("insight", "TRENDS")).lower()
@@ -195,7 +193,11 @@ def log_and_report_insight_activity(
report_user_action(
user,
f"insight {activity}",
- {"insight_id": insight_short_id},
+ {
+ "insight_id": insight_short_id,
+ **insight.get_analytics_query_kinds(),
+ **insight.get_analytics_query_metadata(),
+ },
team=team,
organization=organization,
request=request,
@@ -1854,6 +1856,19 @@ When set, the specified dashboard's filters and date range override will be appl
response = Response(serialized_data)
+ # Track non-web reads (API/MCP/wizard/…) as a distinct event so programmatic
+ # reads are measurable without inflating the web-only `insight viewed` metric.
+ if get_event_source(request) != EventSource.WEB:
+ report_user_action(
+ request.user,
+ "insight read",
+ # Sibling `insight created/updated/deleted` events store the short_id under `insight_id`;
+ # match that (plus query/source kind) so reads correlate with the rest of the lifecycle.
+ {"insight_id": instance.short_id, **instance.get_analytics_query_kinds()},
+ team=self.team,
+ request=request,
+ )
+
return response
@action(methods=["GET"], detail=True)
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index f96189f0a7e7..00c49500ac39 100644
--- a/products/product_analytics/backend/api/test/test_insight.py
+++ b/products/product_analytics/backend/api/test/test_insight.py
@@ -1498,6 +1498,27 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
request=ANY,
)
+ @patch("products.product_analytics.backend.api.insight.report_user_action")
+ def test_non_web_retrieve_fires_insight_read_event(self, mock_report_user_action: mock.Mock) -> None:
+ insight_id, insight_json = self.dashboard_api.create_insight(
+ {"query": DataVisualizationNode(source=HogQLQuery(query="select 1")).model_dump()}
+ )
+ mock_report_user_action.reset_mock()
+
+ self.client.get(f"/api/projects/{self.team.id}/insights/{insight_id}", HTTP_X_POSTHOG_CLIENT="mcp")
+
+ mock_report_user_action.assert_any_call(
+ self.user,
+ "insight read",
+ {
+ "insight_id": insight_json["short_id"],
+ "query_kind": "DataVisualizationNode",
+ "query_source_kind": "HogQLQuery",
+ },
+ team=ANY,
+ request=ANY,
+ )
+
@patch("products.product_analytics.backend.api.insight.report_user_action")
def test_removing_insight_from_dashboard_fires_tile_removed_event(self, mock_report_user_action: mock.Mock) -> None:
dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "test"})
@@ -1516,6 +1537,16 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
request=ANY,
)
+ @patch("products.product_analytics.backend.api.insight.report_user_action")
+ def test_web_retrieve_does_not_fire_insight_read_event(self, mock_report_user_action: mock.Mock) -> None:
+ insight_id, _ = self.dashboard_api.create_insight({})
+ mock_report_user_action.reset_mock()
+
+ self.client.get(f"/api/projects/{self.team.id}/insights/{insight_id}")
+
+ read_calls = [c for c in mock_report_user_action.call_args_list if c.args[1:2] == ("insight read",)]
+ self.assertEqual(read_calls, [])
+
def test_can_update_insight_dashboards_without_deleting_tiles(self) -> None:
dashboard_one_id, _ = self.dashboard_api.create_dashboard({})
dashboard_two_id, _ = self.dashboard_api.create_dashboard({})
diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.py
index b5a586733a68..3e9b0e3ed214 100644
--- a/products/product_analytics/backend/models/insight.py
+++ b/products/product_analytics/backend/models/insight.py
@@ -1,5 +1,5 @@
from functools import cached_property
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Any, Optional
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
@@ -21,6 +21,20 @@ from posthog.utils import absolute_uri, generate_cache_key, generate_short_id
logger = structlog.get_logger(__name__)
+# Insight query kinds for which the rich query metadata is meaningful — mirrors the frontend
+# `sanitizeQuery` gate (isInsightVizNode || isInsightQueryNode).
+_ANALYTICS_INSIGHT_QUERY_KINDS = frozenset(
+ {
+ "TrendsQuery",
+ "FunnelsQuery",
+ "RetentionQuery",
+ "PathsQuery",
+ "StickinessQuery",
+ "LifecycleQuery",
+ "CalendarHeatmapQuery",
+ }
+)
+
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -152,6 +166,80 @@ class Insight(RootTeamMixin, FileSystemSyncMixin, models.Model):
capture_exception(e)
super().save(*args, **kwargs)
+ def get_analytics_query_kinds(self) -> dict[str, str]:
+ """
+ Top-level node kind (`query_kind`, e.g. "InsightVizNode"/"DataTableNode") and source kind
+ (`query_source_kind`, e.g. "TrendsQuery"/"HogQLQuery") for analytics, read straight off the stored
+ query. Covers every query (HogQL/table included). Reliable because the backend has the full query —
+ unlike the web view path, which passes a bare source node.
+ """
+ query = self.query if isinstance(self.query, dict) else None
+ if not query:
+ return {}
+ result: dict[str, str] = {}
+ query_kind = query.get("kind")
+ if query_kind:
+ result["query_kind"] = query_kind
+ source = query.get("source")
+ source_kind = source.get("kind") if isinstance(source, dict) else None
+ if source_kind:
+ result["query_source_kind"] = source_kind
+ return result
+
+ def get_analytics_query_metadata(self) -> dict[str, Any]:
+ """
+ Directly-readable query fields for analytics, mirroring the safe subset of the frontend
+ `sanitizeQuery`. Gated to insight-style queries (like the frontend), so HogQL/SQL/table queries
+ return ``{}``. Deliberately omits fields that depend on frontend default logic (``display``,
+ ``interval``) to avoid web↔backend value drift.
+ """
+ query = self.query if isinstance(self.query, dict) else None
+ if not query:
+ return {}
+ source = query.get("source", query)
+ if not isinstance(source, dict):
+ return {}
+ if query.get("kind") != "InsightVizNode" and source.get("kind") not in _ANALYTICS_INSIGHT_QUERY_KINDS:
+ return {}
+
+ metadata: dict[str, Any] = {}
+ series = source.get("series")
+ if isinstance(series, list):
+ metadata["series_length"] = len(series)
+ metadata["event_entity_count"] = sum(
+ 1 for s in series if isinstance(s, dict) and s.get("kind") == "EventsNode"
+ )
+ metadata["action_entity_count"] = sum(
+ 1 for s in series if isinstance(s, dict) and s.get("kind") == "ActionsNode"
+ )
+ metadata["data_warehouse_entity_count"] = sum(
+ 1 for s in series if isinstance(s, dict) and s.get("kind") == "DataWarehouseNode"
+ )
+ metadata["has_properties"] = bool(source.get("properties"))
+ if "filterTestAccounts" in source:
+ metadata["filter_test_accounts"] = source.get("filterTestAccounts")
+ breakdown_filter = source.get("breakdownFilter")
+ if isinstance(breakdown_filter, dict) and breakdown_filter.get("breakdown_type"):
+ metadata["breakdown_type"] = breakdown_filter.get("breakdown_type")
+ trends_filter = source.get("trendsFilter")
+ if isinstance(trends_filter, dict):
+ metadata["has_formula"] = bool(trends_filter.get("formula") or trends_filter.get("formulas"))
+ funnels_filter = source.get("funnelsFilter")
+ if isinstance(funnels_filter, dict):
+ if funnels_filter.get("funnelVizType"):
+ metadata["funnel_viz_type"] = funnels_filter.get("funnelVizType")
+ if funnels_filter.get("funnelOrderType"):
+ metadata["funnel_order_type"] = funnels_filter.get("funnelOrderType")
+ date_range = source.get("dateRange")
+ if isinstance(date_range, dict):
+ if date_range.get("date_from"):
+ metadata["date_from"] = date_range.get("date_from")
+ if date_range.get("date_to"):
+ metadata["date_to"] = date_range.get("date_to")
+ if source.get("samplingFactor") is not None:
+ metadata["samplingFactor"] = source.get("samplingFactor")
+ return metadata
+
@classmethod
def get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["Insight"]:
base_qs = cls.objects.filter(team=team, deleted=False, saved=True)
diff --git a/products/product_analytics/backend/models/test/test_insight_model.py b/products/product_analytics/backend/models/test/test_insight_model.py
index e5efb027f119..54e65eec04c5 100644
--- a/products/product_analytics/backend/models/test/test_insight_model.py
+++ b/products/product_analytics/backend/models/test/test_insight_model.py
@@ -269,3 +269,89 @@ class TestInsightModel(BaseTest):
team=self.team, query=test_case["query"], filters=test_case.get("filters") or {}
)
assert insight.show_legend is test_case["expected"]
+
+ def test_get_analytics_query_metadata_for_trends_query(self) -> None:
+ insight = Insight.objects.create(
+ team=self.team,
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [
+ {"kind": "EventsNode", "event": "$pageview"},
+ {"kind": "ActionsNode", "id": 1},
+ ],
+ "dateRange": {"date_from": "-7d"},
+ "filterTestAccounts": True,
+ "breakdownFilter": {"breakdown_type": "event"},
+ "trendsFilter": {"formula": "A+B"},
+ },
+ },
+ )
+ assert insight.get_analytics_query_metadata() == {
+ "series_length": 2,
+ "event_entity_count": 1,
+ "action_entity_count": 1,
+ "data_warehouse_entity_count": 0,
+ "has_properties": False,
+ "filter_test_accounts": True,
+ "breakdown_type": "event",
+ "has_formula": True,
+ "date_from": "-7d",
+ }
+
+ def test_get_analytics_query_metadata_for_funnels_query(self) -> None:
+ insight = Insight.objects.create(
+ team=self.team,
+ query={
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "FunnelsQuery",
+ "series": [{"kind": "EventsNode"}, {"kind": "EventsNode"}],
+ "funnelsFilter": {"funnelVizType": "steps", "funnelOrderType": "ordered"},
+ },
+ },
+ )
+ metadata = insight.get_analytics_query_metadata()
+ assert metadata["funnel_viz_type"] == "steps"
+ assert metadata["funnel_order_type"] == "ordered"
+ assert metadata["series_length"] == 2
+
+ @parameterized.expand(
+ [
+ ("hogql_via_data_visualization", {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery"}}),
+ ("bare_hogql", {"kind": "HogQLQuery"}),
+ ("no_query", None),
+ ]
+ )
+ def test_get_analytics_query_metadata_is_empty_for_non_insight_queries(
+ self, _name: str, query: dict | None
+ ) -> None:
+ # Non-insight queries (raw SQL/table) carry no series/breakdown/etc., so they emit only the kinds.
+ insight = Insight.objects.create(team=self.team, query=query)
+ assert insight.get_analytics_query_metadata() == {}
+
+ @parameterized.expand(
+ [
+ (
+ "wrapped_trends",
+ {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}},
+ {"query_kind": "InsightVizNode", "query_source_kind": "TrendsQuery"},
+ ),
+ (
+ "hogql_via_data_visualization",
+ {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery"}},
+ {"query_kind": "DataVisualizationNode", "query_source_kind": "HogQLQuery"},
+ ),
+ (
+ "data_table_events",
+ {"kind": "DataTableNode", "source": {"kind": "EventsQuery"}},
+ {"query_kind": "DataTableNode", "query_source_kind": "EventsQuery"},
+ ),
+ ("bare_hogql_no_source", {"kind": "HogQLQuery"}, {"query_kind": "HogQLQuery"}),
+ ("no_query", None, {}),
+ ]
+ )
+ def test_get_analytics_query_kinds(self, _name: str, query: dict | None, expected: dict) -> None:
+ insight = Insight.objects.create(team=self.team, query=query)
+ assert insight.get_analytics_query_kinds() == expected