: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(web-analytics): serve dashboard trend tiles from precompute buckets (#75706)
Lucas Ricoy151b09105f41
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 8a850cedcdd8..3ef00d49aeab 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -456,6 +456,32 @@ def get_query_runner(user=user,)+ # Queries originating from the web analytics product take a WA-owned+ # subclass that can serve eligible shapes from precompute buckets and+ # falls back to the standard trends path internally. Tags-only check:+ # all real gating (rollout flag, shape, team enrollment) lives in the+ # runner so dispatch stays free of I/O.+ query_tags = get_from_dict_or_attr(query_obj, "tags")+ if query_tags and get_from_dict_or_attr(query_tags, "productKey") == "web_analytics":+ from products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute import (+ is_trends_precompute_enabled_for_team,+ )++ # Flag-gated at dispatch: with the rollout flag off, WA queries take+ # the vanilla trends path with zero new code in the way. Local flag+ # evaluation only — no network I/O here.+ if is_trends_precompute_enabled_for_team(team):+ from products.web_analytics.backend.hogql_queries.web_trends import WebTrendsQueryRunner++ return WebTrendsQueryRunner(+ query=query_obj,+ team=team,+ timings=timings,+ limit_context=limit_context,+ modifiers=modifiers,+ user=user,+ )+from .insights.trends.trends_query_runner import TrendsQueryRunnerreturn TrendsQueryRunner(diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 523a249966e8..4010d3238871 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1256,6 +1256,13 @@ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS: list[int] = [for team_id in get_list(get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS))]+# Dogfooding list for the precompute-backed web analytics trends path — teams+# here take it regardless of the `web-analytics-trends-precompute` rollout flag.+# The shared precompute enrollment gate still applies underneath.+WEB_ANALYTICS_TRENDS_PRECOMPUTE_TEAM_IDS: list[int] = [+ int(team_id) for team_id in get_list(get_from_env("WEB_ANALYTICS_TRENDS_PRECOMPUTE_TEAM_IDS", ""))+]+# Upper bound on the number of distinct precompute shapes (query cache keys) a single# team may have live at once. Any filter combination becomes its own shape, so a# pathological team could otherwise mint unbounded namespaces. This is a coarse backstop,diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 1ef11711499c..eb26e951fc98 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -277,6 +277,18 @@ Because the eager job and the lazy read path consult the same flag, the warmingThis job is complementary to `cache_warming.py`, which replays whatever queries users actually ran in the last N days. The eager job covers the fixed UI matrix; the replay job covers the long tail of team-specific filter combinations.+## Trend tiles (precompute-backed trends)++The dashboard's graph tiles run vanilla `TrendsQuery`, routed at dispatch to `WebTrendsQueryRunner` when the query carries `tags.productKey == "web_analytics"` AND the `web-analytics-trends-precompute` flag (locally evaluated, fails closed) is on for the team. The runner serves eligible single-series shapes — unique visitors, page views, sessions, avg session duration, bounce rate — from the same hourly `web_overview_preaggregated` buckets the overview tile keeps warm (the query is mapped to an inner `WebOverviewQuery`, so the precompute job hash is identical and buckets are shared), and falls back to the standard trends path for everything else.++Rollout gates, in order:++1. `WEB_ANALYTICS_TRENDS_PRECOMPUTE_TEAM_IDS` (env, deploy-time) — dogfooding list that short-circuits the flag.+2. `web-analytics-trends-precompute` PostHog feature flag — the percentage ramp; also folded into the runner's cache key so disabling it invalidates cached precompute-served results immediately.+3. The shared enrollment gate (`web-analytics-precompute-toggle` / `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS`) still applies underneath.++Accepted semantic differences vs vanilla trends (the tiles align with the overview tile instead): session-start-hour attribution, HLL uniques, `$pageview + $screen` counted together, sessionless events excluded. The per-query "Allow precompute" opt-out does not reach trend tiles (TrendsQuery deliberately carries no web-analytics fields); the flag is the kill switch.+## Related code- `products/web_analytics/backend/hogql_queries/web_overview.py` — runner@@ -290,5 +302,6 @@ This job is complementary to `cache_warming.py`, which replays whatever queries- `products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py` — vitals runner- `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` — vitals lazy path- `posthog/clickhouse/preaggregation/web_vitals_paths_preaggregated_sql.py` — vitals schema+- `products/web_analytics/backend/hogql_queries/web_trends.py` + `web_trends_lazy_precompute.py` — trend tiles lazy path- `products/analytics_platform/backend/lazy_computation/` — framework + CONSISTENCY.md + README- `products/web_analytics/dags/eager_web_analytics_precompute.py` — hourly baseline pre-warmerdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.pynew file mode 100644index 000000000000..12250e09a7bb--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_web_trends_lazy_precompute.py@@ -0,0 +1,394 @@+from dataclasses import replace++from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person+from unittest.mock import patch++from django.test import override_settings++from parameterized import parameterized++from posthog.schema import (+ BreakdownFilter,+ ChartDisplayType,+ CompareFilter,+ DateRange,+ EventPropertyFilter,+ EventsNode,+ IntervalType,+ SessionPropertyFilter,+ TrendsFilter,+ TrendsQuery,+)++from posthog.clickhouse.client import sync_execute+from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner+from posthog.hogql_queries.query_runner import get_query_runner+from posthog.models.utils import uuid7++from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.web_analytics.backend.hogql_queries import web_trends_lazy_precompute+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner+from products.web_analytics.backend.hogql_queries.web_trends import WebTrendsQueryRunner+from products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute import (+ WebTrendsMetric,+ build_inner_overview_query,+ trends_precompute_metric,+)+++@override_settings(IN_UNIT_TESTING=True)+class TestWebTrendsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()+ # Precompute rows are "born expired" relative to the real ClickHouse+ # clock under freeze_time; stop TTL merges so they survive until read.+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_overview_preaggregated")++ def _enable_lazy(self):+ return patch(+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",+ return_value=True,+ )++ def _enable_trends_flag(self):+ return override_settings(WEB_ANALYTICS_TRENDS_PRECOMPUTE_TEAM_IDS=[self.team.pk])++ def _seed(self) -> None:+ # p1: two-pageview session on Jan 2; p2: single-pageview bounce on Jan 3.+ # Sessions are fully inside single days so session-start attribution and+ # event-time attribution agree and both paths must return identical data.+ s1 = str(uuid7("2024-01-02"))+ s2 = str(uuid7("2024-01-03"))+ _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={})+ _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={})+ for ts, url in (("2024-01-02T10:00:00Z", "/a"), ("2024-01-02T10:05:00Z", "/b")):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p1",+ timestamp=ts,+ properties={"$session_id": s1, "$host": "example.com", "$current_url": f"https://example.com{url}"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p2",+ timestamp="2024-01-03T11:00:00Z",+ properties={"$session_id": s2, "$host": "other.com", "$current_url": "https://other.com/x"},+ )++ def _build_query(+ self,+ math: str = "dau",+ math_property: str | None = None,+ compare: bool = False,+ interval: IntervalType = IntervalType.DAY,+ ) -> TrendsQuery:+ return TrendsQuery(+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-07"),+ interval=interval,+ series=[+ EventsNode(+ event="$pageview",+ math=math,+ math_property=math_property,+ math_property_type="session_properties" if math_property else None,+ custom_name="My metric",+ )+ ],+ trendsFilter=TrendsFilter(display=ChartDisplayType.ACTIONS_LINE_GRAPH),+ compareFilter=CompareFilter(compare=compare) if compare else None,+ properties=[],+ )++ @parameterized.expand(+ [+ # If the precompute read, zero-fill, or response assembly drifts+ # from the live trends contract, the tile silently renders wrong+ # numbers — this pins precompute output to the live runner's exact+ # data/days/labels for every servable metric.+ ("unique_users", "dau", None),+ ("views", "total", None),+ ("unique_sessions", "unique_session", None),+ ("avg_duration", "avg", "$session_duration"),+ ("bounce_rate", "avg", "$is_bounce"),+ ]+ )+ @freeze_time("2024-01-15T12:00:00Z")+ def test_precompute_matches_live_trends(self, _name: str, math: str, math_property: str | None) -> None:+ self._seed()+ query = self._build_query(math=math, math_property=math_property)++ live = TrendsQueryRunner(team=self.team, query=query).calculate()++ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=query).calculate()++ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0+ assert len(precomputed.results) == 1+ pre_series = precomputed.results[0]+ live_series = live.results[0]+ assert pre_series["data"] == live_series["data"]+ assert pre_series["days"] == live_series["days"]+ assert pre_series["labels"] == live_series["labels"]+ assert pre_series["count"] == live_series["count"]+ assert pre_series["label"] == live_series["label"]+ assert pre_series["action"]["custom_name"] == "My metric"++ @freeze_time("2024-01-15T12:00:00Z")+ def test_compare_period_matches_live_trends(self) -> None:+ self._seed()+ query = self._build_query(compare=True)++ live = TrendsQueryRunner(team=self.team, query=query).calculate()++ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=query).calculate()++ assert len(precomputed.results) == len(live.results) == 2+ for pre_series, live_series in zip(precomputed.results, live.results):+ assert pre_series["compare_label"] == live_series["compare_label"]+ assert pre_series["data"] == live_series["data"]+ assert pre_series["days"] == live_series["days"]+ # The previous series' labels and action.days must use the CURRENT+ # range's context like the live runner does — the compare tooltip+ # pairs points across series by these.+ assert pre_series["labels"] == live_series["labels"]+ assert pre_series["action"]["days"] == live_series["action"]["days"]+ assert precomputed.resolved_compare_date_range is not None++ @freeze_time("2024-01-15T12:00:00Z")+ def test_reuses_overview_precompute_jobs(self) -> None:+ # The whole point of the inner-WebOverviewQuery mapping: trends reads+ # must find the buckets the overview tile already built, not mint a+ # parallel job namespace that doubles insert load.+ self._seed()+ with self._enable_lazy():+ overview_query = build_inner_overview_query(self._build_query(), [])+ WebOverviewQueryRunner(team=self.team, query=overview_query).calculate()+ jobs_after_overview = PreaggregationJob.objects.filter(team_id=self.team.pk).count()+ assert jobs_after_overview > 0++ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=self._build_query()).calculate()++ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == jobs_after_overview+ assert sum(precomputed.results[0]["data"]) > 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_flag_off_falls_back_to_live_path(self) -> None:+ self._seed()+ trends_flag_off = patch(+ "products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=False,+ )+ with self._enable_lazy(), trends_flag_off:+ response = WebTrendsQueryRunner(team=self.team, query=self._build_query()).calculate()++ # Fallback executed the standard trends path: no precompute jobs, and+ # the results still match the live contract.+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0+ assert sum(response.results[0]["data"]) == 2++ @parameterized.expand(+ [+ # Shapes the buckets can't reproduce must fall back — serving them+ # would silently return wrong numbers (e.g. a breakdown collapsed+ # to a single series, or WAU windowed math served as plain uniques).+ ("multi_series", {"series": [EventsNode(event="$pageview"), EventsNode(event="$pageleave")]}),+ ("non_pageview_event", {"series": [EventsNode(event="$autocapture", math="dau")]}),+ ("windowed_math", {"series": [EventsNode(event="$pageview", math="weekly_active")]}),+ (+ "unsupported_math_property",+ {+ "series": [+ EventsNode(event="$pageview", math="avg", math_property="$time", math_property_type="event")+ ]+ },+ ),+ (+ # Same property name, event-level semantics — per-event avg, not+ # per-session; the buckets would silently serve the wrong number.+ "event_property_is_bounce",+ {+ "series": [+ EventsNode(+ event="$pageview", math="avg", math_property="$is_bounce", math_property_type="event"+ )+ ]+ },+ ),+ ("breakdown", {"breakdownFilter": BreakdownFilter(breakdown="$browser", breakdown_type="event")}),+ (+ "world_map_display",+ {"trendsFilter": TrendsFilter(display=ChartDisplayType.WORLD_MAP)},+ ),+ (+ "formula",+ {"trendsFilter": TrendsFilter(display=ChartDisplayType.ACTIONS_LINE_GRAPH, formula="A / B")},+ ),+ ("minute_interval", {"interval": IntervalType.MINUTE}),+ (+ # The live path multiplies before averaging; buckets store raw+ # states, so a multiplier would be silently dropped.+ "math_multiplier",+ {+ "series": [+ EventsNode(+ event="$pageview",+ math="avg",+ math_property="$session_duration",+ math_property_type="session_properties",+ math_multiplier=0.001,+ )+ ]+ },+ ),+ ]+ )+ def test_unservable_shapes_are_rejected(self, _name: str, overrides: dict) -> None:+ query = self._build_query().model_copy(update=overrides)+ assert trends_precompute_metric(query) is None++ def test_servable_shape_maps_to_metric(self) -> None:+ assert trends_precompute_metric(self._build_query()) is WebTrendsMetric.UNIQUE_USERS++ @freeze_time("2024-01-15T12:00:00Z")+ def test_session_filter_falls_back(self) -> None:+ # Session filters pass the shape gate but the shared eligibility check+ # rejects them (the precompute INSERT can't apply them faithfully).+ self._seed()+ query = self._build_query()+ query.properties = [SessionPropertyFilter(key="$channel_type", value=["Direct"], operator="exact")]+ with self._enable_lazy(), self._enable_trends_flag():+ WebTrendsQueryRunner(team=self.team, query=query).calculate()+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0++ def test_dispatch_routes_wa_tagged_trends_queries(self) -> None:+ # Dispatch requires BOTH the WA product tag and the rollout flag; with+ # the flag off even tagged queries must take the untouched vanilla path+ # (the flag is the zero-exposure kill switch for the whole runner).+ tagged = self._build_query().model_dump()+ tagged["tags"] = {"productKey": "web_analytics"}+ with self._enable_trends_flag():+ assert isinstance(get_query_runner(tagged, self.team), WebTrendsQueryRunner)++ flag_off = patch(+ "products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=False,+ )+ with flag_off:+ runner = get_query_runner(tagged, self.team)+ assert isinstance(runner, TrendsQueryRunner)+ assert not isinstance(runner, WebTrendsQueryRunner)++ untagged = self._build_query()+ with self._enable_trends_flag():+ runner = get_query_runner(untagged, self.team)+ assert isinstance(runner, TrendsQueryRunner)+ assert not isinstance(runner, WebTrendsQueryRunner)++ @parameterized.expand(+ [+ # Each interval has its own bucket expression and days-format+ # branch; hour additionally exercises mid-day (non-day-floored)+ # read bounds against day-floored precompute jobs.+ ("hour", IntervalType.HOUR, "2024-01-02", "2024-01-03"),+ ("month", IntervalType.MONTH, "2024-01-01", "2024-01-31"),+ ]+ )+ @freeze_time("2024-01-15T12:00:00Z")+ def test_interval_parity_with_live_trends(+ self, _name: str, interval: IntervalType, date_from: str, date_to: str+ ) -> None:+ self._seed()+ query = self._build_query(interval=interval)+ query.dateRange = DateRange(date_from=date_from, date_to=date_to)++ live = TrendsQueryRunner(team=self.team, query=query).calculate()+ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=query).calculate()++ assert precomputed.results[0]["data"] == live.results[0]["data"]+ assert precomputed.results[0]["days"] == live.results[0]["days"]+ assert precomputed.results[0]["labels"] == live.results[0]["labels"]++ @freeze_time("2024-01-15T12:00:00Z")+ def test_filtered_round_trip_matches_live(self) -> None:+ # Filters must flow into the precompute INSERT and back out — if the+ # series-level merge in effective_properties or the inner query's+ # property mapping drops them, a $host-filtered tile silently shows+ # unfiltered fleet numbers.+ self._seed()+ host_filter = EventPropertyFilter(key="$host", value=["example.com"], operator="exact")+ query = self._build_query()+ query.properties = [host_filter]++ live = TrendsQueryRunner(team=self.team, query=query).calculate()+ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=query).calculate()+ assert precomputed.results[0]["data"] == live.results[0]["data"]+ assert sum(precomputed.results[0]["data"]) == 1 # only p1 on example.com++ # Same filter attached to the series node (how some WA tiles send it)+ # must produce the same served numbers.+ series_query = self._build_query()+ series_query.series[0].properties = [host_filter]+ with self._enable_lazy(), self._enable_trends_flag():+ series_filtered = WebTrendsQueryRunner(team=self.team, query=series_query).calculate()+ assert series_filtered.results[0]["data"] == precomputed.results[0]["data"]++ @freeze_time("2024-01-15T12:00:00Z")+ def test_distinct_id_aggregation_falls_back(self) -> None:+ # Vanilla trends counts distinct_ids for these teams while the buckets+ # store person-id uniq states — genuinely different numbers.+ self._seed()+ with (+ self._enable_lazy(),+ self._enable_trends_flag(),+ patch.object(type(self.team), "aggregate_users_by_distinct_id", property(lambda self: True)),+ ):+ WebTrendsQueryRunner(team=self.team, query=self._build_query()).calculate()+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stale_buckets_are_served_and_revalidated_via_overview_family(self) -> None:+ # Stale-within-grace buckets must be served (falling back would put+ # dashboards on the slow path at every TTL lapse) and the background+ # revalidation must debounce under the web_overview family so one+ # rebuild refreshes the buckets both tiles read.+ self._seed()+ real_ensure = web_trends_lazy_precompute.ensure_web_overview_precomputed++ def stale_ensure(**kwargs):+ result = real_ensure(**kwargs)+ return replace(result, stale=True)++ with (+ self._enable_lazy(),+ self._enable_trends_flag(),+ patch(+ "products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute.ensure_web_overview_precomputed",+ side_effect=stale_ensure,+ ),+ patch(+ "products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute.handle_stale_served"+ ) as mock_stale,+ ):+ response = WebTrendsQueryRunner(team=self.team, query=self._build_query()).calculate()++ assert sum(response.results[0]["data"]) == 2 # served, not fallen back+ assert mock_stale.called+ assert mock_stale.call_args.kwargs["family"] == "web_overview"++ @freeze_time("2024-01-15T12:00:00Z")+ def test_week_interval_zero_fills_full_range(self) -> None:+ self._seed()+ query = self._build_query(interval=IntervalType.WEEK)+ live = TrendsQueryRunner(team=self.team, query=query).calculate()+ with self._enable_lazy(), self._enable_trends_flag():+ precomputed = WebTrendsQueryRunner(team=self.team, query=query).calculate()+ assert precomputed.results[0]["data"] == live.results[0]["data"]+ assert precomputed.results[0]["days"] == live.results[0]["days"]diff --git a/products/web_analytics/backend/hogql_queries/web_trends.py b/products/web_analytics/backend/hogql_queries/web_trends.pynew file mode 100644index 000000000000..1f23e6947dbf--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_trends.py@@ -0,0 +1,55 @@+from posthog.schema import QueryTiming, ResolvedDateRangeResponse, TrendsQueryResponse++from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner++from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_precompute_enabled_for_team+from products.web_analytics.backend.hogql_queries.web_trends_lazy_precompute import (+ execute_lazy_precomputed_trends,+ is_trends_precompute_enabled_for_team,+)+++class WebTrendsQueryRunner(TrendsQueryRunner):+ """Trends runner for queries originating from the web analytics product+ (routed by `tags.productKey` at dispatch). Serves eligible single-series+ shapes from the shared web_overview precompute buckets — the same buckets+ the overview tile keeps warm — and falls back to the standard trends path+ for everything else. Subclassing keeps the response contract and gives the+ HogQL result cache a distinct namespace (class name is part of the cache+ payload), so precompute-served results never collide with vanilla trends+ cache entries.+ """++ def get_cache_payload(self) -> dict:+ payload = super().get_cache_payload()+ # Fold rollout state into the cache key so disabling either flag is an+ # immediate kill switch: without this, cached precompute-served results+ # keep being returned until they stale out naturally (the overview+ # runner does the same via its `_pc` cache-key suffix).+ payload["web_trends_precompute"] = is_trends_precompute_enabled_for_team(+ self.team+ ) and is_precompute_enabled_for_team(self.team)+ return payload++ def _calculate(self) -> TrendsQueryResponse:+ results = execute_lazy_precomputed_trends(self)+ if results is None:+ return super()._calculate()++ timings: list[QueryTiming] = self.timings.to_list()+ return TrendsQueryResponse(+ results=results,+ hasMore=False,+ timings=timings,+ modifiers=self.modifiers,+ resolved_date_range=ResolvedDateRangeResponse(+ date_from=self.query_date_range.date_from(),+ date_to=self.query_date_range.date_to(),+ ),+ resolved_compare_date_range=ResolvedDateRangeResponse(+ date_from=self.query_previous_date_range.date_from(),+ date_to=self.query_previous_date_range.date_to(),+ )+ if self.query.compareFilter is not None and self.query.compareFilter.compare+ else None,+ )diff --git a/products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.pynew file mode 100644index 000000000000..5cf67c8b73f9--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_trends_lazy_precompute.py@@ -0,0 +1,496 @@+import time+from datetime import UTC, datetime+from enum import Enum+from typing import TYPE_CHECKING, Any, Optional++from django.conf import settings++import structlog+import posthoganalytics+from prometheus_client import Counter++from posthog.schema import (+ ChartDisplayType,+ CompareFilter,+ DateRange,+ EventsNode,+ IntervalType,+ TrendsQuery,+ WebOverviewQuery,+)++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (+ DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE,+)+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.hogql_queries.query_runner import resolve_series_custom_name+from posthog.hogql_queries.utils.timestamp_utils import format_label_date+from posthog.models.team import Team+from posthog.week_start_day import WeekStartDay++from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS,+ can_use_lazy_precompute as _can_use_lazy_precompute_shared,+ ceil_utc_day,+ floor_utc_day,+)+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import handle_stale_served+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner+from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (+ _READ_SETTINGS,+ ensure_web_overview_precomputed,+)++if TYPE_CHECKING:+ from products.web_analytics.backend.hogql_queries.web_trends import WebTrendsQueryRunner++logger = structlog.get_logger(__name__)++_FAMILY = "web_trends"++TRENDS_PRECOMPUTE_FLAG_KEY = "web-analytics-trends-precompute"++WEB_TRENDS_LAZY_FAILED = Counter(+ "web_trends_lazy_precompute_failed_total",+ "Web trends lazy precompute path failures, by error class",+ ["error_type"],+)+++class WebTrendsMetric(Enum):+ UNIQUE_USERS = "unique_users"+ VIEWS = "views"+ UNIQUE_SESSIONS = "unique_sessions"+ AVG_DURATION = "avg_duration"+ BOUNCE_RATE = "bounce_rate"+++# Merge expressions over web_overview_preaggregated states. Keyed by enum, never+# interpolated from user input. avg merges are NaN when a bucket group has no+# rows with a non-null state — coerce to 0 like the overview read consumers do.+_METRIC_EXPRS: dict[WebTrendsMetric, str] = {+ WebTrendsMetric.UNIQUE_USERS: "uniqMerge(uniq_users_state)",+ WebTrendsMetric.VIEWS: "sumMerge(sum_pageviews_state)",+ WebTrendsMetric.UNIQUE_SESSIONS: "uniqMerge(uniq_sessions_state)",+ WebTrendsMetric.AVG_DURATION: "ifNotFinite(avgMerge(avg_duration_state), 0)",+ WebTrendsMetric.BOUNCE_RATE: "ifNotFinite(avgMerge(avg_bounce_state), 0)",+}++# Interval → team-local bucket truncation over the hourly-UTC bucket key. The+# shared gate already restricts to whole-hour timezone offsets, so tz conversion+# followed by truncation is exact. Week mode comes from team.week_start_day and+# is formatted in (server-side constant, not user input). The toDateTime wraps+# keep the driver returning datetimes for week/month (toStartOfWeek/Month return+# Dates).+_BUCKET_EXPRS: dict[str, str] = {+ "hour": "toStartOfHour(toTimeZone(time_window_start, %(tz)s))",+ "day": "toDateTime(toStartOfDay(toTimeZone(time_window_start, %(tz)s)))",+ "week": "toDateTime(toStartOfWeek(toTimeZone(time_window_start, %(tz)s), {week_mode}))",+ "month": "toDateTime(toStartOfMonth(toTimeZone(time_window_start, %(tz)s)))",+}++_SUPPORTED_INTERVALS = set(_BUCKET_EXPRS.keys())++_SUPPORTED_EVENTS = ("$pageview", "$screen")+++def is_trends_precompute_enabled_for_team(team: Team) -> bool:+ """Independent ramp for the trends path, on top of the shared precompute+ enrollment the inner gate still enforces. Must never raise — it runs in+ dispatch and in cache-key generation, where an exception would fail the+ request instead of falling back. Fails closed on any error."""+ try:+ if team.id in settings.WEB_ANALYTICS_TRENDS_PRECOMPUTE_TEAM_IDS:+ return True+ return _flag_enabled(team)+ except Exception:+ logger.exception("web_trends_precompute_flag_check_failed", team_id=team.pk)+ return False+++def _flag_enabled(team: Team) -> bool:+ return bool(+ posthoganalytics.feature_enabled(+ TRENDS_PRECOMPUTE_FLAG_KEY,+ str(team.uuid),+ groups={+ "organization": str(team.organization_id),+ "project": str(team.id),+ },+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+++def trends_precompute_metric(query: TrendsQuery) -> Optional[WebTrendsMetric]:+ """Map a TrendsQuery onto a servable preagg metric, or None when the shape+ can't be served from the overview buckets (caller falls back to the live+ trends path). The allowlist is deliberately narrow: it must only admit+ shapes whose semantics the session-start-attributed hourly buckets can+ reproduce."""+ if len(query.series) != 1:+ return None+ series = query.series[0]+ if not isinstance(series, EventsNode):+ return None+ if series.event not in _SUPPORTED_EVENTS:+ return None+ if series.fixedProperties:+ return None++ if query.breakdownFilter is not None:+ return None+ if query.conversionGoal is not None:+ return None+ if query.aggregation_group_type_index is not None:+ return None+ if query.samplingFactor is not None:+ return None++ tf = query.trendsFilter+ if tf is not None:+ if tf.display is not None and tf.display != ChartDisplayType.ACTIONS_LINE_GRAPH:+ return None+ if tf.formula or tf.formulas or tf.formulaNodes:+ return None+ if tf.smoothingIntervals is not None and tf.smoothingIntervals > 1:+ return None+ if tf.hideWeekends:+ return None++ interval = (query.interval or IntervalType.DAY).value+ if interval not in _SUPPORTED_INTERVALS:+ return None++ if query.properties is not None and not isinstance(query.properties, list):+ return None++ if query.dateRange is not None and (query.dateRange.explicitDate or query.dateRange.daysOfWeek):+ return None++ math = series.math+ math_property = series.math_property+ if math == "dau":+ return WebTrendsMetric.UNIQUE_USERS+ if math == "total" or math is None:+ return WebTrendsMetric.VIEWS+ if math == "unique_session":+ return WebTrendsMetric.UNIQUE_SESSIONS+ # The live path multiplies the property before averaging; the buckets+ # store the raw aggregate state, so a multiplier would be silently ignored.+ if getattr(series, "math_multiplier", None) is not None:+ return None+ # Session-property averages only: an avg over an event-property with the+ # same name aggregates per event, not per deduped session, and the live+ # path treats those differently — the buckets can't reproduce that.+ if math == "avg" and getattr(series, "math_property_type", None) == "session_properties":+ if math_property == "$session_duration":+ return WebTrendsMetric.AVG_DURATION+ if math_property == "$is_bounce":+ return WebTrendsMetric.BOUNCE_RATE+ return None+++def effective_properties(query: TrendsQuery) -> list[Any]:+ """Query-level properties plus series-level ones (some WA tiles attach the+ dashboard filters to the series node)."""+ props: list[Any] = list(query.properties or [])+ series = query.series[0]+ if isinstance(series, EventsNode) and series.properties:+ props.extend(series.properties)+ return props+++def build_inner_overview_query(query: TrendsQuery, properties: list[Any]) -> WebOverviewQuery:+ return WebOverviewQuery(+ dateRange=query.dateRange or DateRange(),+ interval=query.interval,+ properties=properties,+ filterTestAccounts=query.filterTestAccounts,+ compareFilter=query.compareFilter or CompareFilter(compare=False),+ # TrendsQuery carries no useWebAnalyticsPrecompute field (the core+ # trends schema stays untouched by design), so the per-query "Allow+ # precompute" opt-out cannot reach this path — the rollout flag baked+ # into the runner's cache key is the kill switch for trend tiles.+ useWebAnalyticsPrecompute=None,+ )+++def can_use_web_trends_precompute(trends_runner: "WebTrendsQueryRunner", inner_runner: WebOverviewQueryRunner) -> bool:+ if not is_trends_precompute_enabled_for_team(trends_runner.team):+ return False+ if trends_precompute_metric(trends_runner.query) is None:+ return False+ return _can_use_lazy_precompute_shared(inner_runner, log_prefix=_FAMILY)+++def _tz_offset_changes(date_range: Any) -> bool:+ start = date_range.date_from()+ end = date_range.date_to()+ if start is None or end is None:+ return False+ return start.utcoffset() != end.utcoffset()+++def _read_series(+ *,+ team: Team,+ metric: WebTrendsMetric,+ interval: str,+ job_ids: list[str],+ range_start_utc: datetime,+ range_end_utc: datetime,+) -> dict[datetime, float]:+ week_mode = WeekStartDay(team.week_start_day or 0).clickhouse_mode+ bucket_expr = _BUCKET_EXPRS[interval].format(week_mode=week_mode)+ sql = f"""+SELECT {bucket_expr} AS bucket, {_METRIC_EXPRS[metric]} AS value+FROM {DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE()}+WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s+ AND time_window_start >= %(range_start)s AND time_window_start < %(range_end)s+GROUP BY bucket+"""+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY, query_type="web_trends_lazy_query")+ rows = sync_execute(+ sql,+ {+ "team_id": team.pk,+ "job_ids": tuple(job_ids),+ "tz": team.timezone,+ "range_start": range_start_utc,+ "range_end": range_end_utc,+ },+ settings=_READ_SETTINGS,+ team_id=team.pk,+ )+ result: dict[datetime, float] = {}+ for bucket, value in rows:+ # The driver returns tz-aware datetimes in the cast timezone; series+ # bucket datetimes from QueryDateRange are team-local too. Compare on+ # naive wall-clock to sidestep tzinfo-object identity mismatches.+ result[bucket.replace(tzinfo=None)] = float(value)+ return result+++def _series_dict(+ runner: "WebTrendsQueryRunner",+ *,+ metric_values: dict[datetime, float],+ date_range: Any,+ is_previous: bool,+) -> dict[str, Any]:+ query = runner.query+ series = query.series[0]+ series_label = runner.series_event(series)++ buckets = date_range.all_values()+ interval_name = date_range.interval_name+ day_fmt = "%Y-%m-%d %H:%M:%S" if interval_name in ("hour", "minute") else "%Y-%m-%d"++ data = [metric_values.get(bucket.replace(tzinfo=None), 0.0) for bucket in buckets]++ series_object: dict[str, Any] = {+ "data": data,+ # Labels are formatted in the CURRENT range's context and action.days is+ # always the current range, even for the previous compare series — the+ # live runner does both (build_series_response passes+ # self.query_date_range regardless of series period).+ "labels": [format_label_date(item, runner.query_date_range, runner.team.week_start_day) for item in buckets],+ "days": [item.strftime(day_fmt) for item in buckets],+ "count": float(sum(data)),+ "label": "All events" if series_label is None else series_label,+ "filter": runner._query_to_filter(),+ "action": {+ "days": runner.query_date_range.all_values(),+ "id": series_label,+ "type": "events",+ "order": 0,+ "name": series_label or "All events",+ "custom_name": resolve_series_custom_name(series, series_label),+ "math": series.math,+ "math_property": series.math_property,+ "math_hogql": series.math_hogql,+ "math_group_type_index": series.math_group_type_index,+ "properties": {},+ },+ "order": 0,+ }+ if query.compareFilter is not None and query.compareFilter.compare:+ series_object["compare"] = True+ series_object["compare_label"] = "previous" if is_previous else "current"+ return series_object+++def execute_lazy_precomputed_trends(runner: "WebTrendsQueryRunner") -> Optional[list[dict[str, Any]]]:+ """Serve the trends series from the shared web_overview preagg buckets.+ Returns the formatted results list, or None on any ineligibility/miss (the+ caller falls back to the live trends path)."""+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)+ team = runner.team+ overall_started = time.perf_counter()+ try:+ metric = trends_precompute_metric(runner.query)+ if metric is None:+ return None++ props = effective_properties(runner.query)+ inner_query = build_inner_overview_query(runner.query, props)+ inner_runner = WebOverviewQueryRunner(query=inner_query, team=team, modifiers=runner.modifiers)++ if not can_use_web_trends_precompute(runner, inner_runner):+ return None++ # Vanilla trends counts distinct_ids for these teams; the buckets store+ # person-id uniq states — the counts genuinely differ, so fall back.+ if runner.team.aggregate_users_by_distinct_id:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="distinct_id_aggregation").inc()+ return None++ interval = (runner.query.interval or IntervalType.DAY).value++ # A DST transition inside an hour-interval range makes two local+ # wall-clock hours collide on one bucket key (fall-back) or produces a+ # nonexistent one (spring-forward); the live path emits 25/23 points+ # there. Applies to the compare range too, which can cross a transition+ # the current range doesn't. Fall back rather than serve a silently+ # different axis.+ has_compare_for_dst = runner.query.compareFilter is not None and bool(runner.query.compareFilter.compare)+ if interval == "hour" and (+ _tz_offset_changes(runner.query_date_range)+ or (has_compare_for_dst and _tz_offset_changes(runner.query_previous_date_range))+ ):+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="dst_transition").inc()+ return None++ cur_buckets = runner.query_date_range.all_values()+ cur_to = runner.query_date_range.date_to()+ if not cur_buckets or cur_to is None:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="empty_range").inc()+ return None+ # The live trends path truncates date_from to the start of the interval+ # (a mid-month absolute date_from with month interval still counts the+ # whole first month) — read and precompute from the first aligned+ # bucket, not the raw date_from.+ cur_start_utc = cur_buckets[0].astimezone(UTC)+ cur_end_utc = cur_to.astimezone(UTC)++ time_range_start = floor_utc_day(cur_start_utc)+ time_range_end = ceil_utc_day(cur_end_utc)+ if time_range_start >= time_range_end:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="empty_range").inc()+ return None++ result = ensure_web_overview_precomputed(+ runner=inner_runner,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ )+ if result.stale:+ # Family web_overview on purpose: one debounced overview re-run+ # rebuilds the buckets both tiles read.+ handle_stale_served(runner=inner_runner, family="web_overview")+ if not result.job_ids:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="no_job_ids").inc()+ return None+ if not result.ready:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="current_not_ready").inc()+ return None+ job_ids = [str(jid) for jid in result.job_ids]++ has_compare = runner.query.compareFilter is not None and bool(runner.query.compareFilter.compare)++ # Both ensures run before any read: if the previous period turns out+ # not ready the whole path falls back, and a current-period read done+ # first would be wasted work mis-tagged as a served lazy query.+ prev_job_ids: list[str] = []+ prev_start_utc = prev_end_utc = None+ prev_buckets: list = []+ if has_compare:+ prev_buckets = runner.query_previous_date_range.all_values()+ prev_to = runner.query_previous_date_range.date_to()+ if not prev_buckets or prev_to is None:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="previous_range_missing").inc()+ return None+ prev_start_utc = prev_buckets[0].astimezone(UTC)+ prev_end_utc = prev_to.astimezone(UTC)+ prev_range_start = floor_utc_day(prev_start_utc)+ prev_range_end = ceil_utc_day(prev_end_utc)+ if prev_range_start < prev_range_end:+ prev_result = ensure_web_overview_precomputed(+ runner=inner_runner,+ time_range_start=prev_range_start,+ time_range_end=prev_range_end,+ )+ if prev_result.stale:+ handle_stale_served(runner=inner_runner, family="web_overview")+ if not prev_result.ready:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="previous_not_ready").inc()+ return None+ # The previous window is fully covered by its own ensure's jobs.+ # Unioning in the current period's jobs would double-count any+ # overlap day (overlapping compare_to windows) if a redundant+ # READY job for the same window exists under both ids.+ prev_job_ids = [str(jid) for jid in prev_result.job_ids]+ else:+ prev_job_ids = list(job_ids)++ results: list[dict[str, Any]] = []+ current_values = _read_series(+ team=team,+ metric=metric,+ interval=interval,+ job_ids=job_ids,+ range_start_utc=cur_start_utc,+ range_end_utc=cur_end_utc,+ )+ results.append(+ _series_dict(runner, metric_values=current_values, date_range=runner.query_date_range, is_previous=False)+ )++ if has_compare:+ assert prev_start_utc is not None and prev_end_utc is not None+ previous_values = _read_series(+ team=team,+ metric=metric,+ interval=interval,+ job_ids=prev_job_ids,+ range_start_utc=prev_start_utc,+ range_end_utc=prev_end_utc,+ )+ # Current first, previous second — mirrors the live runner's series+ # ordering, which the frontend relies on for compare pairing.+ results.append(+ _series_dict(+ runner,+ metric_values=previous_values,+ date_range=runner.query_previous_date_range,+ is_previous=True,+ )+ )++ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=_FAMILY).inc()+ logger.info(+ "web_trends_lazy_precompute_completed",+ team_id=team.pk,+ metric=metric.value,+ interval=interval,+ job_count=len(job_ids),+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return results+ except Exception as exc:+ WEB_TRENDS_LAZY_FAILED.labels(error_type=type(exc).__name__).inc()+ logger.exception(+ "web_trends_lazy_precompute_failed",+ team_id=team.pk,+ error_type=type(exc).__name__,+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return None