: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(insights): collect dashboard cache metrics (#71628)
Paul D'Ambra6f8208e93ef6
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 679fa0230028..21a16479b25f 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -49,6 +49,7 @@ from posthog.utils import get_ip_address, render_templatefrom posthog.views import preflight_checkfrom products.cohorts.backend.models.cohort import Cohort+from products.dashboards.backend.access import dashboard_access_method, record_dashboard_viewfrom products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.exports.backend.api.exports import ExportedAssetSerializer@@ -953,6 +954,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe# exported_data is embedded into the page with stdlib json.dumps, which cannot# serialize raw cached result bytes (orjson.Fragment)"require_parsed_results": True,+ "dashboard_access_method": dashboard_access_method(request, is_shared=True, is_embedded=embedded),}exported_data: dict[str, Any] = {"type": "embed" if embedded else "scene"}@@ -1060,8 +1062,7 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSeelif resource.dashboard and not resource.dashboard.deleted:asset_title = resource.dashboard.nameasset_description = resource.dashboard.description or ""- resource.dashboard.last_accessed_at = now()- resource.dashboard.save(update_fields=["last_accessed_at"])+ record_dashboard_view(resource.dashboard, context["dashboard_access_method"])with task_chain_context():dashboard_data = DashboardSerializer(resource.dashboard, context=context).datadiff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex 6879599fc566..392e1e42d4a7 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -17,6 +17,7 @@ from rest_framework import statusfrom posthog.schema import DateRange, EventPropertyFilter, EventsNode, PropertyOperator, TrendsQueryfrom posthog.api.test.dashboards import DashboardAPI+from posthog.caching.fetch_from_cache import InsightResultfrom posthog.constants import AvailableFeaturefrom posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboardfrom posthog.models import Filter, Team, User@@ -37,6 +38,7 @@ from posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold+from products.dashboards.backend.access import DashboardAccessMethodfrom products.dashboards.backend.api.dashboard import DashboardSerializerfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Text@@ -490,7 +492,10 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):def test_retrieve_dashboard(self):dashboard = Dashboard.objects.create(team=self.team, name="private dashboard", created_by=self.user)- response_data = self.dashboard_api.get_dashboard(dashboard.pk)+ with patch("products.dashboards.backend.access.record_dashboard_access") as mock_record_access:+ response_data = self.dashboard_api.get_dashboard(dashboard.pk)++ mock_record_access.assert_called_once_with(DashboardAccessMethod.HUMAN)self.assertEqual(response_data["name"], "private dashboard")self.assertEqual(response_data["description"], "")@@ -552,6 +557,36 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):dashboard.refresh_from_db()self.assertEqual(dashboard.name, "dashboard new name")+ @patch("products.product_analytics.backend.api.insight.record_dashboard_cache_outcome")+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")+ def test_update_dashboard_does_not_record_cache_outcomes(+ self,+ mock_calculate: mock.MagicMock,+ mock_record_outcome: mock.MagicMock,+ ) -> None:+ dashboard = Dashboard.objects.create(team=self.team, name="Dashboard", created_by=self.user)+ insight = Insight.objects.create(+ team=self.team,+ created_by=self.user,+ query={"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},+ )+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)+ mock_calculate.return_value = InsightResult(+ result=[],+ last_refresh=now(),+ cache_key="cache-key",+ is_cached=False,+ timezone=self.team.timezone,+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}",+ {"name": "Updated dashboard"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_record_outcome.assert_not_called()+def test_cannot_update_dashboard_with_invalid_filters(self):dashboard = Dashboard.objects.create(team=self.team,diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.pyindex a5d527d7ae70..bc3a070c88b4 100644--- a/posthog/api/test/test_sharing.py+++ b/posthog/api/test/test_sharing.py@@ -30,6 +30,7 @@ from posthog.models.share_password import SharePasswordfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.user import User+from products.dashboards.backend.access import DashboardAccessMethodfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.dashboards.backend.models.dashboard_widget import DashboardWidget@@ -47,8 +48,7 @@ def mock_exporter_template(test_func):"""@wraps(test_func)- @patch("posthog.api.sharing.render_template")- def wrapper(self, mock_render_template, *args, **kwargs):+ def wrapper(self, *args, **kwargs):def mock_render_side_effect(template_name, request, context, **kwargs):from django.http import HttpResponse@@ -80,8 +80,9 @@ def mock_exporter_template(test_func):# For non-exporter templates, return a simple responsereturn HttpResponse('<html><body>{"dashboard": "content"}</body></html>')- mock_render_template.side_effect = mock_render_side_effect- return test_func(self, *args, **kwargs)+ with patch("posthog.api.sharing.render_template") as mock_render_template:+ mock_render_template.side_effect = mock_render_side_effect+ return test_func(self, *args, **kwargs)return wrapper@@ -150,6 +151,28 @@ class TestSharing(APIBaseTest):"share_passwords": [],}+ @parameterized.expand(+ [+ ("shared", "/shared/{token}", DashboardAccessMethod.SHARED),+ ("embedded", "/embedded/{token}", DashboardAccessMethod.EMBEDDED),+ ]+ )+ @patch("products.dashboards.backend.access.record_dashboard_access")+ @mock_exporter_template+ def test_shared_dashboard_records_access_method(+ self,+ _name: str,+ path: str,+ expected_access_method: DashboardAccessMethod,+ mock_record_access: Mock,+ ) -> None:+ config = SharingConfiguration.objects.create(team=self.team, dashboard=self.dashboard, enabled=True)++ response = self.client.get(path.format(token=config.access_token))++ assert response.status_code == status.HTTP_200_OK+ mock_record_access.assert_called_once_with(expected_access_method)+@freeze_time("2022-01-01")@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")def test_does_not_change_token_when_toggling_enabled_state(self, patched_exporter_task: Mock):diff --git a/products/dashboards/backend/access.py b/products/dashboards/backend/access.pynew file mode 100644index 000000000000..641ab14a1bb2--- /dev/null+++ b/products/dashboards/backend/access.py@@ -0,0 +1,58 @@+from enum import StrEnum++from django.utils.timezone import now++from prometheus_client import Counter+from rest_framework.request import Request++from posthog.event_usage import EventSource, get_event_source++from products.dashboards.backend.models.dashboard import Dashboard+++class DashboardAccessMethod(StrEnum):+ HUMAN = "human"+ SHARED = "shared"+ EMBEDDED = "embedded"+ API = "api"+++DASHBOARD_ACCESS_COUNTER = Counter(+ "posthog_dashboard_access_total",+ "Dashboard accesses by source",+ ["access_method"],+)+DASHBOARD_CACHE_OUTCOME_COUNTER = Counter(+ "posthog_dashboard_cache_outcome_total",+ "Dashboard insight cache outcomes by access source",+ ["access_method", "result"],+)+++def dashboard_access_method(+ request: Request, *, is_shared: bool = False, is_embedded: bool = False+) -> DashboardAccessMethod:+ if is_embedded:+ return DashboardAccessMethod.EMBEDDED+ if is_shared:+ return DashboardAccessMethod.SHARED+ if get_event_source(request) == EventSource.WEB:+ return DashboardAccessMethod.HUMAN+ return DashboardAccessMethod.API+++def record_dashboard_access(access_method: DashboardAccessMethod) -> None:+ DASHBOARD_ACCESS_COUNTER.labels(access_method=access_method.value).inc()+++def record_dashboard_view(dashboard: Dashboard, access_method: DashboardAccessMethod) -> None:+ dashboard.last_accessed_at = now()+ dashboard.save(update_fields=["last_accessed_at"])+ record_dashboard_access(access_method)+++def record_dashboard_cache_outcome(access_method: DashboardAccessMethod, *, is_cached: bool) -> None:+ DASHBOARD_CACHE_OUTCOME_COUNTER.labels(+ access_method=access_method.value,+ result="hit" if is_cached else "miss",+ ).inc()diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 3dbd39bbd7d3..d85d074a1321 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -94,6 +94,7 @@ from posthog.utils import (from products.ai_observability.backend.dashboard_templates import get_ai_observability_default_templatefrom products.alerts.backend.models.alert import AlertConfiguration+from products.dashboards.backend.access import dashboard_access_method, record_dashboard_access, record_dashboard_viewfrom products.dashboards.backend.api.dashboard_template_json_schema_parser import (DashboardTemplateCreationJSONSchemaParser,)@@ -2326,9 +2327,11 @@ class DashboardsViewSet(def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:dashboard = self.get_object()- dashboard.last_accessed_at = now()- dashboard.save(update_fields=["last_accessed_at"])- serializer = DashboardSerializer(dashboard, context=self.get_serializer_context())+ access_method = dashboard_access_method(request)+ record_dashboard_view(dashboard, access_method)+ serializer_context = self.get_serializer_context()+ serializer_context["dashboard_access_method"] = access_method+ serializer = DashboardSerializer(dashboard, context=serializer_context)data = serializer.dataresponse = Response(data)@@ -2370,18 +2373,25 @@ class DashboardsViewSet(dashboard = self.get_object() # This will raise 404 if not found - let it bubble up normally# Do all database operations and data loading synchronously first- dashboard.last_accessed_at = now()- dashboard.save(update_fields=["last_accessed_at"])+ access_method = dashboard_access_method(request)+ record_dashboard_view(dashboard, access_method)++ context = self.get_serializer_context()# Prepare metadata with initial tiles- metadata_serializer = DashboardMetadataSerializer(dashboard, context=self.get_serializer_context())+ metadata_serializer = DashboardMetadataSerializer(dashboard, context=context)metadata_data = metadata_serializer.data# Create serializer context for tiles. Tiles are rendered with SafeJSONRenderer below,# so raw cached results (orjson.Fragment) are safe even though the negotiated renderer# is the SSE one.- context = self.get_serializer_context()- context.update({"dashboard": dashboard, "raw_results_supported": True})+ context.update(+ {+ "dashboard": dashboard,+ "dashboard_access_method": access_method,+ "raw_results_supported": True,+ }+ )# Get tiles with proper prefetchtiles = DashboardTile.dashboard_queryset(dashboard.tiles.all()).prefetch_related(@@ -2806,8 +2816,12 @@ class DashboardsViewSet(dashboard = self.get_object()output_format = request.query_params.get("output_format", "optimized")+ access_method = dashboard_access_method(request)+ record_dashboard_access(access_method)+context = self.get_serializer_context()context["dashboard"] = dashboard+ context["dashboard_access_method"] = access_method# _format_insight_for_llm consumes results as Python data, so raw cached# result bytes (orjson.Fragment) must not be used here.context["require_parsed_results"] = Truediff --git a/products/dashboards/backend/api/test/test_run_insights.py b/products/dashboards/backend/api/test/test_run_insights.pyindex d2e33b6c8da1..93d70cc35f8b 100644--- a/products/dashboards/backend/api/test/test_run_insights.py+++ b/products/dashboards/backend/api/test/test_run_insights.py@@ -1,6 +1,7 @@import jsonfrom posthog.test.base import APIBaseTest+from unittest.mock import patchfrom rest_framework import status@@ -10,6 +11,7 @@ from posthog.api.test.dashboards import DashboardAPIfrom posthog.models.organization import Organizationfrom posthog.models.team import Team+from products.dashboards.backend.access import DashboardAccessMethodfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Textfrom products.product_analytics.backend.models.insight import Insight@@ -39,6 +41,17 @@ class TestDashboardRunInsights(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)return response.json()+ def test_records_dashboard_access(self) -> None:+ dashboard = Dashboard.objects.create(team=self.team, name="dash")++ with patch("products.dashboards.backend.api.dashboard.record_dashboard_access") as record_access:+ body = self._run(dashboard.id, output_format="json")++ self.assertEqual(body["results"], [])+ record_access.assert_called_once_with(DashboardAccessMethod.HUMAN)+ dashboard.refresh_from_db()+ self.assertIsNone(dashboard.last_accessed_at)+def test_returns_one_result_per_insight_tile(self) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})insight_a_id, _ = self.dashboard_api.create_insight(diff --git a/products/dashboards/backend/test/test_access.py b/products/dashboards/backend/test/test_access.pynew file mode 100644index 000000000000..b502dda5984f--- /dev/null+++ b/products/dashboards/backend/test/test_access.py@@ -0,0 +1,69 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from prometheus_client import REGISTRY+from rest_framework.request import Request+from rest_framework.test import APIRequestFactory++from posthog.event_usage import EventSource++from products.dashboards.backend.access import (+ DashboardAccessMethod,+ dashboard_access_method,+ record_dashboard_access,+ record_dashboard_cache_outcome,+)+++class TestDashboardAccessMetrics:+ @parameterized.expand(+ [+ (False, False, EventSource.WEB, DashboardAccessMethod.HUMAN),+ (False, False, EventSource.API, DashboardAccessMethod.API),+ (True, False, EventSource.WEB, DashboardAccessMethod.SHARED),+ (True, True, EventSource.WEB, DashboardAccessMethod.EMBEDDED),+ ]+ )+ @patch("products.dashboards.backend.access.get_event_source")+ def test_classifies_dashboard_access(+ self,+ is_shared: bool,+ is_embedded: bool,+ event_source: EventSource,+ expected: DashboardAccessMethod,+ mock_get_event_source: MagicMock,+ ) -> None:+ request = Request(APIRequestFactory().get("/"))+ mock_get_event_source.return_value = event_source++ assert dashboard_access_method(request, is_shared=is_shared, is_embedded=is_embedded) == expected++ @parameterized.expand([(access_method,) for access_method in DashboardAccessMethod])+ def test_records_dashboard_access(self, access_method: DashboardAccessMethod) -> None:+ labels = {"access_method": access_method.value}+ before = REGISTRY.get_sample_value("posthog_dashboard_access_total", labels) or 0++ record_dashboard_access(access_method)++ assert REGISTRY.get_sample_value("posthog_dashboard_access_total", labels) == before + 1++ @parameterized.expand(+ [+ (DashboardAccessMethod.HUMAN, True, "hit"),+ (DashboardAccessMethod.SHARED, False, "miss"),+ (DashboardAccessMethod.EMBEDDED, False, "miss"),+ (DashboardAccessMethod.API, True, "hit"),+ ]+ )+ def test_records_dashboard_cache_outcome(+ self,+ access_method: DashboardAccessMethod,+ is_cached: bool,+ expected_result: str,+ ) -> None:+ labels = {"access_method": access_method.value, "result": expected_result}+ before = REGISTRY.get_sample_value("posthog_dashboard_cache_outcome_total", labels) or 0++ record_dashboard_cache_outcome(access_method, is_cached=is_cached)++ assert REGISTRY.get_sample_value("posthog_dashboard_cache_outcome_total", labels) == before + 1diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex 80dc8ba01216..95cdba7c4ddc 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -141,6 +141,11 @@ from posthog.utils import (from products.alerts.backend.models.alert import AlertConfigurationfrom products.cohorts.backend.models.cohort import Cohort+from products.dashboards.backend.access import (+ DashboardAccessMethod,+ dashboard_access_method,+ record_dashboard_cache_outcome,+)from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.product_analytics.backend.api.insight_metadata import (@@ -1287,7 +1292,7 @@ class InsightSerializer(InsightBasicSerializer):and not self.context.get("require_parsed_results"))with tags_context(product=ProductKey.PRODUCT_ANALYTICS, feature=Feature.INSIGHT, **shared_tags):- return calculate_for_query_based_insight(+ insight_result = calculate_for_query_based_insight(insight,team=self.context["get_team"](),dashboard=dashboard,@@ -1301,6 +1306,21 @@ class InsightSerializer(InsightBasicSerializer):analytics_props=get_request_analytics_properties(self.context["request"]),allow_raw_results=allow_raw_results,)+ access_method: DashboardAccessMethod | None = self.context.get("dashboard_access_method")+ if (+ dashboard is not None+ and access_method is not None+ and execution_mode+ not in {+ ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ ExecutionMode.CALCULATE_ASYNC_ALWAYS,+ }+ ):+ record_dashboard_cache_outcome(+ access_method,+ is_cached=insight_result.is_cached,+ )+ return insight_resultexcept (ExposedHogQLError, ExposedCHQueryError, HogVMException) as e:raise ValidationError(str(e), getattr(e, "code_name", None))except ConcurrencyLimitExceeded as e:@@ -2116,7 +2136,14 @@ When set, the specified dashboard's filters and date range override will be applif dashboard_tile is not None:# context is used in the to_representation method to report filters used- serializer_context.update({"dashboard": dashboard_tile.dashboard})+ serializer_context.update(+ {+ "dashboard": dashboard_tile.dashboard,+ "dashboard_access_method": dashboard_access_method(+ request, is_shared=serializer_context["is_shared"]+ ),+ }+ )try:serialized_data = self.get_serializer(instance, context=serializer_context).datadiff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex 77c28f123e5b..cb21871d0375 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -47,6 +47,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog import settingsfrom posthog.api.test.dashboards import DashboardAPI+from posthog.caching.fetch_from_cache import InsightResultfrom posthog.constants import AvailableFeaturefrom posthog.hogql_queries.query_runner import SHARED_FORCE_BLOCKING_STALENESS_WINDOW, ExecutionModefrom posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, User@@ -56,6 +57,7 @@ from posthog.test.persons import create_personfrom products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Thresholdfrom products.cohorts.backend.models.cohort import Cohort+from products.dashboards.backend.access import DashboardAccessMethodfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Textfrom products.product_analytics.backend.models.insight import Insight, InsightViewed@@ -494,6 +496,50 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertNotEqual(insight_in_isolation["filters_hash"], insight_on_dashboard["filters_hash"])+ @parameterized.expand(+ [+ ("hit", True, None, True),+ ("miss", False, None, True),+ ("forced_refresh", False, "force_blocking", False),+ ]+ )+ @patch("products.product_analytics.backend.api.insight.record_dashboard_cache_outcome")+ @patch("posthog.caching.calculate_results.calculate_for_query_based_insight")+ def test_dashboard_insight_records_cache_outcome(+ self,+ _name: str,+ is_cached: bool,+ refresh: str | None,+ expect_recorded: bool,+ mock_calculate: mock.MagicMock,+ mock_record_outcome: mock.MagicMock,+ ) -> None:+ dashboard = Dashboard.objects.create(team=self.team, name="Dashboard", created_by=self.user)+ insight = Insight.objects.create(+ team=self.team,+ created_by=self.user,+ query={"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},+ )+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)+ mock_calculate.return_value = InsightResult(+ result=[],+ last_refresh=timezone.now(),+ cache_key="cache-key",+ is_cached=is_cached,+ timezone=self.team.timezone,+ )++ query_params = {"from_dashboard": str(dashboard.id)}+ if refresh is not None:+ query_params["refresh"] = refresh+ response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight.id}/", query_params)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ if expect_recorded:+ mock_record_outcome.assert_called_once_with(DashboardAccessMethod.HUMAN, is_cached=is_cached)+ else:+ mock_record_outcome.assert_not_called()+def test_get_insight_in_shared_context(self) -> None:filter_dict = {"events": [{"id": "$pageview"}],@@ -511,9 +557,12 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):valid_url = f"{settings.SITE_URL}/shared/{sharing_config.access_token}"- with patch(- "posthog.caching.calculate_results.calculate_for_query_based_insight"- ) as calculate_for_query_based_insight:+ with (+ patch(+ "posthog.caching.calculate_results.calculate_for_query_based_insight"+ ) as calculate_for_query_based_insight,+ patch("products.product_analytics.backend.api.insight.record_dashboard_cache_outcome") as record_outcome,+ ):self.client.get(valid_url)calculate_for_query_based_insight.assert_called_once_with(mock.ANY,@@ -529,6 +578,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):analytics_props=ANY,allow_raw_results=False,)+ record_outcome.assert_not_called()with patch("posthog.caching.calculate_results.calculate_for_query_based_insight"