: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 web vitals tab timeseries from precompute buckets (#85944)
Lucas Ricoyd6c4f2eb883b
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex b15fa0f6c147..73f753a847d3 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -94,6 +94,7 @@ from posthog.schema import (WebNotableChangesQuery,WebOverviewQuery,WebStatsTableQuery,+ WebVitalsQuery,)from posthog.hogql import ast@@ -902,6 +903,41 @@ def get_query_runner(team=team,)+ if kind == "WebVitalsQuery":+ from products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute import (+ is_vitals_precompute_enabled_for_team,+ )++ # This runner is a plain TrendsQueryRunner subclass, so it can only+ # handle the canonical line-graph tab shape over a TrendsQuery source.+ # A non-Trends source, or any other display (total-value, cumulative,+ # calendar heatmap, box plot, slope graph), must reach the source's own+ # dispatch below — several map to dedicated runners — so let those fall+ # through and unwrap to the source rather than take this branch.+ # Routing a non-Trends source here would raise in the constructor, and+ # `get_query_runner_or_none` re-raises that instead of unwrapping.+ source = get_from_dict_or_attr(query, "source")+ source_is_trends = source is not None and get_from_dict_or_attr(source, "kind") == "TrendsQuery"+ source_trends_filter = get_from_dict_or_attr(source, "trendsFilter") if source_is_trends else None+ source_display = get_from_dict_or_attr(source_trends_filter, "display") if source_trends_filter else None+ is_canonical_display = source_display is None or source_display == ChartDisplayType.ACTIONS_LINE_GRAPH++ # Flag-gated at dispatch: with the rollout flag off this kind has no+ # runner branch, so `process_query_model` unwraps to the source+ # exactly as before the runner existed. Local flag evaluation only — no+ # network I/O here.+ if source_is_trends and is_canonical_display and is_vitals_precompute_enabled_for_team(team):+ from products.web_analytics.backend.hogql_queries.web_vitals_timeseries import WebVitalsQueryRunner++ return WebVitalsQueryRunner(+ query=cast(WebVitalsQuery | dict[str, Any], query),+ team=team,+ timings=timings,+ limit_context=limit_context,+ modifiers=modifiers,+ user=user,+ )+if kind == "WebPageURLSearchQuery":from products.web_analytics.backend.hogql_queries.page_url_search_query_runner import PageUrlSearchQueryRunnerdiff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 6e2c80665cb9..55802ed617a7 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -291,6 +291,12 @@ Accepted semantic differences vs vanilla trends (the tiles align with the overviThe Active Hours path is stricter than the trend tiles: it falls back to the live heatmap for teams that track both `$pageview` and `$screen` (the buckets carry no event dimension, and the live heatmap filters exactly to the requested event), for teams aggregating by distinct ID, and for date bounds that are not hour-aligned in UTC (explicit sub-hour ranges, fractional-offset timezones).+### Web Vitals tab timeseries++The Web Vitals tab's timeseries tile sends a `WebVitalsQuery` wrapper whose `source` is a TrendsQuery of four `$web_vitals` percentile series. With the `web-analytics-vitals-precompute` flag (locally evaluated, fails closed) on for the team, dispatch routes it to `WebVitalsQueryRunner`, which merges the per-path quantile states of the `web_vitals_paths_preaggregated` buckets into per-day tab-level percentiles — the same buckets the path-breakdown tile on the same tab keeps warm, so the inner ensure hashes to the sibling tile's job family and both tiles share one set of jobs. With the flag off the kind has no runner branch and `process_query_model` unwraps to the source TrendsQuery, the pre-existing live path.++Servable shapes: the canonical four-series tab query with a shared p75/p90/p99 percentile, day-aligned ranges, and day/week/month intervals (buckets are team-tz daily, so hour interval falls back). p95, compare, breakdowns, formulas, per-series filters, per-series math multipliers, and conversion goals fall back. Only the line-graph display is servable; any other display (total-value, cumulative, and the displays with dedicated runners — calendar heatmap, box plot, slope graph) unwraps to its source TrendsQuery so the source's own dispatch handles it. Accepted semantic difference vs the live path: events with a NULL `$pathname` are absent from the buckets, so they are excluded from the served percentiles.+## Related code- `products/web_analytics/backend/hogql_queries/web_overview.py` — runnerdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.pynew file mode 100644index 000000000000..529637fbdaa4--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_timeseries_lazy_precompute.py@@ -0,0 +1,294 @@+from collections.abc import Iterator+from contextlib import ExitStack, contextmanager+from typing import Any, Optional++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,+ PropertyOperator,+ RetentionFilter,+ RetentionQuery,+ TrendsFilter,+ TrendsQuery,+ WebVitalsQuery,+)++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.query_tagging import Feature, Product, reset_query_tags, tag_queries+from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner+from posthog.hogql_queries.query_runner import get_query_runner_or_none++from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.web_analytics.backend.hogql_queries.web_vitals_timeseries import WebVitalsQueryRunner+from products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute import (+ is_vitals_precompute_enabled_for_team,+ vitals_timeseries_percentile,+)++_METRICS = ["INP", "LCP", "CLS", "FCP"]+++def _series(+ metric: str,+ math: str = "p90",+ math_property: Optional[str] = None,+ math_multiplier: Optional[float] = None,+) -> EventsNode:+ return EventsNode(+ event="$web_vitals",+ name="$web_vitals",+ custom_name=metric,+ math=math,+ math_property=math_property or f"$web_vitals_{metric}_value",+ math_multiplier=math_multiplier,+ )+++def _vitals_query(**overrides: Any) -> WebVitalsQuery:+ source_kwargs: dict[str, Any] = {+ "dateRange": DateRange(date_from="2024-01-01", date_to="2024-01-07"),+ "series": [_series(m) for m in _METRICS],+ "properties": [],+ "filterTestAccounts": False,+ }+ source_kwargs.update(overrides.pop("source_overrides", {}))+ wrapper_kwargs: dict[str, Any] = {"properties": []}+ wrapper_kwargs.update(overrides)+ return WebVitalsQuery(+ source=TrendsQuery(**source_kwargs),+ **wrapper_kwargs,+ )+++class TestVitalsTimeseriesGate(APIBaseTest):+ def test_canonical_tab_shape_is_servable(self) -> None:+ assert vitals_timeseries_percentile(_vitals_query()) == "p90"+ # The tab query the frontend builds pins the line-graph display explicitly.+ assert (+ vitals_timeseries_percentile(+ _vitals_query(+ source_overrides={"trendsFilter": TrendsFilter(display=ChartDisplayType.ACTIONS_LINE_GRAPH)}+ )+ )+ == "p90"+ )++ @parameterized.expand(+ [+ ("p95_not_stored", {"source_overrides": {"series": [_series(m, math="p95") for m in _METRICS]}}),+ (+ "mixed_percentiles",+ {+ "source_overrides": {+ "series": [_series("INP", math="p75")] + [_series(m, math="p90") for m in _METRICS[1:]]+ }+ },+ ),+ ("missing_series", {"source_overrides": {"series": [_series(m) for m in _METRICS[:3]]}}),+ (+ "wrong_math_property",+ {"source_overrides": {"series": [_series(m, math_property="$other") for m in _METRICS]}},+ ),+ ("hour_interval", {"source_overrides": {"interval": IntervalType.HOUR}}),+ (+ "total_value_display",+ {"source_overrides": {"trendsFilter": TrendsFilter(display=ChartDisplayType.ACTIONS_BAR_VALUE)}},+ ),+ (+ "math_multiplier",+ {"source_overrides": {"series": [_series(m, math_multiplier=2.0) for m in _METRICS]}},+ ),+ ("sampled_source", {"source_overrides": {"samplingFactor": 0.5}}),+ (+ "weekday_filtered_range",+ {+ "source_overrides": {+ "dateRange": DateRange(date_from="2024-01-01", date_to="2024-01-07", daysOfWeek=[1, 2, 3])+ }+ },+ ),+ (+ "breakdown",+ {"source_overrides": {"breakdownFilter": BreakdownFilter(breakdown="$browser")}},+ ),+ ("compare", {"source_overrides": {"compareFilter": CompareFilter(compare=True)}}),+ ]+ )+ def test_non_canonical_shapes_fall_back(self, _name: str, overrides: dict[str, Any]) -> None:+ assert vitals_timeseries_percentile(_vitals_query(**overrides)) is None++ def test_flag_check_fails_closed_on_evaluation_error(self) -> None:+ # The gate runs in dispatch and cache-key generation, outside the+ # calculation fallback handler, so a flag-evaluation error must return+ # False (use the live path) rather than fail the request.+ with patch(+ "products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute.posthoganalytics.feature_enabled",+ side_effect=Exception("flag service unavailable"),+ ):+ assert is_vitals_precompute_enabled_for_team(self.team) is False+++@override_settings(IN_UNIT_TESTING=True)+class TestWebVitalsTimeseriesLazyPrecompute(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_vitals_paths_preaggregated")++ @contextmanager+ def _enable(self) -> Iterator[None]:+ with ExitStack() as stack:+ stack.enter_context(+ patch(+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",+ return_value=True,+ )+ )+ stack.enter_context(+ patch(+ "products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=True,+ )+ )+ yield++ def _seed(self) -> None:+ # Vitals samples across two days and two paths — the read must merge+ # quantile states across paths into one per-day tab value.+ _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={})+ for day, path, inp, lcp in [+ ("2024-01-02T10:00:00Z", "/home", 120.0, 2100.0),+ ("2024-01-02T11:00:00Z", "/docs", 480.0, 3900.0),+ ("2024-01-03T09:00:00Z", "/home", 90.0, 1500.0),+ ]:+ _create_event(+ team=self.team,+ event="$web_vitals",+ distinct_id="p1",+ timestamp=day,+ properties={+ "$pathname": path,+ "$web_vitals_INP_value": inp,+ "$web_vitals_LCP_value": lcp,+ "$web_vitals_CLS_value": 0.05,+ "$web_vitals_FCP_value": 900.0,+ },+ )++ def _warm(self, query: WebVitalsQuery) -> None:+ # Mimic the SWR revalidation task: under a warming trigger the ensure+ # runs inserts inline instead of check-only, building the buckets a+ # plain user read can then be served from.+ tag_queries(+ team_id=self.team.pk,+ trigger="webAnalyticsStaleRevalidation",+ feature=Feature.CACHE_WARMUP,+ product=Product.WEB_ANALYTICS,+ )+ try:+ WebVitalsQueryRunner(team=self.team, query=query).calculate()+ finally:+ reset_query_tags()++ @freeze_time("2024-01-15T12:00:00Z")+ def test_precomputed_matches_live_trends(self) -> None:+ self._seed()+ query = _vitals_query()+ source = query.source+ assert isinstance(source, TrendsQuery)++ live = TrendsQueryRunner(team=self.team, query=source).calculate()++ with self._enable():+ self._warm(query)+ precomputed = WebVitalsQueryRunner(team=self.team, query=query).calculate()++ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0+ # The live path stamps printed HogQL on the response; the bucket path+ # never does. A None here proves the serve did not silently fall back.+ assert precomputed.hogql is None+ assert live.hogql is not None+ assert len(precomputed.results) == len(live.results) == 4+ for live_series, pre_series in zip(live.results, precomputed.results):+ assert pre_series["days"] == live_series["days"]+ assert pre_series["data"] == live_series["data"], live_series["action"]["custom_name"]+ assert pre_series["action"]["custom_name"] == live_series["action"]["custom_name"]++ @freeze_time("2024-01-15T12:00:00Z")+ def test_dispatch_routes_only_when_flag_enabled(self) -> None:+ query = _vitals_query().model_dump(mode="json")++ runner = get_query_runner_or_none(query, self.team)+ assert runner is None # Flag off: no runner branch, legacy source unwrap.++ with patch(+ "products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=True,+ ):+ runner = get_query_runner_or_none(query, self.team)+ assert isinstance(runner, WebVitalsQueryRunner)++ def test_dispatch_skips_runner_for_non_line_display(self) -> None:+ # Non-line displays (here a calendar heatmap) have dedicated trends+ # runners the plain-trends WebVitals runner can't reproduce, so with the+ # flag on the wrapper must still unwrap to its source rather than route+ # here.+ query = _vitals_query(+ source_overrides={"trendsFilter": TrendsFilter(display=ChartDisplayType.CALENDAR_HEATMAP)}+ ).model_dump(mode="json")+ with patch(+ "products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=True,+ ):+ runner = get_query_runner_or_none(query, self.team)+ assert runner is None++ def test_dispatch_skips_runner_for_non_trends_source(self) -> None:+ # A schema-valid non-Trends source must fall through to the legacy source+ # unwrap, not raise in the runner constructor (which would surface as an+ # internal error rather than running the query).+ query = WebVitalsQuery(source=RetentionQuery(retentionFilter=RetentionFilter()), properties=[]).model_dump(+ mode="json"+ )+ with patch(+ "products.web_analytics.backend.hogql_queries.web_vitals_timeseries_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=True,+ ):+ runner = get_query_runner_or_none(query, self.team)+ assert runner is None++ def test_cache_payload_carries_flag_state_as_kill_switch(self) -> None:+ query = _vitals_query()+ runner = WebVitalsQueryRunner(team=self.team, query=query)+ assert runner.get_cache_payload()["web_vitals_timeseries_precompute"] is False+ with self._enable():+ assert runner.get_cache_payload()["web_vitals_timeseries_precompute"] is True++ def test_cache_payload_varies_with_wrapper_filters(self) -> None:+ # The precompute read builds its jobs from the wrapper's own properties,+ # so two wrappers sharing a source but differing in outer filters must+ # not share a cache entry.+ base = WebVitalsQueryRunner(team=self.team, query=_vitals_query())+ filtered = WebVitalsQueryRunner(+ team=self.team,+ query=_vitals_query(+ properties=[EventPropertyFilter(key="$host", value="a.com", operator=PropertyOperator.EXACT)]+ ),+ )+ assert (+ base.get_cache_payload()["web_vitals_wrapper_properties"]+ != filtered.get_cache_payload()["web_vitals_wrapper_properties"]+ )diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_timeseries.py b/products/web_analytics/backend/hogql_queries/web_vitals_timeseries.pynew file mode 100644index 000000000000..063b8ddf78f5--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_vitals_timeseries.py@@ -0,0 +1,88 @@+from typing import Any, cast++from posthog.schema import QueryTiming, ResolvedDateRangeResponse, TrendsQuery, TrendsQueryResponse, WebVitalsQuery++from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner+from posthog.schema_helpers import to_dict++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_vitals_timeseries_lazy_precompute import (+ execute_lazy_precomputed_vitals_timeseries,+ is_vitals_precompute_enabled_for_team,+)+++class WebVitalsQueryRunner(TrendsQueryRunner):+ """Runner for the Web Vitals tab query — a WebVitalsQuery wrapper whose+ `source` is a TrendsQuery of the four metric series. Without this runner+ the wrapper has no `get_query_runner` branch and `process_query_model`+ unwraps to the source, so dispatch only routes here when the vitals+ precompute flag is on; falling back preserves that exact live path.++ Serves the timeseries from the shared vitals-paths precompute buckets+ (the ones the path-breakdown tile on the same tab keeps warm) and falls+ back to the live trends path for everything else. Subclassing keeps the+ response contract; the class name gives the result cache a distinct+ namespace from vanilla trends entries.+ """++ def __init__(self, query: WebVitalsQuery | dict[str, Any], **kwargs: Any):+ vitals_query = query if isinstance(query, WebVitalsQuery) else WebVitalsQuery.model_validate(query)+ self.vitals_query = vitals_query+ source = vitals_query.source+ if not isinstance(source, TrendsQuery):+ # Dispatch only routes TrendsQuery-sourced wrappers here (non-Trends+ # sources fall through to the legacy source unwrap), so this guards+ # against direct/invalid construction, not the dispatch path.+ raise ValueError(f"WebVitalsQueryRunner requires a TrendsQuery source, got {type(source).__name__}")+ super().__init__(query=source, **kwargs)++ def get_cache_payload(self) -> dict:+ payload = super().get_cache_payload()+ # Rollout state in the cache key = immediate kill switch: disabling a+ # flag must not keep serving cached precompute-derived results until+ # they stale out (same mechanism as WebTrendsQueryRunner).+ payload["web_vitals_timeseries_precompute"] = is_vitals_precompute_enabled_for_team(+ self.team+ ) and is_precompute_enabled_for_team(self.team)+ # `super()` serializes only the inner TrendsQuery, but the precompute+ # read builds its jobs from the wrapper's own filters (see+ # `_build_inner_path_breakdown_query`). Fold those into the key — using+ # the base payload's normalization — so two wrappers that share a source+ # but differ in outer filters can't collide.+ wrapper = to_dict(self.vitals_query)+ payload["web_vitals_wrapper_properties"] = wrapper.get("properties")+ payload["web_vitals_wrapper_do_path_cleaning"] = wrapper.get("doPathCleaning")+ return payload++ def enqueue_async_calculation(self, *args: Any, **kwargs: Any) -> Any:+ # The async payload is `self.query.model_dump()`, which here is the+ # bare source; a worker rebuilding from that would run plain trends+ # under this runner's cache key. Serialize the wrapper instead so+ # dispatch routes the worker back to this runner.+ original = self.query+ # Deliberate type lie for the duration of the enqueue: the base method+ # only calls model_dump() on it, and the worker validates the payload+ # back into a WebVitalsQuery at dispatch.+ self.query = cast(TrendsQuery, self.vitals_query)+ try:+ return super().enqueue_async_calculation(*args, **kwargs)+ finally:+ self.query = original++ def _calculate(self) -> TrendsQueryResponse:+ results = execute_lazy_precomputed_vitals_timeseries(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(),+ ),+ )diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_timeseries_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_vitals_timeseries_lazy_precompute.pynew file mode 100644index 000000000000..5ad240842ade--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_vitals_timeseries_lazy_precompute.py@@ -0,0 +1,392 @@+import time+from datetime import UTC, datetime+from typing import TYPE_CHECKING, Any, Optional++import structlog+import posthoganalytics+from prometheus_client import Counter++from posthog.schema import (+ ChartDisplayType,+ EventsNode,+ IntervalType,+ TrendsQuery,+ WebVitalsMetric,+ WebVitalsPathBreakdownQuery,+ WebVitalsPercentile,+ WebVitalsQuery,+)++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.preaggregation.web_vitals_paths_preaggregated_sql import (+ DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE,+)+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+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,+ 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_vitals_path_breakdown import WebVitalsPathBreakdownQueryRunner+from products.web_analytics.backend.hogql_queries.web_vitals_paths_lazy_precompute import (+ can_use_lazy_precompute as can_use_vitals_paths_lazy_precompute,+ ensure_web_vitals_paths_precomputed,+)++if TYPE_CHECKING:+ from products.web_analytics.backend.hogql_queries.web_vitals_timeseries import WebVitalsQueryRunner++logger = structlog.get_logger(__name__)++_FAMILY = "web_vitals_timeseries"++VITALS_TIMESERIES_FLAG_KEY = "web-analytics-vitals-precompute"++WEB_VITALS_TIMESERIES_LAZY_FAILED = Counter(+ "web_vitals_timeseries_lazy_precompute_failed_total",+ "Web vitals timeseries lazy precompute path failures, by error class",+ ["error_type"],+)++# The four metric tabs, in the series order the frontend builds them. Each+# series carries `math_property=$web_vitals_<METRIC>_value` and the read maps+# it onto the matching quantile-state column of the shared vitals buckets.+_METRIC_ORDER: list[WebVitalsMetric] = [+ WebVitalsMetric.INP,+ WebVitalsMetric.LCP,+ WebVitalsMetric.CLS,+ WebVitalsMetric.FCP,+]++_MATH_PROPERTY_TO_METRIC: dict[str, WebVitalsMetric] = {+ f"$web_vitals_{metric.value}_value": metric for metric in _METRIC_ORDER+}++_METRIC_STATE_COLUMN: dict[WebVitalsMetric, str] = {+ WebVitalsMetric.INP: "inp_quantiles_state",+ WebVitalsMetric.LCP: "lcp_quantiles_state",+ WebVitalsMetric.CLS: "cls_quantiles_state",+ WebVitalsMetric.FCP: "fcp_quantiles_state",+}++# 1-based `arrayElement` index into the stored `quantiles(0.75, 0.90, 0.99)`+# reservoir. p95 is not stored, so the gate rejects it.+_MATH_TO_PCT_INDEX: dict[str, int] = {"p75": 1, "p90": 2, "p99": 3}++_MATH_TO_PERCENTILE: dict[str, WebVitalsPercentile] = {+ "p75": WebVitalsPercentile.P75,+ "p90": WebVitalsPercentile.P90,+ "p99": WebVitalsPercentile.P99,+}++# Buckets are team-tz daily, so hour interval cannot be served. Week/month+# group the daily keys the same way the trends preagg read does.+_BUCKET_EXPRS: dict[str, str] = {+ "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)))",+}++_READ_SETTINGS = {"max_execution_time": 30}+++def is_vitals_precompute_enabled_for_team(team: Team) -> bool:+ """Evaluate the vitals-timeseries rollout flag locally. 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,+ mirroring the trends precompute ramp."""+ try:+ return bool(+ posthoganalytics.feature_enabled(+ VITALS_TIMESERIES_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,+ )+ )+ except Exception:+ logger.exception("web_vitals_precompute_flag_check_failed", team_id=team.pk)+ return False+++def vitals_timeseries_percentile(query: WebVitalsQuery, source: Optional[TrendsQuery] = None) -> Optional[str]:+ """Return the shared percentile math ('p75'/'p90'/'p99') when the query is+ the canonical Web Vitals tab shape, or None when the shape can't be served+ from the daily vitals buckets (caller falls back to the live trends path).++ The canonical shape is what `webAnalyticsLogic` builds: a TrendsQuery+ source with one `$web_vitals` EventsNode per metric, all carrying the same+ percentile math over `$web_vitals_<METRIC>_value`.+ """+ if source is None:+ source = query.source if isinstance(query.source, TrendsQuery) else None+ if source is None:+ return None+ if query.conversionGoal is not None:+ return None+ if query.compareFilter is not None and query.compareFilter.compare:+ return None+ if source.compareFilter is not None and source.compareFilter.compare:+ return None+ if source.breakdownFilter is not None:+ return None+ if source.samplingFactor is not None:+ # The live path samples events before computing the percentile; the+ # buckets hold the full-population quantile state, so a sampled source+ # would drift (same reason the sibling web_trends gate rejects it).+ return None+ if source.dateRange is not None and source.dateRange.daysOfWeek:+ # Live trends filters events to the selected weekdays (and drops the+ # deselected day buckets for day intervals); the bucket read merges every+ # day in range and emits the full axis, so it can't reproduce that.+ return None+ tf = source.trendsFilter+ if tf is not None:+ # Only the canonical line graph is servable. Total-value displays+ # collapse the range to one row and cumulative displays running-sum each+ # bucket; the per-bucket bucket read reproduces neither (same gate the+ # sibling web_trends runner applies).+ 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++ interval = (source.interval or IntervalType.DAY).value+ if interval not in _BUCKET_EXPRS:+ return None++ if len(source.series) != len(_METRIC_ORDER):+ return None+ shared_math: Optional[str] = None+ for series, expected_metric in zip(source.series, _METRIC_ORDER):+ if not isinstance(series, EventsNode):+ return None+ if series.event != "$web_vitals":+ return None+ if series.fixedProperties or series.properties:+ return None+ # The live path multiplies the property before computing the percentile;+ # the buckets store raw quantile state, so a multiplier would be silently+ # ignored (same reason the sibling web_trends gate rejects it).+ if series.math_multiplier is not None:+ return None+ math = str(series.math) if series.math is not None else ""+ if math not in _MATH_TO_PCT_INDEX:+ return None+ if shared_math is None:+ shared_math = math+ elif math != shared_math:+ return None+ if _MATH_PROPERTY_TO_METRIC.get(series.math_property or "") != expected_metric:+ return None+ return shared_math+++def _build_inner_path_breakdown_query(+ query: WebVitalsQuery, source: TrendsQuery, percentile: WebVitalsPercentile+) -> WebVitalsPathBreakdownQuery:+ """Build the sibling path-breakdown tile's query for the same filters, so+ the ensure hashes to the same bucket family and both vitals tiles share+ one set of precomputed jobs. `metric` and `thresholds` only shape the+ sibling's read, not the insert, so constants are safe here. Filters come+ from the runner's effective source: dashboard filters mutate that copy,+ and building from the pristine wrapper would serve unfiltered buckets."""+ return WebVitalsPathBreakdownQuery(+ dateRange=source.dateRange,+ properties=list(source.properties or []),+ filterTestAccounts=source.filterTestAccounts,+ doPathCleaning=query.doPathCleaning,+ metric=WebVitalsMetric.INP,+ percentile=percentile,+ thresholds=[0.0, 0.0],+ )+++def _read_timeseries(+ *,+ team: Team,+ interval: str,+ pct_index: int,+ job_ids: list[str],+ range_start_utc: datetime,+ range_end_utc: datetime,+) -> dict[WebVitalsMetric, dict[datetime, float]]:+ week_mode = WeekStartDay(team.week_start_day or 0).clickhouse_mode+ bucket_expr = _BUCKET_EXPRS[interval].format(week_mode=week_mode)+ metric_cols = ",\n ".join(+ # An empty reservoir merges to NaN; the live percentile math emits 0+ # for buckets with no samples, so mirror that.+ f"ifNotFinite(arrayElement(quantilesMergeIf(0.75, 0.90, 0.99)("+ f"{_METRIC_STATE_COLUMN[metric]}, and(time_window_start >= %(range_start)s, time_window_start < %(range_end)s)"+ f"), %(pct_index)s), 0) AS {metric.value.lower()}_value"+ for metric in _METRIC_ORDER+ )+ sql = f"""+SELECT {bucket_expr} AS bucket,+ {metric_cols}+FROM {DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE()}+WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s+GROUP BY bucket+"""+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY, query_type="web_vitals_timeseries_lazy_query")+ rows = sync_execute(+ sql,+ {+ "team_id": team.pk,+ "job_ids": tuple(job_ids),+ "tz": team.timezone,+ "pct_index": pct_index,+ "range_start": range_start_utc,+ "range_end": range_end_utc,+ },+ settings=_READ_SETTINGS,+ team_id=team.pk,+ )+ result: dict[WebVitalsMetric, dict[datetime, float]] = {metric: {} for metric in _METRIC_ORDER}+ for row in rows:+ bucket = row[0].replace(tzinfo=None)+ for offset, metric in enumerate(_METRIC_ORDER):+ result[metric][bucket] = float(row[1 + offset])+ return result+++def _series_dict(+ runner: "WebVitalsQueryRunner",+ *,+ order: int,+ series: EventsNode,+ metric_values: dict[datetime, float],+) -> dict[str, Any]:+ date_range = runner.query_date_range+ 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_label = runner.series_event(series)++ return {+ "data": data,+ "labels": [format_label_date(item, 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": date_range.all_values(),+ "id": series_label,+ "type": "events",+ "order": order,+ "name": series_label or "All events",+ "custom_name": series.custom_name,+ "math": series.math,+ "math_property": series.math_property,+ "math_hogql": series.math_hogql,+ "math_group_type_index": series.math_group_type_index,+ "properties": {},+ },+ "order": order,+ }+++def execute_lazy_precomputed_vitals_timeseries(runner: "WebVitalsQueryRunner") -> Optional[list[dict[str, Any]]]:+ """Serve the Web Vitals tab timeseries from the shared vitals-paths preagg+ buckets — the same buckets the path-breakdown tile on the same tab keeps+ warm. Quantile states merge across paths into per-bucket tab-level+ percentiles. Returns the formatted results list, or None on any+ ineligibility/miss (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:+ shared_math = vitals_timeseries_percentile(runner.vitals_query, runner.query)+ if shared_math is None:+ return None+ if not is_vitals_precompute_enabled_for_team(team):+ return None++ inner_query = _build_inner_path_breakdown_query(+ runner.vitals_query, runner.query, _MATH_TO_PERCENTILE[shared_math]+ )+ # The shared gate already rejects teams with property access rules, so no+ # user-scoped restriction can reach a bucket read; the user is threaded+ # through anyway so the inner runner is never more privileged than the+ # request that spawned it.+ inner_runner = WebVitalsPathBreakdownQueryRunner(+ query=inner_query, team=team, modifiers=runner.modifiers, user=runner.user+ )+ if not can_use_vitals_paths_lazy_precompute(inner_runner):+ 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+ 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_vitals_paths_precomputed(+ runner=inner_runner,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ )+ if result.stale:+ handle_stale_served(runner=inner_runner, family="web_vitals_paths")+ 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++ metric_values = _read_timeseries(+ team=team,+ interval=(runner.query.interval or IntervalType.DAY).value,+ pct_index=_MATH_TO_PCT_INDEX[shared_math],+ job_ids=[str(jid) for jid in result.job_ids],+ range_start_utc=cur_start_utc,+ range_end_utc=cur_end_utc,+ )++ results = [+ _series_dict(runner, order=order, series=series, metric_values=metric_values[_METRIC_ORDER[order]])+ for order, series in enumerate(runner.query.series)+ if isinstance(series, EventsNode)+ ]+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=_FAMILY).inc()+ logger.info(+ "web_vitals_timeseries_lazy_precompute_served",+ team_id=team.pk,+ job_count=len(result.job_ids),+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return results+ except Exception as exc:+ WEB_VITALS_TIMESERIES_LAZY_FAILED.labels(error_type=type(exc).__name__).inc()+ logger.exception(+ "web_vitals_timeseries_lazy_precompute_failed",+ team_id=team.pk,+ error_type=type(exc).__name__,+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return None