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(caching): warm the cache key a dashboard with variables reads (#104169)

Sandy Spicer5b83eb1025cc
diff --git a/posthog/caching/test/test_warming.py b/posthog/caching/test/test_warming.py
index b0e971e0f43f..e9715cd9cae3 100644
--- a/posthog/caching/test/test_warming.py
+++ b/posthog/caching/test/test_warming.py
@@ -11,7 +11,7 @@ from posthog.exceptions import ClickHouseAtCapacity
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.product_analytics.backend.facade.api import record_insight_views
-from products.product_analytics.backend.facade.models import Insight
+from products.product_analytics.backend.facade.models import Insight, InsightVariable
class TestWarming(APIBaseTest):
@@ -162,10 +162,42 @@ class TestScheduleWarmingForTeamsTask(APIBaseTest):
class TestWarmInsightCacheTask(APIBaseTest):
+ def test_warms_the_cache_key_a_dashboard_with_variables_reads(self):
+ variable = InsightVariable.objects.create(
+ team=self.team, name="Limit", code_name="limit", type="Number", default_value=1
+ )
+ variable_id = str(variable.id)
+ insight = Insight.objects.create(
+ team=self.team,
+ created_by=self.user,
+ query={
+ "kind": "DataVisualizationNode",
+ "source": {
+ "kind": "HogQLQuery",
+ "query": "select {variables.limit} as n",
+ "variables": {variable_id: {"variableId": variable_id, "code_name": "limit", "value": 1}},
+ },
+ },
+ )
+ dashboard = Dashboard.objects.create(
+ team=self.team,
+ variables={variable_id: {"variableId": variable_id, "code_name": "limit", "value": 5}},
+ )
+ DashboardTile.objects.create(dashboard=dashboard, insight=insight)
+
+ warm_insight_cache_task(insight.pk, dashboard.pk)
+
+ response = self.client.get(
+ f"/api/environments/{self.team.pk}/insights/{insight.pk}/?from_dashboard={dashboard.pk}&refresh=force_cache"
+ )
+ assert response.status_code == 200, response.json()
+ assert response.json()["is_cached"] is True
+ assert response.json()["result"] == [[5]]
+
@patch("posthog.caching.warming.capture_exception")
- @patch("posthog.caching.warming.process_query_dict", side_effect=ClickHouseAtCapacity())
+ @patch("posthog.caching.warming.calculate_for_query_based_insight", side_effect=ClickHouseAtCapacity())
def test_capacity_errors_propagate_for_retry_instead_of_being_captured(
- self, mock_process_query_dict, mock_capture_exception
+ self, mock_calculate, mock_capture_exception
):
insight = Insight.objects.create(team=self.team, query={"kind": "TrendsQuery", "series": []})
@@ -176,9 +208,9 @@ class TestWarmInsightCacheTask(APIBaseTest):
@patch("posthog.caching.warming.capture_exception")
@patch("posthog.caching.warming.ph_scoped_capture")
- @patch("posthog.caching.warming.process_query_dict", side_effect=QueryError("no timestamp binding"))
+ @patch("posthog.caching.warming.calculate_for_query_based_insight", side_effect=QueryError("no timestamp binding"))
def test_query_errors_are_reported_as_an_event_instead_of_being_captured(
- self, mock_process_query_dict, mock_ph_scoped_capture, mock_capture_exception
+ self, mock_calculate, mock_ph_scoped_capture, mock_capture_exception
):
insight = Insight.objects.create(team=self.team, query={"kind": "HogQLQuery", "query": "select 1"})
capture_ph_event = mock_ph_scoped_capture.return_value.__enter__.return_value
diff --git a/posthog/caching/warming.py b/posthog/caching/warming.py
index ad8fa707fd4f..e290846e6a08 100644
--- a/posthog/caching/warming.py
+++ b/posthog/caching/warming.py
@@ -1,7 +1,7 @@
import itertools
from collections.abc import Generator
from datetime import UTC, datetime, timedelta
-from typing import Any, Optional, cast
+from typing import Optional
from django.db.models import Q
@@ -11,10 +11,9 @@ from celery import shared_task
from celery.canvas import chain
from prometheus_client import Counter, Gauge
-from posthog.hogql.constants import LimitContext
from posthog.hogql.errors import ExposedHogQLError, TableAccessDeniedError
-from posthog.api.services.query import process_query_dict
+from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.caching.utils import largest_teams
from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import Feature, get_team_query_tags, tag_queries
@@ -29,8 +28,10 @@ from posthog.query_creator_access import creator_access_revoked, report_creator_
from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
+from posthog.utils import variables_override_requested_by_client
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.facade.api import insight_variables_for_team
from products.product_analytics.backend.facade.models import Insight
logger = structlog.get_logger(__name__)
@@ -247,22 +248,28 @@ def warm_insight_cache_task(insight_id: int, dashboard_id: Optional[int]):
logger.info(f"Warming insight cache: {insight.pk} for team {insight.team_id} and dashboard {dashboard_id}")
try:
- results = process_query_dict(
- insight.team,
- cast(dict[str, Any], insight.query),
- dashboard_filters_json=dashboard.filters if dashboard is not None else None,
+ tile = dashboard.tiles.filter(insight=insight).first() if dashboard is not None else None
+ variables_override = (
+ variables_override_requested_by_client(None, dashboard, insight_variables_for_team(insight.team_id))
+ if dashboard is not None and dashboard.variables
+ else None
+ )
+ # The same call a dashboard load makes, so warming writes the cache key the page reads.
+ results = calculate_for_query_based_insight(
+ insight,
+ team=insight.team,
+ dashboard=dashboard,
# We need an execution mode with recent cache:
# - in case someone refreshed after this task was triggered
# - if insight + dashboard combinations have the same cache key, we prevent needless recalculations
- limit_context=LimitContext.QUERY_ASYNC,
execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
user=insight.created_by,
- insight_id=insight_id,
- dashboard_id=dashboard_id,
+ variables_override=variables_override,
+ tile_filters_override=tile.filters_overrides if tile is not None else None,
analytics_props={"source": EventSource.CACHE_WARMING},
)
- is_cached = getattr(results, "is_cached", False)
+ is_cached = results.is_cached
PRIORITY_INSIGHTS_COUNTER.labels(
team_id=insight.team_id,