Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(web-analytics): lazy precomputation for web stats simple breakdowns (#59713)

Lucas Ricoyd399551915ec
diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsx
index bd8704ed8aaf..f75c3b8df506 100644
--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx
@@ -193,6 +193,7 @@ export function DataTable({
'usedPreAggregatedTables' in response &&
response.usedPreAggregatedTables &&
response?.hogql
+ const usedWebAnalyticsLazyPrecompute = response && 'usedLazyPrecompute' in response && response.usedLazyPrecompute
const dataTableLogicProps: DataTableLogicProps = {
query,
@@ -891,7 +892,11 @@ export function DataTable({
) : null}
{showResultsTable && (
<div className="relative">
- {usedWebAnalyticsPreAggregatedTables && <PreAggregatedBadge />}
+ {usedWebAnalyticsLazyPrecompute ? (
+ <PreAggregatedBadge variant="precomputed" />
+ ) : usedWebAnalyticsPreAggregatedTables ? (
+ <PreAggregatedBadge variant="preagg" />
+ ) : null}
<LemonTable
data-attr={dataAttr}
className="DataTable"
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 72277118b485..430cd277b2fb 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -9982,6 +9982,9 @@
"items": {},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -11946,6 +11949,9 @@
"items": {},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -29252,6 +29258,9 @@
"items": {},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -30289,6 +30298,9 @@
"items": {},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -40446,6 +40458,10 @@
"deprecated": "ignored, always treated as enabled *",
"type": "boolean"
},
+ "useWebAnalyticsPrecompute": {
+ "description": "Opt this specific query into the web stats table 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"
@@ -40508,6 +40524,9 @@
"items": {},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index b13f2c20529f..5d5b8ff6448f 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2367,6 +2367,8 @@ export interface WebStatsTableQuery extends WebAnalyticsQueryBase<WebStatsTableQ
includeHost?: boolean
limit?: integer
offset?: integer
+ /** Opt this specific query into the web stats table 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 interface WebStatsTableQueryResponse extends AnalyticsQueryResponseBase {
results: unknown[]
@@ -2378,6 +2380,7 @@ export interface WebStatsTableQueryResponse extends AnalyticsQueryResponseBase {
limit?: integer
offset?: integer
usedPreAggregatedTables?: boolean
+ usedLazyPrecompute?: boolean
}
export type CachedWebStatsTableQueryResponse = CachedQueryResponse<WebStatsTableQueryResponse>
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 1e9d9381cf69..a11d9ef460ef 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -1160,6 +1160,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
conversionGoal,
orderBy: tablesOrderBy ?? undefined,
tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,
+ useWebAnalyticsPrecompute,
...source,
},
embedded: false,
diff --git a/posthog/clickhouse/migrations/0259_web_stats_preaggregated.py b/posthog/clickhouse/migrations/0259_web_stats_preaggregated.py
new file mode 100644
index 000000000000..b3ffb1a07703
--- /dev/null
+++ b/posthog/clickhouse/migrations/0259_web_stats_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_stats_preaggregated_sql import (
+ DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,
+ SHARDED_WEB_STATS_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_STATS_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_STATS_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+ # Same distributed table also on AUX for ad-hoc debugging — lets operators
+ # `SELECT … FROM web_stats_preaggregated` directly from an AUX node instead
+ # of bouncing through DATA. Same DDL, no production cost.
+ run_sql_with_exceptions(
+ DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index 7542780a40b0..fa39737bdf4e 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0258_hog_invocation_results_warpstream_cyclotron
+0259_web_stats_preaggregated
diff --git a/posthog/clickhouse/preaggregation/web_stats_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_stats_preaggregated_sql.py
new file mode 100644
index 000000000000..9a7409a78fce
--- /dev/null
+++ b/posthog/clickhouse/preaggregation/web_stats_preaggregated_sql.py
@@ -0,0 +1,111 @@
+# Table for storing lazy-precomputed web stats table aggregates
+#
+# Stores per-hour, per-team, per-breakdown aggregate states for the two metrics
+# surfaced by WebStatsTableQueryRunner's simple breakdowns: unique users and
+# total pageviews. Reads merge across hourly buckets to answer arbitrary date
+# ranges within the precomputed window.
+#
+# Shared by every low-cardinality simple breakdown and the channel-type
+# breakdown — the `breakdown_by` column (a WebStatsBreakdown enum value) is the
+# discriminator. Buckets are UTC hourly on the session's start timestamp, so the
+# read matches the raw query's session-start attribution.
+
+from django.conf import settings
+
+from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme
+
+TABLE_BASE_NAME = "web_stats_preaggregated"
+
+
+def DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE():
+ return TABLE_BASE_NAME
+
+
+def SHARDED_WEB_STATS_PREAGGREGATED_TABLE():
+ return f"sharded_{TABLE_BASE_NAME}"
+
+
+def SHARDED_WEB_STATS_PREAGGREGATED_TABLE_ENGINE():
+ return ReplacingMergeTree(TABLE_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")
+
+
+WEB_STATS_PREAGGREGATED_TABLE_BASE_SQL = """
+CREATE TABLE IF NOT EXISTS {table_name}
+(
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket on the session's start timestamp. Reads filter by
+ -- [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- WebStatsBreakdown enum value (`Browser`, `Country`, `InitialChannelType`,
+ -- ...). The discriminator that lets every simple breakdown share this table.
+ breakdown_by String,
+
+ -- The breakdown dimension value, JSON-encoded so tuple/float/null breakdowns
+ -- (Region, City, Viewport, Timezone) round-trip through a single String column.
+ breakdown_value String,
+
+ -- Aggregate states matching WebStatsTableQueryRunner's simple-breakdown
+ -- metrics: unique visitors and total pageviews. `uniq` (HyperLogLog) matches
+ -- the v2 pre-aggregation choice; ~99% accuracy is fine for the table use case.
+ -- Pageviews are counted per session in the INSERT, then summed here.
+ uniq_users_state AggregateFunction(uniq, UUID),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+
+ -- 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_STATS_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. `breakdown_by` is
+ # functionally constant per `job_id` but is kept in ORDER BY so the read-side
+ # `WHERE breakdown_by = ...` filter is index-served; `breakdown_value` must be
+ # in ORDER BY so the ReplacingMergeTree does not collapse distinct breakdown
+ # values within one job.
+ return (
+ WEB_STATS_PREAGGREGATED_TABLE_BASE_SQL
+ + """
+PARTITION BY toYYYYMMDD(expires_at)
+ORDER BY (team_id, job_id, breakdown_by, time_window_start, breakdown_value)
+TTL toDateTime(expires_at)
+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+"""
+ ).format(
+ table_name=SHARDED_WEB_STATS_PREAGGREGATED_TABLE(),
+ engine=SHARDED_WEB_STATS_PREAGGREGATED_TABLE_ENGINE(),
+ )
+
+
+def DISTRIBUTED_WEB_STATS_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_STATS_PREAGGREGATED_TABLE_BASE_SQL.format(
+ table_name=DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE(),
+ engine=Distributed(
+ data_table=SHARDED_WEB_STATS_PREAGGREGATED_TABLE(),
+ sharding_key="sipHash64(job_id)",
+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,
+ ),
+ )
+
+
+def DROP_WEB_STATS_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE()}"
+
+
+def DROP_SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_STATS_PREAGGREGATED_TABLE()} SYNC"
+
+
+def TRUNCATE_WEB_STATS_PREAGGREGATED_TABLE_SQL():
+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_STATS_PREAGGREGATED_TABLE()}"
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index fe911342ac74..dd1f437ef7f3 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -49,6 +49,10 @@ from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (
DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
)
+from posthog.clickhouse.preaggregation.web_stats_preaggregated_sql import (
+ DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,
+ SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,
+)
from posthog.clickhouse.property_values import (
DISTRIBUTED_PROPERTY_VALUES_TABLE_SQL,
KAFKA_PROPERTY_VALUES_TABLE_SQL_FN,
@@ -303,6 +307,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (
SHARDED_EXPERIMENT_EXPOSURES_TABLE_SQL,
SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE_SQL,
SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
+ SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,
DISTINCT_ID_USAGE_DATA_TABLE_SQL,
PROPERTY_DEFINITIONS_TABLE_SQL,
*[table.sharded_table_sql for table in EMBEDDING_TABLES],
@@ -360,6 +365,7 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (
DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE_SQL,
DISTRIBUTED_EXPERIMENT_METRIC_EVENTS_TABLE_SQL,
DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
+ DISTRIBUTED_WEB_STATS_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.ambr
index 0c9f7bf2f5b9..7f05d7e042bb 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -6169,6 +6169,47 @@
'''
# ---
+# name: test_create_table_query[sharded_web_stats_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_web_stats_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket on the session's start timestamp. Reads filter by
+ -- [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- WebStatsBreakdown enum value (`Browser`, `Country`, `InitialChannelType`,
+ -- ...). The discriminator that lets every simple breakdown share this table.
+ breakdown_by String,
+
+ -- The breakdown dimension value, JSON-encoded so tuple/float/null breakdowns
+ -- (Region, City, Viewport, Timezone) round-trip through a single String column.
+ breakdown_value String,
+
+ -- Aggregate states matching WebStatsTableQueryRunner's simple-breakdown
+ -- metrics: unique visitors and total pageviews. `uniq` (HyperLogLog) matches
+ -- the v2 pre-aggregation choice; ~99% accuracy is fine for the table use case.
+ -- Pageviews are counted per session in the INSERT, then summed here.
+ uniq_users_state AggregateFunction(uniq, UUID),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+
+ -- 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_stats_preaggregated', '{replica}', computed_at)
+
+ PARTITION BY toYYYYMMDD(expires_at)
+ ORDER BY (team_id, job_id, breakdown_by, time_window_start, breakdown_value)
+ TTL toDateTime(expires_at)
+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+
+ '''
+# ---
# name: test_create_table_query[tophog]
'''
@@ -6375,6 +6416,42 @@
'''
# ---
+# name: test_create_table_query[web_stats_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS web_stats_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket on the session's start timestamp. Reads filter by
+ -- [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- WebStatsBreakdown enum value (`Browser`, `Country`, `InitialChannelType`,
+ -- ...). The discriminator that lets every simple breakdown share this table.
+ breakdown_by String,
+
+ -- The breakdown dimension value, JSON-encoded so tuple/float/null breakdowns
+ -- (Region, City, Viewport, Timezone) round-trip through a single String column.
+ breakdown_value String,
+
+ -- Aggregate states matching WebStatsTableQueryRunner's simple-breakdown
+ -- metrics: unique visitors and total pageviews. `uniq` (HyperLogLog) matches
+ -- the v2 pre-aggregation choice; ~99% accuracy is fine for the table use case.
+ -- Pageviews are counted per session in the INSERT, then summed here.
+ uniq_users_state AggregateFunction(uniq, UUID),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+
+ -- 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_stats_preaggregated', sipHash64(job_id))
+
+ '''
+# ---
# name: test_create_table_query[writable_app_metrics2]
'''
@@ -9448,6 +9525,47 @@
'''
# ---
+# name: test_create_table_query_replicated_and_storage[sharded_web_stats_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_web_stats_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket on the session's start timestamp. Reads filter by
+ -- [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- WebStatsBreakdown enum value (`Browser`, `Country`, `InitialChannelType`,
+ -- ...). The discriminator that lets every simple breakdown share this table.
+ breakdown_by String,
+
+ -- The breakdown dimension value, JSON-encoded so tuple/float/null breakdowns
+ -- (Region, City, Viewport, Timezone) round-trip through a single String column.
+ breakdown_value String,
+
+ -- Aggregate states matching WebStatsTableQueryRunner's simple-breakdown
+ -- metrics: unique visitors and total pageviews. `uniq` (HyperLogLog) matches
+ -- the v2 pre-aggregation choice; ~99% accuracy is fine for the table use case.
+ -- Pageviews are counted per session in the INSERT, then summed here.
+ uniq_users_state AggregateFunction(uniq, UUID),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+
+ -- 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_stats_preaggregated', '{replica}', computed_at)
+
+ PARTITION BY toYYYYMMDD(expires_at)
+ ORDER BY (team_id, job_id, breakdown_by, time_window_start, breakdown_value)
+ 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.py
index 36bf2b4a355a..90fd1dcade01 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -134,6 +134,7 @@ from posthog.hogql.database.schema.web_analytics_preaggregated import (
WebPreAggregatedStatsTable,
)
from posthog.hogql.database.schema.web_overview_preaggregated import WebOverviewPreaggregatedTable
+from posthog.hogql.database.schema.web_stats_preaggregated import WebStatsPreaggregatedTable
from posthog.hogql.database.utils import get_join_field_chain, qualify_join_key_expr
from posthog.hogql.errors import QueryError, ResolutionError
from posthog.hogql.parser import parse_expr
@@ -291,6 +292,9 @@ def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNod
"web_overview_preaggregated": TableNode(
name="web_overview_preaggregated", table=WebOverviewPreaggregatedTable()
),
+ "web_stats_preaggregated": TableNode(
+ name="web_stats_preaggregated", table=WebStatsPreaggregatedTable()
+ ),
},
),
"system": SystemTables(),
diff --git a/posthog/hogql/database/schema/web_stats_preaggregated.py b/posthog/hogql/database/schema/web_stats_preaggregated.py
new file mode 100644
index 000000000000..8e2e6a5f888b
--- /dev/null
+++ b/posthog/hogql/database/schema/web_stats_preaggregated.py
@@ -0,0 +1,39 @@
+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_stats_preaggregated_sql import DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE
+
+
+class WebStatsPreaggregatedTable(Table):
+ # Mirrors `WebOverviewPreaggregatedTable`: deterministic replica selection
+ # via `load_balancing="in_order"` (read-your-writes) and shard pruning via
+ # `optimize_skip_unused_shards=1` (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"),
+ "breakdown_by": StringDatabaseField(name="breakdown_by"),
+ "breakdown_value": StringDatabaseField(name="breakdown_value"),
+ "uniq_users_state": UnknownDatabaseField(name="uniq_users_state"),
+ "sum_pageviews_state": UnknownDatabaseField(name="sum_pageviews_state"),
+ }
+
+ def to_printed_clickhouse(self, context):
+ return DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE()
+
+ def to_printed_hogql(self):
+ return "web_stats_preaggregated"
diff --git a/posthog/schema.py b/posthog/schema.py
index 8be6a872f0bf..5a5874a178d7 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -9368,6 +9368,7 @@ class WebStatsTableQueryResponse(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = None
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -12805,6 +12806,7 @@ class CachedWebStatsTableQueryResponse(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = None
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -13371,6 +13373,7 @@ class Response5(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = None
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -16261,6 +16264,7 @@ class QueryResponseAlternative24(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = None
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -16795,6 +16799,7 @@ class QueryResponseAlternative44(BaseModel):
description=("Measured timings for different parts of the query generation process"),
)
types: list | None = None
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -18814,6 +18819,14 @@ class WebStatsTableQuery(BaseModel):
samplingFactor: float | None = Field(default=None, description="Sampling rate")
tags: QueryLogTags | None = None
useSessionsTable: bool | None = None
+ useWebAnalyticsPrecompute: bool | None = Field(
+ default=None,
+ description=(
+ "Opt this specific query into the web stats table 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.py
index ef0123ffe7d0..d88f307e792b 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -277,6 +277,7 @@ class LazyComputationTable(StrEnum):
EXPERIMENT_EXPOSURES_PREAGGREGATED = "experiment_exposures_preaggregated"
EXPERIMENT_METRIC_EVENTS_PREAGGREGATED = "experiment_metric_events_preaggregated"
WEB_OVERVIEW_PREAGGREGATED = "web_overview_preaggregated"
+ WEB_STATS_PREAGGREGATED = "web_stats_preaggregated"
# Tables where expires_at is a Date (not DateTime64). Date truncates to midnight,
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index f5a1a1944138..4b28f6b26233 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2746,6 +2746,7 @@ export interface WebStatsTableQueryResponseApi {
/** Measured timings for different parts of the query generation process */
timings?: QueryTimingApi[] | null
types?: unknown[] | null
+ usedLazyPrecompute?: boolean | null
usedPreAggregatedTables?: boolean | null
}
@@ -2790,6 +2791,8 @@ export interface WebStatsTableQueryApi {
samplingFactor?: number | null
tags?: QueryLogTagsApi | null
useSessionsTable?: boolean | null
+ /** Opt this specific query into the web stats table 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
}
@@ -3100,6 +3103,7 @@ export interface Response5Api {
/** Measured timings for different parts of the query generation process */
timings?: QueryTimingApi[] | null
types?: unknown[] | null
+ usedLazyPrecompute?: boolean | null
usedPreAggregatedTables?: boolean | null
}
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index 363465f4dc0d..75a69f37dcac 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -39,6 +39,11 @@ from products.web_analytics.backend.hogql_queries.stats_table_strategies import
StatsTableQueryStrategy,
)
from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner, map_columns
+from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import (
+ LazyStatsResult,
+ can_use_lazy_precompute,
+ execute_lazy_precomputed_read,
+)
BREAKDOWN_NULL_DISPLAY = "(none)"
BREAKDOWN_REFERRER_PREFIX = "referrer:"
@@ -352,7 +357,49 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
properties = self.query.properties + self._test_account_filters
return property_to_expr(properties, team=self.team)
+ def get_lazy_precomputed_result(self) -> Optional[LazyStatsResult]:
+ if not can_use_lazy_precompute(self):
+ return None
+ return execute_lazy_precomputed_read(self)
+
+ def _build_response_from_lazy(self, result: LazyStatsResult) -> WebStatsTableQueryResponse:
+ """Shape the precompute read into a `WebStatsTableQueryResponse` identical
+ to the raw `SimpleBreakdownStrategy` path: breakdown value, visitors and
+ views tuples, the `ui_fill_fraction` bar value and a `cross_sell` column.
+
+ Ordering, filtering, and pagination already happened in ClickHouse — see
+ `execute_read_query`. This function just shapes the rows."""
+ include_previous = self.query_compare_to_date_range is not None
+
+ results: list = []
+ for r in result.rows:
+ visitors = (r.visitors_current, r.visitors_previous if include_previous else None)
+ views = (r.views_current, r.views_previous if include_previous else None)
+ current_metric = r.views_current if result.sort_metric == "views" else r.visitors_current
+ fill_fraction = current_metric / r.fill_total if r.fill_total else 0
+ results.append([r.breakdown_value, visitors, views, fill_fraction, ""])
+
+ return WebStatsTableQueryResponse(
+ columns=[
+ "context.columns.breakdown_value",
+ "context.columns.visitors",
+ "context.columns.views",
+ "context.columns.ui_fill_fraction",
+ "context.columns.cross_sell",
+ ],
+ results=results,
+ modifiers=self.modifiers,
+ usedLazyPrecompute=True,
+ hasMore=result.has_more,
+ limit=self.paginator.limit,
+ offset=self.paginator.offset,
+ )
+
def _calculate(self):
+ lazy_result = self.get_lazy_precomputed_result()
+ if lazy_result is not None:
+ return self._build_response_from_lazy(lazy_result)
+
query = self.to_query()
# Pre-aggregated tables store data in UTC **buckets**, so we need to disable timezone conversion
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
index 87ac060dcda4..cfa8ae83c21c 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
@@ -12,6 +12,12 @@ from products.web_analytics.backend.hogql_queries.metrics import (
WEB_ANALYTICS_QUERY_DURATION,
WEB_ANALYTICS_QUERY_ERRORS,
)
+from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED,
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS,
+ can_use_lazy_precompute,
+)
from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
@@ -77,6 +83,9 @@ class TestWebAnalyticsMetrics(TestCase):
WEB_ANALYTICS_QUERY_COUNTER._metrics.clear()
WEB_ANALYTICS_QUERY_DURATION._metrics.clear()
WEB_ANALYTICS_QUERY_ERRORS._metrics.clear()
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED._metrics.clear()
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK._metrics.clear()
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS._metrics.clear()
@parameterized.expand(
[
@@ -291,6 +300,91 @@ class TestWebAnalyticsMetrics(TestCase):
== 1.0
)
+ @parameterized.expand(
+ [
+ ("web_overview", "web_overview"),
+ ("web_stats", "web_stats"),
+ ]
+ )
+ def test_lazy_precompute_gate_rejection_increments_counter(self, _name, family):
+ runner = MagicMock()
+ runner.team = MagicMock(pk=42, uuid="00000000-0000-0000-0000-000000000000", organization_id=7, id=42)
+ runner.query = MagicMock(useWebAnalyticsPrecompute=True)
+
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
+ return_value=False,
+ ):
+ assert can_use_lazy_precompute(runner, log_prefix=family) is False
+
+ assert (
+ _get_counter_value(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED,
+ {"family": family, "reason": "OrgFeatureFlagDisabled"},
+ )
+ == 1.0
+ )
+
+ @parameterized.expand(
+ [
+ ("web_overview", "web_overview"),
+ ("web_stats", "web_stats"),
+ ]
+ )
+ def test_lazy_precompute_per_query_opt_in_not_set_rejection(self, _name, family):
+ runner = MagicMock()
+ runner.team = MagicMock(pk=42, uuid="00000000-0000-0000-0000-000000000000", organization_id=7, id=42)
+ runner.query = MagicMock(useWebAnalyticsPrecompute=False)
+
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
+ return_value=True,
+ ):
+ assert can_use_lazy_precompute(runner, log_prefix=family) is False
+
+ assert (
+ _get_counter_value(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED,
+ {"family": family, "reason": "PerQueryOptInNotSet"},
+ )
+ == 1.0
+ )
+
+ @parameterized.expand(
+ [
+ ("empty_range",),
+ ("no_job_ids",),
+ ("current_not_ready",),
+ ("previous_not_ready",),
+ ]
+ )
+ def test_lazy_precompute_fallback_counter_label_space(self, reason):
+ # Verifies the metric accepts each `reason` value the lazy modules emit.
+ # Integration coverage of the actual call sites lives in the per-runner
+ # lazy precompute tests; this test is a fast guard against label drift.
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family="web_overview", reason=reason).inc()
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family="web_stats", reason=reason).inc()
+
+ assert (
+ _get_counter_value(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,
+ {"family": "web_overview", "reason": reason},
+ )
+ == 1.0
+ )
+ assert (
+ _get_counter_value(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,
+ {"family": "web_stats", "reason": reason},
+ )
+ == 1.0
+ )
+
+ @parameterized.expand([("web_overview",), ("web_stats",)])
+ def test_lazy_precompute_success_counter_label_space(self, family):
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=family).inc()
+ assert _get_counter_value(WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS, {"family": family}) == 1.0
+
@patch(
"products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
index 1ecf6f41cb17..7ca10a6cd9ca 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
@@ -21,6 +21,7 @@ from posthog.schema import (
WebOverviewQuery,
)
+from posthog.clickhouse.client import sync_execute
from posthog.models.utils import uuid7
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
@@ -33,13 +34,18 @@ class TestWebOverviewLazyPrecompute(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 read.
+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_overview_preaggregated")
def _enable_lazy(self):
# Mock the org-level feature flag check to True so the gate accepts our test
# team. 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_overview_lazy_precompute.posthoganalytics.feature_enabled",
+ "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
return_value=True,
)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
new file mode 100644
index 000000000000..ec3e7a0d6735
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
@@ -0,0 +1,594 @@
+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 (
+ CompareFilter,
+ CustomEventConversionGoal,
+ DateRange,
+ EventPropertyFilter,
+ PropertyOperator,
+ WebAnalyticsOrderByDirection,
+ WebAnalyticsOrderByFields,
+ WebAnalyticsSampling,
+ WebStatsBreakdown,
+ WebStatsTableQuery,
+)
+
+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.stats_table import WebStatsTableQueryRunner
+
+# Low-cardinality breakdowns with a generic seed that have data and are cheap to
+# assert parity on. VIEWPORT is exercised separately — the raw query compares
+# viewport tuple elements against 0, which needs numeric properties the test
+# harness does not materialize.
+PARITY_BREAKDOWNS = [
+ ("browser", WebStatsBreakdown.BROWSER),
+ ("os", WebStatsBreakdown.OS),
+ ("device_type", WebStatsBreakdown.DEVICE_TYPE),
+ ("country", WebStatsBreakdown.COUNTRY),
+ ("region", WebStatsBreakdown.REGION),
+ ("channel_type", WebStatsBreakdown.INITIAL_CHANNEL_TYPE),
+ ("initial_referring_domain", WebStatsBreakdown.INITIAL_REFERRING_DOMAIN),
+]
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestWebStatsLazyPrecompute(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 read.
+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_stats_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 _props(self, **overrides) -> dict:
+ base = {
+ "$browser": "Chrome",
+ "$os": "Linux",
+ "$device_type": "Desktop",
+ "$geoip_country_code": "US",
+ "$geoip_subdivision_1_code": "US-CA",
+ "$geoip_subdivision_1_name": "California",
+ "$viewport_width": 1920,
+ "$viewport_height": 1080,
+ "$referring_domain": "google.com",
+ }
+ base.update(overrides)
+ return base
+
+ def _seed(self) -> None:
+ # u1: session s1 (two pageviews /a /b) + session s3 (one pageview /a).
+ # u2: session s2 (one pageview /x) with different dimensions.
+ s1 = str(uuid7("2024-01-02"))
+ s2 = str(uuid7("2024-01-03"))
+ s3 = str(uuid7("2024-01-04"))
+ _create_person(team_id=self.team.pk, distinct_ids=["u1"], properties={"name": "u1"})
+ _create_person(team_id=self.team.pk, distinct_ids=["u2"], properties={"name": "u2"})
+
+ for path, ts in (("/a", "2024-01-02T10:00:00Z"), ("/b", "2024-01-02T10:05:00Z")):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="u1",
+ timestamp=ts,
+ properties=self._props(
+ **{
+ "$session_id": s1,
+ "$host": "example.com",
+ "$current_url": f"https://example.com{path}",
+ "$pathname": path,
+ }
+ ),
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="u2",
+ timestamp="2024-01-03T11:00:00Z",
+ properties=self._props(
+ **{
+ "$session_id": s2,
+ "$host": "other.com",
+ "$current_url": "https://other.com/x",
+ "$pathname": "/x",
+ "$browser": "Firefox",
+ "$os": "Windows",
+ "$device_type": "Mobile",
+ "$geoip_country_code": "GB",
+ "$geoip_subdivision_1_code": "GB-ENG",
+ "$geoip_subdivision_1_name": "England",
+ "$viewport_width": 375,
+ "$viewport_height": 667,
+ }
+ ),
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="u1",
+ timestamp="2024-01-04T09:00:00Z",
+ properties=self._props(
+ **{
+ "$session_id": s3,
+ "$host": "example.com",
+ "$current_url": "https://example.com/a",
+ "$pathname": "/a",
+ }
+ ),
+ )
+
+ def _build_query(
+ self,
+ breakdown_by: WebStatsBreakdown = WebStatsBreakdown.BROWSER,
+ date_from: str = "2024-01-01",
+ date_to: str = "2024-01-07",
+ properties: list | None = None,
+ compare: bool = False,
+ conversion_goal=None,
+ sampling: WebAnalyticsSampling | None = None,
+ include_bounce_rate: bool = False,
+ include_avg_time_on_page: bool = False,
+ include_scroll_depth: bool = False,
+ opt_in_precompute: bool = True,
+ ) -> WebStatsTableQuery:
+ return WebStatsTableQuery(
+ breakdownBy=breakdown_by,
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ properties=properties or [],
+ compareFilter=CompareFilter(compare=compare) if compare else None,
+ conversionGoal=conversion_goal,
+ sampling=sampling,
+ includeBounceRate=include_bounce_rate,
+ includeAvgTimeOnPage=include_avg_time_on_page,
+ includeScrollDepth=include_scroll_depth,
+ useWebAnalyticsPrecompute=opt_in_precompute,
+ )
+
+ def _run(self, query: WebStatsTableQuery):
+ return WebStatsTableQueryRunner(team=self.team, query=query).calculate()
+
+ @staticmethod
+ def _metrics(response) -> list:
+ # Breakdown value + visitors/views tuples, ignoring the fill-fraction
+ # float (computed differently in SQL vs Python) and the cross_sell column.
+ return [(row[0], tuple(row[1]), tuple(row[2])) for row in response.results]
+
+ 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():
+ self._run(self._build_query())
+
+ assert self._job_count() > 0, "expected at least one precompute job to be created"
+
+ @parameterized.expand(PARITY_BREAKDOWNS)
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_lazy_matches_raw(self, _name: str, breakdown_by: WebStatsBreakdown):
+ self._seed()
+
+ raw = self._metrics(self._run(self._build_query(breakdown_by=breakdown_by)))
+
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query(breakdown_by=breakdown_by))
+ lazy = self._metrics(lazy_response)
+
+ ready_jobs = PreaggregationJob.objects.filter(
+ team_id=self.team.pk, status=PreaggregationJob.Status.READY
+ ).count()
+ assert ready_jobs > 0, f"expected a READY precompute job for {breakdown_by}"
+ assert lazy_response.usedLazyPrecompute is True
+ assert lazy == raw, f"lazy/raw mismatch for {breakdown_by}: raw={raw}, lazy={lazy}"
+
+ @parameterized.expand(PARITY_BREAKDOWNS)
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_lazy_matches_raw_with_compare(self, _name: str, breakdown_by: WebStatsBreakdown):
+ self._seed()
+ # Previous period: one extra session for u1 in the 7 days before Jan 1.
+ prev_session = str(uuid7("2023-12-28"))
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="u1",
+ timestamp="2023-12-28T10:00:00Z",
+ properties=self._props(
+ **{
+ "$session_id": prev_session,
+ "$host": "example.com",
+ "$current_url": "https://example.com/old",
+ "$pathname": "/old",
+ }
+ ),
+ )
+
+ raw = self._metrics(self._run(self._build_query(breakdown_by=breakdown_by, compare=True)))
+
+ with self._enable_lazy():
+ lazy = self._metrics(self._run(self._build_query(breakdown_by=breakdown_by, compare=True)))
+
+ assert lazy == raw, f"lazy/raw compare mismatch for {breakdown_by}: raw={raw}, lazy={lazy}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_viewport_breakdown_lazy_runs(self):
+ # The raw VIEWPORT query compares viewport tuple elements against 0,
+ # which needs numeric properties the harness does not materialize — so
+ # this exercises the lazy path on its own rather than asserting parity.
+ self._seed()
+ with self._enable_lazy():
+ response = self._run(self._build_query(breakdown_by=WebStatsBreakdown.VIEWPORT))
+
+ assert response.usedLazyPrecompute is True
+ assert len(response.results) > 0
+ assert all(isinstance(row[0], tuple) and len(row[0]) == 2 for row in response.results)
+
+ @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"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_host_filter_lazy_matches_raw(self):
+ self._seed()
+ host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
+
+ raw = self._metrics(self._run(self._build_query(properties=[host_filter])))
+ with self._enable_lazy():
+ lazy = self._metrics(self._run(self._build_query(properties=[host_filter])))
+
+ assert lazy == raw, f"host-filtered lazy/raw mismatch: raw={raw}, lazy={lazy}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_distinct_breakdowns_get_distinct_cache_entries(self):
+ self._seed()
+ with self._enable_lazy():
+ self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER))
+ browser_jobs = {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(breakdown_by=WebStatsBreakdown.OS))
+ os_jobs = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ assert browser_jobs.isdisjoint(os_jobs), "different breakdowns must produce distinct cache keys"
+
+ @parameterized.expand(
+ [
+ ("bounce_rate", {"include_bounce_rate": True}),
+ ("avg_time_on_page", {"include_avg_time_on_page": True}),
+ ("scroll_depth", {"include_scroll_depth": True}),
+ ]
+ )
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_extra_metric_falls_through(self, _name: str, kwargs: dict):
+ self._seed()
+ with self._enable_lazy():
+ self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER, **kwargs))
+
+ assert self._job_count() == 0, "extra metrics are not precomputed — must fall through to raw"
+
+ @parameterized.expand(
+ [
+ ("page", WebStatsBreakdown.PAGE),
+ ("initial_page", WebStatsBreakdown.INITIAL_PAGE),
+ ("exit_click", WebStatsBreakdown.EXIT_CLICK),
+ ("initial_referring_url", WebStatsBreakdown.INITIAL_REFERRING_URL),
+ ]
+ )
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_high_cardinality_breakdown_falls_through(self, _name: str, breakdown_by: WebStatsBreakdown):
+ # Page/path/referring-URL breakdowns are intentionally excluded — too
+ # high cardinality for the in-Python read. They fall through to raw.
+ self._seed()
+ with self._enable_lazy():
+ self._run(self._build_query(breakdown_by=breakdown_by))
+
+ assert self._job_count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_frustration_metrics_breakdown_falls_through(self):
+ self._seed()
+ with self._enable_lazy():
+ self._run(self._build_query(breakdown_by=WebStatsBreakdown.FRUSTRATION_METRICS))
+
+ assert self._job_count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_language_breakdown_falls_through(self):
+ # LANGUAGE needs an extra topK aggregation column that can't be rebuilt
+ # from hourly states — it must fall through to the raw path.
+ self._seed()
+ with self._enable_lazy():
+ self._run(self._build_query(breakdown_by=WebStatsBreakdown.LANGUAGE))
+
+ assert self._job_count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_conversion_goal_falls_through(self):
+ self._seed()
+ with self._enable_lazy():
+ self._run(
+ self._build_query(conversion_goal=CustomEventConversionGoal(customEventName="$pageview")),
+ )
+
+ assert self._job_count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_sampling_falls_through(self):
+ self._seed()
+ with self._enable_lazy():
+ self._run(self._build_query(sampling=WebAnalyticsSampling(enabled=True)))
+
+ assert self._job_count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_half_hour_offset_timezone_falls_through(self):
+ self.team.timezone = "Asia/Kolkata"
+ self.team.save()
+ self._seed()
+ with self._enable_lazy():
+ self._run(self._build_query())
+
+ assert self._job_count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_query_optin_alone_falls_through_when_org_flag_disabled(self):
+ self._seed()
+ self._run(self._build_query(opt_in_precompute=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():
+ self._run(self._build_query(opt_in_precompute=False))
+
+ assert self._job_count() == 0
+
+ @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._metrics(self._run(self._build_query()))
+ with self._enable_lazy():
+ lazy = self._metrics(self._run(self._build_query()))
+
+ assert lazy == raw, f"lazy/raw mismatch for {team_tz}: raw={raw}, lazy={lazy}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_pagination_lazy_matches_raw(self):
+ self._seed()
+ query = self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)
+ query.limit = 1
+ query.offset = 1
+
+ raw_response = self._run(query)
+ with self._enable_lazy():
+ lazy_response = self._run(query)
+
+ assert self._metrics(lazy_response) == self._metrics(raw_response)
+ assert lazy_response.hasMore == raw_response.hasMore
+ assert lazy_response.limit == raw_response.limit
+ assert lazy_response.offset == raw_response.offset
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_recomputation_picks_up_late_events(self):
+ self._seed()
+ with self._enable_lazy():
+ first = self._metrics(self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)))
+ first_job_ids = set(PreaggregationJob.objects.filter(team_id=self.team.pk).values_list("id", flat=True))
+ assert first_job_ids
+
+ # A late pageview from a new browser after the cache was built.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="u2",
+ timestamp="2024-01-05T08:00:00Z",
+ properties=self._props(
+ **{
+ "$session_id": str(uuid7("2024-01-05")),
+ "$host": "other.com",
+ "$current_url": "https://other.com/late",
+ "$pathname": "/late",
+ "$browser": "Safari",
+ }
+ ),
+ )
+ # Simulate TTL expiry by dropping the READY job rows.
+ PreaggregationJob.objects.filter(id__in=first_job_ids).delete()
+
+ second = self._metrics(self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)))
+
+ assert any(row[0] == "Safari" for row in second), "recomputed result should include the late pageview"
+ assert first != second
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_session_crossing_midnight_lazy_matches_raw(self):
+ # A session whose pageviews straddle a UTC day boundary. Session-start
+ # bucketing attributes the whole session to its start hour; the forward
+ # pad lets the start day's job still see the post-midnight pageviews.
+ self._seed()
+ _create_person(team_id=self.team.pk, distinct_ids=["mid"], properties={"name": "mid"})
+ mid_session = str(uuid7("2024-01-05"))
+ for ts in ("2024-01-05T23:55:00Z", "2024-01-06T00:10:00Z"):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="mid",
+ timestamp=ts,
+ properties=self._props(
+ **{
+ "$session_id": mid_session,
+ "$host": "example.com",
+ "$current_url": "https://example.com/x",
+ "$pathname": "/x",
+ "$browser": "Safari",
+ }
+ ),
+ )
+
+ raw = self._metrics(self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)))
+ with self._enable_lazy():
+ lazy = self._metrics(self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)))
+
+ assert lazy == raw, f"midnight-crossing session mismatch: raw={raw}, lazy={lazy}"
+ # Non-vacuous: the Safari session must have both pageviews counted.
+ safari = next(r for r in raw if r[0] == "Safari")
+ assert safari[2][0] == 2, f"expected 2 Safari views, got {safari}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_ui_fill_fraction_lazy_matches_raw(self):
+ # Column index 3 is `context.columns.ui_fill_fraction` — recomputed in
+ # Python on the lazy path, so assert parity with the raw SQL window fn.
+ self._seed()
+ raw_response = self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER))
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query(breakdown_by=WebStatsBreakdown.BROWSER))
+
+ raw_fill = [row[3] for row in raw_response.results]
+ lazy_fill = [row[3] for row in lazy_response.results]
+ assert len(raw_fill) == len(lazy_fill) and len(raw_fill) > 0
+ for raw_value, lazy_value in zip(raw_fill, lazy_fill):
+ assert abs(raw_value - lazy_value) < 1e-9, f"ui_fill_fraction mismatch: raw={raw_fill}, lazy={lazy_fill}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_views_desc_orderby_lazy_matches_raw(self):
+ # Forwarding the user's orderBy through to ClickHouse: sorting by views
+ # must beat the silent visitors fallback the original PR relied on.
+ self._seed()
+ query = self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)
+ query.orderBy = [WebAnalyticsOrderByFields.VIEWS, WebAnalyticsOrderByDirection.DESC]
+
+ raw = self._metrics(self._run(query))
+ with self._enable_lazy():
+ lazy = self._metrics(self._run(query))
+
+ assert lazy == raw, f"views-desc parity broken: raw={raw}, lazy={lazy}"
+ views = [row[2][0] for row in lazy]
+ assert views == sorted(views, reverse=True), f"lazy not actually sorted by views desc: {views}"
+
+ @parameterized.expand(
+ [
+ ("bounce_rate", WebAnalyticsOrderByFields.BOUNCE_RATE),
+ ("conversion_rate", WebAnalyticsOrderByFields.CONVERSION_RATE),
+ ("average_scroll", WebAnalyticsOrderByFields.AVERAGE_SCROLL_PERCENTAGE),
+ ]
+ )
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_unsupported_orderby_falls_through(self, _name: str, field: WebAnalyticsOrderByFields):
+ # Fields the precompute schema can't serve must skip lazy entirely, not
+ # silently rewrite the sort to visitors.
+ self._seed()
+ query = self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)
+ query.orderBy = [field, WebAnalyticsOrderByDirection.DESC]
+ with self._enable_lazy():
+ response = self._run(query)
+
+ assert self._job_count() == 0
+ # Raw path leaves `usedLazyPrecompute` unset; the failure mode we're
+ # guarding against is the lazy path silently serving with a rewritten sort.
+ assert response.usedLazyPrecompute is not True
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_pagination_page_two_lazy_matches_raw(self):
+ # The PR's original code sorted + sliced in Python from an arbitrary
+ # `LIMIT 100` cut. With SQL pagination, page 2 must be a contiguous
+ # extension of page 1 — assert by comparing limit=1/offset=N pages.
+ self._seed()
+ base = self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)
+
+ responses_raw, responses_lazy = [], []
+ for offset in range(3):
+ query = self._build_query(breakdown_by=WebStatsBreakdown.BROWSER)
+ query.limit = 1
+ query.offset = offset
+ responses_raw.append(self._run(query))
+ with self._enable_lazy():
+ responses_lazy.append(self._run(query))
+
+ raw_full = self._metrics(self._run(base))
+ for offset, (raw_resp, lazy_resp) in enumerate(zip(responses_raw, responses_lazy)):
+ assert self._metrics(lazy_resp) == self._metrics(raw_resp), (
+ f"offset={offset}: lazy/raw mismatch raw={self._metrics(raw_resp)} lazy={self._metrics(lazy_resp)}"
+ )
+ assert lazy_resp.hasMore == raw_resp.hasMore
+ if offset < len(raw_full):
+ assert self._metrics(lazy_resp)[0] == raw_full[offset], "lazy page row must match unpaginated position"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_high_cardinality_utm_source_orders_in_sql(self):
+ # Veria's concern: with N>>page_size distinct UTM values, the read used
+ # to materialize all rows + paginate in Python. With SQL pagination the
+ # first page must come back ordered by the requested metric and the
+ # `hasMore` flag must accurately reflect the long tail.
+ _create_person(team_id=self.team.pk, distinct_ids=["bot"], properties={"name": "bot"})
+ for i in range(40):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="bot",
+ timestamp=f"2024-01-02T10:{i % 60:02d}:00Z",
+ properties=self._props(
+ **{
+ "$session_id": str(uuid7("2024-01-02")),
+ "$host": "example.com",
+ "$current_url": "https://example.com/x",
+ "$pathname": "/x",
+ # Skew so source_0 has the most visitors, then source_1, etc.
+ "utm_source": f"source_{i % 8}",
+ }
+ ),
+ )
+
+ query = self._build_query(
+ breakdown_by=WebStatsBreakdown.INITIAL_UTM_SOURCE,
+ date_from="2024-01-01",
+ date_to="2024-01-03",
+ )
+ query.limit = 3
+
+ with self._enable_lazy():
+ lazy_response = self._run(query)
+
+ lazy_metrics = self._metrics(lazy_response)
+ assert lazy_response.usedLazyPrecompute is True
+ assert lazy_response.hasMore is True, "should report more rows past the requested page"
+ assert len(lazy_metrics) == 3
+ # Visitors are monotonically non-increasing on the returned page.
+ visitors = [row[1][0] for row in lazy_metrics]
+ assert visitors == sorted(visitors, reverse=True), f"first page not ordered by visitors desc: {visitors}"
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.py
new file mode 100644
index 000000000000..aa5af7808e48
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
@@ -0,0 +1,337 @@
+"""Shared lazy-precompute building blocks for web analytics query runners.
+
+The web overview and web stats table runners both serve eligible queries from
+on-demand precomputed ClickHouse tables via the `lazy_computation` framework.
+The pieces that do not depend on which runner is calling — eligibility gating,
+filter-expression construction, TTL/sizing constants, UTC-day helpers — live
+here so both `web_overview_lazy_precompute.py` and `web_stats_lazy_precompute.py`
+share one implementation.
+"""
+
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+from typing import Optional, Protocol, Union
+
+import structlog
+import posthoganalytics
+from prometheus_client import Counter
+
+from posthog.schema import EventPropertyFilter, PropertyOperator, WebOverviewQuery, WebStatsTableQuery
+
+from posthog.hogql import ast
+from posthog.hogql.property import property_to_expr
+from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
+
+from posthog.models.team import Team
+
+logger = structlog.get_logger(__name__)
+
+
+# Counts requests refused by `can_use_lazy_precompute`. `family` is the
+# `log_prefix` (`web_overview` / `web_stats`); `reason` is the
+# `LazyPrecomputeIneligible` subclass name. Together with `_fallback_total`
+# and `_success_total`, callers can compute lazy adoption per family.
+WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED = Counter(
+ "web_analytics_lazy_precompute_rejected_total",
+ "Requests refused by the lazy precompute gate, by family and rejection reason.",
+ ["family", "reason"],
+)
+
+# Counts requests that passed the gate but couldn't be served from precompute
+# (window empty, no jobs created, current/previous period not yet READY). The
+# caller falls back to the raw / v2 path on each of these.
+WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK = Counter(
+ "web_analytics_lazy_precompute_fallback_total",
+ "Lazy precompute fall-throughs after the gate accepted, by family and reason.",
+ ["family", "reason"],
+)
+
+# Counts requests where the lazy path successfully returned a precomputed row.
+WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS = Counter(
+ "web_analytics_lazy_precompute_success_total",
+ "Requests served from the lazy precompute path, by family.",
+ ["family"],
+)
+
+# Bucketing the precompute hourly keeps reads correct for any whole-hour-offset
+# timezone — boundaries line up exactly when the team-local window is converted
+# to UTC before filtering on `time_window_start`. Half-hour-offset timezones
+# (IST, Newfoundland, Nepal, etc.) are explicitly gated out below.
+LAZY_TTL_SECONDS: dict[str, int] = {
+ "0d": 15 * 60,
+ "1d": 60 * 60,
+ "7d": 24 * 60 * 60,
+ "default": 7 * 24 * 60 * 60,
+}
+
+# Today the gate accepts: empty user filters, or a single EventPropertyFilter
+# on `$host` with operator `exact`. Test-account filters are always allowed
+# (their content is hashed into the cache key).
+SUPPORTED_USER_FILTER_KEYS: set[str] = {"$host"}
+
+# Upper bound on the precompute span. Above this, the framework would create
+# enough daily jobs that the first request burns INSERT slots for minutes.
+MAX_PRECOMPUTE_DAYS = 90
+
+# Forward pad on the per-job event-scan window. The lazy_computation framework
+# chunks the precompute span into daily UTC jobs; each job covers
+# `[time_window_min, time_window_max)`. A session starting at 23:50 with events
+# spilling past midnight would lose its trailing events without a forward pad —
+# the HAVING clause attributes the session to its start hour, but the events
+# table scan needs to see those trailing events to compute correct per-session
+# aggregates. Forward-only is sufficient: the HAVING keeps only sessions whose
+# `min(session.$start_timestamp)` falls inside the job window, and every event
+# of such a session has `timestamp >= session.$start_timestamp`, so backward
+# scanning never picks up anything that survives HAVING.
+#
+# Sessions longer than 24 h crossing a UTC-day boundary are silently
+# undercounted — a documented limitation, not a sizing target (24 h is the
+# posthog-js hard cap, covering effectively the whole population).
+SESSION_FORWARD_PAD_MINUTES = 24 * 60
+
+
+class LazyPrecomputeRunner(Protocol):
+ """Structural type for the attributes the shared helpers read off a runner.
+
+ Both `WebOverviewQueryRunner` and `WebStatsTableQueryRunner` satisfy this.
+ """
+
+ team: Team
+
+ @property
+ def query(self) -> Union[WebOverviewQuery, WebStatsTableQuery]: ...
+
+ @property
+ def query_date_range(self) -> object: ...
+
+ @property
+ def _test_account_filters(self) -> list: ...
+
+ @property
+ def events_session_property(self) -> ast.Expr: ...
+
+
+class LazyPrecomputeIneligible(Exception):
+ """Base class for reasons the lazy precompute path is not eligible.
+
+ Raised by the eligibility checks and caught by `can_use_lazy_precompute`,
+ which logs the exception class name. Subclass names are the canonical
+ identifiers used in logs/metrics — keep them stable across releases.
+ """
+
+
+class OrgFeatureFlagDisabled(LazyPrecomputeIneligible):
+ pass
+
+
+class PerQueryOptInNotSet(LazyPrecomputeIneligible):
+ pass
+
+
+class NonIntegerTimezone(LazyPrecomputeIneligible):
+ pass
+
+
+class ConversionGoalUnsupported(LazyPrecomputeIneligible):
+ pass
+
+
+class SamplingEnabled(LazyPrecomputeIneligible):
+ pass
+
+
+class SessionsV2UuidMode(LazyPrecomputeIneligible):
+ pass
+
+
+class TooManyFilters(LazyPrecomputeIneligible):
+ pass
+
+
+class NonEventPropertyFilter(LazyPrecomputeIneligible):
+ pass
+
+
+class UnsupportedFilterKey(LazyPrecomputeIneligible):
+ def __init__(self, key: str):
+ self.key = key
+ super().__init__(f"key={key!r}")
+
+
+class UnsupportedFilterOperator(LazyPrecomputeIneligible):
+ def __init__(self, operator: object):
+ self.operator = operator
+ super().__init__(f"operator={operator!r}")
+
+
+class NonStringOrEmptyFilterValue(LazyPrecomputeIneligible):
+ pass
+
+
+class MissingDateRange(LazyPrecomputeIneligible):
+ pass
+
+
+class DateRangeOverMax(LazyPrecomputeIneligible):
+ def __init__(self, days: int):
+ self.days = days
+ super().__init__(f"days={days} max={MAX_PRECOMPUTE_DAYS}")
+
+
+def can_use_lazy_precompute(
+ runner: LazyPrecomputeRunner,
+ *,
+ log_prefix: str,
+ extra_check: Optional[Callable[[LazyPrecomputeRunner], None]] = None,
+) -> bool:
+ """Return True iff the lazy precompute gate is eligible. Logs the rejection
+ reason at INFO level so every fall-through can be attributed.
+
+ `log_prefix` differentiates the log event name per runner (e.g.
+ `web_overview` / `web_stats`). `extra_check` lets a runner add its own
+ eligibility checks — it must raise a `LazyPrecomputeIneligible` subclass on
+ rejection, and runs after the shared checks pass.
+ """
+ try:
+ check_common_eligible(runner)
+ if extra_check is not None:
+ extra_check(runner)
+ except LazyPrecomputeIneligible as exc:
+ reason = type(exc).__name__
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED.labels(family=log_prefix, reason=reason).inc()
+ logger.info(
+ f"{log_prefix}_lazy_precompute_rejected",
+ team_id=runner.team.pk,
+ reason=reason,
+ detail=str(exc) or None,
+ )
+ return False
+ logger.info(
+ f"{log_prefix}_lazy_precompute_eligible",
+ team_id=runner.team.pk,
+ )
+ return True
+
+
+def check_common_eligible(runner: LazyPrecomputeRunner) -> None:
+ """Raise a `LazyPrecomputeIneligible` subclass if the query can't go through
+ the lazy path on grounds that apply to every web analytics runner. Returns
+ None on success."""
+ query = runner.query
+
+ # Rollout gate: shared PostHog feature flag AND per-query opt-in.
+ # - `web-analytics-precompute-toggle` (PostHog feature flag): the same
+ # flag the frontend already uses to show/hide the "Allow precompute"
+ # button in the Web Analytics ScenePanel. The flag is evaluated at the
+ # organization level. The SDK swallows its own exceptions and returns
+ # None (falsy) on failure, so a flag-service outage fails-closed.
+ # - `query.useWebAnalyticsPrecompute` (per-query parameter set by the
+ # "Allow precompute" toggle).
+ if not posthoganalytics.feature_enabled(
+ "web-analytics-precompute-toggle",
+ str(runner.team.uuid),
+ groups={
+ "organization": str(runner.team.organization_id),
+ "project": str(runner.team.id),
+ },
+ group_properties={
+ "organization": {"id": str(runner.team.organization_id)},
+ "project": {"id": str(runner.team.id)},
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ ):
+ raise OrgFeatureFlagDisabled()
+
+ if query.useWebAnalyticsPrecompute is not True:
+ raise PerQueryOptInNotSet()
+
+ # 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):
+ raise NonIntegerTimezone()
+
+ if query.conversionGoal is not None:
+ raise ConversionGoalUnsupported()
+
+ if query.sampling is not None and getattr(query.sampling, "enabled", False):
+ raise SamplingEnabled()
+
+ # UUID session-id mode produces `uniqState(UUID)` from
+ # `events.$session_id_uuid`, which fails to insert into the web overview
+ # table's `uniq_sessions_state AggregateFunction(uniq, String)` column. The
+ # web stats table has no session-uniq column (it stores `uniq, UUID` user
+ # state only), so this gate is conservative there — kept shared for
+ # simplicity until the web overview column is re-typed in a follow-up.
+ if query.modifiers and query.modifiers.sessionsV2JoinMode == "uuid":
+ raise SessionsV2UuidMode()
+
+ properties = query.properties or []
+ if len(properties) > 1:
+ raise TooManyFilters()
+ for prop in properties:
+ if not isinstance(prop, EventPropertyFilter):
+ raise NonEventPropertyFilter()
+ if prop.key not in SUPPORTED_USER_FILTER_KEYS:
+ raise UnsupportedFilterKey(prop.key)
+ if prop.operator != PropertyOperator.EXACT:
+ raise UnsupportedFilterOperator(prop.operator)
+ if not isinstance(prop.value, str) or not prop.value:
+ raise NonStringOrEmptyFilterValue()
+
+ 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:
+ raise MissingDateRange()
+
+ days = (date_to - date_from).days
+ if days > MAX_PRECOMPUTE_DAYS:
+ raise DateRangeOverMax(days)
+
+
+def user_filter_expr(runner: LazyPrecomputeRunner) -> ast.Expr:
+ """Build the AST expression that gets substituted into the INSERT's WHERE clause.
+
+ The substituted AST is what `ensure_precomputed` hashes into the cache key —
+ different filter values therefore become different precomputed jobs.
+ """
+ if not runner.query.properties:
+ return ast.Constant(value=True)
+
+ # Gate already enforces single EventPropertyFilter with $host exact + string value.
+ host_filter = runner.query.properties[0]
+ assert isinstance(host_filter, EventPropertyFilter)
+ return ast.Call(
+ name="equals",
+ args=[
+ ast.Field(chain=["events", "properties", host_filter.key]),
+ ast.Constant(value=host_filter.value),
+ ],
+ )
+
+
+def test_account_filter_expr(runner: LazyPrecomputeRunner) -> ast.Expr:
+ """Test-account filters land in the placeholder set, so they also shape the cache key.
+
+ `_test_account_filters` may be an empty list when filterTestAccounts is False
+ or the project has none configured.
+ """
+ if not runner._test_account_filters:
+ return ast.Constant(value=True)
+ return property_to_expr(runner._test_account_filters, team=runner.team)
+
+
+def events_session_id_expr(runner: LazyPrecomputeRunner) -> ast.Expr:
+ return runner.events_session_property
+
+
+def floor_utc_day(dt_utc: datetime) -> datetime:
+ return datetime(dt_utc.year, dt_utc.month, dt_utc.day, tzinfo=UTC)
+
+
+def ceil_utc_day(dt_utc: datetime) -> datetime:
+ floor = floor_utc_day(dt_utc)
+ if floor == dt_utc:
+ return floor
+ return floor + timedelta(days=1)
diff --git a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
index d50600ed457d..d73a5dd072bb 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
@@ -1,16 +1,11 @@
import time
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, datetime
from typing import TYPE_CHECKING, Optional
import structlog
-import posthoganalytics
from prometheus_client import Counter
-from posthog.schema import EventPropertyFilter, PropertyOperator
-
from posthog.hogql import ast
-from posthog.hogql.property import property_to_expr
-from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (
@@ -23,32 +18,27 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
LazyComputationTable,
ensure_precomputed,
)
+from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ LAZY_TTL_SECONDS,
+ SESSION_FORWARD_PAD_MINUTES,
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS,
+ can_use_lazy_precompute as _can_use_lazy_precompute_shared,
+ ceil_utc_day,
+ check_common_eligible,
+ events_session_id_expr,
+ floor_utc_day,
+ test_account_filter_expr,
+ user_filter_expr,
+)
+
+_FAMILY = "web_overview"
if TYPE_CHECKING:
from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
logger = structlog.get_logger(__name__)
-# Bucketing the precompute hourly keeps reads correct for any whole-hour-offset
-# timezone — boundaries line up exactly when the team-local window is converted
-# to UTC before filtering on `time_window_start`. Half-hour-offset timezones
-# (IST, Newfoundland, Nepal, etc.) are explicitly gated out below.
-LAZY_TTL_SECONDS: dict[str, int] = {
- "0d": 15 * 60,
- "1d": 60 * 60,
- "7d": 24 * 60 * 60,
- "default": 7 * 24 * 60 * 60,
-}
-
-# Today the gate accepts: empty user filters, or a single EventPropertyFilter
-# on `$host` with operator `exact`. Test-account filters are always allowed
-# (their content is hashed into the cache key).
-SUPPORTED_USER_FILTER_KEYS: set[str] = {"$host"}
-
-# Upper bound on the precompute span. Above this, the framework would create
-# enough daily jobs that the first request burns INSERT slots for minutes.
-MAX_PRECOMPUTE_DAYS = 90
-
WEB_OVERVIEW_LAZY_FAILED = Counter(
"web_overview_lazy_precompute_failed_total",
@@ -57,248 +47,27 @@ WEB_OVERVIEW_LAZY_FAILED = Counter(
)
-class LazyPrecomputeIneligible(Exception):
- """Base class for reasons the lazy precompute path is not eligible.
-
- Raised by `_check_lazy_precompute_eligible` and caught by
- `can_use_lazy_precompute`, which logs the exception class name. Subclass
- names are the canonical identifiers used in logs/metrics — keep them
- stable across releases.
- """
-
-
-class OrgFeatureFlagDisabled(LazyPrecomputeIneligible):
- pass
-
-
-class PerQueryOptInNotSet(LazyPrecomputeIneligible):
- pass
-
-
-class NonIntegerTimezone(LazyPrecomputeIneligible):
- pass
-
-
-class ConversionGoalUnsupported(LazyPrecomputeIneligible):
- pass
-
-
-class SamplingEnabled(LazyPrecomputeIneligible):
- pass
-
-
-class SessionsV2UuidMode(LazyPrecomputeIneligible):
- pass
-
-
-class TooManyFilters(LazyPrecomputeIneligible):
- pass
-
-
-class NonEventPropertyFilter(LazyPrecomputeIneligible):
- pass
-
-
-class UnsupportedFilterKey(LazyPrecomputeIneligible):
- def __init__(self, key: str):
- self.key = key
- super().__init__(f"key={key!r}")
-
-
-class UnsupportedFilterOperator(LazyPrecomputeIneligible):
- def __init__(self, operator: object):
- self.operator = operator
- super().__init__(f"operator={operator!r}")
-
-
-class NonStringOrEmptyFilterValue(LazyPrecomputeIneligible):
- pass
-
-
-class MissingDateRange(LazyPrecomputeIneligible):
- pass
-
-
-class DateRangeOverMax(LazyPrecomputeIneligible):
- def __init__(self, days: int):
- self.days = days
- super().__init__(f"days={days} max={MAX_PRECOMPUTE_DAYS}")
-
-
def can_use_lazy_precompute(runner: "WebOverviewQueryRunner") -> bool:
- """Return True iff the lazy precompute path is eligible. Logs rejection
- reason at INFO level so we can attribute every fall-through after deploy."""
- try:
- _check_lazy_precompute_eligible(runner)
- except LazyPrecomputeIneligible as exc:
- logger.info(
- "web_overview_lazy_precompute_rejected",
- team_id=runner.team.pk,
- reason=type(exc).__name__,
- detail=str(exc) or None,
- )
- return False
- logger.info(
- "web_overview_lazy_precompute_eligible",
- team_id=runner.team.pk,
- )
- return True
-
-
-def _check_lazy_precompute_eligible(runner: "WebOverviewQueryRunner") -> None:
- """Raise a `LazyPrecomputeIneligible` subclass if the query can't go through
- the lazy path. Returns None on success."""
- query = runner.query
-
- # Rollout gate: shared PostHog feature flag AND per-query opt-in.
- # - `web-analytics-precompute-toggle` (PostHog feature flag): the same
- # flag the frontend already uses to show/hide the "Allow precompute"
- # button in the Web Analytics ScenePanel. One switch controls both the
- # UI surface and the backend gate. The flag is evaluated at the
- # organization level — set up an org-level release condition on the
- # flag to enable rollout per org. The SDK swallows its own exceptions
- # and returns None (falsy) on failure, so a flag-service outage
- # fails-closed (gate raised, fall back to v2 / raw) automatically.
- # - `query.useWebAnalyticsPrecompute` (per-query parameter set by the
- # "Allow precompute" toggle).
- if not posthoganalytics.feature_enabled(
- "web-analytics-precompute-toggle",
- str(runner.team.uuid),
- groups={
- "organization": str(runner.team.organization_id),
- "project": str(runner.team.id),
- },
- group_properties={
- "organization": {"id": str(runner.team.organization_id)},
- "project": {"id": str(runner.team.id)},
- },
- only_evaluate_locally=True,
- send_feature_flag_events=False,
- ):
- raise OrgFeatureFlagDisabled()
-
- if query.useWebAnalyticsPrecompute is not True:
- raise PerQueryOptInNotSet()
-
- # 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):
- raise NonIntegerTimezone()
-
- if query.conversionGoal is not None:
- raise ConversionGoalUnsupported()
-
- if query.sampling is not None and getattr(query.sampling, "enabled", False):
- raise SamplingEnabled()
-
- # UUID session-id mode produces `uniqState(UUID)` from
- # `events.$session_id_uuid`, which fails to insert into the schema's
- # `AggregateFunction(uniq, String)` column. Gate out until the column
- # is re-typed in a follow-up.
- if query.modifiers and query.modifiers.sessionsV2JoinMode == "uuid":
- raise SessionsV2UuidMode()
-
- properties = query.properties or []
- if len(properties) > 1:
- raise TooManyFilters()
- for prop in properties:
- if not isinstance(prop, EventPropertyFilter):
- raise NonEventPropertyFilter()
- if prop.key not in SUPPORTED_USER_FILTER_KEYS:
- raise UnsupportedFilterKey(prop.key)
- if prop.operator != PropertyOperator.EXACT:
- raise UnsupportedFilterOperator(prop.operator)
- if not isinstance(prop.value, str) or not prop.value:
- raise NonStringOrEmptyFilterValue()
-
- date_from = runner.query_date_range.date_from()
- date_to = runner.query_date_range.date_to()
- if date_from is None or date_to is None:
- raise MissingDateRange()
-
- days = (date_to - date_from).days
- if days > MAX_PRECOMPUTE_DAYS:
- raise DateRangeOverMax(days)
-
-
-def _user_filter_expr(runner: "WebOverviewQueryRunner") -> ast.Expr:
- """Build the AST expression that gets substituted into the INSERT's WHERE clause.
-
- The substituted AST is what `ensure_precomputed` hashes into the cache key —
- different filter values therefore become different precomputed jobs.
- """
- if not runner.query.properties:
- return ast.Constant(value=True)
-
- # Gate already enforces single EventPropertyFilter with $host exact + string value.
- host_filter = runner.query.properties[0]
- assert isinstance(host_filter, EventPropertyFilter)
- return ast.Call(
- name="equals",
- args=[
- ast.Field(chain=["events", "properties", host_filter.key]),
- ast.Constant(value=host_filter.value),
- ],
- )
+ """Return True iff the lazy precompute path is eligible for this web
+ overview query. Web overview has no checks beyond the shared gate."""
+ return _can_use_lazy_precompute_shared(runner, log_prefix="web_overview")
-def _test_account_filter_expr(runner: "WebOverviewQueryRunner") -> ast.Expr:
- """Test-account filters land in the placeholder set, so they also shape the cache key.
-
- `_test_account_filters` may be an empty list when filterTestAccounts is False
- or the project has none configured.
- """
- if not runner._test_account_filters:
- return ast.Constant(value=True)
- return property_to_expr(runner._test_account_filters, team=runner.team)
-
-
-def _events_session_id_expr(runner: "WebOverviewQueryRunner") -> ast.Expr:
- return runner.events_session_property
-
-
-# Forward pad on the per-job event-scan window. The lazy_computation framework
-# chunks the precompute span into daily UTC jobs; each job covers
-# `[time_window_min, time_window_max)`. A session starting at 23:50 with events
-# spilling past midnight would lose its trailing events without a forward pad —
-# the HAVING clause attributes the session to its start hour, but the events
-# table scan needs to see those trailing events to compute correct
-# `$session_duration` / `$pageview_count` / `$is_bounce`.
-#
-# Forward-only is sufficient. The HAVING clause keeps only sessions whose
-# `min(session.$start_timestamp)` falls inside `[time_window_min, time_window_max)`.
-# Every event of such a session has `timestamp >= session.$start_timestamp >=
-# time_window_min`, so backward scanning never picks up anything that survives
-# HAVING — it only burns I/O on sessions that get discarded.
-#
-# Session length isn't bounded server-side: `$session_id` is generated by the
-# client SDK (default 30 min inactivity, 24 h hard cap in posthog-js), and the
-# threshold is per-site-configurable. Measured prod distribution (raw_sessions,
-# 1 h slice, 8.3M sessions): p99 = 79 min, p99.9 = 111 min. For team_id=2
-# (posthog.com, docs left open for days) over 7 days: p95 = 75 min,
-# p99 = 19 h, 0.6% of sessions > 24 h. The 24 h hard cap is the meaningful
-# ceiling for ~99.4% of dogfood sessions and effectively 100% of the wider
-# population; anything past it is rare enough to be a documented limitation
-# rather than a sizing target.
-#
-# Trade-off: +24 h forward costs ~2× the events scanned per daily job vs +60 min,
-# but 60 min undercounts 1.45% of sessions site-wide and 4.17% on posthog.com.
-# Correctness wins over INSERT cost at this scale.
-#
-# Sessions longer than `SESSION_FORWARD_PAD_MINUTES` are silently undercounted
-# on cross-boundary days. The long-term fix is to drive the INSERT from
-# `raw_sessions` (bounded by `session_id_v7`'s embedded UUIDv7 timestamp) and
-# source `$session_duration` / `$is_bounce` / `$pageview_count` from the
-# sessions table — same approach as the v2 preagg DAG. That removes the pad
-# entirely.
-SESSION_FORWARD_PAD_MINUTES = 24 * 60
+# Re-exported so callers (and tests) can still reach the eligibility checker
+# through this module.
+_check_lazy_precompute_eligible = check_common_eligible
# 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_overview_preaggregated`. The framework
# automatically prepends `team_id`, `job_id` and appends `expires_at` to the SELECT.
+#
+# The forward pad on the event-scan window (`SESSION_FORWARD_PAD_MINUTES`) lets a
+# session that starts near the trailing edge of a daily UTC job still aggregate
+# its events that spill past midnight — the HAVING clause attributes the session
+# to its start hour, but the events scan needs the trailing events to compute
+# correct `$session_duration` / `$pageview_count` / `$is_bounce`.
INSERT_QUERY_TEMPLATE = """
SELECT
toStartOfHour(start_timestamp) AS time_window_start,
@@ -340,10 +109,10 @@ def ensure_web_overview_precomputed(
time_range_end: datetime,
) -> LazyComputationResult:
placeholders: dict[str, ast.Expr] = {
- "events_session_id": _events_session_id_expr(runner),
+ "events_session_id": events_session_id_expr(runner),
"event_type_filter": runner.event_type_expr,
- "user_filter": _user_filter_expr(runner),
- "test_account_filter": _test_account_filter_expr(runner),
+ "user_filter": user_filter_expr(runner),
+ "test_account_filter": test_account_filter_expr(runner),
"pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
}
@@ -427,17 +196,6 @@ def execute_read_query(
)
-def _floor_utc_day(dt_utc: datetime) -> datetime:
- return datetime(dt_utc.year, dt_utc.month, dt_utc.day, tzinfo=UTC)
-
-
-def _ceil_utc_day(dt_utc: datetime) -> datetime:
- floor = _floor_utc_day(dt_utc)
- if floor == dt_utc:
- return floor
- return floor + timedelta(days=1)
-
-
def _empty_response_row() -> list:
# 5 metric pairs (current, previous) — previous slots are None and discarded
# downstream when compareFilter.compare is False. When compare is True, the
@@ -473,10 +231,11 @@ def execute_lazy_precomputed_read(
# daily-window jobs fully cover the team-tz request. Without this, the
# 08:00 UTC start of "today PT" would fall outside the framework's UTC
# day window and have no precomputed buckets to read.
- time_range_start = _floor_utc_day(current_start_utc)
- time_range_end = _ceil_utc_day(current_end_utc)
+ 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_overview_lazy_precompute_empty_range",
team_id=team_id,
@@ -509,9 +268,11 @@ def execute_lazy_precomputed_read(
)
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()
logger.info(
"web_overview_lazy_precompute_current_not_ready",
team_id=team_id,
@@ -534,8 +295,8 @@ def execute_lazy_precomputed_read(
# query's `WHERE job_id IN %(job_ids)s` filter has no rows
# covering the previous window and every `*MergeIf(..., prev_*)`
# returns 0/NaN, silently breaking compare-period metrics.
- prev_range_start = _floor_utc_day(previous_start_utc)
- prev_range_end = _ceil_utc_day(previous_end_utc)
+ prev_range_start = floor_utc_day(previous_start_utc)
+ prev_range_end = ceil_utc_day(previous_end_utc)
if prev_range_start < prev_range_end:
prev_ensure_started = time.perf_counter()
prev_result = ensure_web_overview_precomputed(
@@ -546,6 +307,7 @@ def execute_lazy_precomputed_read(
ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)
if not prev_result.ready:
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="previous_not_ready").inc()
logger.info(
"web_overview_lazy_precompute_previous_not_ready",
team_id=team_id,
@@ -567,6 +329,7 @@ def execute_lazy_precomputed_read(
read_duration_ms = int((time.perf_counter() - read_started) * 1000)
total_duration_ms = int((time.perf_counter() - overall_started) * 1000)
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=_FAMILY).inc()
logger.info(
"web_overview_lazy_precompute_completed",
team_id=team_id,
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
new file mode 100644
index 000000000000..fd2f0a682257
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
@@ -0,0 +1,609 @@
+import json
+import time
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING, Literal, Optional
+
+import structlog
+from prometheus_client import Counter
+
+from posthog.schema import (
+ HogQLQueryModifiers,
+ WebAnalyticsOrderByDirection,
+ WebAnalyticsOrderByFields,
+ WebStatsBreakdown,
+ WebStatsTableQuery,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_expr, parse_select
+
+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,
+ SESSION_FORWARD_PAD_MINUTES,
+ 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,
+ events_session_id_expr,
+ floor_utc_day,
+ test_account_filter_expr,
+ user_filter_expr,
+)
+
+_FAMILY = "web_stats"
+
+if TYPE_CHECKING:
+ from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+
+logger = structlog.get_logger(__name__)
+
+
+WEB_STATS_LAZY_FAILED = Counter(
+ "web_stats_lazy_precompute_failed_total",
+ "Web stats lazy precompute path failures, by error class",
+ ["error_type"],
+)
+
+# Breakdowns served by `SimpleBreakdownStrategy` / `ChannelTypeStrategy` that we
+# expect to behave well under precompute. UTM/browser/OS/region/city values are
+# user-controlled at ingestion so cardinality is not strictly bounded, but in
+# practice they sit several orders of magnitude below the per-URL breakdowns we
+# deliberately route to the raw path (page/path/referring-URL, FRUSTRATION_METRICS,
+# LANGUAGE). The failure mode for a pathological team is a slow precompute INSERT,
+# not an incorrect result — sort, pagination and HAVING all run in SQL so the
+# read returns exactly the page the user asked for regardless of total distinct
+# values. If a team's INSERT becomes a hotspot we can carve them out via the
+# rollout gate; we are not adding a defensive SQL-side cardinality cap because
+# it would silently truncate results vs. the raw path.
+#
+# Tuple/float breakdowns (REGION, CITY, VIEWPORT, TIMEZONE) are supported: the
+# breakdown value is JSON-encoded into the `breakdown_value` String column and
+# decoded back to its native shape on read.
+SUPPORTED_BREAKDOWNS: set[WebStatsBreakdown] = {
+ WebStatsBreakdown.INITIAL_CHANNEL_TYPE,
+ WebStatsBreakdown.INITIAL_REFERRING_DOMAIN,
+ WebStatsBreakdown.INITIAL_UTM_SOURCE,
+ WebStatsBreakdown.INITIAL_UTM_CAMPAIGN,
+ WebStatsBreakdown.INITIAL_UTM_MEDIUM,
+ WebStatsBreakdown.INITIAL_UTM_TERM,
+ WebStatsBreakdown.INITIAL_UTM_CONTENT,
+ WebStatsBreakdown.INITIAL_UTM_SOURCE_MEDIUM_CAMPAIGN,
+ WebStatsBreakdown.BROWSER,
+ WebStatsBreakdown.OS,
+ WebStatsBreakdown.VIEWPORT,
+ WebStatsBreakdown.DEVICE_TYPE,
+ WebStatsBreakdown.COUNTRY,
+ WebStatsBreakdown.REGION,
+ WebStatsBreakdown.CITY,
+ WebStatsBreakdown.TIMEZONE,
+}
+
+# Breakdowns whose value is a tuple — JSON-decoded as a list and converted back
+# to a tuple so the response matches the raw query exactly.
+TUPLE_BREAKDOWNS: set[WebStatsBreakdown] = {
+ WebStatsBreakdown.REGION,
+ WebStatsBreakdown.CITY,
+ WebStatsBreakdown.VIEWPORT,
+}
+
+
+class BounceRateUnsupported(LazyPrecomputeIneligible):
+ pass
+
+
+class AvgTimeOnPageUnsupported(LazyPrecomputeIneligible):
+ pass
+
+
+class ScrollDepthUnsupported(LazyPrecomputeIneligible):
+ pass
+
+
+class UnsupportedBreakdown(LazyPrecomputeIneligible):
+ def __init__(self, breakdown: object):
+ self.breakdown = breakdown
+ super().__init__(f"breakdown={breakdown!r}")
+
+
+class UnsupportedOrderBy(LazyPrecomputeIneligible):
+ def __init__(self, field: object):
+ self.field = field
+ super().__init__(f"field={field!r}")
+
+
+# orderBy fields the lazy read can serve directly. Anything outside this set
+# (bounce rate, scroll depth, conversion-rate, …) must fall through to the raw
+# path — the precompute table doesn't store those columns.
+SUPPORTED_ORDER_BY_FIELDS: set[WebAnalyticsOrderByFields] = {
+ WebAnalyticsOrderByFields.VISITORS,
+ WebAnalyticsOrderByFields.VIEWS,
+}
+
+
+def _check_stats_eligible(runner: LazyPrecomputeRunner) -> None:
+ """Raise a `LazyPrecomputeIneligible` subclass for stats-table-specific
+ reasons the lazy path can't serve the query.
+
+ Typed to the shared `LazyPrecomputeRunner` protocol so it satisfies
+ `can_use_lazy_precompute`'s `extra_check` parameter (Callable argument
+ types are contravariant). The isinstance narrows `query` from the
+ `Union[WebOverviewQuery, WebStatsTableQuery]` shape to the stats-table
+ fields we actually need."""
+ query = runner.query
+ assert isinstance(query, WebStatsTableQuery), "_check_stats_eligible called on non-stats runner"
+
+ # Bounce rate / avg time / scroll depth are extra metrics the precompute
+ # table does not store. `includeScrollDepth` implicitly turns on bounce rate.
+ if query.includeBounceRate:
+ raise BounceRateUnsupported()
+ if query.includeAvgTimeOnPage:
+ raise AvgTimeOnPageUnsupported()
+ if query.includeScrollDepth:
+ raise ScrollDepthUnsupported()
+
+ if query.breakdownBy not in SUPPORTED_BREAKDOWNS:
+ raise UnsupportedBreakdown(query.breakdownBy)
+
+ # Reject orderBy fields we can't compute from the precompute schema. Falling
+ # back to visitors would silently change row ordering vs. the raw path; let
+ # the raw query handle these instead.
+ if query.orderBy:
+ field = query.orderBy[0]
+ if field not in SUPPORTED_ORDER_BY_FIELDS:
+ raise UnsupportedOrderBy(field)
+
+
+def can_use_lazy_precompute(runner: "WebStatsTableQueryRunner") -> bool:
+ """Return True iff the lazy precompute path is eligible for this web stats
+ table query — the shared web analytics gate plus stats-specific checks."""
+ return _can_use_lazy_precompute_shared(runner, log_prefix="web_stats", extra_check=_check_stats_eligible)
+
+
+# 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_stats_preaggregated`. The framework
+# automatically prepends `team_id`, `job_id` and appends `expires_at` to the SELECT.
+#
+# Mirrors the web overview precompute: events are grouped into sessions, each
+# session is attributed to the hour of `min(session.$start_timestamp)`, and the
+# `HAVING` keeps only sessions whose start hour falls in the job window. This
+# matches the raw stats query's compare path, which attributes a session's
+# metrics by session start. The forward pad (`SESSION_FORWARD_PAD_MINUTES`) lets
+# a session starting near the trailing edge of a daily job still see the events
+# that spill past midnight, so its pageview count is complete.
+INSERT_QUERY_TEMPLATE = """
+SELECT
+ toStartOfHour(start_timestamp) AS time_window_start,
+ {breakdown_by} AS breakdown_by,
+ breakdown_value AS breakdown_value,
+ uniqState(session_person_id) AS uniq_users_state,
+ sumState(assumeNotNull(toInt(filtered_pageview_count))) AS sum_pageviews_state
+FROM (
+ SELECT
+ any(events.person_id) AS session_person_id,
+ {events_session_id} AS session_id,
+ {breakdown_value} AS breakdown_value,
+ min(session.$start_timestamp) AS start_timestamp,
+ countIf(or(equals(event, '$pageview'), equals(event, '$screen'))) AS filtered_pageview_count
+ FROM events
+ WHERE and(
+ {events_session_id} IS NOT NULL,
+ {event_type_filter},
+ timestamp >= {time_window_min},
+ timestamp < ({time_window_max} + toIntervalMinute({pad_minutes})),
+ {user_filter},
+ {test_account_filter}
+ )
+ GROUP BY session_id, breakdown_value
+ HAVING and(
+ toStartOfHour(min(session.$start_timestamp)) >= {time_window_min},
+ toStartOfHour(min(session.$start_timestamp)) < {time_window_max}
+ )
+)
+GROUP BY time_window_start, breakdown_by, breakdown_value
+"""
+
+
+def _breakdown_value_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr:
+ """JSON-encode the breakdown value so tuple/float/null breakdowns round-trip
+ through the `breakdown_value String` column. The wrapped expression is what
+ `ensure_precomputed` hashes into the cache key, so different breakdowns
+ (including path-cleaning / host-prepend variants) get distinct jobs.
+
+ `toJSONString` of a NULL scalar returns NULL, which the non-nullable column
+ would coerce to an unparseable empty string — `coalesce(..., 'null')` keeps
+ a genuine NULL breakdown as the JSON literal `null` instead."""
+ return ast.Call(
+ name="coalesce",
+ args=[
+ ast.Call(name="toJSONString", args=[runner._counts_breakdown_value()]),
+ ast.Constant(value="null"),
+ ],
+ )
+
+
+def ensure_web_stats_precomputed(
+ runner: "WebStatsTableQueryRunner",
+ time_range_start: datetime,
+ time_range_end: datetime,
+) -> LazyComputationResult:
+ placeholders: dict[str, ast.Expr] = {
+ "breakdown_by": ast.Constant(value=runner.query.breakdownBy.value),
+ "breakdown_value": _breakdown_value_expr(runner),
+ "events_session_id": events_session_id_expr(runner),
+ "event_type_filter": runner.event_type_expr,
+ "user_filter": user_filter_expr(runner),
+ "test_account_filter": test_account_filter_expr(runner),
+ "pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
+ }
+
+ 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_STATS_PREAGGREGATED,
+ placeholders=placeholders,
+ query_type=f"web_stats_{runner.query.breakdownBy.value}_lazy_insert",
+ )
+
+
+# HogQL read template — substituted via `parse_select(..., placeholders=...)` so
+# arguments flow through the printer with proper escaping rather than driver-side
+# string formatting. Read-your-writes load balancing and shard pruning are
+# attached automatically via `WebStatsPreaggregatedTable.top_level_settings`.
+#
+# `convertToProjectTimezone=False` is forced on the modifiers in
+# `execute_read_query` so `time_window_start` (stored UTC) is compared directly
+# against the UTC bounds in `{cur_start}` / `{cur_end}` without the printer
+# wrapping them in `toTimeZone(..., team_tz)`.
+#
+# `sum({sort_metric}) OVER ()` runs after `GROUP BY` + `HAVING` and before the
+# `ORDER BY` + LIMIT/OFFSET injected via AST mutation in `execute_read_query`,
+# so the same denominator the raw query computes with `sum(...) OVER ()` makes
+# it onto every paginated row.
+_READ_SQL_TEMPLATE = """
+SELECT
+ breakdown_value,
+ uniqMergeIf(uniq_users_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS visitors,
+ uniqMergeIf(uniq_users_state, and(time_window_start >= {prev_start}, time_window_start < {prev_end})) AS previous_visitors,
+ sumMergeIf(sum_pageviews_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS views,
+ sumMergeIf(sum_pageviews_state, and(time_window_start >= {prev_start}, time_window_start < {prev_end})) AS previous_views,
+ sum({sort_metric}) OVER () AS fill_total
+FROM posthog.web_stats_preaggregated
+WHERE and(team_id = {team_id}, job_id IN {job_ids}, breakdown_by = {breakdown_by})
+GROUP BY breakdown_value
+"""
+
+
+@dataclass
+class LazyStatsRow:
+ """One breakdown value with its decoded value and current/previous metrics.
+
+ `breakdown_value` is decoded back to its native shape (str, tuple, float or
+ None). `*_previous` are read from the precompute table unconditionally; the
+ response builder discards them when the query has no compare period.
+
+ `fill_total` is the SQL-side `sum({sort_metric}) OVER ()` denominator for
+ `ui_fill_fraction`; identical across every row in a single page.
+ """
+
+ breakdown_value: object
+ visitors_current: int
+ visitors_previous: int
+ views_current: int
+ views_previous: int
+ fill_total: int
+
+
+@dataclass
+class LazyStatsResult:
+ rows: list[LazyStatsRow]
+ has_more: bool
+ sort_metric: str
+
+
+def _resolve_sort_metric(query: WebStatsTableQuery) -> tuple[str, bool]:
+ """Pick the SQL column to ORDER BY plus direction. Mirrors what the raw path
+ would do; eligibility guarantees the field is `VISITORS` or `VIEWS`."""
+ sort_metric = "visitors"
+ descending = True
+ if query.orderBy:
+ field = query.orderBy[0]
+ direction = query.orderBy[1]
+ if field == WebAnalyticsOrderByFields.VIEWS:
+ sort_metric = "views"
+ descending = direction != WebAnalyticsOrderByDirection.ASC
+ return sort_metric, descending
+
+
+def _breakdown_having_expr(breakdown_by: WebStatsBreakdown) -> ast.Expr:
+ """HAVING-clause equivalent of the raw query's `outer_where_breakdown()` —
+ operates on the JSON-encoded `breakdown_value` column produced by the INSERT.
+
+ Index 2 / index 1 here are 1-based JSON array positions (`JSONExtractRaw`
+ follows ClickHouse's 1-based indexing). For VIEWPORT specifically, the raw
+ query rejects rows whose width/height are null or zero.
+
+ REGION/CITY *look* like they should drop `(country, null)` rows, but the
+ raw query's `tupleElement(..., 2) IS NOT NULL` runs on a non-nullable
+ `Tuple(String, String, String)` and never matches in practice — so the
+ lazy path keeps null subdivisions too, matching what ships from raw.
+ """
+ if breakdown_by == WebStatsBreakdown.VIEWPORT:
+ return parse_expr(
+ "JSONExtractRaw(breakdown_value, 1) NOT IN ('null', '0') "
+ "AND JSONExtractRaw(breakdown_value, 2) NOT IN ('null', '0')"
+ )
+ if breakdown_by in {
+ WebStatsBreakdown.INITIAL_UTM_SOURCE,
+ WebStatsBreakdown.INITIAL_UTM_CAMPAIGN,
+ WebStatsBreakdown.INITIAL_UTM_MEDIUM,
+ WebStatsBreakdown.INITIAL_UTM_TERM,
+ WebStatsBreakdown.INITIAL_UTM_CONTENT,
+ }:
+ # The raw query intentionally keeps null UTM values.
+ return ast.Constant(value=True)
+ if breakdown_by == WebStatsBreakdown.INITIAL_CHANNEL_TYPE:
+ # JSON scalars: 'null' is genuine null, '""' is empty string.
+ return parse_expr("breakdown_value NOT IN ('null', '\"\"')")
+ # Default: reject only genuine null.
+ return parse_expr("breakdown_value != 'null'")
+
+
+def _decode_breakdown_value(breakdown_by: WebStatsBreakdown, raw: str) -> object:
+ """Reverse the INSERT's `toJSONString` wrapping. Tuple breakdowns come back
+ as lists and are converted to tuples; timezone comes back as a number and is
+ coerced to float to match the raw query's `toFloat` output."""
+ if not raw:
+ # A non-nullable String column can surface a genuine NULL breakdown as
+ # an empty string; treat it as the null breakdown value.
+ return None
+ value = json.loads(raw)
+ if breakdown_by in TUPLE_BREAKDOWNS and isinstance(value, list):
+ return tuple(value)
+ if breakdown_by == WebStatsBreakdown.TIMEZONE and value is not None:
+ return float(value)
+ return value
+
+
+def execute_read_query(
+ *,
+ runner: "WebStatsTableQueryRunner",
+ job_ids: list[str],
+ current_start_utc: datetime,
+ current_end_utc: datetime,
+ previous_start_utc: Optional[datetime],
+ previous_end_utc: Optional[datetime],
+) -> tuple[list[LazyStatsRow], bool, str]:
+ """Read the precomputed rows via HogQL with SQL-side filtering, ordering and
+ pagination. Returns `(rows, has_more, sort_metric)`.
+
+ `parse_select` + placeholders build the column expressions; HAVING/ORDER BY
+ are attached via direct AST mutation so the user's `orderBy` flows into the
+ SQL (rather than a Python re-sort of an arbitrary slice). LIMIT/OFFSET come
+ from `runner.paginator` using the +1 trick to derive `has_more` accurately.
+ """
+ # Sentinel for the no-compare case: an unsatisfiable window so the *MergeIf
+ # aggregates return 0 for the "previous" columns without changing shape.
+ prev_start = previous_start_utc if previous_start_utc is not None else datetime(1970, 1, 1, tzinfo=UTC)
+ prev_end = previous_end_utc if previous_end_utc is not None else datetime(1970, 1, 1, tzinfo=UTC)
+
+ sort_metric, descending = _resolve_sort_metric(runner.query)
+
+ 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]),
+ "breakdown_by": ast.Constant(value=runner.query.breakdownBy.value),
+ "cur_start": ast.Constant(value=current_start_utc),
+ "cur_end": ast.Constant(value=current_end_utc),
+ "prev_start": ast.Constant(value=prev_start),
+ "prev_end": ast.Constant(value=prev_end),
+ "sort_metric": ast.Field(chain=[sort_metric]),
+ }
+
+ parsed = parse_select(_READ_SQL_TEMPLATE, placeholders=placeholders)
+ assert isinstance(parsed, ast.SelectQuery)
+
+ # Filter equivalent to the raw query's `outer_where_breakdown()`. Pushing
+ # this to HAVING means ORDER BY + LIMIT downstream see the same row set the
+ # raw path's pagination operates on.
+ parsed.having = _breakdown_having_expr(runner.query.breakdownBy)
+
+ direction: Literal["ASC", "DESC"] = "DESC" if descending else "ASC"
+ secondary = "views" if sort_metric == "visitors" else "visitors"
+ parsed.order_by = [
+ ast.OrderExpr(expr=ast.Field(chain=[sort_metric]), order=direction),
+ ast.OrderExpr(expr=ast.Field(chain=[secondary]), order=direction),
+ # Stable tiebreaker so consecutive pages don't overlap on equal-metric ties.
+ ast.OrderExpr(expr=ast.Field(chain=["breakdown_value"]), order="ASC"),
+ ]
+
+ # The precomputed `time_window_start` column is UTC; `convertToProjectTimezone`
+ # would wrap it in `toTimeZone(..., team_tz)` and break the direct comparison
+ # against our UTC `cur_start` / `cur_end` constants.
+ 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_stats_lazy_query")
+ runner.paginator.execute_hogql_query(
+ parsed,
+ query_type="web_stats_lazy_query",
+ team=runner.team,
+ timings=runner.timings,
+ modifiers=modifiers,
+ )
+
+ rows = [
+ LazyStatsRow(
+ breakdown_value=_decode_breakdown_value(runner.query.breakdownBy, row[0]),
+ visitors_current=row[1],
+ visitors_previous=row[2],
+ views_current=row[3],
+ views_previous=row[4],
+ fill_total=row[5],
+ )
+ for row in runner.paginator.results
+ ]
+ return rows, runner.paginator.has_more(), sort_metric
+
+
+def execute_lazy_precomputed_read(
+ runner: "WebStatsTableQueryRunner",
+) -> Optional[LazyStatsResult]:
+ """Orchestrate the lazy precompute + read. Returns the decoded rows, 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_stats_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.
+ 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_stats_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_stats_lazy_precompute_started",
+ team_id=team_id,
+ breakdown_by=runner.query.breakdownBy.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_stats_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_stats_lazy_precompute_no_job_ids",
+ team_id=team_id,
+ breakdown_by=runner.query.breakdownBy.value,
+ )
+ return None
+
+ if not result.ready:
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="current_not_ready").inc()
+ logger.info(
+ "web_stats_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]
+
+ previous_start_utc: Optional[datetime] = None
+ previous_end_utc: Optional[datetime] = None
+ if runner.query_compare_to_date_range is not None:
+ prev_from = runner.query_compare_to_date_range.date_from()
+ prev_to = runner.query_compare_to_date_range.date_to()
+ if prev_from is not None and prev_to is not None:
+ previous_start_utc = prev_from.astimezone(UTC)
+ previous_end_utc = prev_to.astimezone(UTC)
+
+ # Precompute the previous period too — without this the read's
+ # `job_id IN` filter has no rows covering the previous window and
+ # every `*MergeIf(..., prev_*)` returns 0.
+ prev_range_start = floor_utc_day(previous_start_utc)
+ prev_range_end = ceil_utc_day(previous_end_utc)
+
+ # Cap the previous period's UTC range at the start of the current
+ # period's so a non-UTC-timezone boundary day does not produce a
+ # job_id shared by both ensure calls (see web overview for the
+ # full rationale).
+ prev_range_end = min(prev_range_end, time_range_start)
+
+ if prev_range_start < prev_range_end:
+ prev_result = ensure_web_stats_precomputed(
+ runner=runner,
+ time_range_start=prev_range_start,
+ time_range_end=prev_range_end,
+ )
+
+ if not prev_result.ready:
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="previous_not_ready").inc()
+ logger.info(
+ "web_stats_lazy_precompute_previous_not_ready",
+ team_id=team_id,
+ prev_job_count=len(prev_result.job_ids),
+ )
+ return None
+
+ job_ids.extend(str(jid) for jid in prev_result.job_ids)
+ else:
+ # Cap collapsed the previous-period window to nothing (e.g. a
+ # non-UTC boundary day shared the same job_id as the current
+ # period). Clear the previous bounds so the read does not
+ # filter for a window with no backing job_ids — otherwise
+ # every `*MergeIf(..., prev_*)` would silently return 0.
+ previous_start_utc = None
+ previous_end_utc = None
+
+ rows, has_more, sort_metric = execute_read_query(
+ runner=runner,
+ job_ids=job_ids,
+ current_start_utc=current_start_utc,
+ current_end_utc=current_end_utc,
+ previous_start_utc=previous_start_utc,
+ previous_end_utc=previous_end_utc,
+ )
+
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=_FAMILY).inc()
+ logger.info(
+ "web_stats_lazy_precompute_completed",
+ team_id=team_id,
+ breakdown_by=runner.query.breakdownBy.value,
+ job_count=len(result.job_ids),
+ rows_returned=len(rows),
+ has_more=has_more,
+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),
+ )
+ return LazyStatsResult(rows=rows, has_more=has_more, sort_metric=sort_metric)
+ except Exception as exc:
+ WEB_STATS_LAZY_FAILED.labels(error_type=type(exc).__name__).inc()
+ logger.exception(
+ "web_stats_lazy_precompute_failed",
+ team_id=team_id,
+ error_type=type(exc).__name__,
+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),
+ )
+ return None
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 55c214b071d5..5e0c95c4376f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2911,6 +2911,7 @@ export namespace Schemas {
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
types?: unknown[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}
@@ -2950,6 +2951,8 @@ export namespace Schemas {
samplingFactor?: number | null;
tags?: QueryLogTags | null;
useSessionsTable?: boolean | null;
+ /** Opt this specific query into the web stats table 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;
}
@@ -9252,6 +9255,7 @@ export namespace Schemas {
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
types?: unknown[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}
@@ -33545,6 +33549,7 @@ export namespace Schemas {
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
types?: unknown[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}
@@ -33920,6 +33925,7 @@ export namespace Schemas {
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
types?: unknown[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}