: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
fix(web-analytics): warm precompute via calculate() to bypass 6h result cache (#62787)
Lucas Ricoy40530ba44bef
diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.pyindex d0c9c73f002c..1af5e13f67a8 100644--- a/products/web_analytics/dags/eager_web_analytics_precompute.py+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py@@ -4,11 +4,24 @@ A single Dagster job that pre-warms the lazy precompute cache for theWeb analytics dashboard's main tile matrix over the trailing 28 days,for every team in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` setting.-The job is intentionally thin: it enumerates the dashboard's query-families and dispatches each through `get_query_runner(...).run(...)`.-The runner routes through its family's lazy precompute path, which-already knows what's stale and INSERTs only what's missing. This DAG is-the *trigger*; the runner is the source of truth for freshness.+The job is intentionally thin: it enumerates the dashboard's query families+and dispatches each through `get_query_runner(...).run(...)` in force-refresh+mode (`ExecutionMode.CALCULATE_BLOCKING_ALWAYS`). The runner routes through+its family's lazy precompute path, which already knows what's stale and+INSERTs only what's missing. This DAG is the *trigger*; the runner is the+source of truth for freshness.++Force-refresh is used deliberately. The DEFAULT execution mode gates on the+HogQL query result cache (6h staleness), which is the wrong clock for a+precompute warmer whose buckets expire on a much shorter TTL (15min for+today's bucket) — it would skip tiles whose Redis result is still "fresh"+while the precompute they feed has gone cold. Force-refresh always recomputes,+so every tick re-enters the precompute path. Crucially it goes through `run()`+(not a bare `calculate()`), so the warm stays inside the same rate-limit and+concurrency wrappers (`_call_with_rate_limits`) as user traffic — the warmer+must not pile unthrottled ClickHouse work on top of a saturated cluster. It+also refreshes the (no-user) result-cache entry as a side effect, which is+harmless; the user-facing replay warming is `cache_warming.py`'s job.Why this exists---------------@@ -52,7 +65,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.cloud_utils import is_cloudfrom posthog.dags.common import JobOwnersfrom posthog.event_usage import EventSource-from posthog.hogql_queries.query_runner import get_query_runner+from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runnerfrom posthog.models import Teamfrom products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_precompute_enabled_for_team@@ -124,6 +137,13 @@ EAGER_PRECOMPUTE_NOT_LAZY_ELIGIBLE = Counter("Teams skipped by the eager warmer because they are not lazy-precompute eligible ""(the gate would route every tile through the raw path).",)+EAGER_PRECOMPUTE_BASELINE_NOT_PRECOMPUTED = Counter(+ "web_analytics_eager_precompute_baseline_not_precomputed_total",+ "Baseline queries that ran but did NOT resolve to a precompute read (fell through "+ "to raw) — the precompute the warmer should keep fresh is stale, missing, or the "+ "breakdown isn't precomputable. Labeled by query kind.",+ ["query_kind"],+)def _resolve_eager_audience() -> tuple[list[int], str, dict]:@@ -217,9 +237,33 @@ def _warm_baseline_for_team(context: dagster.OpExecutionContext, team: Team) ->product=Product.WEB_ANALYTICS,)runner = get_query_runner(query=query, team=team, limit_context=LimitContext.QUERY_ASYNC)- runner.run(analytics_props={"source": EventSource.CACHE_WARMING})+ # Force-refresh via run() — see module docstring (recomputes every tick+ # while staying inside run()'s rate-limit/concurrency wrappers).+ response = runner.run(+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS,+ analytics_props={"source": EventSource.CACHE_WARMING},+ )EAGER_PRECOMPUTE_BASELINE_WARMED.labels(query_kind=label).inc()warmed += 1+ # Self-check the warm actually did its job: the tile must resolve to a+ # precompute read, not fall through to raw. `usedLazyPrecompute` is only+ # True when the read passed the lazy executor's TTL freshness filter+ # (`created_at + TTL >= now`, TTL = 15min today … 7d old), so True is a+ # guarantee the precomputed value is well within the 2h threshold. A tile+ # that comes back `not True` warmed nothing useful — surface it loudly so a+ # stale/missing precompute or a non-precomputable breakdown can't hide.+ if getattr(response, "usedLazyPrecompute", None) is not True:+ EAGER_PRECOMPUTE_BASELINE_NOT_PRECOMPUTED.labels(query_kind=label).inc()+ context.log.warning(+ f"eager_baseline_warming_tile_not_precomputed [{idx}/{total}] team={team.pk} query={label}"+ )+ logger.warning(+ "eager_baseline_warming_tile_not_precomputed",+ team_id=team.pk,+ query=label,+ tile=idx,+ total=total,+ )tile_ms = round((time.monotonic() - tile_started) * 1000)context.log.info(f"eager_baseline_warming_tile_done [{idx}/{total}] team={team.pk} query={label} "diff --git a/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py b/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.pyindex 77f0ad893fe6..dfc2f91d8c27 100644--- a/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py+++ b/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py@@ -12,6 +12,7 @@ from structlog.testing import capture_logsfrom posthog.schema import WebStatsBreakdown+from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models import Organization, Teamfrom products.web_analytics.dags.eager_web_analytics_precompute import (@@ -74,7 +75,7 @@ class TestWarmEagerBaselineOp(APIBaseTest):t1, t2 = self._enroll_teams(count=2)ok_runner = Mock()- ok_runner.run.return_value = None+ ok_runner.run.return_value = Mock(usedLazyPrecompute=True)bad_runner = Mock()bad_runner.run.side_effect = RuntimeError("boom")@@ -124,7 +125,7 @@ class TestWarmBaselineForTeam(APIBaseTest):@patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")def test_warms_full_matrix(self, get_runner, tag_queries_mock):runner = Mock()- runner.run.return_value = None+ runner.run.return_value = Mock(usedLazyPrecompute=True)get_runner.return_value = runnerwarmed, failed = _warm_baseline_for_team(Mock(spec=dagster.OpExecutionContext), self.team)@@ -132,6 +133,27 @@ class TestWarmBaselineForTeam(APIBaseTest):assert warmed == _QUERIES_PER_TEAMassert failed == 0assert runner.run.call_count == _QUERIES_PER_TEAM+ # Force-refresh, not the default mode: the default respects the 6h result-cache+ # staleness and would skip warming while the precompute goes cold. Force-blocking+ # also keeps the warm inside run()'s rate-limit wrappers (vs a bare calculate()).+ for call in runner.run.call_args_list:+ assert call.kwargs["execution_mode"] == ExecutionMode.CALCULATE_BLOCKING_ALWAYS++ @patch("products.web_analytics.dags.eager_web_analytics_precompute.tag_queries")+ @patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")+ def test_flags_tiles_that_do_not_resolve_to_precompute(self, get_runner, tag_queries_mock):+ # A tile whose calculate() does not come back with usedLazyPrecompute=True fell+ # through to raw — the warm populated no fresh precompute. It still counts as+ # "warmed" (it ran without error) but must be surfaced as not-precomputed.+ get_runner.return_value = Mock(run=Mock(return_value=Mock(usedLazyPrecompute=None)))++ with capture_logs() as cap_logs:+ warmed, failed = _warm_baseline_for_team(Mock(spec=dagster.OpExecutionContext), self.team)++ assert warmed == _QUERIES_PER_TEAM+ assert failed == 0+ not_precomputed = [log for log in cap_logs if log.get("event") == "eager_baseline_warming_tile_not_precomputed"]+ assert len(not_precomputed) == _QUERIES_PER_TEAM@patch("products.web_analytics.dags.eager_web_analytics_precompute.tag_queries")@patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")@@ -142,7 +164,7 @@ class TestWarmBaselineForTeam(APIBaseTest):def capture(query, team, limit_context):captured.append(query)- return Mock(run=Mock())+ return Mock(run=Mock(return_value=Mock(usedLazyPrecompute=True)))get_runner.side_effect = capture_warm_baseline_for_team(Mock(spec=dagster.OpExecutionContext), self.team)@@ -190,7 +212,7 @@ class TestWarmBaselineForTeam(APIBaseTest):def record_get_runner(**kwargs):call_order.append("get_runner")- return Mock(run=Mock())+ return Mock(run=Mock(return_value=Mock(usedLazyPrecompute=True)))tag_queries_mock.side_effect = record_tagget_runner.side_effect = record_get_runner@@ -213,7 +235,7 @@ class TestEagerBaselineLogging(APIBaseTest):@patch("products.web_analytics.dags.eager_web_analytics_precompute.tag_queries")@patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")def test_emits_structured_lifecycle_events_on_success(self, get_runner, _tag, _is_cloud):- get_runner.return_value = Mock(run=Mock(return_value=None))+ get_runner.return_value = Mock(run=Mock(return_value=Mock(usedLazyPrecompute=True)))with _eager_audience([self.team.pk]), capture_logs() as cap_logs:warm_eager_baseline_op(dagster.build_op_context())