: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): add dimensional precomputed tables (#60558)
Lucas Ricoy9c474332329d
diff --git a/posthog/clickhouse/migrations/0272_web_dimensional_preaggregated.py b/posthog/clickhouse/migrations/0272_web_dimensional_preaggregated.pynew file mode 100644index 000000000000..1246335d4548--- /dev/null+++ b/posthog/clickhouse/migrations/0272_web_dimensional_preaggregated.py@@ -0,0 +1,45 @@+from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from posthog.clickhouse.preaggregation.web_bounces_dimensional_preaggregated_sql import (+ DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+)+from posthog.clickhouse.preaggregation.web_stats_dimensional_preaggregated_sql import (+ DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+)++operations = [+ # Sharded data tables on AUX (small fixed-dimension precompute tables, never+ # JOINed against events — kept off the main DATA cluster to avoid contention).+ run_sql_with_exceptions(+ SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ sharded=True,+ ),+ run_sql_with_exceptions(+ SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ sharded=True,+ ),+ # Distributed read tables on DATA — production query path fans out from data+ # nodes and resolves to AUX shards via the Distributed engine's `cluster=AUX`.+ run_sql_with_exceptions(+ DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.DATA],+ ),+ run_sql_with_exceptions(+ DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.DATA],+ ),+ # Same distributed tables on AUX too, for ad-hoc debugging directly from an+ # AUX node (same DDL, no production cost).+ run_sql_with_exceptions(+ DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ ),+ run_sql_with_exceptions(+ DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ ),+]diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txtindex 21d6967d8d1f..9bda31f62fe0 100644--- a/posthog/clickhouse/migrations/max_migration.txt+++ b/posthog/clickhouse/migrations/max_migration.txt@@ -1 +1 @@-0271_marketing_touchpoints_preaggregated+0272_web_dimensional_preaggregateddiff --git a/posthog/clickhouse/preaggregation/web_bounces_dimensional_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_bounces_dimensional_preaggregated_sql.pynew file mode 100644index 000000000000..d8a5b7491dea--- /dev/null+++ b/posthog/clickhouse/preaggregation/web_bounces_dimensional_preaggregated_sql.py@@ -0,0 +1,144 @@+# Table for storing scheduled-precomputed web bounce metrics with fixed dimensions.+#+# Precomputation-framework successor to the v2 pre-aggregation table+# `web_pre_aggregated_bounces`. Same fixed dimension set as the stats table minus+# `pathname` (bounces are attributed per session, not per pathname), plus the+# bounce/duration/session-count aggregate states. See+# `web_stats_dimensional_preaggregated_sql.py` for the framework column-injection+# notes (team_id/job_id/expires_at are added automatically; computed_at defaults).++from django.conf import settings++from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme++TABLE_BASE_NAME = "web_bounces_dimensional_preaggregated"+++def DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE():+ return TABLE_BASE_NAME+++def SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE():+ return f"sharded_{TABLE_BASE_NAME}"+++def SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_ENGINE():+ return ReplacingMergeTree(TABLE_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")+++WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_BASE_SQL = """+CREATE TABLE IF NOT EXISTS {table_name}+(+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches v2 `period_bucket`).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_bounces`.+ host String,+ device_type String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states for bounce-rate and session-duration metrics.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),+ bounces_count_state AggregateFunction(sum, Int64),+ total_session_duration_state AggregateFunction(sum, Int64),+ total_session_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+) ENGINE = {engine}+"""+++def SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ # See the stats table for the partitioning / ORDER BY / nullable-key rationale.+ return (+ WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_BASE_SQL+ + """+PARTITION BY toYYYYMMDD(expires_at)+ORDER BY (+ team_id,+ job_id,+ period_bucket,+ host,+ device_type,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+)+TTL toDateTime(expires_at)+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1, allow_nullable_key = 1+"""+ ).format(+ table_name=SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE(),+ engine=SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_ENGINE(),+ )+++def DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ return WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_BASE_SQL.format(+ table_name=DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE(),+ engine=Distributed(+ data_table=SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE(),+ sharding_key="sipHash64(job_id)",+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ ),+ )+++def DROP_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE()}"+++def DROP_SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE()} SYNC"+++def TRUNCATE_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE()}"diff --git a/posthog/clickhouse/preaggregation/web_stats_dimensional_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_stats_dimensional_preaggregated_sql.pynew file mode 100644index 000000000000..dbda119006cc--- /dev/null+++ b/posthog/clickhouse/preaggregation/web_stats_dimensional_preaggregated_sql.py@@ -0,0 +1,158 @@+# Table for storing scheduled-precomputed web stats with fixed dimensions.+#+# This is the precomputation-framework successor to the v2 pre-aggregation table+# `web_pre_aggregated_stats`. It carries the same fixed dimension set (host,+# device_type, pathname, browser, os, utm_*, geoip, …) baked into the schema, so+# reads answer breakdowns without filtering raw sessions/events. Unlike v2 it is+# populated through `ensure_precomputed` (job_id + TTL + ReplacingMergeTree)+# rather than a staging-table + partition-swap ETL, which removes the per-team+# backfill dance.+#+# The framework auto-injects `team_id` (first column), `job_id` (second) and+# `expires_at` (last) into every INSERT, and `computed_at` defaults on insert —+# so the INSERT SELECT only emits `period_bucket`, the dimensions and the+# aggregate states. INSERTs match columns by name, so table column order is free.++from django.conf import settings++from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme++TABLE_BASE_NAME = "web_stats_dimensional_preaggregated"+++def DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE():+ return TABLE_BASE_NAME+++def SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE():+ return f"sharded_{TABLE_BASE_NAME}"+++def SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_ENGINE():+ return ReplacingMergeTree(TABLE_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")+++WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_BASE_SQL = """+CREATE TABLE IF NOT EXISTS {table_name}+(+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches the v2+ -- pre-aggregation `period_bucket`). Reads filter by [window_start, window_end).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_stats`.+ host String,+ device_type String,+ pathname String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states: unique persons, unique sessions and total pageviews.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+) ENGINE = {engine}+"""+++def SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ # Partition by `expires_at` (the TTL column) so `ttl_only_drop_parts=1` drops+ # whole parts atomically once all their rows expire. `job_id` is in ORDER BY+ # so distinct compute jobs coexist (the read path filters to the fresh+ # job_ids); every dimension is in ORDER BY so the ReplacingMergeTree never+ # collapses rows that differ only by a dimension. `allow_nullable_key=1` lets+ # the nullable EU metadata columns participate in the sort key.+ return (+ WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_BASE_SQL+ + """+PARTITION BY toYYYYMMDD(expires_at)+ORDER BY (+ team_id,+ job_id,+ period_bucket,+ host,+ device_type,+ pathname,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+)+TTL toDateTime(expires_at)+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1, allow_nullable_key = 1+"""+ ).format(+ table_name=SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE(),+ engine=SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_ENGINE(),+ )+++def DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ # The sharded table lives on the AUX cluster (kept off the main events data+ # nodes — small table, never JOINed against events). Distributed read table+ # lives on DATA so queries fan out from there and resolve to AUX shards.+ return WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_BASE_SQL.format(+ table_name=DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE(),+ engine=Distributed(+ data_table=SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE(),+ sharding_key="sipHash64(job_id)",+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ ),+ )+++def DROP_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE()}"+++def DROP_SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE()} SYNC"+++def TRUNCATE_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL():+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE()}"diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex 496b64b00d15..f06c3591147e 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -53,10 +53,18 @@ from posthog.clickhouse.preaggregation.sql import (DISTRIBUTED_PREAGGREGATION_RESULTS_TABLE_SQL,SHARDED_PREAGGREGATION_RESULTS_TABLE_SQL,)+from posthog.clickhouse.preaggregation.web_bounces_dimensional_preaggregated_sql import (+ DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_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.preaggregation.web_stats_dimensional_preaggregated_sql import (+ DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+)from posthog.clickhouse.preaggregation.web_stats_preaggregated_sql import (DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,@@ -323,6 +331,8 @@ CREATE_MERGETREE_TABLE_QUERIES = (SHARDED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,SHARDED_WEB_STATS_PREAGGREGATED_TABLE_SQL,SHARDED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+ SHARDED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,DISTINCT_ID_USAGE_DATA_TABLE_SQL,PROPERTY_DEFINITIONS_TABLE_SQL,*[table.sharded_table_sql for table in EMBEDDING_TABLES],@@ -384,6 +394,8 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE_SQL,DISTRIBUTED_WEB_STATS_PREAGGREGATED_TABLE_SQL,DISTRIBUTED_WEB_VITALS_PATHS_PREAGGREGATED_TABLE_SQL,+ DISTRIBUTED_WEB_STATS_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,+ DISTRIBUTED_WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED_TABLE_SQL,DOCUMENT_EMBEDDINGS_BUFFER_WRITABLE_TABLE_SQL,*[table.distributed_table_sql for table in EMBEDDING_TABLES],*[table.writable_table_sql for table in EMBEDDING_TABLES],diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex e0abbf4cb92a..988efed78289 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -6265,6 +6265,92 @@'''# ---+# name: test_create_table_query[sharded_web_bounces_dimensional_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_web_bounces_dimensional_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches v2 `period_bucket`).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_bounces`.+ host String,+ device_type String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states for bounce-rate and session-duration metrics.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),+ bounces_count_state AggregateFunction(sum, Int64),+ total_session_duration_state AggregateFunction(sum, Int64),+ total_session_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.web_bounces_dimensional_preaggregated', '{replica}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (+ team_id,+ job_id,+ period_bucket,+ host,+ device_type,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+ )+ TTL toDateTime(expires_at)+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1, allow_nullable_key = 1++ '''+# ---# name: test_create_table_query[sharded_web_overview_preaggregated]'''@@ -6300,6 +6386,92 @@'''# ---+# name: test_create_table_query[sharded_web_stats_dimensional_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_web_stats_dimensional_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches the v2+ -- pre-aggregation `period_bucket`). Reads filter by [window_start, window_end).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_stats`.+ host String,+ device_type String,+ pathname String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states: unique persons, unique sessions and total pageviews.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.web_stats_dimensional_preaggregated', '{replica}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (+ team_id,+ job_id,+ period_bucket,+ host,+ device_type,+ pathname,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+ )+ TTL toDateTime(expires_at)+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1, allow_nullable_key = 1++ '''+# ---# name: test_create_table_query[sharded_web_stats_preaggregated]'''@@ -6423,6 +6595,60 @@'''# ---+# name: test_create_table_query[web_bounces_dimensional_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS web_bounces_dimensional_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches v2 `period_bucket`).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_bounces`.+ host String,+ device_type String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states for bounce-rate and session-duration metrics.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),+ bounces_count_state AggregateFunction(sum, Int64),+ total_session_duration_state AggregateFunction(sum, Int64),+ total_session_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = Distributed('aux', 'posthog_test', 'sharded_web_bounces_dimensional_preaggregated', sipHash64(job_id))++ '''+# ---# name: test_create_table_query[web_overview_preaggregated]'''@@ -6592,6 +6818,59 @@'''# ---+# name: test_create_table_query[web_stats_dimensional_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS web_stats_dimensional_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches the v2+ -- pre-aggregation `period_bucket`). Reads filter by [window_start, window_end).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_stats`.+ host String,+ device_type String,+ pathname String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states: unique persons, unique sessions and total pageviews.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = Distributed('aux', 'posthog_test', 'sharded_web_stats_dimensional_preaggregated', sipHash64(job_id))++ '''+# ---# name: test_create_table_query[web_stats_preaggregated]'''@@ -9777,6 +10056,92 @@'''# ---+# name: test_create_table_query_replicated_and_storage[sharded_web_bounces_dimensional_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_web_bounces_dimensional_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches v2 `period_bucket`).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_bounces`.+ host String,+ device_type String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states for bounce-rate and session-duration metrics.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),+ bounces_count_state AggregateFunction(sum, Int64),+ total_session_duration_state AggregateFunction(sum, Int64),+ total_session_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.web_bounces_dimensional_preaggregated', '{replica}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (+ team_id,+ job_id,+ period_bucket,+ host,+ device_type,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+ )+ TTL toDateTime(expires_at)+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1, allow_nullable_key = 1++ '''+# ---# name: test_create_table_query_replicated_and_storage[sharded_web_overview_preaggregated]'''@@ -9812,6 +10177,92 @@'''# ---+# name: test_create_table_query_replicated_and_storage[sharded_web_stats_dimensional_preaggregated]+ '''++ CREATE TABLE IF NOT EXISTS sharded_web_stats_dimensional_preaggregated+ (+ team_id Int64,+ job_id UUID,++ -- Hourly UTC bucket on the session's start timestamp (matches the v2+ -- pre-aggregation `period_bucket`). Reads filter by [window_start, window_end).+ period_bucket DateTime,++ -- Fixed dimensions — identical set to v2 `web_pre_aggregated_stats`.+ host String,+ device_type String,+ pathname String,+ entry_pathname String,+ end_pathname String,+ browser String,+ os String,+ viewport_width Int64,+ viewport_height Int64,+ referring_domain String,+ utm_source String,+ utm_medium String,+ utm_campaign String,+ utm_term String,+ utm_content String,+ country_code String,+ city_name String,+ region_code String,+ region_name String,+ has_gclid Bool,+ has_gad_source_paid_search Bool,+ has_fbclid Bool,+ -- EU-only custom metadata; NULL on US. Nullable so the US INSERT can emit NULL.+ mat_metadata_backend Nullable(String),+ mat_metadata_loggedIn Nullable(Bool),++ -- Aggregate states: unique persons, unique sessions and total pageviews.+ persons_uniq_state AggregateFunction(uniq, UUID),+ sessions_uniq_state AggregateFunction(uniq, String),+ pageviews_count_state AggregateFunction(sum, Int64),++ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.+ computed_at DateTime64(6, 'UTC') DEFAULT now(),++ -- Sub-day precision so the framework can attach short TTLs to recent windows.+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.web_stats_dimensional_preaggregated', '{replica}', computed_at)++ PARTITION BY toYYYYMMDD(expires_at)+ ORDER BY (+ team_id,+ job_id,+ period_bucket,+ host,+ device_type,+ pathname,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+ )+ TTL toDateTime(expires_at)+ SETTINGS index_granularity=8192, ttl_only_drop_parts = 1, allow_nullable_key = 1++ '''+# ---# name: test_create_table_query_replicated_and_storage[sharded_web_stats_preaggregated]'''diff --git a/posthog/dags/locations/web_analytics.py b/posthog/dags/locations/web_analytics.pyindex 05c4f49dfd40..65bf553655de 100644--- a/posthog/dags/locations/web_analytics.py+++ b/posthog/dags/locations/web_analytics.py@@ -7,6 +7,7 @@ from products.web_analytics.dags import (cache_warming,eager_web_analytics_precompute,web_analytics_watchdog,+ web_dimensional_precompute,web_pre_aggregated_accuracy,web_preaggregated,web_preaggregated_asset_checks,@@ -22,6 +23,7 @@ schedules = [web_preaggregated_team_selection.web_analytics_team_candidates_schedule,cache_warming.web_analytics_cache_warming_schedule,eager_web_analytics_precompute.web_analytics_eager_baseline_warming_schedule,+ web_dimensional_precompute.web_dimensional_precompute_schedule,cache_favicons.cache_authorized_domain_favicons_schedule,web_analytics_watchdog.web_analytics_watchdog_schedule,]@@ -51,6 +53,7 @@ defs = dagster.Definitions(web_analytics_watchdog.web_analytics_watchdog_job,cache_warming.web_analytics_cache_warming_job,eager_web_analytics_precompute.web_analytics_eager_baseline_warming_job,+ web_dimensional_precompute.web_dimensional_precompute_job,cache_favicons.cache_authorized_domain_favicons_job,],schedules=schedules,diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 3816e5052a43..e0ad044f1251 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -320,6 +320,10 @@ class LazyComputationTable(StrEnum):WEB_VITALS_PATHS_PREAGGREGATED = "web_vitals_paths_preaggregated"WEB_STATS_FRUSTRATION_PREAGGREGATED = "web_stats_frustration_preaggregated"WEB_GOALS_PREAGGREGATED = "web_goals_preaggregated"+ # Fixed-dimension tables driven by the scheduled web_dimensional_precompute+ # Dagster job (the precomputation-framework successor to v2 pre-aggregation).+ WEB_STATS_DIMENSIONAL_PREAGGREGATED = "web_stats_dimensional_preaggregated"+ WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED = "web_bounces_dimensional_preaggregated"# Tables where expires_at is a Date (not DateTime64). Date truncates to midnight,diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.pynew file mode 100644index 000000000000..477e6275d101--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute.py@@ -0,0 +1,304 @@+from datetime import UTC, datetime, timedelta++import unittest+from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person++from django.test import override_settings++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.clickhouse.client import sync_execute+from posthog.models.utils import uuid7++from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ find_missing_contiguous_windows,+ parse_ttl_schedule,+ split_ranges_by_ttl,+)+from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.web_analytics.backend.hogql_queries.web_dimensional_precompute import (+ BOUNCES_INSERT_TEMPLATE,+ DIMENSIONAL_TTL_SECONDS,+ STATS_INSERT_TEMPLATE,+ _base_placeholders,+ ensure_web_bounces_dimensional_precomputed,+ ensure_web_stats_dimensional_precomputed,+)++WINDOW_START = datetime(2024, 1, 1, tzinfo=UTC)+WINDOW_END = datetime(2024, 1, 8, tzinfo=UTC)+++@override_settings(IN_UNIT_TESTING=True)+class TestWebDimensionalPrecompute(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()+ # Rows are born expired against the real CH clock (expires_at derives from+ # the frozen test clock), so stop TTL merges to keep parts between INSERT+ # and read — same guard the lazy precompute tests use.+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_stats_dimensional_preaggregated")+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_bounces_dimensional_preaggregated")++ def _seed_two_sessions(self) -> None:+ # p1: two pageviews on example.com in one session. p2: one pageview on other.com.+ 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 _job_ids_tuple(self, result) -> str:+ return "(" + ", ".join(f"'{jid}'" for jid in result.job_ids) + ")"++ def _read_stats_totals(self, result) -> tuple[int, int, int]:+ rows = sync_execute(+ f"""+ SELECT+ uniqMerge(persons_uniq_state),+ uniqMerge(sessions_uniq_state),+ sumMerge(pageviews_count_state)+ FROM web_stats_dimensional_preaggregated+ WHERE team_id = %(team_id)s AND job_id IN {self._job_ids_tuple(result)}+ """,+ {"team_id": self.team.pk},+ )+ return int(rows[0][0]), int(rows[0][1]), int(rows[0][2])++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stats_ensure_creates_jobs_and_correct_totals(self):+ self._seed_two_sessions()+ result = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)++ assert result.ready+ assert len(result.job_ids) > 0+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == len(result.job_ids)++ persons, sessions, pageviews = self._read_stats_totals(result)+ assert persons == 2+ assert sessions == 2+ assert pageviews == 3++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stats_breaks_down_by_host(self):+ self._seed_two_sessions()+ result = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)++ rows = sync_execute(+ f"""+ SELECT+ host,+ uniqMerge(persons_uniq_state) AS persons,+ uniqMerge(sessions_uniq_state) AS sessions,+ sumMerge(pageviews_count_state) AS pageviews+ FROM web_stats_dimensional_preaggregated+ WHERE team_id = %(team_id)s AND job_id IN {self._job_ids_tuple(result)}+ GROUP BY host+ ORDER BY host+ """,+ {"team_id": self.team.pk},+ )+ by_host = {row[0]: (int(row[1]), int(row[2]), int(row[3])) for row in rows}+ assert by_host["example.com"] == (1, 1, 2)+ assert by_host["other.com"] == (1, 1, 1)++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stats_second_call_is_cache_hit(self):+ self._seed_two_sessions()+ first = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)+ jobs_after_first = PreaggregationJob.objects.filter(team_id=self.team.pk).count()++ second = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)+ jobs_after_second = PreaggregationJob.objects.filter(team_id=self.team.pk).count()++ assert second.ready+ # No new jobs created — the window is already fresh.+ assert jobs_after_second == jobs_after_first+ assert set(second.job_ids) == set(first.job_ids)++ @freeze_time("2024-01-15T12:00:00Z")+ def test_bounces_ensure_creates_jobs_and_correct_totals(self):+ self._seed_two_sessions()+ result = ensure_web_bounces_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)++ assert result.ready+ assert len(result.job_ids) > 0++ rows = sync_execute(+ f"""+ SELECT+ uniqMerge(persons_uniq_state),+ uniqMerge(sessions_uniq_state),+ sumMerge(pageviews_count_state),+ sumMerge(bounces_count_state),+ sumMerge(total_session_count_state)+ FROM web_bounces_dimensional_preaggregated+ WHERE team_id = %(team_id)s AND job_id IN {self._job_ids_tuple(result)}+ """,+ {"team_id": self.team.pk},+ )+ persons, sessions, pageviews, bounces, total_sessions = (int(v) for v in rows[0])+ assert persons == 2+ assert sessions == 2+ assert pageviews == 3+ assert total_sessions == 2+ # Bounce semantics depend on the session table; just assert it's in range.+ assert 0 <= bounces <= 2++ @freeze_time("2024-01-15T12:00:00Z")+ def test_separate_chunks_share_one_query_hash_and_read_reassembles_window(self):+ # Two events in two different 7-day chunks of the same window.+ _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-03T10:00:00Z", # older chunk+ properties={"$session_id": str(uuid7("2024-01-03")), "$host": "example.com"},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p2",+ timestamp="2024-01-10T10:00:00Z", # newer chunk+ properties={"$session_id": str(uuid7("2024-01-10")), "$host": "example.com"},+ )++ chunk_older = ensure_web_stats_dimensional_precomputed(+ self.team, datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC)+ )+ chunk_newer = ensure_web_stats_dimensional_precomputed(+ self.team, datetime(2024, 1, 8, tzinfo=UTC), datetime(2024, 1, 15, tzinfo=UTC)+ )+ assert chunk_older.ready and chunk_newer.ready++ # 1. Every chunk shares ONE cache key (time range is excluded from the hash).+ distinct_hashes = PreaggregationJob.objects.filter(team_id=self.team.pk).values("query_hash").distinct()+ assert distinct_hashes.count() == 1++ # 2/3. A read over the union of all chunk job_ids reassembles the full window.+ all_ids = "(" + ", ".join(f"'{jid}'" for jid in [*chunk_older.job_ids, *chunk_newer.job_ids]) + ")"+ rows = sync_execute(+ f"""+ SELECT uniqMerge(persons_uniq_state), uniqMerge(sessions_uniq_state), sumMerge(pageviews_count_state)+ FROM web_stats_dimensional_preaggregated+ WHERE team_id = %(team_id)s AND job_id IN {all_ids}+ """,+ {"team_id": self.team.pk},+ )+ persons, sessions, pageviews = (int(v) for v in rows[0])+ assert (persons, sessions, pageviews) == (2, 2, 2) # one event in each chunk, merged+++class TestWebDimensionalPrecomputeTemplates(unittest.TestCase):+ """Pure HogQL-parse checks — no DB/ClickHouse, so they validate the templates+ even without a running stack."""++ def _placeholders(self) -> dict[str, ast.Expr]:+ # Mirror what ensure_precomputed supplies: caller placeholders plus the+ # framework-managed time window sentinels.+ return {+ **_base_placeholders(),+ "time_window_min": ast.Constant(value="__MIN__"),+ "time_window_max": ast.Constant(value="__MAX__"),+ }++ def test_templates_parse_and_alias_every_top_level_column(self):+ # The framework requires every top-level SELECT expression to be aliased+ # (it derives the INSERT column list from the aliases), and the only+ # unbound placeholders may be time_window_min/max.+ for template in (STATS_INSERT_TEMPLATE, BOUNCES_INSERT_TEMPLATE):+ query = parse_select(template, placeholders=self._placeholders())+ assert isinstance(query, ast.SelectQuery)+ assert query.select+ assert all(isinstance(expr, ast.Alias) for expr in query.select)++ def test_stats_and_bounces_emit_expected_aggregate_columns(self):+ stats = parse_select(STATS_INSERT_TEMPLATE, placeholders=self._placeholders())+ bounces = parse_select(BOUNCES_INSERT_TEMPLATE, placeholders=self._placeholders())+ assert isinstance(stats, ast.SelectQuery) and isinstance(bounces, ast.SelectQuery)+ stats_aliases = {expr.alias for expr in stats.select if isinstance(expr, ast.Alias)}+ bounces_aliases = {expr.alias for expr in bounces.select if isinstance(expr, ast.Alias)}+ assert {"persons_uniq_state", "sessions_uniq_state", "pageviews_count_state"}.issubset(stats_aliases)+ assert {+ "persons_uniq_state",+ "sessions_uniq_state",+ "pageviews_count_state",+ "bounces_count_state",+ "total_session_duration_state",+ "total_session_count_state",+ }.issubset(bounces_aliases)+ # Stats is per-pathname; bounces has no pathname dimension.+ assert "pathname" in stats_aliases+ assert "pathname" not in bounces_aliases+++class TestColdBackfillSplitsByTtlBandNotPerDay(unittest.TestCase):+ """A cold N-day request does NOT issue one INSERT per day.++ `find_missing_contiguous_windows` merges all missing days into a single+ contiguous range; `split_ranges_by_ttl` then cuts that range only at the+ TTL-band cutoffs. So the number of INSERTs equals the number of TTL bands the+ window spans (a handful), and the bulk of history is one big INSERT — not 90.+ """++ @freeze_time("2024-06-15T12:00:00Z")+ def test_dimensional_schedule_90d_cold_range_is_three_bands(self):+ end = datetime(2024, 6, 15, 12, tzinfo=UTC)+ start = end - timedelta(days=90)++ # Cold cache (no existing jobs) -> a single contiguous missing range.+ missing = find_missing_contiguous_windows([], start, end)+ assert len(missing) == 1++ bands = split_ranges_by_ttl(missing, parse_ttl_schedule(DIMENSIONAL_TTL_SECONDS, team_timezone="UTC"))++ # DIMENSIONAL_TTL_SECONDS has 3 entries (0d / 2d / default) -> 3 INSERTs,+ # oldest first. NOT 90.+ ttls = [ttl for _s, _e, ttl in bands]+ assert ttls == [90 * 86400, 86400, 3600]++ # The bulk of history is ONE query covering many days, not one-per-day.+ oldest_start, oldest_end, _ = bands[0]+ assert (oldest_end - oldest_start).days >= 60++ # Bands tile the window contiguously and cover the whole ~90 days.+ for (_s1, e1, _t1), (s2, _e2, _t2) in zip(bands, bands[1:]):+ assert e1 == s2+ assert sum((e - s).days for s, e, _ in bands) >= 90++ @freeze_time("2024-06-15T12:00:00Z")+ def test_today_yesterday_7d_rest_schedule_is_four_bands(self):+ # The exact schedule shape described in review: today / yesterday / last+ # 7 days / the rest -> four INSERTs for a cold 90-day range.+ end = datetime(2024, 6, 15, 12, tzinfo=UTC)+ start = end - timedelta(days=90)+ schedule = parse_ttl_schedule(+ {"0d": 15 * 60, "1d": 60 * 60, "7d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60},+ team_timezone="UTC",+ )+ bands = split_ranges_by_ttl(find_missing_contiguous_windows([], start, end), schedule)+ assert len(bands) == 4diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.pynew file mode 100644index 000000000000..f5f1f55108c8--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_web_dimensional_precompute_parity.py@@ -0,0 +1,220 @@+"""Parity tests: the precomputation-framework dimensional tables must produce the+same aggregates as the v2 pre-aggregation tables for the same events.++The v2 INSERT (`WEB_STATS_INSERT_SQL` / `WEB_BOUNCES_INSERT_SQL`) is hand-written+ClickHouse over the physical `raw_sessions` table and materialized event columns;+the new path is HogQL over `events`+`sessions` driven by `ensure_precomputed`.+We run both over the same seeded window and compare.++Metrics are event-derived and must match exactly. We compare metrics grouped by+the dimensions both paths source identically (see the dimension-list comment+below for what is and isn't comparable, and why), which is the guarantee these+tables exist to provide.+"""++from datetime import UTC, datetime++from freezegun import freeze_time+from posthog.test.base import _create_event, _create_person++from posthog.clickhouse.client import sync_execute+from posthog.models.utils import uuid7+from posthog.models.web_preaggregated.sql import WEB_BOUNCES_INSERT_SQL, WEB_STATS_INSERT_SQL++from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (+ WebAnalyticsPreAggregatedTestBase,+)+from products.web_analytics.backend.hogql_queries.web_dimensional_precompute import (+ ensure_web_bounces_dimensional_precomputed,+ ensure_web_stats_dimensional_precomputed,+)++DATE_START = "2024-01-01"+DATE_END = "2024-01-02"+WINDOW_START = datetime(2024, 1, 1, tzinfo=UTC)+WINDOW_END = datetime(2024, 1, 2, tzinfo=UTC)++# Dimensions compared against v2. The comparison is restricted to dimensions both+# paths source identically for a given table:+# - `pathname` is excluded everywhere: v2 reads the materialized `mat_$pathname`,+# whose backfill is unreliable in the test harness (existing v2 tests never+# assert values), whereas the new path reads `properties.$pathname`. The new+# table's pathname breakdown is asserted separately. (Bounces have no pathname.)+# - geoip (country/city/region) is compared for stats (v2 sources it from the+# event's `mat_$geoip_*`, same as the new path) but excluded for bounces, where+# v2 sources it from the session's initial geoip (empty in the harness) while+# the new path uses event geoip.+_DEVICE_DIMS = ["host", "device_type", "browser", "os", "viewport_width", "viewport_height"]+_GEOIP_DIMS = ["country_code", "city_name", "region_code"]+STATS_COMPARABLE_DIMS = [*_DEVICE_DIMS, *_GEOIP_DIMS]+BOUNCES_COMPARABLE_DIMS = _DEVICE_DIMS+++class TestWebDimensionalPrecomputeParity(WebAnalyticsPreAggregatedTestBase):+ def setUp(self):+ super().setUp()+ # Born-expired rows vs the real CH clock — keep parts between INSERT and read.+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_stats_dimensional_preaggregated")+ sync_execute("SYSTEM STOP TTL MERGES sharded_web_bounces_dimensional_preaggregated")++ def _pageview(self, distinct_id: str, session: str, ts: str, **props) -> None:+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=distinct_id,+ timestamp=ts,+ properties={"$session_id": session, **props},+ )++ def _setup_test_data(self):+ sa, sb, sc = (str(uuid7(DATE_START)) for _ in range(3))+ with freeze_time("2024-01-01T09:00:00Z"):+ # Create persons so events resolve to a stable person_id per distinct_id+ # (without this, _create_event assigns a fresh random person_id per row).+ for did in ("user_a", "user_b", "user_c"):+ _create_person(team_id=self.team.pk, distinct_ids=[did])+ # user_a: non-bounce session, two pathnames on app.example.com.+ desktop_us = {+ "$host": "app.example.com",+ "$device_type": "Desktop",+ "$browser": "Chrome",+ "$os": "Windows",+ "$viewport_width": 1920,+ "$viewport_height": 1080,+ "$geoip_country_code": "US",+ "$geoip_city_name": "New York",+ "$geoip_subdivision_1_code": "NY",+ }+ self._pageview("user_a", sa, "2024-01-01T10:00:00Z", **{**desktop_us, "$pathname": "/"})+ self._pageview("user_a", sa, "2024-01-01T10:03:00Z", **{**desktop_us, "$pathname": "/pricing"})+ # user_b: single-pageview (bounce) on app.example.com, mobile.+ self._pageview(+ "user_b",+ sb,+ "2024-01-01T11:00:00Z",+ **{+ "$host": "app.example.com",+ "$device_type": "Mobile",+ "$browser": "Safari",+ "$os": "iOS",+ "$viewport_width": 390,+ "$viewport_height": 844,+ "$geoip_country_code": "US",+ "$geoip_city_name": "San Francisco",+ "$geoip_subdivision_1_code": "CA",+ "$pathname": "/",+ },+ )+ # user_c: single pageview on blog.example.com, different geo.+ self._pageview(+ "user_c",+ sc,+ "2024-01-01T12:00:00Z",+ **{+ "$host": "blog.example.com",+ "$device_type": "Desktop",+ "$browser": "Firefox",+ "$os": "Linux",+ "$viewport_width": 1280,+ "$viewport_height": 720,+ "$geoip_country_code": "GB",+ "$geoip_city_name": "London",+ "$geoip_subdivision_1_code": "ENG",+ "$pathname": "/blog",+ },+ )++ def _job_ids_tuple(self, result) -> str:+ return "(" + ", ".join(f"'{jid}'" for jid in result.job_ids) + ")"++ def _read_breakdown(self, table: str, metrics: str, dims: list[str], job_filter: str = "") -> dict:+ dim_sql = ", ".join(dims)+ rows = sync_execute(+ f"""+ SELECT {dim_sql}, {metrics}+ FROM {table}+ WHERE team_id = %(team_id)s {job_filter}+ GROUP BY {dim_sql}+ """,+ {"team_id": self.team.pk},+ )+ n = len(dims)+ return {tuple(row[:n]): tuple(int(v) for v in row[n:]) for row in rows}++ @freeze_time("2024-01-15T12:00:00Z")+ def test_stats_parity_with_v2(self):+ # v2 path: populate web_pre_aggregated_stats directly.+ sync_execute(+ WEB_STATS_INSERT_SQL(+ date_start=DATE_START,+ date_end=DATE_END,+ team_ids=[self.team.pk],+ table_name="web_pre_aggregated_stats",+ )+ )+ # new path: precomputation framework into the dimensional table.+ result = ensure_web_stats_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)++ metrics = "uniqMerge(persons_uniq_state), uniqMerge(sessions_uniq_state), sumMerge(pageviews_count_state)"+ job_filter = f"AND job_id IN {self._job_ids_tuple(result)}"+ v2 = self._read_breakdown("web_pre_aggregated_stats", metrics, STATS_COMPARABLE_DIMS)+ new = self._read_breakdown(+ "web_stats_dimensional_preaggregated", metrics, STATS_COMPARABLE_DIMS, job_filter=job_filter+ )++ assert new == v2, f"stats breakdown mismatch\nv2={v2}\nnew={new}"+ # Seed sanity: no person/session spans hosts, so per-host sums add up to+ # 3 persons, 3 sessions, 4 pageviews overall.+ totals = tuple(sum(v[i] for v in new.values()) for i in range(3))+ assert totals == (3, 3, 4), totals++ # The new table breaks down by pathname (read from properties, not a+ # materialized column) — validate that independently of v2.+ by_path = self._read_breakdown(+ "web_stats_dimensional_preaggregated",+ "sumMerge(pageviews_count_state)",+ ["pathname"],+ job_filter=job_filter,+ )+ assert by_path == {("/",): (2,), ("/pricing",): (1,), ("/blog",): (1,)}, by_path++ @freeze_time("2024-01-15T12:00:00Z")+ def test_bounces_parity_with_v2(self):+ sync_execute(+ WEB_BOUNCES_INSERT_SQL(+ date_start=DATE_START,+ date_end=DATE_END,+ team_ids=[self.team.pk],+ table_name="web_pre_aggregated_bounces",+ )+ )+ result = ensure_web_bounces_dimensional_precomputed(self.team, WINDOW_START, WINDOW_END)++ # Event-derived / deterministic metrics must match exactly.+ metrics = (+ "uniqMerge(persons_uniq_state), uniqMerge(sessions_uniq_state), "+ "sumMerge(pageviews_count_state), sumMerge(total_session_count_state)"+ )+ v2 = self._read_breakdown("web_pre_aggregated_bounces", metrics, BOUNCES_COMPARABLE_DIMS)+ new = self._read_breakdown(+ "web_bounces_dimensional_preaggregated",+ metrics,+ BOUNCES_COMPARABLE_DIMS,+ job_filter=f"AND job_id IN {self._job_ids_tuple(result)}",+ )+ assert new == v2, f"bounces breakdown mismatch\nv2={v2}\nnew={new}"++ # Bounce + duration are session-derived; compare grand totals (each path+ # reads its own session table, but for this seed they should agree).+ bounce_metrics = "sumMerge(bounces_count_state), sumMerge(total_session_duration_state)"+ v2_tot = sync_execute(+ f"SELECT {bounce_metrics} FROM web_pre_aggregated_bounces WHERE team_id = %(team_id)s",+ {"team_id": self.team.pk},+ )[0]+ new_tot = sync_execute(+ f"SELECT {bounce_metrics} FROM web_bounces_dimensional_preaggregated "+ f"WHERE team_id = %(team_id)s AND job_id IN {self._job_ids_tuple(result)}",+ {"team_id": self.team.pk},+ )[0]+ assert int(new_tot[0]) == int(v2_tot[0]), f"bounce count mismatch v2={v2_tot[0]} new={new_tot[0]}"+ assert int(new_tot[1]) == int(v2_tot[1]), f"duration mismatch v2={v2_tot[1]} new={new_tot[1]}"diff --git a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.pynew file mode 100644index 000000000000..b21eeab54567--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py@@ -0,0 +1,336 @@+"""HogQL INSERT templates for the fixed-dimension web precompute tables.++These are the precomputation-framework successors to the v2 pre-aggregation+`WEB_STATS_INSERT_SQL` / `WEB_BOUNCES_INSERT_SQL` (`posthog/models/web_preaggregated/sql.py`).+Where v2 was hand-written ClickHouse SQL run by a staging-table + partition-swap+Dagster ETL, these are HogQL templates fed to `ensure_precomputed`, which manages+job tracking, TTLs and the `ReplacingMergeTree` INSERTs. The scheduled+`web_dimensional_precompute` Dagster job is the only caller (the write path is+not wired into any query runner yet).++The framework auto-prepends `team_id`/`job_id` and appends `expires_at` to the+top-level SELECT, and substitutes `{time_window_min}` / `{time_window_max}` per+daily job. Buckets are hourly UTC on the session start timestamp (matching the+web_overview lazy precompute), so reads convert team-local windows to UTC before+filtering `period_bucket`.++Parity with v2 is intentional, with two deliberate deviations:+ - `region_name` is taken from the event's `$geoip_subdivision_1_name` (like the+ other geoip dimensions) because the HogQL `sessions` table exposes no initial+ geoip fields. v2 sourced it from the session's initial geoip.+ - `viewport_width`/`viewport_height` coalesce a failed cast to 0 rather than+ NULL, so they fit the non-nullable Int64 columns deterministically.+"""++from datetime import datetime++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr++from posthog.models.team import Team+from posthog.models.web_preaggregated.sql import is_eu_cluster++from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationResult,+ LazyComputationTable,+ ensure_precomputed,+)+from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import SESSION_FORWARD_PAD_MINUTES++# TTL tuned for "keep ~90 days warm, don't recompute every time": today's window+# refreshes hourly, the last two days daily, everything older is computed once and+# held for 90 days. The scheduled job re-runs over the rolling window and the+# framework only recomputes windows whose jobs have expired.+DIMENSIONAL_TTL_SECONDS: dict[str, int] = {+ "0d": 60 * 60,+ "2d": 24 * 60 * 60,+ "default": 90 * 24 * 60 * 60,+}+++# Per-session row, then aggregated into hourly buckets. `host`/`device_type`/+# `pathname`/`browser`/`os`/`viewport_*`/geoip are event-level group keys; the+# remaining dimensions are session-level and pulled via `any(session.…)`.+STATS_INSERT_TEMPLATE = """+SELECT+ toStartOfHour(start_timestamp) AS period_bucket,+ host AS host,+ device_type AS device_type,+ pathname AS pathname,+ entry_pathname AS entry_pathname,+ end_pathname AS end_pathname,+ browser AS browser,+ os AS os,+ viewport_width AS viewport_width,+ viewport_height AS viewport_height,+ referring_domain AS referring_domain,+ utm_source AS utm_source,+ utm_medium AS utm_medium,+ utm_campaign AS utm_campaign,+ utm_term AS utm_term,+ utm_content AS utm_content,+ country_code AS country_code,+ city_name AS city_name,+ region_code AS region_code,+ region_name AS region_name,+ has_gclid AS has_gclid,+ has_gad_source_paid_search AS has_gad_source_paid_search,+ has_fbclid AS has_fbclid,+ mat_metadata_backend AS mat_metadata_backend,+ mat_metadata_loggedIn AS mat_metadata_loggedIn,+ uniqState(session_person_id) AS persons_uniq_state,+ uniqState(session_id) AS sessions_uniq_state,+ sumState(pageview_count) AS pageviews_count_state+FROM (+ SELECT+ any(events.person_id) AS session_person_id,+ events.$session_id AS session_id,+ min(session.$start_timestamp) AS start_timestamp,+ events.properties.$host AS host,+ events.properties.$device_type AS device_type,+ events.properties.$pathname AS pathname,+ events.properties.$browser AS browser,+ events.properties.$os AS os,+ toIntOrZero(toString(events.properties.$viewport_width)) AS viewport_width,+ toIntOrZero(toString(events.properties.$viewport_height)) AS viewport_height,+ events.properties.$geoip_country_code AS country_code,+ events.properties.$geoip_city_name AS city_name,+ events.properties.$geoip_subdivision_1_code AS region_code,+ events.properties.$geoip_subdivision_1_name AS region_name,+ any(session.$entry_pathname) AS entry_pathname,+ any(session.$end_pathname) AS end_pathname,+ any(session.$entry_referring_domain) AS referring_domain,+ any(session.$entry_utm_source) AS utm_source,+ any(session.$entry_utm_medium) AS utm_medium,+ any(session.$entry_utm_campaign) AS utm_campaign,+ any(session.$entry_utm_term) AS utm_term,+ any(session.$entry_utm_content) AS utm_content,+ any(and(notEmpty(coalesce(session.$entry_gclid, '')), notEquals(coalesce(session.$entry_gclid, ''), 'null'))) AS has_gclid,+ any(equals(coalesce(session.$entry_gad_source, ''), '1')) AS has_gad_source_paid_search,+ any(and(notEmpty(coalesce(session.$entry_fbclid, '')), notEquals(coalesce(session.$entry_fbclid, ''), 'null'))) AS has_fbclid,+ {mat_logged_in_inner} AS mat_metadata_loggedIn,+ {mat_backend_inner} AS mat_metadata_backend,+ assumeNotNull(toInt(countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))))) AS pageview_count+ FROM events+ WHERE and(+ events.$session_id IS NOT NULL,+ or(equals(events.event, '$pageview'), equals(events.event, '$screen')),+ events.timestamp >= {time_window_min},+ events.timestamp < ({time_window_max} + toIntervalMinute({pad_minutes}))+ )+ GROUP BY+ session_id,+ host,+ device_type,+ pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ country_code,+ city_name,+ region_code,+ region_name+ HAVING and(+ toStartOfHour(min(session.$start_timestamp)) >= {time_window_min},+ toStartOfHour(min(session.$start_timestamp)) < {time_window_max}+ )+)+GROUP BY+ period_bucket,+ host,+ device_type,+ pathname,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+"""+++# Bounces are attributed per session (no pathname dimension). The inner query+# collapses to one row per session and reads the session's computed `$is_bounce`+# / `$session_duration`; the outer query sums them into hourly buckets.+BOUNCES_INSERT_TEMPLATE = """+SELECT+ toStartOfHour(start_timestamp) AS period_bucket,+ host AS host,+ device_type AS device_type,+ entry_pathname AS entry_pathname,+ end_pathname AS end_pathname,+ browser AS browser,+ os AS os,+ viewport_width AS viewport_width,+ viewport_height AS viewport_height,+ referring_domain AS referring_domain,+ utm_source AS utm_source,+ utm_medium AS utm_medium,+ utm_campaign AS utm_campaign,+ utm_term AS utm_term,+ utm_content AS utm_content,+ country_code AS country_code,+ city_name AS city_name,+ region_code AS region_code,+ region_name AS region_name,+ has_gclid AS has_gclid,+ has_gad_source_paid_search AS has_gad_source_paid_search,+ has_fbclid AS has_fbclid,+ mat_metadata_backend AS mat_metadata_backend,+ mat_metadata_loggedIn AS mat_metadata_loggedIn,+ uniqState(session_person_id) AS persons_uniq_state,+ uniqState(session_id) AS sessions_uniq_state,+ sumState(pageview_count) AS pageviews_count_state,+ sumState(assumeNotNull(toInt(ifNull(is_bounce, 0)))) AS bounces_count_state,+ sumState(session_duration) AS total_session_duration_state,+ sumState(assumeNotNull(toInt(1))) AS total_session_count_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(events.properties.$host) AS host,+ any(events.properties.$device_type) AS device_type,+ any(events.properties.$browser) AS browser,+ any(events.properties.$os) AS os,+ toIntOrZero(toString(any(events.properties.$viewport_width))) AS viewport_width,+ toIntOrZero(toString(any(events.properties.$viewport_height))) AS viewport_height,+ any(events.properties.$geoip_country_code) AS country_code,+ any(events.properties.$geoip_city_name) AS city_name,+ any(events.properties.$geoip_subdivision_1_code) AS region_code,+ any(events.properties.$geoip_subdivision_1_name) AS region_name,+ any(session.$entry_pathname) AS entry_pathname,+ any(session.$end_pathname) AS end_pathname,+ any(session.$entry_referring_domain) AS referring_domain,+ any(session.$entry_utm_source) AS utm_source,+ any(session.$entry_utm_medium) AS utm_medium,+ any(session.$entry_utm_campaign) AS utm_campaign,+ any(session.$entry_utm_term) AS utm_term,+ any(session.$entry_utm_content) AS utm_content,+ any(and(notEmpty(coalesce(session.$entry_gclid, '')), notEquals(coalesce(session.$entry_gclid, ''), 'null'))) AS has_gclid,+ any(equals(coalesce(session.$entry_gad_source, ''), '1')) AS has_gad_source_paid_search,+ any(and(notEmpty(coalesce(session.$entry_fbclid, '')), notEquals(coalesce(session.$entry_fbclid, ''), 'null'))) AS has_fbclid,+ {mat_logged_in_inner} AS mat_metadata_loggedIn,+ {mat_backend_inner} AS mat_metadata_backend,+ any(session.$is_bounce) AS is_bounce,+ assumeNotNull(toInt(any(session.$session_duration))) AS session_duration,+ assumeNotNull(toInt(countIf(or(equals(events.event, '$pageview'), equals(events.event, '$screen'))))) AS pageview_count+ FROM events+ WHERE and(+ events.$session_id IS NOT NULL,+ or(equals(events.event, '$pageview'), equals(events.event, '$screen')),+ events.timestamp >= {time_window_min},+ events.timestamp < ({time_window_max} + toIntervalMinute({pad_minutes}))+ )+ GROUP BY session_id+ HAVING and(+ toStartOfHour(min(session.$start_timestamp)) >= {time_window_min},+ toStartOfHour(min(session.$start_timestamp)) < {time_window_max}+ )+)+GROUP BY+ period_bucket,+ host,+ device_type,+ entry_pathname,+ end_pathname,+ browser,+ os,+ viewport_width,+ viewport_height,+ referring_domain,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ country_code,+ city_name,+ region_code,+ region_name,+ has_gclid,+ has_gad_source_paid_search,+ has_fbclid,+ mat_metadata_backend,+ mat_metadata_loggedIn+"""+++def _mat_metadata_placeholders() -> dict[str, ast.Expr]:+ """Build the EU/US `mat_metadata_*` placeholder expressions.++ On EU the custom metadata is a materialized event property, aggregated per+ session-group with `any()` (mirroring v2). On US these columns are always+ NULL, typed so the INSERT into the Nullable columns succeeds.+ """+ if not is_eu_cluster():+ # Typed NULLs without a CAST (HogQL rejects `CAST(NULL AS Nullable(...))`):+ # `if(false, <typed literal>, NULL)` yields Nullable(Bool)/Nullable(String).+ return {+ "mat_logged_in_inner": parse_expr("if(1 = 0, true, NULL)"),+ "mat_backend_inner": parse_expr("if(1 = 0, '', NULL)"),+ }++ return {+ "mat_logged_in_inner": parse_expr(+ "any(if(events.properties.`metadata.loggedIn` IS NULL, NULL, equals(events.properties.`metadata.loggedIn`, 'true')))"+ ),+ "mat_backend_inner": parse_expr("any(events.properties.`metadata.backend`)"),+ }+++def _base_placeholders() -> dict[str, ast.Expr]:+ return {+ "pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),+ **_mat_metadata_placeholders(),+ }+++def ensure_web_stats_dimensional_precomputed(+ team: Team,+ time_range_start: datetime,+ time_range_end: datetime,+) -> LazyComputationResult:+ return ensure_precomputed(+ team=team,+ insert_query=STATS_INSERT_TEMPLATE,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ ttl_seconds=DIMENSIONAL_TTL_SECONDS,+ table=LazyComputationTable.WEB_STATS_DIMENSIONAL_PREAGGREGATED,+ placeholders=_base_placeholders(),+ query_type="web_stats_dimensional_insert",+ )+++def ensure_web_bounces_dimensional_precomputed(+ team: Team,+ time_range_start: datetime,+ time_range_end: datetime,+) -> LazyComputationResult:+ return ensure_precomputed(+ team=team,+ insert_query=BOUNCES_INSERT_TEMPLATE,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ ttl_seconds=DIMENSIONAL_TTL_SECONDS,+ table=LazyComputationTable.WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED,+ placeholders=_base_placeholders(),+ query_type="web_bounces_dimensional_insert",+ )diff --git a/products/web_analytics/dags/tests/test_web_dimensional_precompute.py b/products/web_analytics/dags/tests/test_web_dimensional_precompute.pynew file mode 100644index 000000000000..96f756f9177b--- /dev/null+++ b/products/web_analytics/dags/tests/test_web_dimensional_precompute.py@@ -0,0 +1,154 @@+import os+from datetime import UTC, datetime++from posthog.test.base import APIBaseTest+from unittest.mock import patch++import dagster++from posthog.models import Organization, Team++from products.web_analytics.dags.web_dimensional_precompute import (+ DEFAULT_ROLLOUT_TEAM_IDS,+ PRECOMPUTE_CHUNK_DAYS,+ PRECOMPUTE_WINDOW_DAYS,+ SELECTED_TEAM_IDS_ENV_VAR,+ chunk_ranges,+ ensure_web_dimensional_precompute_op,+ get_selected_team_ids,+ web_dimensional_precompute_job,+)++_IS_CLOUD = "products.web_analytics.dags.web_dimensional_precompute.is_cloud"++# 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"+++class TestChunkRanges:+ def test_splits_newest_first_and_bounds_each_chunk(self):+ start = datetime(2024, 1, 1, tzinfo=UTC)+ end = datetime(2024, 1, 31, tzinfo=UTC)+ chunks = chunk_ranges(start, end, 7)+ # Newest first, each <= 7 days, contiguous, fully covering [start, end].+ assert chunks[0][1] == end+ assert chunks[-1][0] == start+ assert all((c_end - c_start).days <= 7 for c_start, c_end in chunks)+ for newer, older in zip(chunks, chunks[1:]):+ assert older[1] == newer[0] # contiguous+ assert len(chunks) == 5 # 30 days / 7++ def test_single_chunk_when_window_fits(self):+ start = datetime(2024, 1, 1, tzinfo=UTC)+ end = datetime(2024, 1, 5, tzinfo=UTC)+ assert chunk_ranges(start, end, 90) == [(start, end)]++ def test_default_chunk_is_one_day(self):+ # Conservative default: each INSERT scans a single day to bound CH memory.+ assert PRECOMPUTE_CHUNK_DAYS == 1+++class TestGetSelectedTeamIds:+ def test_env_override_parses_comma_separated_ids(self):+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: "2, 47074 ,55348"}):+ assert get_selected_team_ids() == [2, 47074, 55348]++ def test_env_override_skips_blank_and_invalid(self):+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: " , abc, 2 ,"}):+ assert get_selected_team_ids() == [2]++ def test_env_set_empty_disables(self):+ # An explicit empty value disables the job even on cloud.+ 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):+ os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)+ assert get_selected_team_ids() == DEFAULT_ROLLOUT_TEAM_IDS++ def test_unset_is_empty_off_cloud(self):+ with patch(_IS_CLOUD, return_value=False), patch.dict(os.environ, {}, clear=False):+ os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)+ assert get_selected_team_ids() == []+++class TestEnsureWebDimensionalPrecomputeOp(APIBaseTest):+ """Orchestration-shaped tests; the ensure_* functions are patched so no+ ClickHouse traffic is needed."""++ def _make_team(self, name: str) -> Team:+ org = Organization.objects.create(name=name)+ return Team.objects.create(organization=org, name=f"{name}-team")++ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_bounces_dimensional_precomputed")+ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_stats_dimensional_precomputed")+ @patch(_SINGLE_CHUNK, PRECOMPUTE_WINDOW_DAYS) # one chunk → one ensure call per team/table+ def test_drives_both_tables_for_every_selected_team(self, stats_mock, bounces_mock):+ t1 = self._make_team("A")+ t2 = self._make_team("B")+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{t1.pk},{t2.pk}"}):+ result = ensure_web_dimensional_precompute_op(dagster.build_op_context())++ assert result == {"teams": 2, "failures": 0}+ assert stats_mock.call_count == 2+ assert bounces_mock.call_count == 2+ warmed_teams = {call.args[0].pk for call in stats_mock.call_args_list}+ assert warmed_teams == {t1.pk, t2.pk}+ start, end = stats_mock.call_args_list[0].args[1], stats_mock.call_args_list[0].args[2]+ assert (end - start).days == PRECOMPUTE_WINDOW_DAYS++ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_bounces_dimensional_precomputed")+ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_stats_dimensional_precomputed")+ def test_chunking_issues_multiple_bounded_calls(self, stats_mock, bounces_mock):+ # Chunking bounds each ensure call to <= chunk_days so no single INSERT+ # scans the whole window. Exercised here with a 7-day chunk for clarity.+ t1 = self._make_team("A")+ with patch(_SINGLE_CHUNK, 7), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{t1.pk}"}):+ ensure_web_dimensional_precompute_op(dagster.build_op_context())+ assert stats_mock.call_count > 1+ assert all((e - s).days <= 7 for _t, s, e in (c.args for c in stats_mock.call_args_list))++ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_bounces_dimensional_precomputed")+ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_stats_dimensional_precomputed")+ @patch(_SINGLE_CHUNK, PRECOMPUTE_WINDOW_DAYS)+ def test_one_team_failure_does_not_poison_others(self, stats_mock, bounces_mock):+ t1 = self._make_team("A")+ t2 = self._make_team("B")++ def stats_side_effect(team, start, end):+ if team.pk == t1.pk:+ raise RuntimeError("boom")++ stats_mock.side_effect = stats_side_effect++ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{t1.pk},{t2.pk}"}):+ result = ensure_web_dimensional_precompute_op(dagster.build_op_context())++ assert result["teams"] == 2+ assert result["failures"] == 1+ assert stats_mock.call_count == 2+ assert bounces_mock.call_count == 2++ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_bounces_dimensional_precomputed")+ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_stats_dimensional_precomputed")+ def test_empty_allowlist_is_a_noop(self, stats_mock, bounces_mock):+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):+ result = ensure_web_dimensional_precompute_op(dagster.build_op_context())+ assert result == {"teams": 0, "failures": 0}+ stats_mock.assert_not_called()+ bounces_mock.assert_not_called()++ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_bounces_dimensional_precomputed")+ @patch("products.web_analytics.dags.web_dimensional_precompute.ensure_web_stats_dimensional_precomputed")+ def test_missing_team_is_skipped(self, stats_mock, bounces_mock):+ # A non-existent team id in the allowlist is logged and skipped, not fatal.+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: "999999999"}):+ result = ensure_web_dimensional_precompute_op(dagster.build_op_context())+ assert result == {"teams": 0, "failures": 0}+ stats_mock.assert_not_called()++ def test_job_has_owner_and_runtime_tags(self):+ tags = web_dimensional_precompute_job.tags+ assert tags["owner"] == "team-web-analytics"+ assert "dagster/max_runtime" in tagsdiff --git a/products/web_analytics/dags/web_dimensional_precompute.py b/products/web_analytics/dags/web_dimensional_precompute.pynew file mode 100644index 000000000000..ac44a0fca4df--- /dev/null+++ b/products/web_analytics/dags/web_dimensional_precompute.py@@ -0,0 +1,205 @@+"""Scheduled population of the fixed-dimension web precompute tables.++This job drives the precomputation framework: for each selected team it calls+`ensure_*_dimensional_precomputed` over a rolling 90-day window, and the+framework splits that into daily jobs, tracks them in Postgres+(`PreaggregationJob`) and only (re)computes windows whose jobs have expired. So+the heavy raw-table scan happens on a schedule for a known audience rather than+lazily on every user query, while re-runs are cheap because already-fresh+windows 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+`WEB_DIMENSIONAL_PRECOMPUTE_TEAM_IDS` env var (comma-separated team IDs; set it+to empty to disable the job). Self-hosted instances default to no teams so the+job never precomputes for unrelated teams that happen to share those IDs. There+is no dependency on the v2 team-selection dictionary or flag.++The write path is not yet wired into any query runner — this job only populates+the tables (so the new output can be compared with v2's side by side).+"""++import os+from datetime import UTC, datetime, timedelta++import dagster+import structlog+from prometheus_client import Counter++from posthog.cloud_utils import is_cloud+from posthog.dags.common import JobOwners+from posthog.models import Team++from products.web_analytics.backend.hogql_queries.web_dimensional_precompute import (+ ensure_web_bounces_dimensional_precomputed,+ ensure_web_stats_dimensional_precomputed,+)+from products.web_analytics.dags.web_preaggregated import skip_on_kill_switch+from products.web_analytics.dags.web_preaggregated_utils import check_for_concurrent_runs++logger = structlog.get_logger(__name__)++# Rolling window kept warm. Matches the lazy precompute MAX_PRECOMPUTE_DAYS so a+# later read path can serve any sub-window without falling back to raw tables.+PRECOMPUTE_WINDOW_DAYS = int(os.getenv("WEB_DIMENSIONAL_PRECOMPUTE_WINDOW_DAYS", "90"))++# Each ensure_precomputed call covers at most this many days. The framework merges+# a fully-missing range into ONE INSERT, so without chunking a cold backfill would+# scan the entire window (e.g. 90 days of raw sessions+events) in a single query —+# the real memory/overload risk for a high-volume team. Chunking bounds each INSERT's+# scan; combined with the job's max_runtime and ensure_precomputed's idempotency, a+# cold backfill self-paces across runs (a killed run resumes from the first unfilled+# chunk). Defaults to 1 so every INSERT scans a single UTC day — the safest memory+# profile, matching v2's per-day partition granularity. Raise via the env var to+# 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;+# set to empty to disable the job entirely.+SELECTED_TEAM_IDS_ENV_VAR = "WEB_DIMENSIONAL_PRECOMPUTE_TEAM_IDS"+++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.+ """+ 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()]+++def chunk_ranges(start: datetime, end: datetime, chunk_days: int) -> list[tuple[datetime, datetime]]:+ """Split [start, end) into <=chunk_days sub-windows, newest first.++ Newest-first so recent data (which carries the shortest TTL and is requested+ most) is refreshed before older history is backfilled.+ """+ chunks = []+ cur_end = end+ step = timedelta(days=max(chunk_days, 1))+ while cur_end > start:+ cur_start = max(start, cur_end - step)+ chunks.append((cur_start, cur_end))+ cur_end = cur_start+ return chunks+++WEB_DIMENSIONAL_PRECOMPUTE_TEAM_DONE = Counter(+ "web_dimensional_precompute_team_done_total",+ "Teams whose dimensional precompute window was ensured, by table.",+ ["table"],+)+WEB_DIMENSIONAL_PRECOMPUTE_TEAM_FAILED = Counter(+ "web_dimensional_precompute_team_failed_total",+ "Teams whose dimensional precompute failed, by table and exception type.",+ ["table", "error_type"],+)+++def _ensure_for_team(+ context: dagster.OpExecutionContext, team: Team, start: datetime, end: datetime, chunk_days: int+) -> int:+ """Ensure both dimensional tables for one team, one bounded chunk at a time.++ Each chunk is a separate ensure_precomputed call (one INSERT scanning at most+ `chunk_days` of raw data), so no single query scans the whole window. Failures+ per (table, chunk) are caught so one bad chunk doesn't poison the rest;+ already-fresh chunks are cheap PG cache-checks with no INSERT.+ """+ failures = 0+ for table_label, ensure_fn in (+ ("web_stats_dimensional_preaggregated", ensure_web_stats_dimensional_precomputed),+ ("web_bounces_dimensional_preaggregated", ensure_web_bounces_dimensional_precomputed),+ ):+ for chunk_start, chunk_end in chunk_ranges(start, end, chunk_days):+ try:+ ensure_fn(team, chunk_start, chunk_end)+ WEB_DIMENSIONAL_PRECOMPUTE_TEAM_DONE.labels(table=table_label).inc()+ except Exception as exc:+ WEB_DIMENSIONAL_PRECOMPUTE_TEAM_FAILED.labels(table=table_label, error_type=type(exc).__name__).inc()+ context.log.exception(+ f"web_dimensional_precompute_failed team={team.pk} table={table_label} "+ f"chunk=[{chunk_start}, {chunk_end})"+ )+ failures += 1+ return failures+++def ensure_web_dimensional_precompute_op(context: dagster.OpExecutionContext) -> dict[str, int]:+ """Drive `ensure_*_dimensional_precomputed` over the rolling window for each selected team."""+ end = datetime.now(UTC)+ start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)++ team_ids = get_selected_team_ids()+ context.log.info(+ f"web_dimensional_precompute_start teams={len(team_ids)} window=[{start}, {end}) "+ f"chunk_days={PRECOMPUTE_CHUNK_DAYS}"+ )+ if not team_ids:+ context.log.info(f"web_dimensional_precompute_noop ({SELECTED_TEAM_IDS_ENV_VAR} is empty)")+ result = {"teams": 0, "failures": 0}+ context.add_output_metadata(result)+ return result++ teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids)}++ failures = 0+ processed = 0+ for team_id in team_ids:+ team = teams_by_id.get(team_id)+ if team is None:+ context.log.warning(f"web_dimensional_precompute_team_missing team_id={team_id}")+ continue+ failures += _ensure_for_team(context, team, start, end, PRECOMPUTE_CHUNK_DAYS)+ processed += 1++ context.log.info(f"web_dimensional_precompute_complete teams={processed} failures={failures}")+ result = {"teams": processed, "failures": failures}+ context.add_output_metadata(result)+ return result+++ description=(+ f"Populates the fixed-dimension web precompute tables (web_stats_dimensional_preaggregated / "+ f"web_bounces_dimensional_preaggregated) over the trailing {PRECOMPUTE_WINDOW_DAYS} days for the teams in "+ f"the {SELECTED_TEAM_IDS_ENV_VAR} allowlist, by driving the precomputation framework's ensure_precomputed. "+ f"No-op when the allowlist is empty. Re-runs only recompute windows whose jobs have expired."+ ),+ tags={+ "owner": JobOwners.TEAM_WEB_ANALYTICS.value,+ "dagster/max_runtime": str(2 * 60 * 60),+ },+)+def web_dimensional_precompute_job():+ ensure_web_dimensional_precompute_op()+++ # Hourly. Recent windows carry a short TTL (see DIMENSIONAL_TTL_SECONDS), so an+ # hourly cadence keeps today fresh; older windows are computed once and skipped.+ cron_schedule="20 * * * *",+ job=web_dimensional_precompute_job,+ execution_timezone="UTC",+ tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},+)+@skip_on_kill_switch+def web_dimensional_precompute_schedule(+ context: dagster.ScheduleEvaluationContext,+) -> "dagster.RunRequest | dagster.SkipReason":+ skip_reason = check_for_concurrent_runs(context)+ if skip_reason:+ return skip_reason+ return dagster.RunRequest()