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_overview_query (#59075)

Lucas Ricoy1562565f5557
diff --git a/frontend/src/lib/components/PreAggregatedBadge/PreAggregatedBadge.tsx b/frontend/src/lib/components/PreAggregatedBadge/PreAggregatedBadge.tsx
index 8d9e3771f358..c4e503a91d8e 100644
--- a/frontend/src/lib/components/PreAggregatedBadge/PreAggregatedBadge.tsx
+++ b/frontend/src/lib/components/PreAggregatedBadge/PreAggregatedBadge.tsx
@@ -1,12 +1,35 @@
-import { IconBolt } from '@posthog/icons'
+import { IconBolt, IconSparkles } from '@posthog/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-export function PreAggregatedBadge(): JSX.Element {
+export type PreAggregatedBadgeVariant = 'preagg' | 'precomputed'
+
+interface PreAggregatedBadgeProps {
+ variant?: PreAggregatedBadgeVariant
+}
+
+const VARIANT_CONFIG: Record<
+ PreAggregatedBadgeVariant,
+ { tooltip: string; iconClassName: string; Icon: typeof IconBolt }
+> = {
+ preagg: {
+ tooltip: 'Optimized with new query engine',
+ iconClassName: 'text-warning w-4 h-4',
+ Icon: IconBolt,
+ },
+ precomputed: {
+ tooltip: 'Served from precomputed cache',
+ iconClassName: 'text-success w-4 h-4',
+ Icon: IconSparkles,
+ },
+}
+
+export function PreAggregatedBadge({ variant = 'preagg' }: PreAggregatedBadgeProps = {}): JSX.Element {
+ const { tooltip, iconClassName, Icon } = VARIANT_CONFIG[variant]
return (
- <Tooltip title="Optimized with new query engine">
+ <Tooltip title={tooltip}>
<div className="absolute top-2 right-2 z-10">
- <IconBolt className="text-warning w-4 h-4" />
+ <Icon className={iconClassName} />
</div>
</Tooltip>
)
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b8614f6db807..4e04bf44fdd2 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -505,6 +505,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_LIVE_REFERRERS: 'web-analytics-live-referrers', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_MARKETING: 'marketing-analytics', // owner: @jabahamondes #team-web-analytics
WEB_ANALYTICS_OPEN_URL: 'web-analytics-open-url', // owner: @lricoy #team-web-analytics
+ WEB_ANALYTICS_PRECOMPUTE_TOGGLE: 'web-analytics-precompute-toggle', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_REGIONS_MAP: 'web-analytics-regions-map', // owner: @jordanm-posthog #team-web-analytics
WEB_ANALYTICS_SESSION_PROPERTY_CHARTS: 'web-analytics-session-property-charts', // owner: @lricoy #team-web-analytics
WEB_ANALYTICS_TILE_SKELETONS: 'web-analytics-tile-skeletons', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
index 8f9412af59da..b7f094789777 100644
--- a/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewGrid.tsx
@@ -46,6 +46,7 @@ interface OverviewGridProps {
numSkeletons: number
samplingRate?: SamplingRate
usedPreAggregatedTables?: boolean
+ usedLazyPrecompute?: boolean
labelFromKey: (key: string) => string
filterEmptyItems?: (item: OverviewItem) => boolean
compact?: boolean
@@ -57,6 +58,7 @@ export function OverviewGrid({
numSkeletons,
samplingRate,
usedPreAggregatedTables = false,
+ usedLazyPrecompute = false,
labelFromKey,
filterEmptyItems = () => true,
compact = false,
@@ -81,6 +83,7 @@ export function OverviewGrid({
key={item.key}
item={item}
usedPreAggregatedTables={usedPreAggregatedTables}
+ usedLazyPrecompute={usedLazyPrecompute}
labelFromKey={labelFromKey}
compact={compact}
/>
@@ -125,6 +128,7 @@ const OverviewItemCellSkeleton = ({ compact }: { compact: boolean }): JSX.Elemen
interface OverviewItemCellProps {
item: OverviewItem
usedPreAggregatedTables: boolean
+ usedLazyPrecompute: boolean
labelFromKey: (key: string) => string
compact: boolean
}
@@ -132,6 +136,7 @@ interface OverviewItemCellProps {
const OverviewItemCell = ({
item,
usedPreAggregatedTables,
+ usedLazyPrecompute,
labelFromKey,
compact,
}: OverviewItemCellProps): JSX.Element => {
@@ -186,7 +191,11 @@ const OverviewItemCell = ({
'relative'
)}
>
- {usedPreAggregatedTables && <PreAggregatedBadge />}
+ {usedLazyPrecompute ? (
+ <PreAggregatedBadge variant="precomputed" />
+ ) : usedPreAggregatedTables ? (
+ <PreAggregatedBadge variant="preagg" />
+ ) : null}
<div className="flex flex-row w-full justify-center items-center gap-1">
<div className={`uppercase py-0.5 ${compact ? 'text-[10px]' : 'text-xs font-bold'}`}>{label}</div>
{item.warning && (
diff --git a/frontend/src/queries/nodes/WebOverview/WebOverview.tsx b/frontend/src/queries/nodes/WebOverview/WebOverview.tsx
index aea261b8dadc..0e7e5fe20bb7 100644
--- a/frontend/src/queries/nodes/WebOverview/WebOverview.tsx
+++ b/frontend/src/queries/nodes/WebOverview/WebOverview.tsx
@@ -3,7 +3,6 @@ import { useState } from 'react'
import { reverseProxyCheckerLogic } from 'lib/components/ReverseProxyChecker/reverseProxyCheckerLogic'
import { FEATURE_FLAGS } from 'lib/constants'
-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { capitalizeFirstLetter } from 'lib/utils'
@@ -46,12 +45,9 @@ export function WebOverview(props: {
const numSkeletons = props.query.conversionGoal ? 4 : 5
- const canUseWebAnalyticsPreAggregatedTables = useFeatureFlag('SETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES')
const usedWebAnalyticsPreAggregatedTables =
- canUseWebAnalyticsPreAggregatedTables &&
- response &&
- 'usedPreAggregatedTables' in response &&
- response.usedPreAggregatedTables
+ response && 'usedPreAggregatedTables' in response && response.usedPreAggregatedTables
+ const usedWebAnalyticsLazyPrecompute = response && 'usedLazyPrecompute' in response && response.usedLazyPrecompute
const showWarning = hasReverseProxy === false && !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_EMPTY_ONBOARDING]
@@ -79,6 +75,7 @@ export function WebOverview(props: {
numSkeletons={numSkeletons}
samplingRate={samplingRate}
usedPreAggregatedTables={usedWebAnalyticsPreAggregatedTables}
+ usedLazyPrecompute={usedWebAnalyticsLazyPrecompute}
labelFromKey={labelFromKey}
/>
)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 501f39c746c6..b4f5da8d963c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -9802,6 +9802,9 @@
},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -11879,6 +11882,9 @@
},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -29170,6 +29176,9 @@
},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -30204,6 +30213,9 @@
},
"type": "array"
},
+ "usedLazyPrecompute": {
+ "type": "boolean"
+ },
"usedPreAggregatedTables": {
"type": "boolean"
}
@@ -40076,6 +40088,10 @@
"deprecated": "ignored, always treated as enabled *",
"type": "boolean"
},
+ "useWebAnalyticsPrecompute": {
+ "description": "Opt this specific query into the web_overview_query precompute path. Requires the team to be in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` allowlist for the gate to pass. *",
+ "type": "boolean"
+ },
"version": {
"description": "version of the node, used for schema migrations",
"type": "number"
@@ -40129,6 +40145,9 @@
},
"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 0a85e363e0a4..e07621cbb4c0 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2287,6 +2287,8 @@ interface WebAnalyticsQueryBase<R extends Record<string, any>> extends DataNode<
export interface WebOverviewQuery extends WebAnalyticsQueryBase<WebOverviewQueryResponse> {
kind: NodeKind.WebOverviewQuery
+ /** Opt this specific query into the web_overview_query precompute path. Requires the team to be in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` allowlist for the gate to pass. **/
+ useWebAnalyticsPrecompute?: boolean
}
export type WebAnalyticsItemKind = 'unit' | 'duration_s' | 'percentage' | 'currency'
@@ -2313,6 +2315,7 @@ export interface WebOverviewQueryResponse extends AnalyticsQueryResponseBase {
dateFrom?: string
dateTo?: string
usedPreAggregatedTables?: boolean
+ usedLazyPrecompute?: boolean
}
export type CachedWebOverviewQueryResponse = CachedQueryResponse<WebOverviewQueryResponse>
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx
index 7b244e6e05a7..5cab78829133 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx
@@ -5,6 +5,7 @@ import { IconSearch } from '@posthog/icons'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { Link } from 'lib/lemon-ui/Link'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { urls } from 'scenes/urls'
@@ -30,10 +31,12 @@ const ANALYTICS_TILES = [
]
export const WebAnalyticsMenu = (): JSX.Element => {
- const { shouldFilterTestAccounts, hiddenTiles, productTab } = useValues(webAnalyticsLogic)
+ const { shouldFilterTestAccounts, useWebAnalyticsPrecompute, hiddenTiles, productTab } =
+ useValues(webAnalyticsLogic)
const { featureFlags } = useValues(featureFlagLogic)
- const { setShouldFilterTestAccounts, setTileVisibility } = useActions(webAnalyticsLogic)
+ const { setShouldFilterTestAccounts, setUseWebAnalyticsPrecompute, setTileVisibility } =
+ useActions(webAnalyticsLogic)
const showTileToggles = featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_TILE_TOGGLES]
const availableTiles = productTab === ProductTab.ANALYTICS ? ANALYTICS_TILES : []
@@ -56,6 +59,19 @@ export const WebAnalyticsMenu = (): JSX.Element => {
<LemonSwitch checked={shouldFilterTestAccounts} size="xsmall" />
Filter out internal and test users
</ButtonPrimitive>
+ {featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PRECOMPUTE_TOGGLE] && (
+ <Tooltip title="Serve eligible Web Overview queries from the precomputed cache. Only takes effect for teams enrolled by the admin via WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS.">
+ <ButtonPrimitive
+ menuItem
+ onClick={() => {
+ setUseWebAnalyticsPrecompute(!useWebAnalyticsPrecompute)
+ }}
+ >
+ <LemonSwitch checked={useWebAnalyticsPrecompute} size="xsmall" />
+ Allow precompute
+ </ButtonPrimitive>
+ </Tooltip>
+ )}
</ScenePanelActionsSection>
{showTileToggles && availableTiles.length > 0 && (
<>
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 116cc535b6cf..62bf2d8b61b8 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -214,6 +214,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
}),
setIsPathCleaningEnabled: (isPathCleaningEnabled: boolean) => ({ isPathCleaningEnabled }),
setShouldFilterTestAccounts: (shouldFilterTestAccounts: boolean) => ({ shouldFilterTestAccounts }),
+ setUseWebAnalyticsPrecompute: (useWebAnalyticsPrecompute: boolean) => ({ useWebAnalyticsPrecompute }),
setShouldStripQueryParams: (shouldStripQueryParams: boolean) => ({ shouldStripQueryParams }),
setIncludeHostPath: (includeHostPath: boolean) => ({ includeHostPath }),
setConversionGoal: (conversionGoal: WebAnalyticsConversionGoal | null) => ({ conversionGoal }),
@@ -429,6 +430,13 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
clearFilters: () => false,
},
],
+ useWebAnalyticsPrecompute: [
+ false as boolean,
+ persistConfig,
+ {
+ setUseWebAnalyticsPrecompute: (_, { useWebAnalyticsPrecompute }) => useWebAnalyticsPrecompute,
+ },
+ ],
shouldStripQueryParams: [
false as boolean,
persistConfig,
@@ -745,6 +753,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
s.shouldFilterTestAccounts,
s.shouldStripQueryParams,
s.includeHostPath,
+ s.useWebAnalyticsPrecompute,
s.featureFlags,
],
(
@@ -752,12 +761,14 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
filterTestAccounts: boolean,
shouldStripQueryParams: boolean,
includeHostPath: boolean,
+ useWebAnalyticsPrecompute: boolean,
featureFlags: Record<string, boolean>
) => ({
isPathCleaningEnabled,
filterTestAccounts,
shouldStripQueryParams,
includeHostPath: !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_INCLUDE_HOST] && includeHostPath,
+ useWebAnalyticsPrecompute,
}),
],
filters: [
@@ -922,7 +933,13 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
(
productTab,
{ graphsTab, sourceTab, deviceTab, pathTab, geographyTab, shouldShowGeoIPQueries, activeHoursTab },
- { isPathCleaningEnabled, filterTestAccounts, shouldStripQueryParams, includeHostPath },
+ {
+ isPathCleaningEnabled,
+ filterTestAccounts,
+ shouldStripQueryParams,
+ includeHostPath,
+ useWebAnalyticsPrecompute,
+ },
{
webAnalyticsFilters,
replayFilters,
@@ -1256,6 +1273,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
compareFilter,
filterTestAccounts,
conversionGoal,
+ useWebAnalyticsPrecompute,
},
insightProps: createInsightProps(TileId.OVERVIEW),
canOpenInsight: true,
diff --git a/posthog/clickhouse/migrations/0256_web_overview_preaggregated.py b/posthog/clickhouse/migrations/0256_web_overview_preaggregated.py
new file mode 100644
index 000000000000..80b7043cb82b
--- /dev/null
+++ b/posthog/clickhouse/migrations/0256_web_overview_preaggregated.py
@@ -0,0 +1,22 @@
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (
+ DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
+ SHARDED_WEB_OVERVIEW_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_OVERVIEW_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ sharded=True,
+ ),
+ # Distributed read table on DATA — queries fan out from data nodes and
+ # resolve to AUX shards via the Distributed engine's `cluster=AUX` setting.
+ run_sql_with_exceptions(
+ DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index abfe663c726c..fa7fdec0ef91 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0255_nuke_session_replay_features
+0256_web_overview_preaggregated
diff --git a/posthog/clickhouse/preaggregation/web_overview_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_overview_preaggregated_sql.py
new file mode 100644
index 000000000000..f4f05e9b01d3
--- /dev/null
+++ b/posthog/clickhouse/preaggregation/web_overview_preaggregated_sql.py
@@ -0,0 +1,102 @@
+# Table for storing lazy-precomputed web overview aggregates
+#
+# Stores per-hour, per-team aggregate states for the five metrics surfaced by
+# WebOverviewQueryRunner: unique users, unique sessions, total pageviews,
+# average session duration, average bounce rate. Reads merge across hourly
+# buckets to answer arbitrary date ranges within the precomputed window.
+#
+# Buckets are UTC hourly so reads stay correct for any whole-hour-offset team
+# timezone without storing per-team-tz data.
+
+from django.conf import settings
+
+from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme
+
+TABLE_BASE_NAME = "web_overview_preaggregated"
+
+
+def DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE():
+ return TABLE_BASE_NAME
+
+
+def SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE():
+ return f"sharded_{TABLE_BASE_NAME}"
+
+
+def SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_ENGINE():
+ return ReplacingMergeTree(TABLE_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")
+
+
+WEB_OVERVIEW_PREAGGREGATED_TABLE_BASE_SQL = """
+CREATE TABLE IF NOT EXISTS {table_name}
+(
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket. Reads filter by [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- Aggregate states matching WebOverviewQueryRunner.outer_select metrics.
+ -- `uniq` (HyperLogLog) is used over `uniqExact` because HogQL exposes
+ -- `uniqMergeIf` but not `uniqExactMergeIf`, and ~99% accuracy is fine for the
+ -- dashboard use case (matches the v2 pre-aggregation choice).
+ uniq_users_state AggregateFunction(uniq, UUID),
+ uniq_sessions_state AggregateFunction(uniq, String),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+ avg_duration_state AggregateFunction(avg, Float64),
+ avg_bounce_state AggregateFunction(avg, 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_OVERVIEW_PREAGGREGATED_TABLE_SQL():
+ # Partition by `expires_at` (the TTL column) so `ttl_only_drop_parts=1` can
+ # actually drop whole parts atomically when all rows in them expire. Rows
+ # for the same UTC day share a partition regardless of which `time_window_start`
+ # hour they cover, so mixed-TTL writes (15m for today, 7d for older) end up
+ # in distinct parts and the short-TTL parts drop cleanly.
+ return (
+ WEB_OVERVIEW_PREAGGREGATED_TABLE_BASE_SQL
+ + """
+PARTITION BY toYYYYMMDD(expires_at)
+ORDER BY (team_id, job_id, time_window_start)
+TTL toDateTime(expires_at)
+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+"""
+ ).format(
+ table_name=SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE(),
+ engine=SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_ENGINE(),
+ )
+
+
+def DISTRIBUTED_WEB_OVERVIEW_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_OVERVIEW_PREAGGREGATED_TABLE_BASE_SQL.format(
+ table_name=DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE(),
+ engine=Distributed(
+ data_table=SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE(),
+ sharding_key="sipHash64(job_id)",
+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,
+ ),
+ )
+
+
+def DROP_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE()}"
+
+
+def DROP_SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE()} SYNC"
+
+
+def TRUNCATE_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL():
+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE()}"
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index 69e556469312..fe911342ac74 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -45,6 +45,10 @@ from posthog.clickhouse.preaggregation.sql import (
DISTRIBUTED_PREAGGREGATION_RESULTS_TABLE_SQL,
SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL,
)
+from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (
+ DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
+ SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
+)
from posthog.clickhouse.property_values import (
DISTRIBUTED_PROPERTY_VALUES_TABLE_SQL,
KAFKA_PROPERTY_VALUES_TABLE_SQL_FN,
@@ -298,6 +302,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (
SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL,
SHARDED_EXPERIMENT_EXPOSURES_TABLE_SQL,
SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE_SQL,
+ SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,
DISTINCT_ID_USAGE_DATA_TABLE_SQL,
PROPERTY_DEFINITIONS_TABLE_SQL,
*[table.sharded_table_sql for table in EMBEDDING_TABLES],
@@ -354,6 +359,7 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (
DISTRIBUTED_PREAGGREGATION_RESULTS_TABLE_SQL,
DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE_SQL,
DISTRIBUTED_EXPERIMENT_METRIC_EVENTS_TABLE_SQL,
+ DISTRIBUTED_WEB_OVERVIEW_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 32bd5d7d019a..a43700192b3a 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -6132,6 +6132,41 @@
'''
# ---
+# name: test_create_table_query[sharded_web_overview_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_web_overview_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket. Reads filter by [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- Aggregate states matching WebOverviewQueryRunner.outer_select metrics.
+ -- `uniq` (HyperLogLog) is used over `uniqExact` because HogQL exposes
+ -- `uniqMergeIf` but not `uniqExactMergeIf`, and ~99% accuracy is fine for the
+ -- dashboard use case (matches the v2 pre-aggregation choice).
+ uniq_users_state AggregateFunction(uniq, UUID),
+ uniq_sessions_state AggregateFunction(uniq, String),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+ avg_duration_state AggregateFunction(avg, Float64),
+ avg_bounce_state AggregateFunction(avg, 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_overview_preaggregated', '{replica}', computed_at)
+
+ PARTITION BY toYYYYMMDD(expires_at)
+ ORDER BY (team_id, job_id, time_window_start)
+ TTL toDateTime(expires_at)
+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+
+ '''
+# ---
# name: test_create_table_query[tophog]
'''
@@ -6169,6 +6204,36 @@
'''
# ---
+# name: test_create_table_query[web_overview_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS web_overview_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket. Reads filter by [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- Aggregate states matching WebOverviewQueryRunner.outer_select metrics.
+ -- `uniq` (HyperLogLog) is used over `uniqExact` because HogQL exposes
+ -- `uniqMergeIf` but not `uniqExactMergeIf`, and ~99% accuracy is fine for the
+ -- dashboard use case (matches the v2 pre-aggregation choice).
+ uniq_users_state AggregateFunction(uniq, UUID),
+ uniq_sessions_state AggregateFunction(uniq, String),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+ avg_duration_state AggregateFunction(avg, Float64),
+ avg_bounce_state AggregateFunction(avg, 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_overview_preaggregated', sipHash64(job_id))
+
+ '''
+# ---
# name: test_create_table_query[web_pre_aggregated_bounces]
'''
@@ -9346,6 +9411,41 @@
'''
# ---
+# name: test_create_table_query_replicated_and_storage[sharded_web_overview_preaggregated]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_web_overview_preaggregated
+ (
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket. Reads filter by [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- Aggregate states matching WebOverviewQueryRunner.outer_select metrics.
+ -- `uniq` (HyperLogLog) is used over `uniqExact` because HogQL exposes
+ -- `uniqMergeIf` but not `uniqExactMergeIf`, and ~99% accuracy is fine for the
+ -- dashboard use case (matches the v2 pre-aggregation choice).
+ uniq_users_state AggregateFunction(uniq, UUID),
+ uniq_sessions_state AggregateFunction(uniq, String),
+ sum_pageviews_state AggregateFunction(sum, Int64),
+ avg_duration_state AggregateFunction(avg, Float64),
+ avg_bounce_state AggregateFunction(avg, 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_overview_preaggregated', '{replica}', computed_at)
+
+ PARTITION BY toYYYYMMDD(expires_at)
+ ORDER BY (team_id, job_id, time_window_start)
+ 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 7f04b7cf2239..7ee1b020e558 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -133,6 +133,7 @@ from posthog.hogql.database.schema.web_analytics_preaggregated import (
WebPreAggregatedBouncesTable,
WebPreAggregatedStatsTable,
)
+from posthog.hogql.database.schema.web_overview_preaggregated import WebOverviewPreaggregatedTable
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
@@ -287,6 +288,9 @@ def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNod
name="error_tracking_fingerprint_issue_state",
table=ErrorTrackingFingerprintIssueStateTable(),
),
+ "web_overview_preaggregated": TableNode(
+ name="web_overview_preaggregated", table=WebOverviewPreaggregatedTable()
+ ),
},
),
"system": SystemTables(),
diff --git a/posthog/hogql/database/schema/web_overview_preaggregated.py b/posthog/hogql/database/schema/web_overview_preaggregated.py
new file mode 100644
index 000000000000..e2f0b46fe637
--- /dev/null
+++ b/posthog/hogql/database/schema/web_overview_preaggregated.py
@@ -0,0 +1,47 @@
+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_overview_preaggregated_sql import (
+ DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE,
+)
+
+
+class WebOverviewPreaggregatedTable(Table):
+ # `load_balancing="in_order"` matches sibling lazy-precompute tables and is
+ # important for read-your-writes: both INSERT (via _get_insert_settings) and
+ # SELECT deterministically prefer the same replica, so the read sees data the
+ # INSERT just wrote. `optimize_skip_unused_shards=1` adds shard pruning since
+ # our combiner filters by `job_id IN (...)` and the table is sharded by
+ # `sipHash64(job_id)`.
+ 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"),
+ # Aggregate-state columns are passed straight to `uniqMergeIf`/`sumMergeIf`/`avgMergeIf`
+ # in the read query. HogQL doesn't need to know their internal shape —
+ # `UnknownDatabaseField` is opaque enough.
+ "uniq_users_state": UnknownDatabaseField(name="uniq_users_state"),
+ "uniq_sessions_state": UnknownDatabaseField(name="uniq_sessions_state"),
+ "sum_pageviews_state": UnknownDatabaseField(name="sum_pageviews_state"),
+ "avg_duration_state": UnknownDatabaseField(name="avg_duration_state"),
+ "avg_bounce_state": UnknownDatabaseField(name="avg_bounce_state"),
+ }
+
+ def to_printed_clickhouse(self, context):
+ return DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE()
+
+ def to_printed_hogql(self):
+ return "web_overview_preaggregated"
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_overview_lazy_precompute.py b/posthog/hogql_queries/web_analytics/test/test_web_overview_lazy_precompute.py
new file mode 100644
index 000000000000..d9f03b175486
--- /dev/null
+++ b/posthog/hogql_queries/web_analytics/test/test_web_overview_lazy_precompute.py
@@ -0,0 +1,580 @@
+import uuid
+
+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,
+ DateRange,
+ EventPropertyFilter,
+ HogQLQueryModifiers,
+ PropertyOperator,
+ SessionPropertyFilter,
+ SessionsV2JoinMode,
+ WebAnalyticsSampling,
+ WebOverviewQuery,
+)
+
+from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
+from posthog.models.instance_setting import override_instance_config
+from posthog.models.utils import uuid7
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
+from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()
+
+ def _enable_lazy(self):
+ return override_instance_config("WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS", [self.team.pk])
+
+ def _seed_two_sessions(self) -> None:
+ # p1 has two pageviews in one session, p2 has a single pageview (bounce).
+ s1 = str(uuid7("2024-01-02"))
+ s2 = str(uuid7("2024-01-03"))
+ _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
+ _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p1",
+ timestamp="2024-01-02T10:00:00Z",
+ properties={"$session_id": s1, "$host": "example.com", "$current_url": "https://example.com/a"},
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p1",
+ timestamp="2024-01-02T10:05:00Z",
+ properties={"$session_id": s1, "$host": "example.com", "$current_url": "https://example.com/b"},
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p2",
+ timestamp="2024-01-03T11:00:00Z",
+ properties={"$session_id": s2, "$host": "other.com", "$current_url": "https://other.com/x"},
+ )
+
+ def _build_query(
+ self,
+ 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,
+ opt_in_precompute: bool = True,
+ ) -> WebOverviewQuery:
+ return WebOverviewQuery(
+ 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,
+ useWebAnalyticsPrecompute=opt_in_precompute,
+ )
+
+ def _run(self, query: WebOverviewQuery):
+ return WebOverviewQueryRunner(team=self.team, query=query).calculate()
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_unfiltered_round_trip_creates_precompute_job(self):
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(self._build_query())
+
+ jobs = list(PreaggregationJob.objects.filter(team_id=self.team.pk))
+ assert len(jobs) > 0, "expected at least one precompute job to be created"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_lazy_result_matches_raw_result(self):
+ """Run the same query with and without the lazy path enabled, assert results match."""
+ self._seed_two_sessions()
+
+ # Path A: raw events scan (no lazy gate).
+ raw_response = self._run(self._build_query())
+ raw_visitors = raw_response.results[0].value
+ raw_views = raw_response.results[1].value
+ raw_sessions = raw_response.results[2].value
+
+ # Path B: lazy precompute.
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query())
+
+ # Confirm we actually went through the lazy path.
+ ready_jobs = PreaggregationJob.objects.filter(
+ team_id=self.team.pk, status=PreaggregationJob.Status.READY
+ ).count()
+ assert ready_jobs > 0, "expected at least one READY precompute job"
+
+ lazy_visitors = lazy_response.results[0].value
+ lazy_views = lazy_response.results[1].value
+ lazy_sessions = lazy_response.results[2].value
+
+ assert lazy_visitors == raw_visitors, f"visitors mismatch: lazy={lazy_visitors}, raw={raw_visitors}"
+ assert lazy_views == raw_views, f"views mismatch: lazy={lazy_views}, raw={raw_views}"
+ assert lazy_sessions == raw_sessions, f"sessions mismatch: lazy={lazy_sessions}, raw={raw_sessions}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_host_filter_gets_distinct_cache_entry(self):
+ self._seed_two_sessions()
+ host_filter = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
+
+ with self._enable_lazy():
+ self._run(self._build_query())
+ unfiltered_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(properties=[host_filter]))
+ filtered_jobs = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ assert unfiltered_jobs, "expected unfiltered run to create at least one job"
+ assert filtered_jobs, "expected host-filtered run to create at least one job"
+ assert unfiltered_jobs.isdisjoint(filtered_jobs), (
+ f"unfiltered and host-filtered runs must produce distinct cache keys, "
+ f"got overlap: {unfiltered_jobs & filtered_jobs}"
+ )
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_distinct_host_values_get_distinct_cache_entries(self):
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(
+ self._build_query(
+ properties=[EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)]
+ )
+ )
+ example_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(
+ properties=[EventPropertyFilter(key="$host", value="other.com", operator=PropertyOperator.EXACT)]
+ )
+ )
+ other_jobs = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ assert example_jobs.isdisjoint(other_jobs), (
+ f"different $host values must produce distinct cache keys, got overlap: {example_jobs & other_jobs}"
+ )
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_disqualifying_filter_falls_through(self):
+ self._seed_two_sessions()
+ # $pathname is not in the MVP allowlist → gate returns False → no job created.
+ with self._enable_lazy():
+ self._run(
+ self._build_query(
+ properties=[
+ EventPropertyFilter(key="$pathname", value="/a", operator=PropertyOperator.EXACT),
+ ]
+ )
+ )
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_session_property_falls_through(self):
+ # Session-level filters never qualify for MVP — only EventPropertyFilter on $host.
+ with self._enable_lazy():
+ self._run(
+ self._build_query(
+ properties=[
+ SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT),
+ ]
+ )
+ )
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_sampling_falls_through(self):
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(self._build_query(sampling=WebAnalyticsSampling(enabled=True)))
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_disabled_team_falls_through(self):
+ # Both gates closed: not in allowlist AND modifier not set.
+ self._seed_two_sessions()
+ self._run(self._build_query(opt_in_precompute=False))
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_query_optin_alone_falls_through_when_team_not_enrolled(self):
+ # `query.useWebAnalyticsPrecompute=True` BUT team is not in the
+ # `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` allowlist. Should fall
+ # through — the env var is the operator-controlled rollout gate.
+ self._seed_two_sessions()
+ self._run(self._build_query(opt_in_precompute=True))
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_allowlist_alone_falls_through_when_query_not_opted_in(self):
+ # Team is in the allowlist BUT the query param is not set (the team
+ # hasn't enabled the "Allow precompute" toggle in the ScenePanel).
+ # Should fall through — the param is the per-team opt-in / kill switch.
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(self._build_query(opt_in_precompute=False))
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_cache_hit_on_second_call(self):
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(self._build_query())
+ first_run_jobs = list(PreaggregationJob.objects.filter(team_id=self.team.pk))
+ first_run_summary = [(str(j.id), j.status, j.error or "") for j in first_run_jobs]
+
+ self._run(self._build_query())
+ second_run_jobs = list(PreaggregationJob.objects.filter(team_id=self.team.pk))
+ second_run_summary = [(str(j.id), j.status, j.error or "") for j in second_run_jobs]
+
+ # The second call should not create *new* successful jobs — it should reuse ready ones.
+ first_ready_ids = {jid for jid, status, _err in first_run_summary if status == PreaggregationJob.Status.READY}
+ new_jobs_in_second = {jid for jid, _, _ in second_run_summary} - {jid for jid, _, _ in first_run_summary}
+
+ assert first_ready_ids, (
+ f"first run should have produced at least one READY job, statuses were: {first_run_summary}"
+ )
+ # Any newly-created jobs in the second call must be replacements for FAILED first-run jobs,
+ # not duplicates of READY ones.
+ for new_id in new_jobs_in_second:
+ new_job = next(j for j in second_run_jobs if str(j.id) == new_id)
+ assert new_job.status == PreaggregationJob.Status.READY
+ # Most importantly: no READY job from the first run should be discarded.
+ ready_jobs_preserved = first_ready_ids.issubset({jid for jid, _, _ in second_run_summary})
+ assert ready_jobs_preserved, (
+ f"second run dropped some first-run READY jobs. first: {first_run_summary}, second: {second_run_summary}"
+ )
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_compare_to_period_reuses_cache(self):
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(self._build_query())
+ no_compare_jobs = {str(j.id) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ self._run(self._build_query(compare=True))
+ after_compare_jobs = {str(j.id) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ # Compare reads from the same precomputed window with a wider date range, so
+ # it should reuse existing jobs and not multiply them.
+ assert no_compare_jobs.issubset(after_compare_jobs)
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_compare_to_period_returns_real_previous_values(self):
+ """Regression: ensure compare-period metrics come from real precomputed
+ previous-period data, not 0/NaN. The bug surfaced when the lazy path
+ only precomputed the current window, leaving the read query with no
+ rows to merge for the `prev_*` columns. Compare to the same query
+ evaluated through the raw events path to assert parity."""
+ # Current period: standard 2-session fixture (Jan 2 + Jan 3).
+ self._seed_two_sessions()
+ # Previous period: 1 extra session in the 7 days before Jan 1.
+ _create_person(team_id=self.team.pk, distinct_ids=["prev_p1"], properties={"name": "prev_p1"})
+ prev_session = str(uuid7("2023-12-28"))
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="prev_p1",
+ timestamp="2023-12-28T10:00:00Z",
+ properties={
+ "$session_id": prev_session,
+ "$host": "example.com",
+ "$current_url": "https://example.com/old",
+ },
+ )
+
+ # Path A: raw events scan, compare=True. Ground truth for previous values.
+ raw_response = self._run(self._build_query(compare=True))
+ raw_visitors = raw_response.results[0]
+ raw_sessions = raw_response.results[2]
+
+ # Path B: lazy precompute, compare=True. Must match the raw response.
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query(compare=True))
+ lazy_visitors = lazy_response.results[0]
+ lazy_sessions = lazy_response.results[2]
+
+ assert lazy_visitors.previous == raw_visitors.previous, (
+ f"previous visitors mismatch: lazy={lazy_visitors.previous}, raw={raw_visitors.previous}. "
+ f"If lazy is 0/None, the previous-period precompute is missing."
+ )
+ assert lazy_sessions.previous == raw_sessions.previous, (
+ f"previous sessions mismatch: lazy={lazy_sessions.previous}, raw={raw_sessions.previous}."
+ )
+ # Sanity: the raw path must actually report > 0 in the previous period
+ # — otherwise the assertion above could be a vacuous 0 == 0 and miss the
+ # regression we're trying to catch.
+ assert raw_visitors.previous and raw_visitors.previous > 0, (
+ f"raw previous visitors should be > 0 with seeded prev_p1 event, got {raw_visitors.previous}"
+ )
+
+ # --- Group A: timezone correctness --------------------------------------
+
+ @parameterized.expand(
+ [
+ ("utc", "UTC"),
+ ("pacific", "America/Los_Angeles"),
+ ("tokyo", "Asia/Tokyo"),
+ ]
+ )
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_lazy_result_matches_raw_for_whole_hour_timezones(self, _name: str, team_tz: str) -> None:
+ """Whole-hour-offset teams must produce the same metrics through the lazy and raw paths."""
+ self.team.timezone = team_tz
+ self.team.save()
+ self._seed_two_sessions()
+
+ raw_response = self._run(self._build_query())
+ raw_values = [(r.key, r.value) for r in raw_response.results]
+
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query())
+
+ ready_jobs = PreaggregationJob.objects.filter(
+ team_id=self.team.pk, status=PreaggregationJob.Status.READY
+ ).count()
+ assert ready_jobs > 0, f"expected READY precompute job for {team_tz}, got 0"
+
+ lazy_values = [(r.key, r.value) for r in lazy_response.results]
+ assert lazy_values == raw_values, f"lazy/raw mismatch for {team_tz}: raw={raw_values}, lazy={lazy_values}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_half_hour_offset_timezone_falls_through(self):
+ # IST is UTC+5:30 — hourly UTC buckets can't represent the team-local
+ # midnight, so the gate must refuse.
+ self.team.timezone = "Asia/Kolkata"
+ self.team.save()
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(self._build_query())
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ # --- Group B: gate strictness -------------------------------------------
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_multiple_host_filters_fall_through(self):
+ # Gate accepts at most one user-supplied property — multi-host inputs
+ # collide on a single-filter cache key and must be rejected.
+ self._seed_two_sessions()
+ host_a = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)
+ host_b = EventPropertyFilter(key="$host", value="other.com", operator=PropertyOperator.EXACT)
+ with self._enable_lazy():
+ self._run(self._build_query(properties=[host_a, host_b]))
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_uuid_session_mode_falls_through(self):
+ # `events.$session_id_uuid` would produce `uniqState(UUID)` which the
+ # `(uniq, String)` column rejects non-retryably. Gate must refuse.
+ self._seed_two_sessions()
+ query = self._build_query()
+ query.modifiers = HogQLQueryModifiers(sessionsV2JoinMode=SessionsV2JoinMode.UUID)
+ with self._enable_lazy():
+ self._run(query)
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @parameterized.expand(
+ [
+ ("none_value", None),
+ ("list_value", ["example.com", "other.com"]),
+ ("empty_string", ""),
+ ]
+ )
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_non_string_host_value_falls_through(self, _name: str, host_value) -> None:
+ self._seed_two_sessions()
+ prop = EventPropertyFilter(key="$host", value=host_value, operator=PropertyOperator.EXACT)
+ with self._enable_lazy():
+ self._run(self._build_query(properties=[prop]))
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_window_over_max_days_falls_through(self):
+ # 365 days >> MAX_PRECOMPUTE_DAYS — gate refuses to avoid spawning
+ # hundreds of daily INSERT jobs in one request.
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(self._build_query(date_from="2023-01-01", date_to="2024-01-07"))
+
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+
+ # --- Group C: forward-only pad + compare readiness ---------------------
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_session_just_after_window_start_attributed_correctly(self):
+ # Forward-only pad regression: a session starting near the leading edge
+ # of a daily UTC bucket must still aggregate its full set of events.
+ # If the inner-SELECT loses the trailing events, sessions/duration/views
+ # would not match the raw path.
+ session_id = str(uuid7("2024-01-02"))
+ _create_person(team_id=self.team.pk, distinct_ids=["edge_p1"], properties={"name": "edge_p1"})
+ for offset_min in (5, 15, 30):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="edge_p1",
+ timestamp=f"2024-01-02T00:{offset_min:02d}:00Z",
+ properties={
+ "$session_id": session_id,
+ "$host": "example.com",
+ "$current_url": f"https://example.com/p{offset_min}",
+ },
+ )
+
+ raw_response = self._run(self._build_query(date_from="2024-01-02", date_to="2024-01-02"))
+ raw_values = [(r.key, r.value) for r in raw_response.results]
+
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query(date_from="2024-01-02", date_to="2024-01-02"))
+ lazy_values = [(r.key, r.value) for r in lazy_response.results]
+
+ assert lazy_values == raw_values, f"forward-only pad parity broken: raw={raw_values}, lazy={lazy_values}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_compare_period_falls_back_when_previous_not_ready(self):
+ # If the previous-period precompute hasn't reached READY across all jobs,
+ # we must not read — the read would silently return 0/NaN for `prev_*`
+ # columns. The lazy path returns None to signal fall-back to raw.
+ first_call = {"done": False}
+
+ def fake_ensure(runner, time_range_start, time_range_end):
+ if not first_call["done"]:
+ first_call["done"] = True
+ return LazyComputationResult(ready=True, job_ids=[uuid.uuid4()])
+ return LazyComputationResult(ready=False, job_ids=[uuid.uuid4()])
+
+ from posthog.hogql_queries.web_analytics.web_overview_lazy_precompute import execute_lazy_precomputed_read
+
+ with (
+ self._enable_lazy(),
+ patch(
+ "posthog.hogql_queries.web_analytics.web_overview_lazy_precompute.ensure_web_overview_precomputed",
+ side_effect=fake_ensure,
+ ),
+ ):
+ runner = WebOverviewQueryRunner(team=self.team, query=self._build_query(compare=True))
+ result = execute_lazy_precomputed_read(runner)
+
+ assert result is None, f"expected fall-back to raw when previous precompute not ready, got {result!r}"
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_recomputation_picks_up_late_events_changing_bounce_and_duration(self):
+ # After a late event arrives, the next precompute run (cache invalidated
+ # via job deletion = simulated TTL expiry) must reflect the new
+ # session-level state:
+ # • bounce flips from 1.0 → 0.0 when a second pageview lands
+ # • session_duration grows from 0 → non-zero
+ # • views grows from 1 → 2
+ # The stale precomputed row stays in ClickHouse with the old job_id;
+ # the new read passes the new job_id, so ReplacingMergeTree partitioning
+ # by job_id naturally isolates the runs.
+ session_id = str(uuid7("2024-01-02"))
+ _create_person(team_id=self.team.pk, distinct_ids=["recompute_p1"], properties={"name": "recompute_p1"})
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="recompute_p1",
+ timestamp="2024-01-02T10:00:00Z",
+ properties={
+ "$session_id": session_id,
+ "$host": "example.com",
+ "$current_url": "https://example.com/first",
+ },
+ )
+
+ with self._enable_lazy():
+ first_resp = self._run(self._build_query(date_from="2024-01-02", date_to="2024-01-02"))
+ first_metrics = {r.key: r.value for r in first_resp.results}
+ first_job_ids = set(PreaggregationJob.objects.filter(team_id=self.team.pk).values_list("id", flat=True))
+
+ assert first_job_ids, "first run should have created at least one precompute job"
+
+ # Stale-state sanity: single pageview = bounce (100%), zero duration.
+ assert first_metrics["bounce rate"] == 100.0, f"first run bounce rate should be 100.0%, got {first_metrics}"
+ assert first_metrics["views"] == 1.0, f"first run views should be 1, got {first_metrics}"
+
+ # Late event arrives, extending the same session.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="recompute_p1",
+ timestamp="2024-01-02T10:15:00Z",
+ properties={
+ "$session_id": session_id,
+ "$host": "example.com",
+ "$current_url": "https://example.com/second",
+ },
+ )
+
+ # Invalidate the cache by deleting the READY job rows. This
+ # simulates TTL expiry; the next ensure_precomputed cycle will
+ # create fresh job_ids and re-INSERT with the updated session
+ # aggregates.
+ PreaggregationJob.objects.filter(id__in=first_job_ids).delete()
+
+ second_resp = self._run(self._build_query(date_from="2024-01-02", date_to="2024-01-02"))
+ second_metrics = {r.key: r.value for r in second_resp.results}
+ second_job_ids = set(PreaggregationJob.objects.filter(team_id=self.team.pk).values_list("id", flat=True))
+
+ assert second_job_ids, "second run should have created new precompute jobs after invalidation"
+ assert second_job_ids.isdisjoint(first_job_ids), (
+ "recomputation should produce fresh job_ids, not reuse deleted ones"
+ )
+
+ # Recomputed state must reflect the late event.
+ assert second_metrics["views"] == 2.0, f"recomputed views should be 2, got {second_metrics}"
+ assert second_metrics["bounce rate"] == 0.0, (
+ f"recomputed bounce rate should flip to 0.0% after second pageview, got {second_metrics}"
+ )
+ assert second_metrics["session duration"] is not None and second_metrics["session duration"] > 0, (
+ f"recomputed session duration should be > 0, got {second_metrics}"
+ )
+
+ # Cross-check parity vs the raw events path after the late event.
+ raw_resp = self._run(self._build_query(date_from="2024-01-02", date_to="2024-01-02"))
+ raw_metrics = {r.key: r.value for r in raw_resp.results}
+ for metric in ("views", "bounce rate", "session duration", "visitors", "sessions"):
+ assert second_metrics[metric] == raw_metrics[metric], (
+ f"recomputed lazy != raw for {metric}: lazy={second_metrics[metric]}, raw={raw_metrics[metric]}"
+ )
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_falls_back_when_current_period_not_ready(self):
+ # Symmetric to the previous test: if the current-period precompute
+ # hasn't reached READY, the read would scan empty buckets. Fall back.
+ from posthog.hogql_queries.web_analytics.web_overview_lazy_precompute import execute_lazy_precomputed_read
+
+ with (
+ self._enable_lazy(),
+ patch(
+ "posthog.hogql_queries.web_analytics.web_overview_lazy_precompute.ensure_web_overview_precomputed",
+ return_value=LazyComputationResult(ready=False, job_ids=[uuid.uuid4()]),
+ ),
+ ):
+ runner = WebOverviewQueryRunner(team=self.team, query=self._build_query())
+ result = execute_lazy_precomputed_read(runner)
+
+ assert result is None, f"expected fall-back to raw when current precompute not ready, got {result!r}"
diff --git a/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py b/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
index 3049e6471cb1..844af91de0d7 100644
--- a/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
+++ b/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
@@ -85,9 +85,9 @@ class WebAnalyticsQueryRunner(AnalyticsQueryRunner[WAR], ABC):
def calculate(self) -> WAR:
# Every web analytics query runner produces user-facing dashboard
- # queries. Tag here so all downstream `sync_execute` calls (live and
- # preagg paths) inherit product/feature and don't trip DEBUG-mode
- # `UntaggedQueryError`.
+ # queries. Tag here so all downstream `sync_execute` calls (live,
+ # preagg, lazy precompute) inherit `product`/`feature` and don't
+ # trip DEBUG-mode `UntaggedQueryError`.
tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)
query_kind = getattr(self.query, "kind", "Unknown")
diff --git a/posthog/hogql_queries/web_analytics/web_overview.py b/posthog/hogql_queries/web_analytics/web_overview.py
index cb7d53db1d32..0957043a0712 100644
--- a/posthog/hogql_queries/web_analytics/web_overview.py
+++ b/posthog/hogql_queries/web_analytics/web_overview.py
@@ -16,6 +16,10 @@ from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
+from posthog.hogql_queries.web_analytics.web_overview_lazy_precompute import (
+ can_use_lazy_precompute,
+ execute_lazy_precomputed_read,
+)
from posthog.hogql_queries.web_analytics.web_overview_pre_aggregated import WebOverviewPreAggregatedQueryBuilder
from posthog.models.filters.mixins.utils import cached_property
@@ -75,7 +79,52 @@ class WebOverviewQueryRunner(WebAnalyticsQueryRunner[WebOverviewQueryResponse]):
logger.exception("Error getting pre-aggregated web_overview", error=e)
return None
+ def get_lazy_precomputed_row(self) -> Optional[list]:
+ if not can_use_lazy_precompute(self):
+ return None
+ return execute_lazy_precomputed_read(self)
+
+ def _build_response_from_row(
+ self,
+ row: list,
+ used_pre_aggregated: bool,
+ used_lazy_precompute: bool = False,
+ ) -> WebOverviewQueryResponse:
+ # Only called from the lazy precompute short-circuit; that path's gate
+ # already rejects conversionGoal, so we don't need a separate branch
+ # here. The v2/raw path builds its response inline in `_calculate`.
+ assert not self.query.conversionGoal, "lazy precompute does not support conversionGoal"
+
+ include_previous = bool(self.query.compareFilter and self.query.compareFilter.compare)
+
+ def get_prev_val(idx, use_unsample=True):
+ if not include_previous:
+ return None
+ return self._unsample(row[idx]) if use_unsample else row[idx]
+
+ results = [
+ to_data("visitors", "unit", self._unsample(row[0]), get_prev_val(1)),
+ to_data("views", "unit", self._unsample(row[2]), get_prev_val(3)),
+ to_data("sessions", "unit", self._unsample(row[4]), get_prev_val(5)),
+ to_data("session duration", "duration_s", row[6], get_prev_val(7, False)),
+ to_data("bounce rate", "percentage", row[8], get_prev_val(9, False), is_increase_bad=True),
+ ]
+
+ return WebOverviewQueryResponse(
+ results=results,
+ samplingRate=self._sample_rate,
+ modifiers=self.modifiers,
+ dateFrom=self.query_date_range.date_from_str,
+ dateTo=self.query_date_range.date_to_str,
+ usedPreAggregatedTables=used_pre_aggregated,
+ usedLazyPrecompute=used_lazy_precompute,
+ )
+
def _calculate(self) -> WebOverviewQueryResponse:
+ lazy_row = self.get_lazy_precomputed_row()
+ if lazy_row is not None:
+ return self._build_response_from_row(lazy_row, used_pre_aggregated=True, used_lazy_precompute=True)
+
pre_aggregated_response = self.get_pre_aggregated_response()
response = (
diff --git a/posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py b/posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py
new file mode 100644
index 000000000000..9df8da6527c1
--- /dev/null
+++ b/posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py
@@ -0,0 +1,572 @@
+import time
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING, Optional
+
+import structlog
+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 (
+ DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE,
+)
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.models.instance_setting import get_instance_setting
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationResult,
+ LazyComputationTable,
+ ensure_precomputed,
+)
+
+if TYPE_CHECKING:
+ from posthog.hogql_queries.web_analytics.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",
+ "Lazy precompute path failures, by error class",
+ ["error_type"],
+)
+
+
+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 TeamNotInAllowlist(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: instance allowlist AND per-query opt-in.
+ # - `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` (admin-controlled instance
+ # setting): scope of teams eligible to opt in.
+ # - `query.useWebAnalyticsPrecompute` (per-query parameter set by the
+ # "Allow precompute" toggle in the Web Analytics ScenePanel).
+ enabled_team_ids = get_instance_setting("WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS") or []
+ if runner.team.pk not in enabled_team_ids:
+ raise TeamNotInAllowlist()
+
+ 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),
+ ],
+ )
+
+
+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
+
+
+# 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.
+INSERT_QUERY_TEMPLATE = """
+SELECT
+ toStartOfHour(start_timestamp) AS time_window_start,
+ uniqState(session_person_id) AS uniq_users_state,
+ uniqState(session_id) AS uniq_sessions_state,
+ sumState(assumeNotNull(toInt(filtered_pageview_count))) AS sum_pageviews_state,
+ avgState(assumeNotNull(toFloat(session_duration))) AS avg_duration_state,
+ avgState(assumeNotNull(toInt(is_bounce))) AS avg_bounce_state
+FROM (
+ SELECT
+ any(events.person_id) AS session_person_id,
+ {events_session_id} AS session_id,
+ min(session.$start_timestamp) AS start_timestamp,
+ any(session.$session_duration) AS session_duration,
+ countIf(or(equals(event, '$pageview'), equals(event, '$screen'))) AS filtered_pageview_count,
+ any(session.$is_bounce) AS is_bounce
+ 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
+ HAVING and(
+ toStartOfHour(min(session.$start_timestamp)) >= {time_window_min},
+ toStartOfHour(min(session.$start_timestamp)) < {time_window_max}
+ )
+)
+GROUP BY time_window_start
+"""
+
+
+def ensure_web_overview_precomputed(
+ runner: "WebOverviewQueryRunner",
+ time_range_start: datetime,
+ time_range_end: datetime,
+) -> LazyComputationResult:
+ placeholders: dict[str, ast.Expr] = {
+ "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_OVERVIEW_PREAGGREGATED,
+ placeholders=placeholders,
+ query_type="web_overview_lazy_insert",
+ )
+
+
+_READ_SQL = f"""
+SELECT
+ uniqMergeIf(uniq_users_state, time_window_start >= %(cur_start)s AND time_window_start < %(cur_end)s) AS unique_users,
+ uniqMergeIf(uniq_users_state, time_window_start >= %(prev_start)s AND time_window_start < %(prev_end)s) AS previous_unique_users,
+ sumMergeIf(sum_pageviews_state, time_window_start >= %(cur_start)s AND time_window_start < %(cur_end)s) AS views,
+ sumMergeIf(sum_pageviews_state, time_window_start >= %(prev_start)s AND time_window_start < %(prev_end)s) AS previous_views,
+ uniqMergeIf(uniq_sessions_state, time_window_start >= %(cur_start)s AND time_window_start < %(cur_end)s) AS sessions,
+ uniqMergeIf(uniq_sessions_state, time_window_start >= %(prev_start)s AND time_window_start < %(prev_end)s) AS previous_sessions,
+ avgMergeIf(avg_duration_state, time_window_start >= %(cur_start)s AND time_window_start < %(cur_end)s) AS avg_duration,
+ avgMergeIf(avg_duration_state, time_window_start >= %(prev_start)s AND time_window_start < %(prev_end)s) AS previous_avg_duration,
+ avgMergeIf(avg_bounce_state, time_window_start >= %(cur_start)s AND time_window_start < %(cur_end)s) AS bounce_rate,
+ avgMergeIf(avg_bounce_state, time_window_start >= %(prev_start)s AND time_window_start < %(prev_end)s) AS previous_bounce_rate
+FROM {DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE()}
+WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s
+"""
+
+
+_READ_SETTINGS = {
+ # Approach E from `products/analytics_platform/backend/lazy_computation/CONSISTENCY.md`:
+ # both INSERT (via `_get_insert_settings`) and SELECT use `in_order` so they
+ # deterministically prefer the same replica. Combined with the global
+ # `distributed_foreground_insert=1`, the SELECT sees data the INSERT just wrote.
+ #
+ # `select_sequential_consistency=1` was tried here and is documented broken in
+ # CONSISTENCY.md when combined with `insert_quorum_parallel=1` (the default).
+ "load_balancing": "in_order",
+ # Shard pruning: sharding key is `sipHash64(job_id)`; `job_id IN (...)` matches
+ # exactly the shards we wrote to.
+ "optimize_skip_unused_shards": 1,
+}
+
+
+def execute_read_query(
+ *,
+ team_id: int,
+ job_ids: list[str],
+ current_start_utc: datetime,
+ current_end_utc: datetime,
+ previous_start_utc: Optional[datetime],
+ previous_end_utc: Optional[datetime],
+) -> list:
+ """Run the precompute-read SQL via `sync_execute`.
+
+ Bypasses HogQL so we can set `select_sequential_consistency=1` on the SELECT —
+ HogQLGlobalSettings forbids extra keys, and the read query shape is stable
+ enough that string parameterization is appropriate.
+ """
+ # Sentinel for the no-compare case: an unsatisfiable window so the *MergeIf
+ # aggregates return 0 / NaN 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)
+
+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY, query_type="web_overview_lazy_query")
+ return sync_execute(
+ _READ_SQL,
+ {
+ "team_id": team_id,
+ "job_ids": tuple(str(jid) for jid in job_ids),
+ "cur_start": current_start_utc,
+ "cur_end": current_end_utc,
+ "prev_start": prev_start,
+ "prev_end": prev_end,
+ },
+ settings=_READ_SETTINGS,
+ team_id=team_id,
+ )
+
+
+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
+ # response gets fully populated from the read query, so this default is only
+ # used for genuinely empty windows.
+ return [0, None, 0, None, 0, None, 0, None, 0, None]
+
+
+def execute_lazy_precomputed_read(
+ runner: "WebOverviewQueryRunner",
+) -> Optional[list]:
+ """Orchestrate the lazy precompute + read. Returns the response row, or None
+ on any failure (caller falls through to the v2/raw path)."""
+ # Tag the whole lazy path (INSERT + read) with product/feature so the INSERT
+ # `sync_execute` inside `ensure_web_overview_precomputed` doesn't trip
+ # DEBUG-mode `UntaggedQueryError`. The read query overrides `query_type`
+ # later via `tag_queries(...)` inside `execute_read_query`.
+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)
+ team_id = runner.team.pk
+ overall_started = time.perf_counter()
+ try:
+ date_from = runner.query_date_range.date_from()
+ date_to = runner.query_date_range.date_to()
+ assert date_from is not None and date_to is not None
+
+ # Convert team-tz bounds to tz-aware UTC. We keep `tzinfo` so the HogQL
+ # printer doesn't fall back to host-local timezone interpretation when
+ # escaping the datetime constants in the filter.
+ current_start_utc = date_from.astimezone(UTC)
+ current_end_utc = date_to.astimezone(UTC)
+
+ # Expand the precompute span to UTC day boundaries so the framework's
+ # daily-window jobs fully cover the team-tz request. 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)
+
+ if time_range_start >= time_range_end:
+ logger.info(
+ "web_overview_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_overview_lazy_precompute_started",
+ team_id=team_id,
+ time_range_start=time_range_start.isoformat(),
+ time_range_end=time_range_end.isoformat(),
+ time_range_days=(time_range_end - time_range_start).days,
+ )
+
+ ensure_started = time.perf_counter()
+ result = ensure_web_overview_precomputed(
+ runner=runner,
+ time_range_start=time_range_start,
+ time_range_end=time_range_end,
+ )
+ ensure_duration_ms = int((time.perf_counter() - ensure_started) * 1000)
+
+ logger.info(
+ "web_overview_lazy_precompute_ensure_done",
+ team_id=team_id,
+ job_count=len(result.job_ids),
+ ensure_duration_ms=ensure_duration_ms,
+ )
+
+ if not result.job_ids:
+ return None
+
+ if not result.ready:
+ logger.info(
+ "web_overview_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
+ # 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)
+ if prev_range_start < prev_range_end:
+ prev_ensure_started = time.perf_counter()
+ prev_result = ensure_web_overview_precomputed(
+ runner=runner,
+ time_range_start=prev_range_start,
+ time_range_end=prev_range_end,
+ )
+ ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)
+
+ if not prev_result.ready:
+ logger.info(
+ "web_overview_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)
+
+ read_started = time.perf_counter()
+ rows = execute_read_query(
+ team_id=team_id,
+ 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,
+ )
+ read_duration_ms = int((time.perf_counter() - read_started) * 1000)
+ total_duration_ms = int((time.perf_counter() - overall_started) * 1000)
+
+ logger.info(
+ "web_overview_lazy_precompute_completed",
+ team_id=team_id,
+ job_count=len(result.job_ids),
+ rows_returned=len(rows) if rows else 0,
+ ensure_duration_ms=ensure_duration_ms,
+ read_duration_ms=read_duration_ms,
+ total_duration_ms=total_duration_ms,
+ )
+ if not rows:
+ return _empty_response_row()
+ return list(rows[0])
+ except Exception as exc:
+ WEB_OVERVIEW_LAZY_FAILED.labels(error_type=type(exc).__name__).inc()
+ logger.exception(
+ "web_overview_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/posthog/schema.py b/posthog/schema.py
index 22cafc21e24a..420a4f544ccc 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -9287,6 +9287,7 @@ class WebOverviewQueryResponse(BaseModel):
default=None,
description=("Measured timings for different parts of the query generation process"),
)
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -12701,6 +12702,7 @@ class CachedWebOverviewQueryResponse(BaseModel):
default=None,
description=("Measured timings for different parts of the query generation process"),
)
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -13316,6 +13318,7 @@ class Response4(BaseModel):
default=None,
description=("Measured timings for different parts of the query generation process"),
)
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -16205,6 +16208,7 @@ class QueryResponseAlternative23(BaseModel):
default=None,
description=("Measured timings for different parts of the query generation process"),
)
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -16738,6 +16742,7 @@ class QueryResponseAlternative43(BaseModel):
default=None,
description=("Measured timings for different parts of the query generation process"),
)
+ usedLazyPrecompute: bool | None = None
usedPreAggregatedTables: bool | None = None
@@ -18693,6 +18698,14 @@ class WebOverviewQuery(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_overview_query precompute path."
+ " Requires the team to be in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS`"
+ " allowlist for the gate to pass. *"
+ ),
+ )
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index aca278bc6dfe..b8adb6977cbc 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -279,6 +279,11 @@ CONSTANCE_CONFIG = {
"Team IDs that use prefiltered events subqueries in web analytics bounce/scroll queries for better granule pruning",
list[int],
),
+ "WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS": (
+ get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS", default=[], type_cast=list[int]),
+ "Team IDs enrolled in the web_overview_query lazy precompute path. Admin-controlled rollout gate.",
+ list[int],
+ ),
}
SETTINGS_ALLOWING_API_OVERRIDE = (
@@ -328,6 +333,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = (
"CLICKHOUSE_KILL_SWITCH_FULL_TEAMS",
"CLICKHOUSE_HEDGED_APP_QUERIES",
"WEB_ANALYTICS_EVENTS_PREFILTER_TEAM_IDS",
+ "WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS",
"REDIRECT_APP_TO_US",
"WEB_ANALYTICS_WARMING_DAYS",
"WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT",
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 d8891b4dda8d..ef0123ffe7d0 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -276,6 +276,7 @@ class LazyComputationTable(StrEnum):
PREAGGREGATION_RESULTS = "preaggregation_results"
EXPERIMENT_EXPOSURES_PREAGGREGATED = "experiment_exposures_preaggregated"
EXPERIMENT_METRIC_EVENTS_PREAGGREGATED = "experiment_metric_events_preaggregated"
+ WEB_OVERVIEW_PREAGGREGATED = "web_overview_preaggregated"
# Tables where expires_at is a Date (not DateTime64). Date truncates to midnight,
@@ -931,6 +932,7 @@ def ensure_precomputed(
table: LazyComputationTable = LazyComputationTable.PREAGGREGATION_RESULTS,
placeholders: dict[str, ast.Expr] | None = None,
sentinel_placeholders: set[str] | None = None,
+ query_type: str | None = None,
) -> LazyComputationResult:
"""
Ensure lazy-computed data exists for the given query and time range.
@@ -1038,7 +1040,10 @@ def ensure_precomputed(
base_placeholders=base_placeholders,
)
set_ch_query_started(job.id)
- with tags_context(client_query_id=str(job.id), team_id=t.id):
+ tag_kwargs: dict = {"client_query_id": str(job.id), "team_id": t.id}
+ if query_type:
+ tag_kwargs["query_type"] = query_type
+ with tags_context(**tag_kwargs):
sync_execute(
insert_sql,
values,
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index e15521d79b0e..e6669e587162 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2815,6 +2815,7 @@ export interface WebOverviewQueryResponseApi {
samplingRate?: SamplingRateApi | null
/** Measured timings for different parts of the query generation process */
timings?: QueryTimingApi[] | null
+ usedLazyPrecompute?: boolean | null
usedPreAggregatedTables?: boolean | null
}
@@ -2847,6 +2848,8 @@ export interface WebOverviewQueryApi {
samplingFactor?: number | null
tags?: QueryLogTagsApi | null
useSessionsTable?: boolean | null
+ /** Opt this specific query into the web_overview_query precompute path. Requires the team to be in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` allowlist for the gate to pass. * */
+ useWebAnalyticsPrecompute?: boolean | null
/** version of the node, used for schema migrations */
version?: number | null
}
@@ -3058,6 +3061,7 @@ export interface Response4Api {
samplingRate?: SamplingRateApi | null
/** Measured timings for different parts of the query generation process */
timings?: QueryTimingApi[] | null
+ usedLazyPrecompute?: boolean | null
usedPreAggregatedTables?: boolean | null
}
diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.md
new file mode 100644
index 000000000000..3b368816434f
--- /dev/null
+++ b/products/web_analytics/PRECOMPUTATION.md
@@ -0,0 +1,158 @@
+# Web analytics precomputation
+
+PostHog web analytics has two parallel precomputation systems. They target the same problem (avoid scanning raw events on every dashboard load) but use different mechanisms and apply to different query shapes.
+
+## The two systems
+
+### v2 pre-aggregated tables
+
+DAG-warmed ClickHouse tables (`web_pre_aggregated_stats`, `web_pre_aggregated_bounces`) that store hourly-rollup data computed in the background. Gated per-team by the `useWebAnalyticsPreAggregatedTables` modifier plus the `SETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES` feature flag.
+
+- **Owned by**: web analytics team
+- **Population**: scheduled Dagster jobs in `products/web_analytics/dags/`
+- **Coverage**: stats table queries, web overview (partial)
+- **Adoption** (as of 2026-05): effectively zero — only one team has the modifier on in prod
+
+### Lazy computation
+
+The newer general-purpose framework at `products/analytics_platform/backend/lazy_computation/`. Computes precomputed buckets on first read, caches them in a dedicated CH table per query family, and serves subsequent reads from the cache. Gated per-team by `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` instance setting (defaults to empty).
+
+- **Owned by**: web analytics team, riding on the analytics_platform framework
+- **Population**: synchronous, on first read miss; subsequent reads hit the cache
+- **Coverage** (today): `web_overview_query` only — see `posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py`
+- **Adoption** (as of 2026-05): freshly enabled, allowlist gates further rollout
+
+## When to use which
+
+Both systems can coexist. The runner tries each in order; if both miss or are disabled the runner falls through to a raw events scan.
+
+| You want… | Use |
+| --------------------------------------------------------------------- | --------------------------------------------------- |
+| A new query family where the cache shape is bounded and stable | lazy computation |
+| Coverage of an existing query family that v2 already handles | v2 if a team already has v2 enabled; otherwise lazy |
+| Per-team custom precompute logic (uncommon) | lazy computation |
+| Background warming on a schedule | v2 |
+| First-read latency budget that includes a precompute cost (~1.3x raw) | lazy computation accepts this; v2 doesn't have it |
+
+## Lazy computation for web overview (current production path)
+
+`WebOverviewQueryRunner._calculate` runs three checks in order:
+
+1. **Lazy precompute** (`can_use_lazy_precompute` + `execute_lazy_precomputed_read`) — the path described below.
+2. **v2 pre-agg** (`get_pre_aggregated_response`) — the legacy path; falls through unless the team modifier is on.
+3. **Raw events scan** — the original path.
+
+### Schema
+
+`web_overview_preaggregated` (sharded by `sipHash64(job_id)`, partitioned by `toYYYYMMDD(expires_at)`, `ReplicatedReplacingMergeTree` with `computed_at` as the version column). Five aggregate state columns matching the runner's metric tuple:
+
+- `uniq_users_state AggregateFunction(uniq, UUID)` — unique persons (HLL ~99%)
+- `uniq_sessions_state AggregateFunction(uniq, String)` — unique sessions (HLL ~99%)
+- `sum_pageviews_state AggregateFunction(sum, Int64)` — pageviews/screens
+- `avg_duration_state AggregateFunction(avg, Float64)` — average session duration (seconds)
+- `avg_bounce_state AggregateFunction(avg, Int64)` — bounce rate (0/1 per session)
+
+Partition key on `expires_at` rather than `time_window_start` so `ttl_only_drop_parts=1` can drop expired parts atomically.
+
+### Bucketing and timezones
+
+Buckets are **UTC hourly**. The read converts the team's local request window to UTC and filters bucket boundaries on hour edges. This means:
+
+- **Whole-hour-offset timezones** (UTC, PT, ET, JST, etc. — ~99% of teams) read exact-to-the-hour data.
+- **Half-hour-offset timezones** (IST `+5:30`, Newfoundland `-3:30`, Nepal `+5:45`, Iran `+3:30`) cannot be served correctly by UTC hourly buckets — the `can_use_lazy_precompute` gate refuses them via `is_integer_timezone()`. They fall through to v2/raw.
+
+### Sessions that straddle bucket boundaries
+
+The framework chunks the precompute span into **daily UTC jobs**. Each job's INSERT scans `[time_window_min, time_window_max)` for events, groups by `session_id`, and emits one hourly bucket row per session, keyed on `toStartOfHour(min(session.$start_timestamp))`.
+
+A session that starts at 23:30 UTC with an event at 00:15 UTC the next day spans two daily jobs. Without help, the first job would only see the 23:30 event and miscount that session's pageviews.
+
+To fix this, the INSERT widens the event scan by `SESSION_BOUNDARY_PAD_MINUTES` (currently 60 min) on each side of the job's `[time_window_min, time_window_max)` window. The `HAVING` clause keeps each session attributed to its actual start hour — so over-scan adds INSERT cost but cannot produce duplicate rows in any bucket.
+
+The pad value is the maximum realistic session duration. PostHog sessions cap at ~30 min of inactivity, so 60 min is a 2x safety margin while keeping over-scan tiny (~5%, vs. the 200% cost of a full ±1 day pad).
+
+### Eligibility gate
+
+`can_use_lazy_precompute(runner)` in `web_overview_lazy_precompute.py`. Refuses when any of:
+
+- Team is not in `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS`
+- Team timezone has a non-whole-hour UTC offset
+- `query.conversionGoal` is set
+- `query.sampling.enabled` is True
+- `query.modifiers.sessionsV2JoinMode == "uuid"` (column type mismatch — temporary; should be re-enabled by re-typing `uniq_sessions_state` to `(uniq, UUID)`)
+- `query.properties` contains more than one filter
+- The single filter is not `EventPropertyFilter(key="$host", operator="exact", value=<non-empty string>)`
+- Date range exceeds `MAX_PRECOMPUTE_DAYS` (180)
+- Either date_from or date_to is None
+
+When the gate returns False the runner silently falls through to v2 / raw. **Today there is no telemetry on gate rejections** — operators tuning the rollout have to read the source to know why a team isn't seeing the lazy path. A `web_overview_lazy_gate_rejected_total{reason}` counter would close that gap (open issue).
+
+### TTL schedule
+
+Different freshness per how recent the data is:
+
+| Window | TTL | Rationale |
+| --------- | ------ | ----------------------------------------------- |
+| Today | 15 min | Dashboard refresh feels current |
+| Yesterday | 1 hr | Recently-stabilized data, occasional re-compute |
+| Last 7d | 1 day | Stable enough that hourly recompute is wasteful |
+| Older | 7 days | Functionally static |
+
+Stored via the `LAZY_TTL_SECONDS` dict; consumed by `lazy_computation_executor.parse_ttl_schedule` against the team's timezone.
+
+### Read path
+
+The read is a single `sync_execute` call (not HogQL — see "Why bypass HogQL" below). It computes the 5 metric pairs (current + previous period) via `*MergeIf` aggregates filtered by the team-tz date range converted to UTC. Settings:
+
+- `load_balancing="in_order"` — paired with the INSERT side's same setting for read-your-writes via Approach E in [CONSISTENCY.md](../../products/analytics_platform/backend/lazy_computation/CONSISTENCY.md).
+- `optimize_skip_unused_shards=1` — `job_id IN (...)` + sharding-by-`sipHash64(job_id)` lets ClickHouse prune to the right shards.
+
+Result is built into the standard `WebOverviewQueryResponse` via `_build_response_from_row`, with `usedPreAggregatedTables=True`.
+
+#### Why bypass HogQL
+
+HogQL `HogQLGlobalSettings` is `extra="forbid"`, so we couldn't get arbitrary CH settings (originally `select_sequential_consistency=1`, since dropped) through `execute_hogql_query`. The read query shape is stable enough that `sync_execute` with parameterized values is appropriate. The team_id WHERE clause is enforced manually (the HogQL printer's auto-injected `team_id_guard_for_table` is not applied for sync_execute).
+
+If we later move back to HogQL (after the consistency story is settled), the HogQL table registration at `posthog/hogql/database/schema/web_overview_preaggregated.py` is still present and ready.
+
+### Observability
+
+- **Read query**: tagged `query_type="web_overview_lazy_query"` in `system.query_log.log_comment`.
+- **INSERT query**: tagged `query_type="web_overview_lazy_insert"` (via the framework's `query_type` kwarg added in this commit family).
+- **Failures**: `web_overview_lazy_precompute_failed_total{error_type}` Prometheus counter (bounded by Python exception class).
+- **Cache warmer**: the DAG at `products/web_analytics/dags/cache_warming.py` recognizes both `web_overview_query` and `web_overview_lazy_query`.
+- **Adoption / latency**: see [`evaluating-web-analytics-performance`](https://github.com/PostHog/posthog/blob/master/.agents/skills/) or query `system.query_log` directly.
+
+### Known limitations / open issues
+
+1. **No gate-rejection telemetry** — operators can't see why a team isn't seeing the lazy path. Counter pending.
+2. **`error_type` Prometheus label is too coarse** — `ServerException` from CH could mean quorum / memory / schema. Should bucket by CH error code.
+3. **UUID session mode rejected**, not handled. Re-typing `uniq_sessions_state` to `(uniq, UUID)` would lift this; tracked as a follow-up.
+4. **Empty `*MergeIf` rows are treated as legitimate empty windows.** Empty `sync_execute` result on this query shape is almost always a driver/transport error rather than "no data"; should be treated as failure + fall through.
+5. **HogQL `top_level_settings`** on `WebOverviewPreaggregatedTable` is currently unused (read bypasses HogQL); kept as a hook if we re-route through HogQL later.
+
+## Adding lazy computation to another web analytics query family
+
+Reference implementation: `posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py`.
+
+Roughly:
+
+1. **Schema** — new CH table under `posthog/clickhouse/preaggregation/`. ReplacingMergeTree with `(team_id, job_id, time_window_start)` ORDER BY, sharded by `sipHash64(job_id)`, partitioned by `toYYYYMMDD(expires_at)`. Register in `posthog/clickhouse/schema.py` test fixtures.
+2. **Migration** — `posthog/clickhouse/migrations/0XXX_<name>.py`. Sharded + distributed CREATE on `NodeRole.DATA`.
+3. **HogQL table** — `posthog/hogql/database/schema/<name>.py`. Register in `posthog/hogql/database/database.py`.
+4. **`LazyComputationTable` enum** — add a value in `products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py`.
+5. **Insert query** — HogQL template using `{time_window_min}`/`{time_window_max}` placeholders. Add a session-boundary pad if the query has session-level joins.
+6. **Read** — `sync_execute` with parameterized SQL, settings = `{"load_balancing": "in_order", "optimize_skip_unused_shards": 1}`. Filter by `team_id` AND `job_id IN (...)` in the WHERE clause.
+7. **Runner integration** — add a `can_use_*` gate and an `execute_*_read` orchestrator; short-circuit in `_calculate` before the v2/raw fallthrough.
+8. **Tests** — round-trip (lazy == raw) parameterized over team timezones, gate fallthrough for each disqualifying condition, half-hour-offset fallthrough, cache hit (second call doesn't create new jobs).
+9. **Cache warmer** — add the new `query_type` to the warmer DAG's allowlist in `products/web_analytics/dags/cache_warming.py`.
+
+Roadmap order in `~/notes/work/posthog/web-analytics/investigations/2026-05-19-lazy-computation-candidates.md`: `web_overview_query` (shipped, this doc), `stats_table_main_query` (next), `stats_table_path_bounce_query` (after that), then `web_goals_query` deferred for custom-goal-definition complexity.
+
+## Related code
+
+- `posthog/hogql_queries/web_analytics/web_overview.py` — runner
+- `posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py` — lazy path implementation
+- `posthog/hogql_queries/web_analytics/web_overview_pre_aggregated.py` — v2 path
+- `posthog/clickhouse/preaggregation/web_overview_preaggregated_sql.py` — schema
+- `products/analytics_platform/backend/lazy_computation/` — framework + CONSISTENCY.md + README
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index 277803799bca..fb912c5704c8 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -83,6 +83,7 @@ def queries_to_keep_fresh(
'web_goals_query',
'web_overview_preaggregated_query',
'web_overview_query',
+ 'web_overview_lazy_query',
'web_vitals_path_breakdown_query',
'external_clicks_query'
)
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 6be7f836c659..a45b83f3b1f4 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2878,7 +2878,7 @@
},
"llma-personal-spend": {
"description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. Pass `product` (e.g. `posthog_code`, `background_agents`) to scope the tool / model / trace breakdowns to a single product; `by_product` always returns the cross-product view. Pass `refresh=true` to bypass the 5-minute cache.",
- "category": "LLM analytics",
+ "category": "AI observability",
"feature": "llm_analytics",
"summary": "Get my LLM spend analysis",
"title": "Get my LLM spend analysis",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index aa0758042481..db76287998fd 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3191,7 +3191,7 @@
},
"llma-personal-spend": {
"description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. Pass `product` (e.g. `posthog_code`, `background_agents`) to scope the tool / model / trace breakdowns to a single product; `by_product` always returns the cross-product view. Pass `refresh=true` to bypass the 5-minute cache.",
- "category": "LLM analytics",
+ "category": "AI observability",
"feature": "llm_analytics",
"summary": "Get my LLM spend analysis",
"title": "Get my LLM spend analysis",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c928f013d816..8f7f6872443d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2956,6 +2956,7 @@ export namespace Schemas {
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}
@@ -2983,6 +2984,8 @@ export namespace Schemas {
samplingFactor?: number | null;
tags?: QueryLogTags | null;
useSessionsTable?: boolean | null;
+ /** Opt this specific query into the web_overview_query precompute path. Requires the team to be in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` allowlist for the gate to pass. * */
+ useWebAnalyticsPrecompute?: boolean | null;
/** version of the node, used for schema migrations */
version?: number | null;
}
@@ -8958,6 +8961,7 @@ export namespace Schemas {
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}
@@ -33197,6 +33201,7 @@ export namespace Schemas {
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}
@@ -33571,6 +33576,7 @@ export namespace Schemas {
samplingRate?: SamplingRate | null;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
+ usedLazyPrecompute?: boolean | null;
usedPreAggregatedTables?: boolean | null;
}