:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): enroll v2 readers in dimensional precompute (#90374)
Lucas Ricoy474be7058924
diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 55802ed617a7..2e87e475c757 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -1,10 +1,11 @@# 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.+PostHog web analytics has two production precomputation systems, plus an experimental third (the dimensional tables).+They target the same problem (avoid scanning raw events on every dashboard load) but use different mechanisms and apply to different query shapes.For how these tiers fit into the full serving ladder (fast paths, full join, dispatch order, query_type tags), see [docs/internal/web-analytics-query-serving.md](../../docs/internal/web-analytics-query-serving.md).-## The two systems+## The systems### v2 pre-aggregated tables@@ -17,6 +18,34 @@ DAG-warmed ClickHouse tables (`web_pre_aggregated_stats`, `web_pre_aggregated_bo- **Coverage**: stats table queries, web overview (partial)- **Adoption** (as of 2026-05): effectively zero — only one team has the modifier on in prod+### Dimensional pre-aggregated tables (experimental)++**Status: experimental, write-only.**+The precomputation-framework successor to the v2 tables: an experiment in whether v2's fixed-dimension read model can run on the lazy-computation framework (per-team jobs + TTLs) instead of v2's staging-table + partition-swap ETL.+No read path is merged — the runner never reads these tables today (PR #62437, the read path, is closed).++Two ClickHouse tables carry the same fixed dimension set as v2 (`host`, `device_type`, `pathname`, `browser`, `os`, `viewport`, `referring_domain`, `utm_*`, geoip, …):++- `web_stats_dimensional_preaggregated` — stats (persons / sessions / pageviews states).+- `web_bounces_dimensional_preaggregated` — bounces (adds bounce / duration / session-count states).++Both are `ReplacingMergeTree` (version column `computed_at`), sharded by `sipHash64(job_id)` on the AUX cluster, partitioned by `toYYYYMMDD(expires_at)`.++- **Owned by**: web analytics team, on the analytics_platform framework.+- **Population**: the hourly `web_dimensional_precompute` Dagster job (`products/web_analytics/dags/web_dimensional_precompute.py`).+ For each team on a region-scoped allowlist it drives `ensure_precomputed` over a rolling 90-day window, chunked to one UTC day per INSERT.+ Every window is a `PreaggregationJob` (Postgres) with a `job_id` and a TTL by age (today 1h, ≤2 days 1 day, older 90 days); re-runs recompute only expired windows.+ The allowlist defaults per Cloud region (`DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION`) and is overridable via `WEB_DIMENSIONAL_PRECOMPUTE_TEAM_IDS`; an empty list disables the job.+- **Coverage**: the same stats-breakdown and overview shapes v2 serves — about 45% of user-facing web-analytics reads by shape (stats breakdowns on the stored dimensions, plus overview).+ Not goals, vitals, frustration metrics, external clicks, or the other engines (Trends / Retention / HogQL).+ Its differentiator over lazy: arbitrary multi-dimension filters within the fixed set resolve from one table, with no per-filter-combination warming.+- **Adoption**: none in prod — a write-only pilot for a v2 side-by-side.++Read-cost finding (2026-08): for clean single-generation reads these tables match v2 on rows and bytes (within ±7%) and use far less query memory.+Because `job_id` is in the `ORDER BY`, recompute generations never collapse, so a read spanning un-deduped generations inflates scan cost roughly linearly with the generation count — that, not the schema, is the historical "not as fast" result.+Reviving the read path needs precise ready-job filtering plus a way to collapse superseded generations.+Schema: `posthog/clickhouse/preaggregation/web_*_dimensional_preaggregated_sql.py`; INSERT templates: `products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py`.+### Lazy computationThe newer general-purpose framework at `products/analytics_platform/backend/lazy_computation/`. Builds precomputed buckets in the background, caches them in a dedicated CH table per query family, and serves reads from the cache; a user read that misses serves the live path and enqueues a debounced background warm. Gated per-org by the `web-analytics-precompute-toggle` PostHog feature flag (evaluated against the team's organization).diff --git a/products/web_analytics/dags/tests/test_web_dimensional_precompute.py b/products/web_analytics/dags/tests/test_web_dimensional_precompute.pyindex 96f756f9177b..9dec9ba6f905 100644--- a/products/web_analytics/dags/tests/test_web_dimensional_precompute.py+++ b/products/web_analytics/dags/tests/test_web_dimensional_precompute.py@@ -5,11 +5,12 @@ from posthog.test.base import APIBaseTestfrom unittest.mock import patchimport dagster+from parameterized import parameterizedfrom posthog.models import Organization, Teamfrom products.web_analytics.dags.web_dimensional_precompute import (- DEFAULT_ROLLOUT_TEAM_IDS,+ DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION,PRECOMPUTE_CHUNK_DAYS,PRECOMPUTE_WINDOW_DAYS,SELECTED_TEAM_IDS_ENV_VAR,@@ -20,6 +21,7 @@ from products.web_analytics.dags.web_dimensional_precompute import ()_IS_CLOUD = "products.web_analytics.dags.web_dimensional_precompute.is_cloud"+_CLOUD_DEPLOYMENT = "products.web_analytics.dags.web_dimensional_precompute.settings.CLOUD_DEPLOYMENT"# Patch chunking to a single chunk so call counts are deterministic in the op tests._SINGLE_CHUNK = "products.web_analytics.dags.web_dimensional_precompute.PRECOMPUTE_CHUNK_DAYS"@@ -62,10 +64,25 @@ class TestGetSelectedTeamIds:with patch(_IS_CLOUD, return_value=True), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):assert get_selected_team_ids() == []- def test_unset_uses_default_rollout_on_cloud(self):- with patch(_IS_CLOUD, return_value=True), patch.dict(os.environ, {}, clear=False):+ @parameterized.expand([("US",), ("EU",)])+ def test_unset_uses_region_default_on_cloud(self, region: str):+ with (+ patch(_IS_CLOUD, return_value=True),+ patch(_CLOUD_DEPLOYMENT, region),+ patch.dict(os.environ, {}, clear=False),+ ):os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)- assert get_selected_team_ids() == DEFAULT_ROLLOUT_TEAM_IDS+ assert get_selected_team_ids() == DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION[region]++ def test_unset_unknown_region_is_empty(self):+ # A region without a default entry must not fall back to another region's list.+ with (+ patch(_IS_CLOUD, return_value=True),+ patch(_CLOUD_DEPLOYMENT, "DEV"),+ patch.dict(os.environ, {}, clear=False),+ ):+ os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)+ assert get_selected_team_ids() == []def test_unset_is_empty_off_cloud(self):with patch(_IS_CLOUD, return_value=False), patch.dict(os.environ, {}, clear=False):diff --git a/products/web_analytics/dags/web_dimensional_precompute.py b/products/web_analytics/dags/web_dimensional_precompute.pyindex 6d43d12d6f09..df40f59ba758 100644--- a/products/web_analytics/dags/web_dimensional_precompute.py+++ b/products/web_analytics/dags/web_dimensional_precompute.py@@ -9,8 +9,8 @@ lazily on every user query, while re-runs are cheap because already-freshwindows are skipped.Rollout is intentionally decoupled from the v2 pre-aggregation pipeline and its-team selection. The audience defaults to a small built-in rollout list-(`DEFAULT_ROLLOUT_TEAM_IDS`) on PostHog Cloud, and is fully overridable via the+team selection. The audience defaults to a small per-region built-in rollout list+(`DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION`) on PostHog Cloud, and is fully overridable via the`WEB_DIMENSIONAL_PRECOMPUTE_TEAM_IDS` env var (comma-separated team IDs; set itto empty to disable the job). Self-hosted instances default to no teams so thejob never precomputes for unrelated teams that happen to share those IDs. There@@ -23,6 +23,8 @@ the tables (so the new output can be compared with v2's side by side).import osfrom datetime import UTC, datetime, timedelta+from django.conf import settings+import dagsterimport structlogfrom prometheus_client import Counter@@ -54,12 +56,18 @@ PRECOMPUTE_WINDOW_DAYS = int(os.getenv("WEB_DIMENSIONAL_PRECOMPUTE_WINDOW_DAYS",# trade more bytes/INSERT for fewer INSERTs on lower-volume teams.PRECOMPUTE_CHUNK_DAYS = int(os.getenv("WEB_DIMENSIONAL_PRECOMPUTE_CHUNK_DAYS", "1"))-# Built-in rollout audience used when the env var is unset: PostHog's internal-# dogfood project plus one high-volume pilot team, for the v2 side-by-side. Applied-# on PostHog Cloud only (see get_selected_team_ids).-DEFAULT_ROLLOUT_TEAM_IDS = [2, 55348]--# Comma-separated team IDs to precompute. Overrides DEFAULT_ROLLOUT_TEAM_IDS;+# Built-in rollout audience used when the env var is unset, keyed by Cloud region.+# Region-keyed because team IDs are not unique across US and EU — a single flat list+# would enroll an unrelated same-ID team in the other region. Applied on PostHog+# Cloud only (see get_selected_team_ids). US holds the dogfood project (2), the+# high-volume pilot (55348), and the teams currently reading the v2 tables, for the+# v2 side-by-side.+DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION: dict[str, list[int]] = {+ "US": [2, 39058, 47074, 55348],+ "EU": [1, 1589, 126918],+}++# Comma-separated team IDs to precompute. Overrides the per-region default;# set to empty to disable the job entirely.SELECTED_TEAM_IDS_ENV_VAR = "WEB_DIMENSIONAL_PRECOMPUTE_TEAM_IDS"@@ -68,14 +76,17 @@ def get_selected_team_ids() -> list[int]:"""Resolve the team allowlist.The env var wins if set (even to empty): a comma-separated list, blank/invalid- entries skipped. If unset, fall back to DEFAULT_ROLLOUT_TEAM_IDS — but only on- PostHog Cloud; self-hosted defaults to none so the job never runs for unrelated- teams that happen to share those IDs.+ entries skipped. If unset, fall back to the current region's default — but only+ on PostHog Cloud; self-hosted defaults to none so the job never runs for+ unrelated teams that happen to share those IDs."""raw = os.getenv(SELECTED_TEAM_IDS_ENV_VAR)- if raw is None:- return list(DEFAULT_ROLLOUT_TEAM_IDS) if is_cloud() else []- return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]+ if raw is not None:+ return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]+ if not is_cloud():+ return []+ region = (settings.CLOUD_DEPLOYMENT or "").upper()+ return list(DEFAULT_ROLLOUT_TEAM_IDS_BY_REGION.get(region, []))WEB_DIMENSIONAL_PRECOMPUTE_TEAM_DONE = Counter(