: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(caching): expose cache version consumption telemetry (#106559)
Vasco de Krijger38b5d6ac3cd2
diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.pyindex e9715cd9cae3..a5120f87a415 100644--- a/posthog/caching/test/test_warming.py+++ b/posthog/caching/test/test_warming.py@@ -1,7 +1,7 @@from datetime import UTC, datetime, timedeltafrom posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom posthog.hogql.errors import QueryError@@ -129,6 +129,22 @@ class TestScheduleWarmingForTeamsTask(APIBaseTest):self.team1 = self.create_team_with_organization(organization=self.organization)self.team2 = self.create_team_with_organization(organization=self.organization)+ @patch("posthog.caching.warming.chain")+ @patch("posthog.caching.warming.ph_scoped_capture")+ @patch("posthog.caching.warming.teams_enabled_for_cache_warming", return_value=[])+ @patch("posthog.caching.warming.largest_teams")+ @patch("posthog.caching.warming.insights_to_keep_fresh")+ def test_reports_selected_contexts_separately(+ self, candidates: MagicMock, teams: MagicMock, _enabled: MagicMock, capture: MagicMock, _chain: MagicMock+ ) -> None:+ teams.return_value = [self.team1.pk]+ candidates.return_value = iter([(1234, None), (1234, 5678), (2345, 5678)])+ schedule_warming_for_teams_task()+ properties = capture.return_value.__enter__.return_value.call_args.kwargs["properties"]+ assert properties["count"] == 3+ assert properties["standalone_count"] == 1+ assert properties["dashboard_count"] == 2+@patch("posthog.caching.warming.largest_teams")@patch("posthog.caching.warming.insights_to_keep_fresh")@patch("posthog.caching.warming.warm_insight_cache_task.si")diff --git a/posthog/caching/warming.py b/posthog/caching/warming.pyindex e290846e6a08..dfd69cd1c74a 100644--- a/posthog/caching/warming.py+++ b/posthog/caching/warming.py@@ -196,6 +196,8 @@ def schedule_warming_for_teams_task():event="cache warming - insights to cache",properties={"count": len(insight_tuples),+ "standalone_count": sum(dashboard_id is None for _, dashboard_id in insight_tuples),+ "dashboard_count": sum(dashboard_id is not None for _, dashboard_id in insight_tuples),"team_id": team.id,"organization_id": team.organization_id,"shared_only": shared_only,diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 2ebb1a0c87b0..e2624660267b 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -351,6 +351,7 @@ class QueryRun:"execution_mode": self.execution_mode.value,"query_type": self.query_type,"cache_key": self.cache_key,+ "request_trigger": self.trigger,}@@ -2852,6 +2853,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):# validation is a failed run that published nothing.response = CachedResponse(**fresh_response_dict)+ stored = Falseif cacheable:with self.timings.measure("cache_write"):stored = cache_manager.store_result(@@ -2878,6 +2880,8 @@ class QueryRunner(ABC, Generic[Q, R, CR]):query_executed_props = {**query_run.event_properties(),"cache_hit": False,+ "last_refresh": last_refresh.isoformat(),+ "cache_write_success": stored,"cache_age_override": getattr(self, "_cache_age_override", None),"calculation_trigger": query_run.trigger,"response_time_ms": query_run.elapsed_ms(),diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.pyindex df67cb53fb98..5b618327d070 100644--- a/posthog/hogql_queries/test/test_query_runner.py+++ b/posthog/hogql_queries/test/test_query_runner.py@@ -475,6 +475,47 @@ class TestQueryRunner(BaseTest):validation_rule.validate.assert_called_once_with(runner.validation_context)mock_calculate.assert_not_called()+ def test_cached_consumption_identifies_the_producer_and_current_caller(self) -> None:+ Runner = self.setup_test_query_runner_class()+ runner = Runner(query={"some_attr": "warming-consumption"}, team=self.team)+ with mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report:+ with mock.patch("posthog.hogql_queries.query_runner.get_query_tag_value", return_value="warmingV2"):+ first_response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ produced = report.call_args.args[1]+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)+ warmer_hit = report.call_args.args[1]+ with mock.patch("posthog.hogql_queries.query_runner.get_query_tag_value", return_value=None):+ runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)+ consumed = report.call_args.args[1]+ with time_machine.travel(datetime.now(UTC) + timedelta(hours=1), tick=False):+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ replacement = report.call_args.args[1]++ assert replacement["cache_key"] == produced["cache_key"]+ assert replacement["last_refresh"] != produced["last_refresh"]+ assert produced["cache_write_success"] is True+ assert produced["last_refresh"] == first_response.last_refresh.isoformat()+ assert consumed["cache_hit"] is True+ assert consumed["cache_key"] == produced["cache_key"]+ assert consumed["last_refresh"] == produced["last_refresh"]+ assert consumed["calculation_trigger"] == "warmingV2"+ assert consumed["request_trigger"] is None+ assert warmer_hit["request_trigger"] == "warmingV2"++ @parameterized.expand([("failed_write", LimitContext.QUERY), ("uncached_export", LimitContext.EXPORT)])+ def test_failed_cache_write_is_not_reported_as_a_warmed_version(+ self, _name: str, limit_context: LimitContext+ ) -> None:+ Runner = self.setup_test_query_runner_class()+ runner = Runner(query={"some_attr": "cache-write-failure"}, team=self.team, limit_context=limit_context)+ with (+ mock.patch("posthog.hogql_queries.query_runner.QueryCache.store_result", return_value=False),+ mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report,+ ):+ response = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ assert report.call_args.args[1]["cache_write_success"] is False+ assert report.call_args.args[1]["last_refresh"] == response.last_refresh.isoformat()+def test_fresh_run_reports_its_own_phase_times_on_the_query_executed_event(self) -> None:TestQueryRunner = self.setup_test_query_runner_class()runner = TestQueryRunner(query={"some_attr": "bla"}, team=self.team)