: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): lazy precomputation for web vitals paths tile (#59791)
Lucas Ricoy497871e34d88
diff --git a/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.tsx b/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.tsxindex a99d35122637..56815021b926 100644--- a/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.tsx+++ b/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.tsx@@ -3,6 +3,7 @@ import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'import { useMemo, useState } from 'react'import { parseAliasToReadable } from 'lib/components/PathCleanFilters/PathCleanFilterItem'+import { PreAggregatedBadge } from 'lib/components/PreAggregatedBadge'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'@@ -52,7 +53,8 @@ export function WebVitalsPathBreakdown(props: {const webVitalsQueryResponse = response as WebVitalsPathBreakdownQueryResponse | undefinedreturn (- <div className="border rounded bg-surface-primary grid grid-cols-1 md:grid-cols-3 divide-y md:divide-y-0 md:divide-x min-h-60 h-full">+ <div className="relative border rounded bg-surface-primary grid grid-cols-1 md:grid-cols-3 divide-y md:divide-y-0 md:divide-x min-h-60 h-full">+ {webVitalsQueryResponse?.usedLazyPrecompute && <PreAggregatedBadge variant="precomputed" />}<div className="p-4"><Header band="good" label="Good" /><Content band="good" response={webVitalsQueryResponse} responseLoading={responseLoading} />diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 56818ae37e58..96c0bb6b5895 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -10191,6 +10191,9 @@"$ref": "#/definitions/QueryTiming"},"type": "array"+ },+ "usedLazyPrecompute": {+ "type": "boolean"}},"required": [@@ -12122,6 +12125,9 @@"$ref": "#/definitions/QueryTiming"},"type": "array"+ },+ "usedLazyPrecompute": {+ "type": "boolean"}},"required": ["results"],@@ -29441,6 +29447,9 @@"$ref": "#/definitions/QueryTiming"},"type": "array"+ },+ "usedLazyPrecompute": {+ "type": "boolean"}},"required": ["results"],@@ -30481,6 +30490,9 @@"$ref": "#/definitions/QueryTiming"},"type": "array"+ },+ "usedLazyPrecompute": {+ "type": "boolean"}},"required": ["results"],@@ -40931,6 +40943,10 @@"deprecated": "ignored, always treated as enabled *","type": "boolean"},+ "useWebAnalyticsPrecompute": {+ "description": "Opt this specific query into the web vitals path breakdown precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. *",+ "type": "boolean"+ },"version": {"description": "version of the node, used for schema migrations","type": "number"@@ -40976,6 +40992,9 @@"$ref": "#/definitions/QueryTiming"},"type": "array"+ },+ "usedLazyPrecompute": {+ "type": "boolean"}},"required": ["results"],diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex d0723e881314..3e709fb4f0a5 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2469,6 +2469,8 @@ export interface WebVitalsPathBreakdownQuery extends WebAnalyticsQueryBase<WebVi// This tuple represents a [good, poor] threshold, where values below good are good and values above poor are poor// Values in between the two values are the threshold for needs_improvementsthresholds: [number, number]+ /** Opt this specific query into the web vitals path breakdown precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. **/+ useWebAnalyticsPrecompute?: boolean}export type WebVitalsPathBreakdownResultItem = { path: string; value: number }@@ -2478,6 +2480,7 @@ export type WebVitalsPathBreakdownResult = Record<WebVitalsMetricBand, WebVitals// hence the tuple type rather than a single object.export interface WebVitalsPathBreakdownQueryResponse extends AnalyticsQueryResponseBase {results: [WebVitalsPathBreakdownResult]+ usedLazyPrecompute?: boolean}export type CachedWebVitalsPathBreakdownQueryResponse = CachedQueryResponse<WebVitalsPathBreakdownQueryResponse>diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsxindex f5f69322427d..50337639141c 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx@@ -1253,6 +1253,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([WEB_VITALS_THRESHOLDS[webVitalsTab].good,WEB_VITALS_THRESHOLDS[webVitalsTab].poor,],+ useWebAnalyticsPrecompute,},insightProps: {dashboardItemId: getDashboardItemId(diff --git a/posthog/clickhouse/migrations/0264_web_vitals_paths_preaggregated.py b/posthog/clickhouse/migrations/0264_web_vitals_paths_preaggregated.pynew file mode 100644index 000000000000..3503cec75d10--- /dev/null+++ b/posthog/clickhouse/migrations/0264_web_vitals_paths_preaggregated.py@@ -0,0 +1,29 @@+from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from posthog.clickhouse.preaggregation.web_vitals_paths_preaggregated_sql import (+ DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,+)++operations = [+ # Sharded data table on AUX (the precompute table is small and never JOINed+ # against events — keeping it off the main DATA cluster avoids contention).+ run_sql_with_exceptions(+ SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ sharded=True,+ ),+ # Distributed read table on DATA — production query path fans out from data+ # nodes and resolves to AUX shards via the Distributed engine's `cluster=AUX`.+ run_sql_with_exceptions(+ DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.DATA],+ ),+ # Same distributed table also on AUX for ad-hoc debugging — lets operators+ # `SELECT … FROM web_vitals_paths_preaggregated` directly from an AUX node+ # instead of bouncing through DATA. Same DDL, no production cost.+ run_sql_with_exceptions(+ DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ ),+]diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txtindex 56b88e5b70fc..093470765f58 100644--- a/posthog/clickhouse/migrations/max_migration.txt+++ b/posthog/clickhouse/migrations/max_migration.txt@@ -1 +1 @@-0263_web_goals_and_frustration_preaggregated+0264_web_vitals_paths_preaggregateddiff --git a/posthog/clickhouse/preaggregation/web_vitals_paths_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_vitals_paths_preaggregated_sql.pynew file mode 100644index 000000000000..7968f1376be6--- /dev/null+++ b/posthog/clickhouse/preaggregation/web_vitals_paths_preaggregated_sql.py@@ -0,0 +1,114 @@+# Table for storing lazy-precomputed web vitals path-breakdown quantiles+#+# Stores per-day, per-team, per-path quantile-state aggregates matching+# `WebVitalsPathBreakdownQueryRunner`'s output. Reads merge across daily+# buckets and pick a single percentile (p75/p90/p99) via array indexing.+#+# Buckets are keyed by `toStartOfDay(event.timestamp, team_tz)` — the start+# of the team-local day (no session join in the raw query, so no session pad+# on the INSERT). One state column per Web Vitals metric (INP/LCP/CLS/FCP)+# — keeps the INSERT a single GROUP BY (vs. a discriminator column that+# would need ARRAY JOIN to fan out one event into four rows) and lets each+# metric tab read just one column.++from django.conf import settings++from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme++TABLE_BASE_NAME = "web_vitals_paths_preaggregated"+++def DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE():+ return TABLE_BASE_NAME+++def SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE():+ return f"sharded_{TABLE_BASE_NAME}"+++def SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_ENGINE():+ return ReplacingMergeTree(TABLE_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")+++WEB_VITALS_PATHS_PREAGGREGATED_TABLE_BASE_SQL = """+CREATE TABLE IF NOT EXISTS {table_name}+(+ team_id Int64,+ job_id UUID,++ -- Daily bucket keyed by `toStartOfDay(event.timestamp, team_tz)` — start+ -- of the team-local day. The raw vitals query has no session join, so no+ -- session-boundary pad is needed.+ time_window_start DateTime64(6, 'UTC'),++ -- Cleaned (or raw) `$pathname` — same expression the raw query uses, so+ -- post-cleaning paths land in the same row. Different `doPathCleaning`+ -- values hash to different cache keys via the placeholder substitution.+ path String,++ -- One reservoir per (path, day, metric) covering p75/p90/p99 in a single+ -- state. Reads pick a single percentile via+ -- `arrayElement(quantilesMergeIf(...), pct_index)`. Same reservoir+ -- algorithm as the raw `quantile(p)`; values match exactly when reservoir+ -- isn't saturated, within sampling noise once it is. Four columns instead+ -- of one row-per-metric keeps the INSERT a single GROUP BY without+ -- ARRAY JOIN, which is cheaper and avoids the new-analyzer's restriction+ -- on bare `events.properties` references in ARRAY JOIN source arrays.+ inp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ lcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ cls_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ fcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach TTLs like 15 min for "today".+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+) ENGINE = {engine}+"""+++def SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL():+ # Partition by `expires_at` (the TTL column) so `ttl_only_drop_parts=1` can+ # drop whole parts atomically when all rows in them expire. `path` must be+ # in ORDER BY so the ReplacingMergeTree does not collapse distinct paths+ # within one (job, day).+ return (+ WEB_VITALS_PATHS_PREAGGREGATED_TABLE_BASE_SQL+ + """+PARTITION BY toYYYYMMDD(expires_at)+ORDER BY (team_id, job_id, time_window_start, path)+TTL toDateTime(expires_at)+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1+"""+ ).format(+ table_name=SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE(),+ engine=SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_ENGINE(),+ )+++def DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL():+ # The sharded table lives on the AUX cluster (kept off the main events+ # data nodes — the precompute table is small and read by a narrow set of+ # queries that never JOIN against events). Distributed read table lives+ # on DATA so queries fan out from there and resolve to AUX shards.+ return WEB_VITALS_PATHS_PREAGGREGATED_TABLE_BASE_SQL.format(+ table_name=DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE(),+ engine=Distributed(+ data_table=SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE(),+ sharding_key="sipHash64(job_id)",+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ ),+ )+++def DROP_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE()}"+++def DROP_SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE()} SYNC"+++def TRUNCATE_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL():+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE()}"diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex 026f387ed5ca..cd9976a54f73 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -57,6 +57,10 @@ from posthog.clickhouse.preaggregation.web_stats_preaggregated_sql import (DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,)+from posthog.clickhouse.preaggregation.web_vitals_paths_preaggregated_sql import (+ DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,+)from posthog.clickhouse.property_values import (DISTRIBUTED_PROPERTY_VALUES_TABLE_SQL,KAFKA_PROPERTY_VALUES_TABLE_SQL_FN,@@ -313,6 +317,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (SHARDED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,DISTINCT_ID_USAGE_DATA_TABLE_SQL,PROPERTY_DEFINITIONS_TABLE_SQL,*[table.sharded_table_sql for table in EMBEDDING_TABLES],@@ -372,6 +377,7 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (DISTRIBUTED_CONVERSION_GOAL_ATTRIBUTED_TABLE_SQL,DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,+ DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,DOCUMENT_EMBEDDINGS_BUFFER_WRITABLE_TABLE_SQL,*[table.distributed_table_sql for table in EMBEDDING_TABLES],*[table.writable_table_sql for table in EMBEDDING_TABLES],diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex 4bbc45dfdc0c..a53547742f48 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -6276,6 +6276,51 @@'''# ---+# name: test_create_table_query[sharded_web_vitals_paths_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_web_vitals_paths_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Daily bucket keyed by `toStartOfDay(event.timestamp, team_tz)` — start+ -- of the team-local day. The raw vitals query has no session join, so no+ -- session-boundary pad is needed.+ time_window_start DateTime64(6, 'UTC'),++ -- Cleaned (or raw) `$pathname` — same expression the raw query uses, so+ -- post-cleaning paths land in the same row. Different `doPathCleaning`+ -- values hash to different cache keys via the placeholder substitution.+ path String,++ -- One reservoir per (path, day, metric) covering p75/p90/p99 in a single+ -- state. Reads pick a single percentile via+ -- `arrayElement(quantilesMergeIf(...), pct_index)`. Same reservoir+ -- algorithm as the raw `quantile(p)`; values match exactly when reservoir+ -- isn't saturated, within sampling noise once it is. Four columns instead+ -- of one row-per-metric keeps the INSERT a single GROUP BY without+ -- ARRAY JOIN, which is cheaper and avoids the new-analyzer's restriction+ -- on bare `events.properties` references in ARRAY JOIN source arrays.+ inp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ lcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ cls_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ fcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach TTLs like 15 min for "today".+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.web_vitals_paths_preaggregated', '{replica}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (team_id, job_id, time_window_start, path)+ TTL toDateTime(expires_at)+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1++ '''+# ---# name: test_create_table_query[tophog]'''@@ -6518,6 +6563,46 @@'''# ---+# name: test_create_table_query[web_vitals_paths_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS web_vitals_paths_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Daily bucket keyed by `toStartOfDay(event.timestamp, team_tz)` — start+ -- of the team-local day. The raw vitals query has no session join, so no+ -- session-boundary pad is needed.+ time_window_start DateTime64(6, 'UTC'),++ -- Cleaned (or raw) `$pathname` — same expression the raw query uses, so+ -- post-cleaning paths land in the same row. Different `doPathCleaning`+ -- values hash to different cache keys via the placeholder substitution.+ path String,++ -- One reservoir per (path, day, metric) covering p75/p90/p99 in a single+ -- state. Reads pick a single percentile via+ -- `arrayElement(quantilesMergeIf(...), pct_index)`. Same reservoir+ -- algorithm as the raw `quantile(p)`; values match exactly when reservoir+ -- isn't saturated, within sampling noise once it is. Four columns instead+ -- of one row-per-metric keeps the INSERT a single GROUP BY without+ -- ARRAY JOIN, which is cheaper and avoids the new-analyzer's restriction+ -- on bare `events.properties` references in ARRAY JOIN source arrays.+ inp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ lcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ cls_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ fcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach TTLs like 15 min for "today".+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = Distributed('aux', 'posthog_test', 'sharded_web_vitals_paths_preaggregated', sipHash64(job_id))++ '''+# ---# name: test_create_table_query[writable_app_metrics2]'''@@ -9667,6 +9752,51 @@'''# ---+# name: test_create_table_query_replicated_and_storage[sharded_web_vitals_paths_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_web_vitals_paths_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Daily bucket keyed by `toStartOfDay(event.timestamp, team_tz)` — start+ -- of the team-local day. The raw vitals query has no session join, so no+ -- session-boundary pad is needed.+ time_window_start DateTime64(6, 'UTC'),++ -- Cleaned (or raw) `$pathname` — same expression the raw query uses, so+ -- post-cleaning paths land in the same row. Different `doPathCleaning`+ -- values hash to different cache keys via the placeholder substitution.+ path String,++ -- One reservoir per (path, day, metric) covering p75/p90/p99 in a single+ -- state. Reads pick a single percentile via+ -- `arrayElement(quantilesMergeIf(...), pct_index)`. Same reservoir+ -- algorithm as the raw `quantile(p)`; values match exactly when reservoir+ -- isn't saturated, within sampling noise once it is. Four columns instead+ -- of one row-per-metric keeps the INSERT a single GROUP BY without+ -- ARRAY JOIN, which is cheaper and avoids the new-analyzer's restriction+ -- on bare `events.properties` references in ARRAY JOIN source arrays.+ inp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ lcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ cls_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),+ fcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach TTLs like 15 min for "today".+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.web_vitals_paths_preaggregated', '{replica}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (team_id, job_id, time_window_start, path)+ TTL toDateTime(expires_at)+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1++ '''+# ---# name: test_create_table_query_replicated_and_storage[web_pre_aggregated_bounces]'''diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex ac024d9c9a71..12daacc4325d 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -141,6 +141,7 @@ from posthog.hogql.database.schema.web_overview_preaggregated import WebOverviewfrom posthog.hogql.database.schema.web_stats_frustration_preaggregated import WebStatsFrustrationPreaggregatedTablefrom posthog.hogql.database.schema.web_stats_paths_preaggregated import WebStatsPathsPreaggregatedTablefrom posthog.hogql.database.schema.web_stats_preaggregated import WebStatsPreaggregatedTable+from posthog.hogql.database.schema.web_vitals_paths_preaggregated import WebVitalsPathsPreaggregatedTablefrom posthog.hogql.database.utils import get_join_field_chain, qualify_join_key_exprfrom posthog.hogql.errors import QueryError, ResolutionErrorfrom posthog.hogql.parser import parse_expr@@ -308,6 +309,9 @@ def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNod"web_stats_preaggregated": TableNode(name="web_stats_preaggregated", table=WebStatsPreaggregatedTable()),+ "web_vitals_paths_preaggregated": TableNode(+ name="web_vitals_paths_preaggregated", table=WebVitalsPathsPreaggregatedTable()+ ),"web_stats_frustration_preaggregated": TableNode(name="web_stats_frustration_preaggregated", table=WebStatsFrustrationPreaggregatedTable()),diff --git a/posthog/hogql/database/schema/web_vitals_paths_preaggregated.py b/posthog/hogql/database/schema/web_vitals_paths_preaggregated.pynew file mode 100644index 000000000000..cec0ddea7c13--- /dev/null+++ b/posthog/hogql/database/schema/web_vitals_paths_preaggregated.py@@ -0,0 +1,45 @@+from pydantic import Field++from posthog.hogql.constants import HogQLQuerySettings+from posthog.hogql.database.models import (+ DateTimeDatabaseField,+ FieldOrTable,+ IntegerDatabaseField,+ StringDatabaseField,+ Table,+ UnknownDatabaseField,+)++from posthog.clickhouse.preaggregation.web_vitals_paths_preaggregated_sql import (+ DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE,+)+++class WebVitalsPathsPreaggregatedTable(Table):+ # Mirrors `WebStatsPreaggregatedTable` / `WebOverviewPreaggregatedTable`:+ # deterministic replica selection via `load_balancing="in_order"` for+ # read-your-writes, and shard pruning via `optimize_skip_unused_shards=1`+ # since the table is sharded by `sipHash64(job_id)` and the read filters+ # `job_id IN (...)`.+ top_level_settings: HogQLQuerySettings | None = Field(+ default_factory=lambda: HogQLQuerySettings(load_balancing="in_order", optimize_skip_unused_shards=True)+ )++ fields: dict[str, FieldOrTable] = {+ "team_id": IntegerDatabaseField(name="team_id"),+ "job_id": StringDatabaseField(name="job_id"),+ "time_window_start": DateTimeDatabaseField(name="time_window_start"),+ "path": StringDatabaseField(name="path"),+ # One AggregateFunction(quantiles(0.75,0.9,0.99), Float64) column per+ # metric; the read picks the column for the queried metric.+ "inp_quantiles_state": UnknownDatabaseField(name="inp_quantiles_state"),+ "lcp_quantiles_state": UnknownDatabaseField(name="lcp_quantiles_state"),+ "cls_quantiles_state": UnknownDatabaseField(name="cls_quantiles_state"),+ "fcp_quantiles_state": UnknownDatabaseField(name="fcp_quantiles_state"),+ }++ def to_printed_clickhouse(self, context):+ return DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE()++ def to_printed_hogql(self):+ return "web_vitals_paths_preaggregated"diff --git a/posthog/hogql/functions/aggregations.py b/posthog/hogql/functions/aggregations.pyindex ab0f99bc0690..f498ab8f7846 100644--- a/posthog/hogql/functions/aggregations.py+++ b/posthog/hogql/functions/aggregations.py@@ -309,6 +309,14 @@ HOGQL_AGGREGATIONS: dict[str, HogQLFunctionMeta] = {"quantileIf": HogQLFunctionMeta("quantileIf", 2, 2, min_params=1, max_params=1, aggregate=True),"quantiles": HogQLFunctionMeta("quantiles", 1, None, aggregate=True),"quantilesIf": HogQLFunctionMeta("quantilesIf", 2, 2, min_params=1, max_params=1, aggregate=True),+ # `-State` and `-Merge*` combinators needed by lazy precompute paths that+ # store quantile reservoirs (e.g. web_vitals_paths_preaggregated). Params+ # are the percentile list; args are the value (for `-State`) or the+ # state + filter condition (for `-MergeIf`).+ "quantilesState": HogQLFunctionMeta("quantilesState", 1, 1, min_params=1, max_params=None, aggregate=True),+ "quantilesStateIf": HogQLFunctionMeta("quantilesStateIf", 2, 2, min_params=1, max_params=None, aggregate=True),+ "quantilesMerge": HogQLFunctionMeta("quantilesMerge", 1, 1, min_params=1, max_params=None, aggregate=True),+ "quantilesMergeIf": HogQLFunctionMeta("quantilesMergeIf", 2, 2, min_params=1, max_params=None, aggregate=True),"quantileExact": HogQLFunctionMeta("quantileExact", 1, 1, min_params=1, max_params=1, aggregate=True),# "quantileExactIf": HogQLFunctionMeta("quantileExactIf", 2, 2, aggregate=True),# "quantileExactLow": HogQLFunctionMeta("quantileExactLow", 1, 1, aggregate=True),diff --git a/posthog/schema.py b/posthog/schema.pyindex b6e5ca473d6e..4a306821fe7f 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -12855,6 +12855,7 @@ class CachedWebVitalsPathBreakdownQueryResponse(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ usedLazyPrecompute: bool | None = Noneclass CalendarHeatmapResponse(BaseModel):@@ -13443,6 +13444,7 @@ class Response8(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ usedLazyPrecompute: bool | None = Noneclass Response9(BaseModel):@@ -16334,6 +16336,7 @@ class QueryResponseAlternative27(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ usedLazyPrecompute: bool | None = Noneclass QueryResponseAlternative28(BaseModel):@@ -16869,6 +16872,7 @@ class QueryResponseAlternative47(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ usedLazyPrecompute: bool | None = Noneclass QueryResponseAlternative48(BaseModel):@@ -18910,6 +18914,7 @@ class WebVitalsPathBreakdownQueryResponse(BaseModel):default=None,description=("Measured timings for different parts of the query generation process"),)+ usedLazyPrecompute: bool | None = Noneclass WebVitalsQueryResponse(BaseModel):@@ -20524,6 +20529,14 @@ class WebVitalsPathBreakdownQuery(BaseModel):tags: QueryLogTags | None = Nonethresholds: list[float] = Field(..., max_length=2, min_length=2)useSessionsTable: bool | None = None+ useWebAnalyticsPrecompute: bool | None = Field(+ default=None,+ description=(+ "Opt this specific query into the web vitals path breakdown precompute"+ " path. Requires the `web-analytics-precompute-toggle` PostHog feature flag"+ " to be on for the team's organization for the gate to pass. *"+ ),+ )version: float | None = Field(default=None, description="version of the node, used for schema migrations")diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex e567b63f0318..b94733254388 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -280,6 +280,7 @@ class LazyComputationTable(StrEnum):WEB_OVERVIEW_PREAGGREGATED = "web_overview_preaggregated"WEB_STATS_PREAGGREGATED = "web_stats_preaggregated"WEB_STATS_PATHS_PREAGGREGATED = "web_stats_paths_preaggregated"+ WEB_VITALS_PATHS_PREAGGREGATED = "web_vitals_paths_preaggregated"WEB_STATS_FRUSTRATION_PREAGGREGATED = "web_stats_frustration_preaggregated"WEB_GOALS_PREAGGREGATED = "web_goals_preaggregated"diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambrindex 27dc3aaeac81..3b6fa7a7024d 100644--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr@@ -70,7 +70,7 @@These are the aggregated HogQL functions:```- ['avgIf', 'avgArray', 'avgArrayIf', 'avgArrayOrDefault', 'avgArrayOrDefaultIf', 'avgArrayOrNull', 'avgArrayOrNullIf', 'avgMap', 'avgMapIf', 'avgMapOrDefault', 'avgMapOrDefaultIf', 'avgMapOrNull', 'avgMapOrNullIf', 'avgState', 'avgStateIf', 'avgStateOrDefault', 'avgStateOrDefaultIf', 'avgStateOrNull', 'avgStateOrNullIf', 'avgMerge', 'avgMergeIf', 'avgMergeOrDefault', 'avgMergeOrDefaultIf', 'avgMergeOrNull', 'avgMergeOrNullIf', 'avgForEach', 'avgForEachIf', 'avgForEachOrDefault', 'avgForEachOrDefaultIf', 'avgForEachOrNull', 'avgForEachOrNullIf', 'avgOrDefault', 'avgOrDefaultIf', 'avgOrNull', 'avgOrNullIf', 'avgArgMin', 'avgArgMinIf', 'avgArgMinOrDefault', 'avgArgMinOrDefaultIf', 'avgArgMinOrNull', 'avgArgMinOrNullIf', 'avgArgMax', 'avgArgMaxIf', 'avgArgMaxOrDefault', 'avgArgMaxOrDefaultIf', 'avgArgMaxOrNull', 'avgArgMaxOrNullIf', 'sumIf', 'sumArray', 'sumArrayIf', 'sumArrayOrDefault', 'sumArrayOrDefaultIf', 'sumArrayOrNull', 'sumArrayOrNullIf', 'sumMap', 'sumMapIf', 'sumMapOrDefault', 'sumMapOrDefaultIf', 'sumMapOrNull', 'sumMapOrNullIf', 'sumState', 'sumStateIf', 'sumStateOrDefault', 'sumStateOrDefaultIf', 'sumStateOrNull', 'sumStateOrNullIf', 'sumMerge', 'sumMergeIf', 'sumMergeOrDefault', 'sumMergeOrDefaultIf', 'sumMergeOrNull', 'sumMergeOrNullIf', 'sumForEach', 'sumForEachIf', 'sumForEachOrDefault', 'sumForEachOrDefaultIf', 'sumForEachOrNull', 'sumForEachOrNullIf', 'sumOrDefault', 'sumOrDefaultIf', 'sumOrNull', 'sumOrNullIf', 'sumArgMin', 'sumArgMinIf', 'sumArgMinOrDefault', 'sumArgMinOrDefaultIf', 'sumArgMinOrNull', 'sumArgMinOrNullIf', 'sumArgMax', 'sumArgMaxIf', 'sumArgMaxOrDefault', 'sumArgMaxOrDefaultIf', 'sumArgMaxOrNull', 'sumArgMaxOrNullIf', 'minIf', 'minArray', 'minArrayIf', 'minArrayOrDefault', 'minArrayOrDefaultIf', 'minArrayOrNull', 'minArrayOrNullIf', 'minMap', 'minMapIf', 'minMapOrDefault', 'minMapOrDefaultIf', 'minMapOrNull', 'minMapOrNullIf', 'minState', 'minStateIf', 'minStateOrDefault', 'minStateOrDefaultIf', 'minStateOrNull', 'minStateOrNullIf', 'minMerge', 'minMergeIf', 'minMergeOrDefault', 'minMergeOrDefaultIf', 'minMergeOrNull', 'minMergeOrNullIf', 'minForEach', 'minForEachIf', 'minForEachOrDefault', 'minForEachOrDefaultIf', 'minForEachOrNull', 'minForEachOrNullIf', 'minOrDefault', 'minOrDefaultIf', 'minOrNull', 'minOrNullIf', 'minArgMin', 'minArgMinIf', 'minArgMinOrDefault', 'minArgMinOrDefaultIf', 'minArgMinOrNull', 'minArgMinOrNullIf', 'minArgMax', 'minArgMaxIf', 'minArgMaxOrDefault', 'minArgMaxOrDefaultIf', 'minArgMaxOrNull', 'minArgMaxOrNullIf', 'maxIf', 'maxArray', 'maxArrayIf', 'maxArrayOrDefault', 'maxArrayOrDefaultIf', 'maxArrayOrNull', 'maxArrayOrNullIf', 'maxMap', 'maxMapIf', 'maxMapOrDefault', 'maxMapOrDefaultIf', 'maxMapOrNull', 'maxMapOrNullIf', 'maxState', 'maxStateIf', 'maxStateOrDefault', 'maxStateOrDefaultIf', 'maxStateOrNull', 'maxStateOrNullIf', 'maxMerge', 'maxMergeIf', 'maxMergeOrDefault', 'maxMergeOrDefaultIf', 'maxMergeOrNull', 'maxMergeOrNullIf', 'maxForEach', 'maxForEachIf', 'maxForEachOrDefault', 'maxForEachOrDefaultIf', 'maxForEachOrNull', 'maxForEachOrNullIf', 'maxOrDefault', 'maxOrDefaultIf', 'maxOrNull', 'maxOrNullIf', 'maxArgMin', 'maxArgMinIf', 'maxArgMinOrDefault', 'maxArgMinOrDefaultIf', 'maxArgMinOrNull', 'maxArgMinOrNullIf', 'maxArgMax', 'maxArgMaxIf', 'maxArgMaxOrDefault', 'maxArgMaxOrDefaultIf', 'maxArgMaxOrNull', 'maxArgMaxOrNullIf', 'countIf', 'countArray', 'countArrayIf', 'countArrayOrDefault', 'countArrayOrDefaultIf', 'countArrayOrNull', 'countArrayOrNullIf', 'countMap', 'countMapIf', 'countMapOrDefault', 'countMapOrDefaultIf', 'countMapOrNull', 'countMapOrNullIf', 'countState', 'countStateIf', 'countStateOrDefault', 'countStateOrDefaultIf', 'countStateOrNull', 'countStateOrNullIf', 'countMerge', 'countMergeIf', 'countMergeOrDefault', 'countMergeOrDefaultIf', 'countMergeOrNull', 'countMergeOrNullIf', 'countForEach', 'countForEachIf', 'countForEachOrDefault', 'countForEachOrDefaultIf', 'countForEachOrNull', 'countForEachOrNullIf', 'countOrDefault', 'countOrDefaultIf', 'countOrNull', 'countOrNullIf', 'countArgMin', 'countArgMinIf', 'countArgMinOrDefault', 'countArgMinOrDefaultIf', 'countArgMinOrNull', 'countArgMinOrNullIf', 'countArgMax', 'countArgMaxIf', 'countArgMaxOrDefault', 'countArgMaxOrDefaultIf', 'countArgMaxOrNull', 'countArgMaxOrNullIf', 'countDistinctIf', 'countDistinctArray', 'countDistinctArrayIf', 'countDistinctArrayOrDefault', 'countDistinctArrayOrDefaultIf', 'countDistinctArrayOrNull', 'countDistinctArrayOrNullIf', 'countDistinctMap', 'countDistinctMapIf', 'countDistinctMapOrDefault', 'countDistinctMapOrDefaultIf', 'countDistinctMapOrNull', 'countDistinctMapOrNullIf', 'countDistinctState', 'countDistinctStateIf', 'countDistinctStateOrDefault', 'countDistinctStateOrDefaultIf', 'countDistinctStateOrNull', 'countDistinctStateOrNullIf', 'countDistinctMerge', 'countDistinctMergeIf', 'countDistinctMergeOrDefault', 'countDistinctMergeOrDefaultIf', 'countDistinctMergeOrNull', 'countDistinctMergeOrNullIf', 'countDistinctForEach', 'countDistinctForEachIf', 'countDistinctForEachOrDefault', 'countDistinctForEachOrDefaultIf', 'countDistinctForEachOrNull', 'countDistinctForEachOrNullIf', 'countDistinctOrDefault', 'countDistinctOrDefaultIf', 'countDistinctOrNull', 'countDistinctOrNullIf', 'countDistinctArgMin', 'countDistinctArgMinIf', 'countDistinctArgMinOrDefault', 'countDistinctArgMinOrDefaultIf', 'countDistinctArgMinOrNull', 'countDistinctArgMinOrNullIf', 'countDistinctArgMax', 'countDistinctArgMaxIf', 'countDistinctArgMaxOrDefault', 'countDistinctArgMaxOrDefaultIf', 'countDistinctArgMaxOrNull', 'countDistinctArgMaxOrNullIf', 'medianIf', 'medianArray', 'medianArrayIf', 'medianArrayOrDefault', 'medianArrayOrDefaultIf', 'medianArrayOrNull', 'medianArrayOrNullIf', 'medianMap', 'medianMapIf', 'medianMapOrDefault', 'medianMapOrDefaultIf', 'medianMapOrNull', 'medianMapOrNullIf', 'medianState', 'medianStateIf', 'medianStateOrDefault', 'medianStateOrDefaultIf', 'medianStateOrNull', 'medianStateOrNullIf', 'medianMerge', 'medianMergeIf', 'medianMergeOrDefault', 'medianMergeOrDefaultIf', 'medianMergeOrNull', 'medianMergeOrNullIf', 'medianForEach', 'medianForEachIf', 'medianForEachOrDefault', 'medianForEachOrDefaultIf', 'medianForEachOrNull', 'medianForEachOrNullIf', 'medianOrDefault', 'medianOrDefaultIf', 'medianOrNull', 'medianOrNullIf', 'medianArgMin', 'medianArgMinIf', 'medianArgMinOrDefault', 'medianArgMinOrDefaultIf', 'medianArgMinOrNull', 'medianArgMinOrNullIf', 'medianArgMax', 'medianArgMaxIf', 'medianArgMaxOrDefault', 'medianArgMaxOrDefaultIf', 'medianArgMaxOrNull', 'medianArgMaxOrNullIf', 'count', 'countDistinct', 'min', 'max', 'sum', 'avg', 'avgMapState', 'avgMapMerge', 'avgMapMergeIf', 'any', 'anyIf', 'stddevPop', 'stddevPopIf', 'stddevSamp', 'stddevSampIf', 'varPop', 'varPopIf', 'varSamp', 'varSampIf', 'covarPop', 'covarPopIf', 'covarSamp', 'covarSampIf', 'corr', 'array_agg', 'groupArray', 'json_agg', 'string_agg', 'every', 'anyHeavy', 'anyHeavyIf', 'anyLast', 'anyLastIf', 'argMin', 'argMinIf', 'argMax', 'argMaxIf', 'argMinMerge', 'argMaxMerge', 'argMinState', 'argMaxState', 'sumForEachState', 'sumForEachMerge', 'avgWeighted', 'avgWeightedIf', 'topK', 'groupArrayIf', 'groupUniqArray', 'groupUniqArrayIf', 'groupUniqArrayArray', 'groupUniqArrayArrayIf', 'groupArrayInsertAt', 'groupArrayInsertAtIf', 'groupArrayMovingAvg', 'groupArrayMovingAvgIf', 'groupArrayMovingSum', 'groupArrayMovingSumIf', 'groupArraySample', 'groupArraySampleIf', 'groupBitAnd', 'groupBitAndIf', 'groupBitOr', 'groupBitOrIf', 'groupBitXor', 'groupBitXorIf', 'groupBitmap', 'groupBitmapIf', 'groupBitmapState', 'groupBitmapAnd', 'groupBitmapAndIf', 'groupBitmapAndState', 'groupBitmapOr', 'groupBitmapOrIf', 'groupBitmapOrState', 'groupBitmapXor', 'groupBitmapXorIf', 'sumWithOverflow', 'sumWithOverflowIf', 'deltaSum', 'deltaSumIf', 'deltaSumTimestamp', 'deltaSumTimestampIf', 'sumMapMerge', 'sumMapMergeIf', 'skewSamp', 'skewSampIf', 'skewPop', 'skewPopIf', 'kurtSamp', 'kurtSampIf', 'kurtPop', 'kurtPopIf', 'uniq', 'uniqIf', 'uniqExact', 'uniqExactState', 'uniqExactMerge', 'uniqExactIf', 'uniqHLL12', 'uniqHLL12If', 'uniqTheta', 'uniqThetaIf', 'uniqMerge', 'uniqMergeIf', 'uniqMap', 'uniqMapMerge', 'uniqMapMergeIf', 'uniqState', 'uniqStateIf', 'uniqUpToMerge', 'median', 'medianExact', 'medianExactIf', 'medianExactLow', 'medianExactLowIf', 'medianExactHigh', 'medianExactHighIf', 'medianExactWeighted', 'medianExactWeightedIf', 'medianTiming', 'medianTimingIf', 'medianTimingWeighted', 'medianTimingWeightedIf', 'medianDeterministic', 'medianDeterministicIf', 'medianTDigest', 'medianTDigestIf', 'medianTDigestWeighted', 'medianTDigestWeightedIf', 'medianBFloat16', 'medianBFloat16If', 'percentile_cont', 'percentile_disc', 'quantile', 'quantileIf', 'quantiles', 'quantilesIf', 'quantileExact', 'simpleLinearRegression', 'simpleLinearRegressionIf', 'contingency', 'contingencyIf', 'cramersV', 'cramersVIf', 'cramersVBiasCorrected', 'cramersVBiasCorrectedIf', 'theilsU', 'theilsUIf', 'maxIntersections', 'maxIntersectionsIf', 'maxIntersectionsPosition', 'maxIntersectionsPositionIf', 'windowFunnel', 'md5']+ ['avgIf', 'avgArray', 'avgArrayIf', 'avgArrayOrDefault', 'avgArrayOrDefaultIf', 'avgArrayOrNull', 'avgArrayOrNullIf', 'avgMap', 'avgMapIf', 'avgMapOrDefault', 'avgMapOrDefaultIf', 'avgMapOrNull', 'avgMapOrNullIf', 'avgState', 'avgStateIf', 'avgStateOrDefault', 'avgStateOrDefaultIf', 'avgStateOrNull', 'avgStateOrNullIf', 'avgMerge', 'avgMergeIf', 'avgMergeOrDefault', 'avgMergeOrDefaultIf', 'avgMergeOrNull', 'avgMergeOrNullIf', 'avgForEach', 'avgForEachIf', 'avgForEachOrDefault', 'avgForEachOrDefaultIf', 'avgForEachOrNull', 'avgForEachOrNullIf', 'avgOrDefault', 'avgOrDefaultIf', 'avgOrNull', 'avgOrNullIf', 'avgArgMin', 'avgArgMinIf', 'avgArgMinOrDefault', 'avgArgMinOrDefaultIf', 'avgArgMinOrNull', 'avgArgMinOrNullIf', 'avgArgMax', 'avgArgMaxIf', 'avgArgMaxOrDefault', 'avgArgMaxOrDefaultIf', 'avgArgMaxOrNull', 'avgArgMaxOrNullIf', 'sumIf', 'sumArray', 'sumArrayIf', 'sumArrayOrDefault', 'sumArrayOrDefaultIf', 'sumArrayOrNull', 'sumArrayOrNullIf', 'sumMap', 'sumMapIf', 'sumMapOrDefault', 'sumMapOrDefaultIf', 'sumMapOrNull', 'sumMapOrNullIf', 'sumState', 'sumStateIf', 'sumStateOrDefault', 'sumStateOrDefaultIf', 'sumStateOrNull', 'sumStateOrNullIf', 'sumMerge', 'sumMergeIf', 'sumMergeOrDefault', 'sumMergeOrDefaultIf', 'sumMergeOrNull', 'sumMergeOrNullIf', 'sumForEach', 'sumForEachIf', 'sumForEachOrDefault', 'sumForEachOrDefaultIf', 'sumForEachOrNull', 'sumForEachOrNullIf', 'sumOrDefault', 'sumOrDefaultIf', 'sumOrNull', 'sumOrNullIf', 'sumArgMin', 'sumArgMinIf', 'sumArgMinOrDefault', 'sumArgMinOrDefaultIf', 'sumArgMinOrNull', 'sumArgMinOrNullIf', 'sumArgMax', 'sumArgMaxIf', 'sumArgMaxOrDefault', 'sumArgMaxOrDefaultIf', 'sumArgMaxOrNull', 'sumArgMaxOrNullIf', 'minIf', 'minArray', 'minArrayIf', 'minArrayOrDefault', 'minArrayOrDefaultIf', 'minArrayOrNull', 'minArrayOrNullIf', 'minMap', 'minMapIf', 'minMapOrDefault', 'minMapOrDefaultIf', 'minMapOrNull', 'minMapOrNullIf', 'minState', 'minStateIf', 'minStateOrDefault', 'minStateOrDefaultIf', 'minStateOrNull', 'minStateOrNullIf', 'minMerge', 'minMergeIf', 'minMergeOrDefault', 'minMergeOrDefaultIf', 'minMergeOrNull', 'minMergeOrNullIf', 'minForEach', 'minForEachIf', 'minForEachOrDefault', 'minForEachOrDefaultIf', 'minForEachOrNull', 'minForEachOrNullIf', 'minOrDefault', 'minOrDefaultIf', 'minOrNull', 'minOrNullIf', 'minArgMin', 'minArgMinIf', 'minArgMinOrDefault', 'minArgMinOrDefaultIf', 'minArgMinOrNull', 'minArgMinOrNullIf', 'minArgMax', 'minArgMaxIf', 'minArgMaxOrDefault', 'minArgMaxOrDefaultIf', 'minArgMaxOrNull', 'minArgMaxOrNullIf', 'maxIf', 'maxArray', 'maxArrayIf', 'maxArrayOrDefault', 'maxArrayOrDefaultIf', 'maxArrayOrNull', 'maxArrayOrNullIf', 'maxMap', 'maxMapIf', 'maxMapOrDefault', 'maxMapOrDefaultIf', 'maxMapOrNull', 'maxMapOrNullIf', 'maxState', 'maxStateIf', 'maxStateOrDefault', 'maxStateOrDefaultIf', 'maxStateOrNull', 'maxStateOrNullIf', 'maxMerge', 'maxMergeIf', 'maxMergeOrDefault', 'maxMergeOrDefaultIf', 'maxMergeOrNull', 'maxMergeOrNullIf', 'maxForEach', 'maxForEachIf', 'maxForEachOrDefault', 'maxForEachOrDefaultIf', 'maxForEachOrNull', 'maxForEachOrNullIf', 'maxOrDefault', 'maxOrDefaultIf', 'maxOrNull', 'maxOrNullIf', 'maxArgMin', 'maxArgMinIf', 'maxArgMinOrDefault', 'maxArgMinOrDefaultIf', 'maxArgMinOrNull', 'maxArgMinOrNullIf', 'maxArgMax', 'maxArgMaxIf', 'maxArgMaxOrDefault', 'maxArgMaxOrDefaultIf', 'maxArgMaxOrNull', 'maxArgMaxOrNullIf', 'countIf', 'countArray', 'countArrayIf', 'countArrayOrDefault', 'countArrayOrDefaultIf', 'countArrayOrNull', 'countArrayOrNullIf', 'countMap', 'countMapIf', 'countMapOrDefault', 'countMapOrDefaultIf', 'countMapOrNull', 'countMapOrNullIf', 'countState', 'countStateIf', 'countStateOrDefault', 'countStateOrDefaultIf', 'countStateOrNull', 'countStateOrNullIf', 'countMerge', 'countMergeIf', 'countMergeOrDefault', 'countMergeOrDefaultIf', 'countMergeOrNull', 'countMergeOrNullIf', 'countForEach', 'countForEachIf', 'countForEachOrDefault', 'countForEachOrDefaultIf', 'countForEachOrNull', 'countForEachOrNullIf', 'countOrDefault', 'countOrDefaultIf', 'countOrNull', 'countOrNullIf', 'countArgMin', 'countArgMinIf', 'countArgMinOrDefault', 'countArgMinOrDefaultIf', 'countArgMinOrNull', 'countArgMinOrNullIf', 'countArgMax', 'countArgMaxIf', 'countArgMaxOrDefault', 'countArgMaxOrDefaultIf', 'countArgMaxOrNull', 'countArgMaxOrNullIf', 'countDistinctIf', 'countDistinctArray', 'countDistinctArrayIf', 'countDistinctArrayOrDefault', 'countDistinctArrayOrDefaultIf', 'countDistinctArrayOrNull', 'countDistinctArrayOrNullIf', 'countDistinctMap', 'countDistinctMapIf', 'countDistinctMapOrDefault', 'countDistinctMapOrDefaultIf', 'countDistinctMapOrNull', 'countDistinctMapOrNullIf', 'countDistinctState', 'countDistinctStateIf', 'countDistinctStateOrDefault', 'countDistinctStateOrDefaultIf', 'countDistinctStateOrNull', 'countDistinctStateOrNullIf', 'countDistinctMerge', 'countDistinctMergeIf', 'countDistinctMergeOrDefault', 'countDistinctMergeOrDefaultIf', 'countDistinctMergeOrNull', 'countDistinctMergeOrNullIf', 'countDistinctForEach', 'countDistinctForEachIf', 'countDistinctForEachOrDefault', 'countDistinctForEachOrDefaultIf', 'countDistinctForEachOrNull', 'countDistinctForEachOrNullIf', 'countDistinctOrDefault', 'countDistinctOrDefaultIf', 'countDistinctOrNull', 'countDistinctOrNullIf', 'countDistinctArgMin', 'countDistinctArgMinIf', 'countDistinctArgMinOrDefault', 'countDistinctArgMinOrDefaultIf', 'countDistinctArgMinOrNull', 'countDistinctArgMinOrNullIf', 'countDistinctArgMax', 'countDistinctArgMaxIf', 'countDistinctArgMaxOrDefault', 'countDistinctArgMaxOrDefaultIf', 'countDistinctArgMaxOrNull', 'countDistinctArgMaxOrNullIf', 'medianIf', 'medianArray', 'medianArrayIf', 'medianArrayOrDefault', 'medianArrayOrDefaultIf', 'medianArrayOrNull', 'medianArrayOrNullIf', 'medianMap', 'medianMapIf', 'medianMapOrDefault', 'medianMapOrDefaultIf', 'medianMapOrNull', 'medianMapOrNullIf', 'medianState', 'medianStateIf', 'medianStateOrDefault', 'medianStateOrDefaultIf', 'medianStateOrNull', 'medianStateOrNullIf', 'medianMerge', 'medianMergeIf', 'medianMergeOrDefault', 'medianMergeOrDefaultIf', 'medianMergeOrNull', 'medianMergeOrNullIf', 'medianForEach', 'medianForEachIf', 'medianForEachOrDefault', 'medianForEachOrDefaultIf', 'medianForEachOrNull', 'medianForEachOrNullIf', 'medianOrDefault', 'medianOrDefaultIf', 'medianOrNull', 'medianOrNullIf', 'medianArgMin', 'medianArgMinIf', 'medianArgMinOrDefault', 'medianArgMinOrDefaultIf', 'medianArgMinOrNull', 'medianArgMinOrNullIf', 'medianArgMax', 'medianArgMaxIf', 'medianArgMaxOrDefault', 'medianArgMaxOrDefaultIf', 'medianArgMaxOrNull', 'medianArgMaxOrNullIf', 'count', 'countDistinct', 'min', 'max', 'sum', 'avg', 'avgMapState', 'avgMapMerge', 'avgMapMergeIf', 'any', 'anyIf', 'stddevPop', 'stddevPopIf', 'stddevSamp', 'stddevSampIf', 'varPop', 'varPopIf', 'varSamp', 'varSampIf', 'covarPop', 'covarPopIf', 'covarSamp', 'covarSampIf', 'corr', 'array_agg', 'groupArray', 'json_agg', 'string_agg', 'every', 'anyHeavy', 'anyHeavyIf', 'anyLast', 'anyLastIf', 'argMin', 'argMinIf', 'argMax', 'argMaxIf', 'argMinMerge', 'argMaxMerge', 'argMinState', 'argMaxState', 'sumForEachState', 'sumForEachMerge', 'avgWeighted', 'avgWeightedIf', 'topK', 'groupArrayIf', 'groupUniqArray', 'groupUniqArrayIf', 'groupUniqArrayArray', 'groupUniqArrayArrayIf', 'groupArrayInsertAt', 'groupArrayInsertAtIf', 'groupArrayMovingAvg', 'groupArrayMovingAvgIf', 'groupArrayMovingSum', 'groupArrayMovingSumIf', 'groupArraySample', 'groupArraySampleIf', 'groupBitAnd', 'groupBitAndIf', 'groupBitOr', 'groupBitOrIf', 'groupBitXor', 'groupBitXorIf', 'groupBitmap', 'groupBitmapIf', 'groupBitmapState', 'groupBitmapAnd', 'groupBitmapAndIf', 'groupBitmapAndState', 'groupBitmapOr', 'groupBitmapOrIf', 'groupBitmapOrState', 'groupBitmapXor', 'groupBitmapXorIf', 'sumWithOverflow', 'sumWithOverflowIf', 'deltaSum', 'deltaSumIf', 'deltaSumTimestamp', 'deltaSumTimestampIf', 'sumMapMerge', 'sumMapMergeIf', 'skewSamp', 'skewSampIf', 'skewPop', 'skewPopIf', 'kurtSamp', 'kurtSampIf', 'kurtPop', 'kurtPopIf', 'uniq', 'uniqIf', 'uniqExact', 'uniqExactState', 'uniqExactMerge', 'uniqExactIf', 'uniqHLL12', 'uniqHLL12If', 'uniqTheta', 'uniqThetaIf', 'uniqMerge', 'uniqMergeIf', 'uniqMap', 'uniqMapMerge', 'uniqMapMergeIf', 'uniqState', 'uniqStateIf', 'uniqUpToMerge', 'median', 'medianExact', 'medianExactIf', 'medianExactLow', 'medianExactLowIf', 'medianExactHigh', 'medianExactHighIf', 'medianExactWeighted', 'medianExactWeightedIf', 'medianTiming', 'medianTimingIf', 'medianTimingWeighted', 'medianTimingWeightedIf', 'medianDeterministic', 'medianDeterministicIf', 'medianTDigest', 'medianTDigestIf', 'medianTDigestWeighted', 'medianTDigestWeightedIf', 'medianBFloat16', 'medianBFloat16If', 'percentile_cont', 'percentile_disc', 'quantile', 'quantileIf', 'quantiles', 'quantilesIf', 'quantilesState', 'quantilesStateIf', 'quantilesMerge', 'quantilesMergeIf', 'quantileExact', 'simpleLinearRegression', 'simpleLinearRegressionIf', 'contingency', 'contingencyIf', 'cramersV', 'cramersVIf', 'cramersVBiasCorrected', 'cramersVBiasCorrectedIf', 'theilsU', 'theilsUIf', 'maxIntersections', 'maxIntersectionsIf', 'maxIntersectionsPosition', 'maxIntersectionsPositionIf', 'windowFunnel', 'md5']```And lastly these are some HogQL specific functions:diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex e9236d1671fb..4d1bdd267f83 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -3169,6 +3169,7 @@ export interface Response8Api {results: WebVitalsPathBreakdownResultApi[]/** Measured timings for different parts of the query generation process */timings?: QueryTimingApi[] | null+ usedLazyPrecompute?: boolean | null}export interface Response9Api {@@ -5007,6 +5008,7 @@ export interface WebVitalsPathBreakdownQueryResponseApi {results: WebVitalsPathBreakdownResultApi[]/** Measured timings for different parts of the query generation process */timings?: QueryTimingApi[] | null+ usedLazyPrecompute?: boolean | null}export interface WebVitalsPathBreakdownQueryApi {@@ -5045,6 +5047,8 @@ export interface WebVitalsPathBreakdownQueryApi {*/thresholds: number[]useSessionsTable?: boolean | null+ /** Opt this specific query into the web vitals path breakdown precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. * */+ useWebAnalyticsPrecompute?: boolean | null/** version of the node, used for schema migrations */version?: number | null}diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 2a2a44f226e0..9d2cf828ef06 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -182,6 +182,74 @@ Single `sync_execute` over `web_stats_paths_preaggregated` with `uniqMergeIf` /- INITIAL_PAGE + bounce (entry-pathname tab) is a different SQL shape — separate precompute table or shared one with an entry-only state column.- `usedLazyPrecompute` is set on the response; the frontend's `PreAggregatedBadge` already keys off `usedPreAggregatedTables` so users see the badge without further wiring. Distinguishing lazy from v2 in the UI is a separate follow-up.+## Lazy computation for the web vitals path-breakdown tile++`WebVitalsPathBreakdownQueryRunner._calculate` follows the same gate-then-fallthrough shape as web overview:++1. **Lazy precompute** (`can_use_lazy_precompute` + `execute_lazy_precomputed_read`) — short-circuits when eligible and returns immediately.+2. **Raw events scan** — the original `quantile(p)(toFloat(properties.$web_vitals_*_value))` per path.++### Schema++`web_vitals_paths_preaggregated` (sharded by `sipHash64(job_id)`, partitioned by `toYYYYMMDD(expires_at)`, `ReplicatedReplacingMergeTree` with `computed_at` as the version column). One row per `(team, job, hour, path)`, four state columns — one per Web Vitals metric:++- `inp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64)`+- `lcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64)`+- `cls_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64)`+- `fcp_quantiles_state AggregateFunction(quantiles(0.75, 0.90, 0.99), Float64)`++Each state holds one reservoir covering all three percentiles. Reads pick the queried percentile via `arrayElement(quantilesMergeIf(0.75, 0.90, 0.99)(state, range_filter), pct_index)`. Same reservoir algorithm as the raw `quantile(p)` — exact when unsaturated, within sampling noise once it is.++Four columns vs. a metric discriminator: ARRAY JOIN would fan one event into four rows, but the new ClickHouse analyzer rejects bare `events.properties` references inside the ARRAY JOIN source array (the source array is resolved before the FROM alias scope). Four columns let the INSERT stay a single `FROM events GROUP BY (hour, path)`, no fan-out, and each metric tab reads exactly one column.++### Bucketing and timezones++**Daily, team-tz aligned.** Bucket key is `toStartOfDay(timestamp, team_tz)` — start of the team's local day. The underlying Unix timestamp stored in `time_window_start` is the UTC instant of that local midnight, so reads filter against the team-tz date range converted to UTC and get exact alignment.++This differs from web overview / web stats which use UTC-hourly buckets:++- The path-breakdown tile only consumes day-aligned date ranges from the dashboard filter, so a daily bucket is sufficient and ~24× smaller than hourly.+- Bucketing in the team's tz means **half-hour-offset timezones** (IST +5:30, Newfoundland -3:30, Nepal +5:45, Iran +3:30) are supported too — this runner opts out of the shared `is_integer_timezone` gate.+- A UTC-daily INSERT job typically writes into TWO team-tz day buckets (events in the first hours of UTC day N belong to team-tz day N-1 for non-UTC teams). The `ReplacingMergeTree` key `(team_id, job_id, time_window_start, path)` keeps the rows distinct per job; reads merge them via `quantilesMergeIf` for full team-tz day coverage.++No session join in the raw query, so no `SESSION_FORWARD_PAD_MINUTES` — each event maps to exactly one (team-tz day, path) bucket.++### Read++Mirrors the raw query's outer shape:++```sql+SELECT multiIf(value <= good, 'good', value <= needs_improvements, 'needs_improvements', 'poor') AS band, path, value+FROM (+ SELECT path,+ arrayElement(quantilesMergeIf(0.75, 0.90, 0.99)(<metric>_quantiles_state, time_filter), pct_index) AS value+ FROM posthog.web_vitals_paths_preaggregated+ WHERE team_id = ? AND job_id IN (...)+ GROUP BY path HAVING value >= 0+)+ORDER BY value ASC, path ASC+LIMIT 20 BY band+```++The runner re-partitions the resulting `(band, path, value)` tuples into the `good` / `needs_improvements` / `poor` arrays the response expects.++### Eligibility gate++`can_use_lazy_precompute` in `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` delegates to the shared gate with `require_integer_timezone=False` (see "Bucketing and timezones" above). The shared gate rejects: org feature flag off, per-query opt-in not set, conversion goal, sampling enabled, `sessionsV2JoinMode=uuid`, more than one property filter, anything other than a `$host` exact-equals filter, missing date range, and date range over 90 days.++### Observability++- **Read query**: tagged `query_type="web_vitals_paths_lazy_query"`.+- **INSERT query**: tagged `query_type="web_vitals_paths_lazy_insert"`.+- **Failures**: `web_vitals_paths_lazy_precompute_failed_total{error_type}` Prometheus counter.+- **Cache warmer**: `web_vitals_paths_lazy_query` is in the warmer DAG allowlist in `products/web_analytics/dags/cache_warming.py`.++### Known limitations++1. **`WebVitalsQuery` (line-chart tile) is not covered.** That query wraps a `TrendsQuery` and dispatches through `TrendsQueryRunner`; lazy precompute for it would need a different shape and is deferred.+2. **Adding a metric** (e.g. TTFB) is a schema change — add the column to `web_vitals_paths_preaggregated`, the HogQL table registration, the INSERT template, and the `_METRIC_STATE_COLUMN` map.+3. **Bands are computed in ClickHouse from the runtime thresholds**, not stored — so a threshold change is free on the read side.+## Related code- `posthog/hogql_queries/web_analytics/web_overview.py` — runner@@ -192,4 +260,7 @@ Single `sync_execute` over `web_stats_paths_preaggregated` with `uniqMergeIf` /- `posthog/hogql_queries/web_analytics/web_lazy_precompute_common.py` — shared eligibility gate + helpers- `posthog/clickhouse/preaggregation/web_overview_preaggregated_sql.py` — overview schema- `posthog/clickhouse/preaggregation/web_stats_paths_preaggregated_sql.py` — PATHS schema+- `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/analytics_platform/backend/lazy_computation/` — framework + CONSISTENCY.md + READMEdiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.pynew file mode 100644index 000000000000..fe7b473608fd--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py@@ -0,0 +1,299 @@+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 (+ CustomEventConversionGoal,+ DateRange,+ EventPropertyFilter,+ PropertyOperator,+ WebAnalyticsSampling,+ WebVitalsMetric,+ WebVitalsMetricBand,+ WebVitalsPathBreakdownQuery,+ WebVitalsPercentile,+)++from posthog.clickhouse.client import sync_execute+from posthog.models.utils import uuid7++from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.web_analytics.backend.hogql_queries.web_vitals_path_breakdown import WebVitalsPathBreakdownQueryRunner++# (metric, percentile) parity matrix. Reservoir is unsaturated for these test+# sizes (≤8192 samples), so `quantilesMerge` is exact and matches the raw+# `quantile(p)` exactly.+PARITY_MATRIX = [+ (f"{metric.value}_{pct.value}", metric, pct) for metric in WebVitalsMetric for pct in WebVitalsPercentile+]+++@override_settings(IN_UNIT_TESTING=True)+class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()+ # The lazy framework derives `expires_at` from the (frozen) test clock,+ # so precompute rows are "born expired" relative to the real ClickHouse+ # server clock. Stop TTL merges on the precompute table so those parts+ # are not dropped in the window between the precompute INSERT and the+ # subsequent read.+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_vitals_paths_preaggregated")++ def _enable_lazy(self):+ # Mock the org-level feature flag check to True. Outside this context+ # manager the default `posthoganalytics.feature_enabled` returns False+ # (no API key in tests), which models a flag-disabled org.+ return patch(+ "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",+ return_value=True,+ )++ def _seed(self) -> None:+ # Three paths with controlled metric values so band classification is+ # deterministic for LCP (good ≤2500, poor >4000):+ # /fast → LCP 1000 (good)+ # /mid → LCP 3000 (needs_improvements)+ # /slow → LCP 5000 (poor)+ # INP / CLS / FCP values are also seeded so per-metric parity tests+ # have data to read.+ _create_person(team_id=self.team.pk, distinct_ids=["u1"], properties={})++ paths_metrics: list[tuple[str, dict, str]] = [+ ("/fast", {"LCP": 1000, "INP": 50, "CLS": 0.02, "FCP": 800}, "2024-01-02T10:00:00Z"),+ ("/mid", {"LCP": 3000, "INP": 150, "CLS": 0.15, "FCP": 1800}, "2024-01-02T11:00:00Z"),+ ("/slow", {"LCP": 5000, "INP": 350, "CLS": 0.30, "FCP": 3500}, "2024-01-02T12:00:00Z"),+ ]+ for path, vitals, ts in paths_metrics:+ _create_event(+ team=self.team,+ event="$web_vitals",+ distinct_id="u1",+ timestamp=ts,+ properties={+ "$pathname": path,+ "$current_url": f"https://example.com{path}",+ "$host": "example.com",+ "$session_id": str(uuid7("2024-01-02")),+ "$web_vitals_LCP_value": vitals["LCP"],+ "$web_vitals_INP_value": vitals["INP"],+ "$web_vitals_CLS_value": vitals["CLS"],+ "$web_vitals_FCP_value": vitals["FCP"],+ },+ )++ def _build_query(+ self,+ *,+ metric: WebVitalsMetric = WebVitalsMetric.LCP,+ percentile: WebVitalsPercentile = WebVitalsPercentile.P75,+ date_from: str = "2024-01-01",+ date_to: str = "2024-01-07",+ properties: list | None = None,+ conversion_goal=None,+ sampling: WebAnalyticsSampling | None = None,+ opt_in_precompute: bool = True,+ thresholds: list[float] | None = None,+ ) -> WebVitalsPathBreakdownQuery:+ # Default thresholds picked so the LCP seed splits paths into 3 bands:+ # 1000 → good, 3000 → needs_improvements, 5000 → poor.+ return WebVitalsPathBreakdownQuery(+ metric=metric,+ percentile=percentile,+ dateRange=DateRange(date_from=date_from, date_to=date_to),+ properties=properties or [],+ conversionGoal=conversion_goal,+ sampling=sampling,+ thresholds=thresholds if thresholds is not None else [2500.0, 4000.0],+ useWebAnalyticsPrecompute=opt_in_precompute,+ )++ def _run(self, query: WebVitalsPathBreakdownQuery):+ return WebVitalsPathBreakdownQueryRunner(team=self.team, query=query).calculate()++ @staticmethod+ def _band_paths(response, band: WebVitalsMetricBand) -> list[str]:+ result = response.results[0]+ items = getattr(result, band.value)+ return sorted(item.path for item in items)++ @staticmethod+ def _paths_with_values(response) -> dict[str, tuple[str, float]]:+ """Flatten the band-partitioned response into `path → (band, value)`."""+ out: dict[str, tuple[str, float]] = {}+ for band in WebVitalsMetricBand:+ items = getattr(response.results[0], band.value)+ for item in items:+ out[item.path] = (band.value, item.value)+ return out++ def _job_count(self) -> int:+ return PreaggregationJob.objects.filter(team_id=self.team.pk).count()++ @freeze_time("2024-01-15T12:00:00Z")+ def test_round_trip_creates_precompute_job(self):+ self._seed()+ with self._enable_lazy():+ response = self._run(self._build_query())+ assert response.usedLazyPrecompute is True+ assert self._job_count() > 0, "expected at least one precompute job to be created"++ @parameterized.expand(PARITY_MATRIX)+ @freeze_time("2024-01-15T12:00:00Z")+ def test_lazy_matches_raw_per_metric_percentile(+ self, _name: str, metric: WebVitalsMetric, percentile: WebVitalsPercentile+ ):+ self._seed()++ raw = self._paths_with_values(self._run(self._build_query(metric=metric, percentile=percentile)))++ with self._enable_lazy():+ lazy_response = self._run(self._build_query(metric=metric, percentile=percentile))+ lazy = self._paths_with_values(lazy_response)++ assert lazy_response.usedLazyPrecompute is True+ assert lazy.keys() == raw.keys(), f"path set mismatch for {metric}/{percentile}: raw={raw}, lazy={lazy}"+ for path in raw:+ raw_band, raw_value = raw[path]+ lazy_band, lazy_value = lazy[path]+ assert raw_band == lazy_band, f"band mismatch for {path} {metric}/{percentile}: raw={raw}, lazy={lazy}"+ assert abs(raw_value - lazy_value) < 1e-6, (+ f"value mismatch for {path} {metric}/{percentile}: raw={raw_value}, lazy={lazy_value}"+ )++ @freeze_time("2024-01-15T12:00:00Z")+ def test_lazy_classifies_bands_correctly(self):+ self._seed()+ with self._enable_lazy():+ response = self._run(self._build_query(metric=WebVitalsMetric.LCP, percentile=WebVitalsPercentile.P75))+ assert self._band_paths(response, WebVitalsMetricBand.GOOD) == ["/fast"]+ assert self._band_paths(response, WebVitalsMetricBand.NEEDS_IMPROVEMENTS) == ["/mid"]+ assert self._band_paths(response, WebVitalsMetricBand.POOR) == ["/slow"]++ @freeze_time("2024-01-15T12:00:00Z")+ def test_conversion_goal_falls_through(self):+ self._seed()+ with self._enable_lazy():+ response = self._run(+ self._build_query(conversion_goal=CustomEventConversionGoal(customEventName="$pageview")),+ )+ assert response.usedLazyPrecompute is not True+ assert self._job_count() == 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_sampling_falls_through(self):+ self._seed()+ with self._enable_lazy():+ response = self._run(self._build_query(sampling=WebAnalyticsSampling(enabled=True)))+ assert response.usedLazyPrecompute is not True+ assert self._job_count() == 0++ @parameterized.expand(+ [+ ("sub_day", "2024-01-02T10:00:00", "2024-01-02T12:00:00"),+ ("start_misaligned", "2024-01-02T10:00:00", "2024-01-03T00:00:00"),+ ("end_misaligned", "2024-01-02T00:00:00", "2024-01-02T12:00:00"),+ ]+ )+ @freeze_time("2024-01-15T12:00:00Z")+ def test_explicit_sub_day_range_falls_through(self, _name: str, date_from: str, date_to: str):+ # Only `explicitDate=True` lets the query date range surface non-midnight+ # times; without it, the parser silently truncates to start/end of day.+ # The runner buckets per team-tz day, so the read filter would compare+ # an hour-precise range against day-aligned bucket keys and silently+ # return empty. Eligibility must reject these ranges.+ self._seed()+ query = self._build_query(date_from=date_from, date_to=date_to)+ query.dateRange = DateRange(date_from=date_from, date_to=date_to, explicitDate=True)+ with self._enable_lazy():+ response = self._run(query)+ assert response.usedLazyPrecompute is not True+ assert self._job_count() == 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_half_hour_offset_timezone_matches_raw(self):+ # Vitals buckets by team-tz day, so half-hour-offset timezones (IST +5:30+ # here) align cleanly and don't fall through to raw.+ self.team.timezone = "Asia/Kolkata"+ self.team.save()+ self._seed()++ raw = self._paths_with_values(self._run(self._build_query()))+ with self._enable_lazy():+ lazy_response = self._run(self._build_query())+ lazy = self._paths_with_values(lazy_response)++ assert lazy_response.usedLazyPrecompute is True+ assert raw == lazy, f"lazy/raw mismatch in IST: raw={raw}, lazy={lazy}"++ @freeze_time("2024-01-15T12:00:00Z")+ def test_query_optin_alone_falls_through_when_org_flag_disabled(self):+ self._seed()+ response = self._run(self._build_query(opt_in_precompute=True))+ assert response.usedLazyPrecompute is not True+ assert self._job_count() == 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_org_flag_alone_falls_through_when_query_not_opted_in(self):+ self._seed()+ with self._enable_lazy():+ response = self._run(self._build_query(opt_in_precompute=False))+ assert response.usedLazyPrecompute is not True+ assert self._job_count() == 0++ @freeze_time("2024-01-15T12:00:00Z")+ def test_host_filter_gets_distinct_cache_entry(self):+ self._seed()+ host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)++ with self._enable_lazy():+ self._run(self._build_query())+ unfiltered = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()++ self._run(self._build_query(properties=[host_filter]))+ filtered = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}++ assert unfiltered and filtered+ assert unfiltered.isdisjoint(filtered), "host filter must produce a distinct cache key"++ @parameterized.expand([("utc", "UTC"), ("pacific", "America/Los_Angeles"), ("tokyo", "Asia/Tokyo")])+ @freeze_time("2024-01-15T12:00:00Z")+ def test_lazy_matches_raw_for_whole_hour_timezones(self, _name: str, team_tz: str):+ self.team.timezone = team_tz+ self.team.save()+ self._seed()++ raw = self._paths_with_values(self._run(self._build_query()))+ with self._enable_lazy():+ lazy = self._paths_with_values(self._run(self._build_query()))++ assert raw == lazy, f"lazy/raw mismatch for {team_tz}: raw={raw}, lazy={lazy}"++ @freeze_time("2024-01-15T12:00:00Z")+ def test_lazy_returns_at_most_20_per_band(self):+ _create_person(team_id=self.team.pk, distinct_ids=["bulk_user"], properties={})+ # 25 distinct paths all classifying as "poor" (LCP 6000+).+ for i in range(25):+ _create_event(+ team=self.team,+ event="$web_vitals",+ distinct_id="bulk_user",+ timestamp=f"2024-01-02T10:{i:02d}:00Z",+ properties={+ "$pathname": f"/bulk_{i}",+ "$host": "example.com",+ "$session_id": str(uuid7("2024-01-02")),+ "$web_vitals_LCP_value": 6000 + i,+ },+ )++ with self._enable_lazy():+ response = self._run(self._build_query(metric=WebVitalsMetric.LCP))++ poor_items = response.results[0].poor+ assert len(poor_items) == 20, f"expected exactly 20 paths in poor band, got {len(poor_items)}"diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.pyindex aa5af7808e48..8279e2f59a8e 100644--- a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py@@ -16,7 +16,13 @@ import structlogimport posthoganalyticsfrom prometheus_client import Counter-from posthog.schema import EventPropertyFilter, PropertyOperator, WebOverviewQuery, WebStatsTableQuery+from posthog.schema import (+ EventPropertyFilter,+ PropertyOperator,+ WebOverviewQuery,+ WebStatsTableQuery,+ WebVitalsPathBreakdownQuery,+)from posthog.hogql import astfrom posthog.hogql.property import property_to_expr@@ -93,13 +99,14 @@ SESSION_FORWARD_PAD_MINUTES = 24 * 60class LazyPrecomputeRunner(Protocol):"""Structural type for the attributes the shared helpers read off a runner.- Both `WebOverviewQueryRunner` and `WebStatsTableQueryRunner` satisfy this.+ `WebOverviewQueryRunner`, `WebStatsTableQueryRunner` and+ `WebVitalsPathBreakdownQueryRunner` all satisfy this."""team: Team@property- def query(self) -> Union[WebOverviewQuery, WebStatsTableQuery]: ...+ def query(self) -> Union[WebOverviewQuery, WebStatsTableQuery, WebVitalsPathBreakdownQuery]: ...@propertydef query_date_range(self) -> object: ...@@ -183,6 +190,7 @@ def can_use_lazy_precompute(*,log_prefix: str,extra_check: Optional[Callable[[LazyPrecomputeRunner], None]] = None,+ require_integer_timezone: bool = True,) -> bool:"""Return True iff the lazy precompute gate is eligible. Logs the rejectionreason at INFO level so every fall-through can be attributed.@@ -190,10 +198,12 @@ def can_use_lazy_precompute(`log_prefix` differentiates the log event name per runner (e.g.`web_overview` / `web_stats`). `extra_check` lets a runner add its owneligibility checks — it must raise a `LazyPrecomputeIneligible` subclass on- rejection, and runs after the shared checks pass.+ rejection, and runs after the shared checks pass. `require_integer_timezone`+ can be opted out by runners whose bucket key is computed in the team's+ timezone (and therefore aligns cleanly for half-hour-offset teams too)."""try:- check_common_eligible(runner)+ check_common_eligible(runner, require_integer_timezone=require_integer_timezone)if extra_check is not None:extra_check(runner)except LazyPrecomputeIneligible as exc:@@ -213,10 +223,14 @@ def can_use_lazy_precompute(return True-def check_common_eligible(runner: LazyPrecomputeRunner) -> None:+def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timezone: bool = True) -> None:"""Raise a `LazyPrecomputeIneligible` subclass if the query can't go throughthe lazy path on grounds that apply to every web analytics runner. Returns- None on success."""+ None on success.++ `require_integer_timezone` defaults to True for hourly-UTC-bucketed runners+ (overview, stats). Runners that bucket in the team's timezone can opt out.+ """query = runner.query# Rollout gate: shared PostHog feature flag AND per-query opt-in.@@ -248,8 +262,9 @@ def check_common_eligible(runner: LazyPrecomputeRunner) -> None:# Half-hour-offset timezones (IST +5:30, Newfoundland -3:30, Nepal +5:45, etc.)# can't be served by UTC hourly buckets without sub-hour precision. Skip them- # rather than return wrong totals on the boundary days.- if not is_integer_timezone(runner.team.timezone):+ # rather than return wrong totals on the boundary days. Runners that bucket+ # by team-tz day instead (e.g. web vitals) can opt out of this check.+ if require_integer_timezone and not is_integer_timezone(runner.team.timezone):raise NonIntegerTimezone()if query.conversionGoal is not None:diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.pyindex 4f63c0b75bcf..3f0d24321644 100644--- a/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py+++ b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py@@ -15,6 +15,10 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.queries.trends.util import PROPERTY_MATH_FUNCTIONSfrom products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner+from products.web_analytics.backend.hogql_queries.web_vitals_paths_lazy_precompute import (+ can_use_lazy_precompute,+ execute_lazy_precomputed_read,+)class WebVitalsPathBreakdownQueryRunner(WebAnalyticsQueryRunner[WebVitalsPathBreakdownQueryResponse]):@@ -80,6 +84,15 @@ HAVING value >= 0return parse_expr(f"{percentile_function}(toFloat({metric_value_field}))")def _calculate(self):+ # Lazy precompute path: short-circuits the raw events scan when the team+ # opted in via the per-query toggle and the shared gate accepts the+ # request. Any failure (gate rejection, INSERT/READ error) returns None+ # and falls through to the raw path below.+ if can_use_lazy_precompute(self):+ lazy_response = execute_lazy_precomputed_read(self)+ if lazy_response is not None:+ return lazy_response+query = self.to_query()response = execute_hogql_query(query_type="web_vitals_path_breakdown_query",diff --git a/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.pynew file mode 100644index 000000000000..adfbf1125aa0--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py@@ -0,0 +1,429 @@+import time+from datetime import (+ UTC,+ datetime,+ time as dt_time,+)+from typing import TYPE_CHECKING, Optional++import structlog+from prometheus_client import Counter++from posthog.schema import (+ HogQLQueryModifiers,+ WebVitalsMetric,+ WebVitalsMetricBand,+ WebVitalsPathBreakdownQueryResponse,+ WebVitalsPathBreakdownResult,+ WebVitalsPathBreakdownResultItem,+ WebVitalsPercentile,+)++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries++from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationResult,+ LazyComputationTable,+ ensure_precomputed,+)+from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (+ LAZY_TTL_SECONDS,+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS,+ LazyPrecomputeIneligible,+ LazyPrecomputeRunner,+ can_use_lazy_precompute as _can_use_lazy_precompute_shared,+ ceil_utc_day,+ floor_utc_day,+ test_account_filter_expr,+ user_filter_expr,+)++_FAMILY = "web_vitals_paths"++if TYPE_CHECKING:+ from products.web_analytics.backend.hogql_queries.web_vitals_path_breakdown import WebVitalsPathBreakdownQueryRunner++logger = structlog.get_logger(__name__)+++WEB_VITALS_LAZY_FAILED = Counter(+ "web_vitals_paths_lazy_precompute_failed_total",+ "Web vitals paths lazy precompute path failures, by error class",+ ["error_type"],+)+++class NonDayAlignedRange(LazyPrecomputeIneligible):+ pass+++# `date_to` from the query date range arrives as either midnight (exclusive next+# day) or end-of-day (inclusive last day) — both are day-aligned and the bucket+# math still works. Anything else (10:00, 12:00, …) is a sub-day filter we can't+# serve from day buckets.+_DAY_ALIGNED_END_TIMES: frozenset[dt_time] = frozenset(+ [+ dt_time(0, 0, 0, 0),+ dt_time(23, 59, 59, 999999),+ ]+)+++def _check_vitals_eligible(runner: LazyPrecomputeRunner) -> None:+ """Reject sub-day date ranges. The runner buckets into team-tz days via+ `toStartOfDay(timestamp, team_tz)`, so the read filter+ (`time_window_start >= cur_start AND ... < cur_end`) compares against+ bucket keys at team-local midnight. A sub-day range like 10:00–12:00 would+ miss the surrounding day bucket and silently return empty results, while+ the raw query computes the same range correctly from event timestamps.+ """+ date_from = runner.query_date_range.date_from() # type: ignore[attr-defined]+ date_to = runner.query_date_range.date_to() # type: ignore[attr-defined]+ if date_from is None or date_to is None:+ return # Caught by check_common_eligible's MissingDateRange.+ if date_from.time() != dt_time(0, 0):+ raise NonDayAlignedRange()+ if date_to.time() not in _DAY_ALIGNED_END_TIMES:+ raise NonDayAlignedRange()+++# 1-based ClickHouse `arrayElement` index into the quantiles tuple stored in+# the metric's `quantiles_state` column (`quantiles(0.75, 0.90, 0.99)`).+_PCT_INDEX: dict[WebVitalsPercentile, int] = {+ WebVitalsPercentile.P75: 1,+ WebVitalsPercentile.P90: 2,+ WebVitalsPercentile.P99: 3,+}++_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",+}+++def can_use_lazy_precompute(runner: "WebVitalsPathBreakdownQueryRunner") -> bool:+ """Return True iff the lazy precompute path is eligible for this web vitals+ path-breakdown query — the shared web analytics gate plus a day-alignment+ check on the requested range.++ Bucket key is computed in the team's timezone, so half-hour-offset timezones+ (IST/Newfoundland/Nepal/Iran) are also supported — the integer-timezone gate+ is opted out.+ """+ return _can_use_lazy_precompute_shared(+ runner,+ log_prefix=_FAMILY,+ extra_check=_check_vitals_eligible,+ require_integer_timezone=False,+ )+++# HogQL template for the precompute INSERT. The lazy_computation framework+# substitutes the listed placeholders (including `time_window_min` /+# `time_window_max`), parses the result, and INSERTs into+# `web_vitals_paths_preaggregated`. The framework automatically prepends+# `team_id`, `job_id` and appends `expires_at` to the SELECT.+#+# Bucketing strategy: per-(team-tz-day, path), not per-hour. The path-breakdown+# tile only consumes day-aligned date ranges from the dashboard filter, so a+# daily bucket is sufficient and ~24× smaller than hourly. The bucket key is+# `toStartOfDay(timestamp, team_tz)` — start of the team-local day, with the+# underlying Unix timestamp being the UTC instant of that local midnight. This+# aligns cleanly for every timezone (including half-hour offsets like IST),+# which is why this runner opts out of the shared `is_integer_timezone` gate.+#+# Note that a UTC daily INSERT job typically writes into TWO team-tz day+# buckets — events in the first hours of UTC day N belong to team-tz day N-1+# for non-UTC teams. Reads merge both rows via the ReplacingMergeTree key+# `(team_id, job_id, time_window_start, path)`.+#+# The raw vitals query has no session join, so no session-boundary pad on the+# event scan is needed — each event maps to one (team-tz day, path) bucket.+# One state column per metric: ARRAY JOIN would fan one event into four rows+# but the new analyzer rejects bare `events.properties` references inside the+# ARRAY JOIN source array, so we collapse per-event into per-row.+INSERT_QUERY_TEMPLATE = """+SELECT+ toStartOfDay(event_timestamp, {team_tz}) AS time_window_start,+ path AS path,+ quantilesStateIf(0.75, 0.90, 0.99)(assumeNotNull(inp_value), isNotNull(inp_value)) AS inp_quantiles_state,+ quantilesStateIf(0.75, 0.90, 0.99)(assumeNotNull(lcp_value), isNotNull(lcp_value)) AS lcp_quantiles_state,+ quantilesStateIf(0.75, 0.90, 0.99)(assumeNotNull(cls_value), isNotNull(cls_value)) AS cls_quantiles_state,+ quantilesStateIf(0.75, 0.90, 0.99)(assumeNotNull(fcp_value), isNotNull(fcp_value)) AS fcp_quantiles_state+FROM (+ SELECT+ events.timestamp AS event_timestamp,+ {breakdown_by} AS path,+ toFloat(events.properties.`$web_vitals_INP_value`) AS inp_value,+ toFloat(events.properties.`$web_vitals_LCP_value`) AS lcp_value,+ toFloat(events.properties.`$web_vitals_CLS_value`) AS cls_value,+ toFloat(events.properties.`$web_vitals_FCP_value`) AS fcp_value+ FROM events+ WHERE and(+ equals(events.event, '$web_vitals'),+ isNotNull({breakdown_by}),+ events.timestamp >= {time_window_min},+ events.timestamp < {time_window_max},+ {user_filter},+ {test_account_filter}+ )+)+GROUP BY time_window_start, path+"""+++def _breakdown_expr(runner: "WebVitalsPathBreakdownQueryRunner") -> ast.Expr:+ """The path expression — `_apply_path_cleaning` returns either the raw+ `events.properties.$pathname` field or the cleaned variant when+ `query.doPathCleaning` is True. The substituted AST is what+ `ensure_precomputed` hashes into the cache key, so the cleaning-on and+ cleaning-off variants each get a distinct precomputed job."""+ return runner._apply_path_cleaning(ast.Field(chain=["events", "properties", "$pathname"]))+++def ensure_web_vitals_paths_precomputed(+ runner: "WebVitalsPathBreakdownQueryRunner",+ time_range_start: datetime,+ time_range_end: datetime,+) -> LazyComputationResult:+ placeholders: dict[str, ast.Expr] = {+ "breakdown_by": _breakdown_expr(runner),+ "user_filter": user_filter_expr(runner),+ "test_account_filter": test_account_filter_expr(runner),+ # Team timezone goes into the cache key — a team that changes its+ # timezone naturally invalidates existing jobs.+ "team_tz": ast.Constant(value=runner.team.timezone),+ }++ return ensure_precomputed(+ team=runner.team,+ insert_query=INSERT_QUERY_TEMPLATE,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ ttl_seconds=LAZY_TTL_SECONDS,+ table=LazyComputationTable.WEB_VITALS_PATHS_PREAGGREGATED,+ placeholders=placeholders,+ query_type="web_vitals_paths_lazy_insert",+ )+++# HogQL read template — substituted via `parse_select(..., placeholders=...)` so+# arguments flow through the printer with proper escaping. The+# `arrayElement(quantilesMergeIf(...), pct_index)` picks one percentile out+# of the three stored in the reservoir. `HAVING value >= 0` mirrors the raw+# query: an all-NULL or empty reservoir comes back as NULL/<0 here, and the+# raw path drops those rows the same way.+#+# `LIMIT 20 BY band` matches the raw query: at most 20 rows per band sorted by+# ascending value. The runner-side response builder then re-partitions the rows+# into the `good`/`needs_improvements`/`poor` arrays.+#+# The metric-specific state column is substituted as a `Field` placeholder, so+# only one of `inp_quantiles_state` / `lcp_quantiles_state` / ... is read.+_READ_SQL_TEMPLATE = """+SELECT+ multiIf(+ value <= {good_threshold}, 'good',+ value <= {needs_improvements_threshold}, 'needs_improvements',+ 'poor'+ ) AS band,+ path,+ value+FROM (+ SELECT+ path,+ arrayElement(+ quantilesMergeIf(0.75, 0.90, 0.99)(+ {state_column},+ and(time_window_start >= {cur_start}, time_window_start < {cur_end})+ ),+ {pct_index}+ ) AS value+ FROM posthog.web_vitals_paths_preaggregated+ WHERE and(team_id = {team_id}, job_id IN {job_ids})+ GROUP BY path+ HAVING value >= 0+)+ORDER BY value ASC, path ASC+LIMIT 20 BY band+"""+++def execute_read_query(+ *,+ runner: "WebVitalsPathBreakdownQueryRunner",+ job_ids: list[str],+ current_start_utc: datetime,+ current_end_utc: datetime,+) -> list[tuple[str, str, float]]:+ """Read the precomputed rows via HogQL. Returns the raw `(band, path, value)`+ triples in the same shape the raw runner's `_calculate` consumes.++ `convertToProjectTimezone=False` is forced so the printer does not wrap+ `time_window_start` (stored UTC) in `toTimeZone(..., team_tz)` and break the+ direct comparison against our UTC `cur_start` / `cur_end` constants.+ """+ pct_index = _PCT_INDEX[runner.query.percentile]+ good_threshold = float(runner.query.thresholds[0])+ needs_improvements_threshold = float(runner.query.thresholds[1])+ state_column = _METRIC_STATE_COLUMN[runner.query.metric]++ placeholders: dict[str, ast.Expr] = {+ "team_id": ast.Constant(value=runner.team.pk),+ "job_ids": ast.Constant(value=[str(jid) for jid in job_ids]),+ "state_column": ast.Field(chain=[state_column]),+ "cur_start": ast.Constant(value=current_start_utc),+ "cur_end": ast.Constant(value=current_end_utc),+ "pct_index": ast.Constant(value=pct_index),+ "good_threshold": ast.Constant(value=good_threshold),+ "needs_improvements_threshold": ast.Constant(value=needs_improvements_threshold),+ }++ parsed = parse_select(_READ_SQL_TEMPLATE, placeholders=placeholders)++ modifiers = runner.modifiers.model_copy() if runner.modifiers else HogQLQueryModifiers()+ modifiers.convertToProjectTimezone = False++ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY, query_type="web_vitals_paths_lazy_query")+ response = execute_hogql_query(+ query_type="web_vitals_paths_lazy_query",+ query=parsed,+ team=runner.team,+ timings=runner.timings,+ modifiers=modifiers,+ limit_context=runner.limit_context,+ )+ assert response.results is not None+ return [(row[0], row[1], row[2]) for row in response.results]+++def _build_response(+ runner: "WebVitalsPathBreakdownQueryRunner",+ rows: list[tuple[str, str, float]],+) -> WebVitalsPathBreakdownQueryResponse:+ def _band_rows(band: WebVitalsMetricBand) -> list[WebVitalsPathBreakdownResultItem]:+ return [WebVitalsPathBreakdownResultItem(path=row[1], value=row[2]) for row in rows if row[0] == band.value]++ return WebVitalsPathBreakdownQueryResponse(+ results=[+ WebVitalsPathBreakdownResult(+ good=_band_rows(WebVitalsMetricBand.GOOD),+ needs_improvements=_band_rows(WebVitalsMetricBand.NEEDS_IMPROVEMENTS),+ poor=_band_rows(WebVitalsMetricBand.POOR),+ )+ ],+ timings=runner.timings.to_list() if runner.timings else None,+ modifiers=runner.modifiers,+ usedLazyPrecompute=True,+ )+++def execute_lazy_precomputed_read(+ runner: "WebVitalsPathBreakdownQueryRunner",+) -> Optional[WebVitalsPathBreakdownQueryResponse]:+ """Orchestrate the lazy precompute + read. Returns the response, or None on+ any failure (caller falls through to the raw path)."""+ # Tag the whole lazy path (INSERT + read) with product/feature so the INSERT+ # `sync_execute` inside `ensure_web_vitals_paths_precomputed` doesn't trip+ # DEBUG-mode `UntaggedQueryError`. The read query overrides `query_type`+ # later via `tag_queries(...)` inside `execute_read_query`.+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)+ team_id = runner.team.pk+ overall_started = time.perf_counter()+ try:+ date_from = runner.query_date_range.date_from()+ date_to = runner.query_date_range.date_to()+ assert date_from is not None and date_to is not None++ # Convert team-tz bounds to tz-aware UTC. We keep `tzinfo` so the HogQL+ # printer doesn't fall back to host-local timezone interpretation when+ # escaping the datetime constants in the filter.+ current_start_utc = date_from.astimezone(UTC)+ current_end_utc = date_to.astimezone(UTC)++ # Expand the precompute span to UTC day boundaries so the framework's+ # daily-window jobs fully cover the team-tz request.+ time_range_start = floor_utc_day(current_start_utc)+ time_range_end = ceil_utc_day(current_end_utc)++ if time_range_start >= time_range_end:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="empty_range").inc()+ logger.info(+ "web_vitals_paths_lazy_precompute_empty_range",+ team_id=team_id,+ time_range_start=time_range_start.isoformat(),+ time_range_end=time_range_end.isoformat(),+ )+ return None++ logger.info(+ "web_vitals_paths_lazy_precompute_started",+ team_id=team_id,+ metric=runner.query.metric.value,+ percentile=runner.query.percentile.value,+ time_range_start=time_range_start.isoformat(),+ time_range_end=time_range_end.isoformat(),+ time_range_days=(time_range_end - time_range_start).days,+ )++ result = ensure_web_vitals_paths_precomputed(+ runner=runner,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ )++ if not result.job_ids:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="no_job_ids").inc()+ logger.info(+ "web_vitals_paths_lazy_precompute_no_job_ids",+ team_id=team_id,+ metric=runner.query.metric.value,+ )+ return None++ if not result.ready:+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="current_not_ready").inc()+ logger.info(+ "web_vitals_paths_lazy_precompute_current_not_ready",+ team_id=team_id,+ job_count=len(result.job_ids),+ )+ return None++ job_ids: list[str] = [str(jid) for jid in result.job_ids]++ rows = execute_read_query(+ runner=runner,+ job_ids=job_ids,+ current_start_utc=current_start_utc,+ current_end_utc=current_end_utc,+ )++ response = _build_response(runner, rows)+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=_FAMILY).inc()+ logger.info(+ "web_vitals_paths_lazy_precompute_completed",+ team_id=team_id,+ metric=runner.query.metric.value,+ percentile=runner.query.percentile.value,+ job_count=len(result.job_ids),+ rows_returned=len(rows),+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return response+ except Exception as exc:+ WEB_VITALS_LAZY_FAILED.labels(error_type=type(exc).__name__).inc()+ logger.exception(+ "web_vitals_paths_lazy_precompute_failed",+ team_id=team_id,+ error_type=type(exc).__name__,+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return Nonediff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex 7d0b5f1d49fb..83a175ccd95a 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -86,6 +86,7 @@ def queries_to_keep_fresh('web_overview_lazy_query','web_stats_paths_lazy_query','web_vitals_path_breakdown_query',+ 'web_vitals_paths_lazy_query','external_clicks_query'))diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 11384ddd0a13..4f2cdfda62e1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9346,6 +9346,7 @@ export namespace Schemas {results: WebVitalsPathBreakdownResult[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;+ usedLazyPrecompute?: boolean | null;}export interface Response9 {@@ -10308,6 +10309,7 @@ export namespace Schemas {results: WebVitalsPathBreakdownResult[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;+ usedLazyPrecompute?: boolean | null;}export interface WebVitalsPathBreakdownQuery {@@ -10341,6 +10343,8 @@ export namespace Schemas {*/thresholds: number[];useSessionsTable?: boolean | null;+ /** Opt this specific query into the web vitals path breakdown precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. * */+ useWebAnalyticsPrecompute?: boolean | null;/** version of the node, used for schema migrations */version?: number | null;}@@ -33786,6 +33790,7 @@ export namespace Schemas {results: WebVitalsPathBreakdownResult[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;+ usedLazyPrecompute?: boolean | null;}export interface QueryResponseAlternative28 {@@ -34162,6 +34167,7 @@ export namespace Schemas {results: WebVitalsPathBreakdownResult[];/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;+ usedLazyPrecompute?: boolean | null;}export interface QueryResponseAlternative48 {