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(web-analytics): widen warming replays only for lazy-eligible shapes (#72789)

Lucas Ricoy73ecfc962aa5
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index 170d29c1f9e1..0d2bbd45f012 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -1,6 +1,7 @@
import re
import json
import statistics
+from typing import TYPE_CHECKING, Optional
from django.utils.dateparse import parse_datetime
@@ -22,9 +23,30 @@ from posthog.models.instance_setting import get_instance_setting
from posthog.settings import CLICKHOUSE_CLUSTER
from products.analytics_platform.backend.lazy_computation.stale_policy import SHARED_BACKGROUND_WARMING_TRIGGERS
+from products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import (
+ can_use_lazy_precompute as can_use_goals_lazy_precompute,
+)
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import BACKGROUND_WARMING_TRIGGERS
+from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (
+ can_use_lazy_precompute as can_use_overview_lazy_precompute,
+)
+from products.web_analytics.backend.hogql_queries.web_stats_frustration_lazy_precompute import (
+ can_use_lazy_precompute as can_use_frustration_lazy_precompute,
+)
+from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import (
+ can_use_lazy_precompute as can_use_stats_lazy_precompute,
+)
+from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import (
+ can_use_lazy_precompute as can_use_paths_lazy_precompute,
+)
+from products.web_analytics.backend.hogql_queries.web_vitals_paths_lazy_precompute import (
+ can_use_lazy_precompute as can_use_vitals_paths_lazy_precompute,
+)
from products.web_analytics.dags.web_preaggregated_utils import check_for_concurrent_runs
+if TYPE_CHECKING:
+ from posthog.hogql_queries.query_runner import QueryRunner
+
WARMING_SHAPES_SELECTED_GAUGE = Gauge(
"posthog_web_analytics_warming_shapes_selected",
"Number of hot query shapes selected for web analytics warming in the last run",
@@ -140,6 +162,49 @@ def maybe_expand_warming_date_range(query_json: dict) -> dict:
return {**query_json, "dateRange": {**date_range, "date_from": WARMING_EXPANDED_DATE_FROM}}
+# Family-level eligibility dispatch, mirroring each runner's own lazy-path
+# entry points (stats_table tries three families; a shape is lazy-served iff
+# any accepts). Keyed by query kind — only LAZY_PRECOMPUTE_QUERY_KINDS appear.
+_LAZY_FAMILY_CHECKS: dict[str, tuple] = {
+ "WebOverviewQuery": (can_use_overview_lazy_precompute,),
+ "WebStatsTableQuery": (
+ can_use_paths_lazy_precompute,
+ can_use_frustration_lazy_precompute,
+ can_use_stats_lazy_precompute,
+ ),
+ "WebGoalsQuery": (can_use_goals_lazy_precompute,),
+ "WebVitalsPathBreakdownQuery": (can_use_vitals_paths_lazy_precompute,),
+}
+
+
+def build_replay_runner(team: Team, query_json: dict) -> tuple[Optional["QueryRunner"], dict]:
+ """Build the runner for a warming replay, widening the date range only for
+ shapes the lazy path will actually serve.
+
+ The per-query opt-in does not guarantee the lazy path: shapes the gates
+ reject (conversion goals, sampling, unsupported breakdowns/metrics like
+ bounce rate, …) execute on the raw path, where a widened replay would be a
+ 30-day scan the tenant never ran — background load outside their request
+ throttles, mintable up to MAX_SHAPES_PER_TEAM per hour. Those shapes replay
+ with their faithful original range instead. Eligibility is decided by the
+ same per-family `can_use_lazy_precompute` dispatch the runner uses, so this
+ check and execution can't disagree. Under the warming tag the enrollment
+ gate is bypassed by design — building buckets for not-yet-enrolled teams is
+ the warmer's purpose — so the decision rests on the shape itself.
+ """
+ expanded_json = maybe_expand_warming_date_range(query_json)
+ if expanded_json is query_json:
+ return get_query_runner_or_none(query=query_json, team=team, limit_context=LimitContext.QUERY_ASYNC), query_json
+
+ runner = get_query_runner_or_none(query=expanded_json, team=team, limit_context=LimitContext.QUERY_ASYNC)
+ if runner is None:
+ return None, expanded_json
+ family_checks = _LAZY_FAMILY_CHECKS.get(expanded_json.get("kind", ""), ())
+ if any(check(runner) for check in family_checks):
+ return runner, expanded_json
+ return get_query_runner_or_none(query=query_json, team=team, limit_context=LimitContext.QUERY_ASYNC), query_json
+
+
def queries_to_keep_fresh(
context: dagster.OpExecutionContext, days: int = 2, minimum_query_count: int = 10, max_shapes: int = 20000
) -> list[dict]:
@@ -289,16 +354,11 @@ def warm_queries_op(context: dagster.OpExecutionContext, queries: list[dict]) ->
tag_queries(team_id=team_id, trigger="webAnalyticsQueryWarming", feature=Feature.CACHE_WARMUP)
query_json = maybe_opt_into_lazy_precompute(query_json)
- query_json = maybe_expand_warming_date_range(query_json)
# None only for kinds without a get_query_runner branch — the backstop
# for runnerless kinds the selection doesn't know to exclude yet.
# Validation errors on supported kinds still raise into the failure path.
- runner = get_query_runner_or_none(
- query=query_json,
- team=team,
- limit_context=LimitContext.QUERY_ASYNC,
- )
+ runner, query_json = build_replay_runner(team, query_json)
if runner is None:
WARMING_QUERIES_COUNTER.labels(outcome="unsupported").inc()
queries_unsupported += 1
diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.py
index 787c2db6ffd5..68b6a4f775f8 100644
--- a/products/web_analytics/dags/tests/test_cache_warming.py
+++ b/products/web_analytics/dags/tests/test_cache_warming.py
@@ -4,7 +4,10 @@ from unittest.mock import MagicMock, patch
import dagster
from parameterized import parameterized
+from posthog.clickhouse.query_tagging import Feature, reset_query_tags, tag_queries
+
from products.web_analytics.dags.cache_warming import (
+ build_replay_runner,
get_warmable_queries_op,
maybe_expand_warming_date_range,
maybe_opt_into_lazy_precompute,
@@ -93,6 +96,77 @@ class TestMaybeExpandWarmingDateRange(BaseTest):
self.assertEqual(maybe_expand_warming_date_range(query), query)
+class TestBuildReplayRunner(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The warm op tags before building runners; the enrollment gate treats
+ # tagged warming requests as enabled, so tests must run under the same
+ # tags to exercise the production decision.
+ tag_queries(team_id=self.team.pk, trigger="webAnalyticsQueryWarming", feature=Feature.CACHE_WARMUP)
+
+ def tearDown(self) -> None:
+ reset_query_tags()
+ super().tearDown()
+
+ def test_lazy_eligible_shape_keeps_widened_range(self) -> None:
+ # Under the warming tag even a non-enrolled team widens: building
+ # buckets for not-yet-enrolled teams is the warmer's purpose.
+ query = {
+ "kind": "WebOverviewQuery",
+ "properties": [],
+ "useWebAnalyticsPrecompute": True,
+ "dateRange": {"date_from": "-7d"},
+ }
+
+ runner, used_json = build_replay_runner(self.team, query)
+
+ self.assertIsNotNone(runner)
+ self.assertEqual(used_json["dateRange"]["date_from"], "-30d")
+
+ @parameterized.expand(
+ [
+ # Shapes every lazy family rejects execute on the raw path — a
+ # widened replay there is a 30-day scan the tenant never ran,
+ # outside their request throttles. If this stops falling back, the
+ # warmer becomes a background-load amplifier for mintable
+ # ineligible shapes.
+ ("conversion_goal", {"kind": "WebOverviewQuery", "conversionGoal": {"customEventName": "purchase"}}),
+ # Passes the shared gate; rejected by all three stats families
+ # (paths/frustration: wrong breakdown, simple: bounce rate).
+ (
+ "bounce_rate_browser",
+ {"kind": "WebStatsTableQuery", "breakdownBy": "Browser", "includeBounceRate": True},
+ ),
+ ]
+ )
+ def test_family_rejected_shape_replays_faithful_range(self, _name: str, extra: dict) -> None:
+ query = {
+ "properties": [],
+ "useWebAnalyticsPrecompute": True,
+ "dateRange": {"date_from": "-7d"},
+ **extra,
+ }
+
+ runner, used_json = build_replay_runner(self.team, query)
+
+ self.assertIsNotNone(runner)
+ self.assertEqual(used_json["dateRange"]["date_from"], "-7d")
+
+ def test_outside_warming_context_gate_fails_closed(self) -> None:
+ reset_query_tags()
+ query = {
+ "kind": "WebOverviewQuery",
+ "properties": [],
+ "useWebAnalyticsPrecompute": True,
+ "dateRange": {"date_from": "-7d"},
+ }
+
+ runner, used_json = build_replay_runner(self.team, query)
+
+ self.assertIsNotNone(runner)
+ self.assertEqual(used_json["dateRange"]["date_from"], "-7d")
+
+
class TestFleetQuerySelection(BaseTest):
@patch("products.web_analytics.dags.cache_warming.sync_execute")
def test_parses_fleet_rows_into_query_infos(self, mock_exec: MagicMock) -> None: