: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
fix(web-analytics): stop reading the team selection dictionary in pre-aggregation (#105406)
Lucas Ricoy8b03b893fcee
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex 0729033e8513..4ed509652535 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -361,6 +361,7 @@ from posthog.models.usage_ingestion.billing_usage_records import (WRITABLE_BILLING_USAGE_RECORDS_TABLE_SQL,)from posthog.models.web_preaggregated.sql import WEB_BOUNCES_SQL, WEB_STATS_SQL+from posthog.models.web_preaggregated.team_selection import WEB_PRE_AGGREGATED_TEAM_SELECTION_TABLE_SQLfrom posthog.session_recordings.sql.session_replay_event_sql import (DISTRIBUTED_SESSION_REPLAY_EVENTS_TABLE_SQL,KAFKA_SESSION_REPLAY_EVENTS_TABLE_SQL,@@ -445,6 +446,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (DOCUMENT_EMBEDDINGS_BUFFER_SHARDED_TABLE_SQL,WEB_STATS_SQL,WEB_BOUNCES_SQL,+ WEB_PRE_AGGREGATED_TEAM_SELECTION_TABLE_SQL,SHARDED_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,QUERY_LOG_ARCHIVE_BUFFER_OPS_TABLE_SQL,COHORT_MEMBERSHIP_TABLE_SQL,diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex 4c95547f91c5..c14aaa7608d6 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -9902,6 +9902,18 @@'''# ---+# name: test_create_table_query[web_pre_aggregated_teams]+ '''++ CREATE TABLE IF NOT EXISTS `web_pre_aggregated_teams` (+ team_id UInt64,+ enabled_by String DEFAULT 'system',+ version UInt32 DEFAULT toUnixTimestamp(now())+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.web_analytics_team_selection', '{replica}-{shard}', version)+ ORDER BY (team_id);++ '''+# ---# name: test_create_table_query[web_sessions_dimensional_preaggregated]'''@@ -15316,6 +15328,18 @@'''# ---+# name: test_create_table_query_replicated_and_storage[web_pre_aggregated_teams]+ '''++ CREATE TABLE IF NOT EXISTS `web_pre_aggregated_teams` (+ team_id UInt64,+ enabled_by String DEFAULT 'system',+ version UInt32 DEFAULT toUnixTimestamp(now())+ ) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.web_analytics_team_selection', '{replica}-{shard}', version)+ ORDER BY (team_id);++ '''+# ---# name: test_create_table_query_replicated_and_storage[writable_session_replay_events]'''diff --git a/posthog/models/web_preaggregated/sql.py b/posthog/models/web_preaggregated/sql.pyindex fbfca0927fca..480d5349787f 100644--- a/posthog/models/web_preaggregated/sql.py+++ b/posthog/models/web_preaggregated/sql.py@@ -6,7 +6,7 @@ from posthog.hogql.database.schema.web_analytics_s3 import get_s3_function_argsfrom posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.table_engines import MergeTreeEngine, ReplicationScheme-from posthog.models.web_preaggregated.team_selection import WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME+from posthog.models.web_preaggregated.team_selection import WEB_PRE_AGGREGATED_SELECTED_TEAMS_SQLdef is_eu_cluster() -> bool:@@ -377,12 +377,14 @@ def get_team_filters(team_ids: list[int] | None) -> dict[str, str]:"person_distinct_id_overrides": f"person_distinct_id_overrides.team_id IN({team_ids_str})","events": f"e.team_id IN({team_ids_str})",}- else:- return {- "raw_sessions": f"dictHas('{WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME}', raw_sessions.team_id)",- "person_distinct_id_overrides": f"dictHas('{WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME}', person_distinct_id_overrides.team_id)",- "events": f"dictHas('{WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME}', e.team_id)",- }++ # GLOBAL IN reads the team selection once on the initiator, so data hosts do not need the selection table+ selected_teams = f"GLOBAL IN ({WEB_PRE_AGGREGATED_SELECTED_TEAMS_SQL().strip()})"+ return {+ "raw_sessions": f"raw_sessions.team_id {selected_teams}",+ "person_distinct_id_overrides": f"person_distinct_id_overrides.team_id {selected_teams}",+ "events": f"e.team_id {selected_teams}",+ }def get_date_filters(date_start: str, date_end: str, timezone: str, granularity: str = "daily") -> dict[str, str]:diff --git a/posthog/models/web_preaggregated/team_selection.py b/posthog/models/web_preaggregated/team_selection.pyindex 3553cb548750..15dad0f17929 100644--- a/posthog/models/web_preaggregated/team_selection.py+++ b/posthog/models/web_preaggregated/team_selection.py@@ -107,7 +107,7 @@ INSERT INTO `{WEB_PRE_AGGREGATED_TEAM_SELECTION_TABLE_NAME}` (team_id, enabled_b{values};"""-def WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_QUERY():+def WEB_PRE_AGGREGATED_SELECTED_TEAMS_SQL():return f"""SELECTteam_id@@ -115,7 +115,11 @@ FROM`{CLICKHOUSE_DATABASE}`.`{WEB_PRE_AGGREGATED_TEAM_SELECTION_TABLE_NAME}`FINALWHERE version > 0-""".replace("\n", " ").strip()+"""+++def WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_QUERY():+ return WEB_PRE_AGGREGATED_SELECTED_TEAMS_SQL().replace("\n", " ").strip()_dict_reader_creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)diff --git a/posthog/models/web_preaggregated/test_web_preaggregated_sql.py b/posthog/models/web_preaggregated/test_web_preaggregated_sql.pyindex 8758d8d4ea86..be24bb44126d 100644--- a/posthog/models/web_preaggregated/test_web_preaggregated_sql.py+++ b/posthog/models/web_preaggregated/test_web_preaggregated_sql.py@@ -2,6 +2,8 @@ import pytestimport time_machinefrom posthog.test.base import _create_event, _create_person+from parameterized import parameterized+from posthog.clickhouse.client.execute import sync_executefrom posthog.models.utils import uuid7from posthog.models.web_preaggregated.sql import (@@ -18,6 +20,7 @@ from posthog.models.web_preaggregated.sql import (get_web_bounces_insert_columns,get_web_stats_insert_columns,)+from posthog.models.web_preaggregated.team_selection import WEB_PRE_AGGREGATED_TEAM_SELECTION_DATA_SQLfrom products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (WebAnalyticsPreAggregatedTestBase,@@ -239,24 +242,25 @@ class TestWebPreaggregatedInserts(WebAnalyticsPreAggregatedTestBase):},)- def test_insert_queries_can_execute(self, date_start: str = "2024-01-01", date_end: str = "2024-01-02"):- bounces_insert = WEB_BOUNCES_INSERT_SQL(- date_start=date_start,- date_end=date_end,- team_ids=[self.team.pk],- table_name="web_pre_aggregated_bounces",- )- stats_insert = WEB_STATS_INSERT_SQL(- date_start=date_start,- date_end=date_end,- team_ids=[self.team.pk],- table_name="web_pre_aggregated_stats",- )-- # Basic smoke test - ensures both insert queries execute without errors- sync_execute(stats_insert)- sync_execute(bounces_insert)- assert True+ @parameterized.expand([("explicit_team_ids", True), ("team_selection_table", False)])+ def test_insert_queries_aggregate_the_selected_team(self, _name: str, pass_team_ids: bool):+ if pass_team_ids:+ team_ids: list[int] | None = [self.team.pk]+ else:+ team_ids = None+ sync_execute(WEB_PRE_AGGREGATED_TEAM_SELECTION_DATA_SQL([self.team.pk]))++ for table_name, sql_builder in [+ ("web_pre_aggregated_stats", WEB_STATS_INSERT_SQL),+ ("web_pre_aggregated_bounces", WEB_BOUNCES_INSERT_SQL),+ ]:+ sync_execute(+ sql_builder(date_start="2024-01-01", date_end="2024-01-02", team_ids=team_ids, table_name=table_name)+ )+ [(row_count,)] = sync_execute(+ f"SELECT count() FROM {table_name} WHERE team_id = %(team_id)s", {"team_id": self.team.pk}+ )+ assert row_count > 0, table_namedef test_insert_queries_contain_all_columns_for_stats(self):stats_insert = WEB_STATS_INSERT_SQL(@@ -303,13 +307,18 @@ class TestCentralizedFilters:assert "person_distinct_id_overrides.team_id IN(123, 456, 789)" == filters["person_distinct_id_overrides"]assert "e.team_id IN(123, 456, 789)" == filters["events"]- def test_get_team_filters_without_team_ids_uses_dictionary(self):- filters = get_team_filters(None)+ @pytest.mark.parametrize("team_ids", [None, []])+ def test_get_team_filters_without_team_ids_uses_team_selection_table(self, team_ids):+ filters = get_team_filters(team_ids)- assert "dictHas(" in filters["raw_sessions"]- assert "dictHas(" in filters["person_distinct_id_overrides"]- assert "dictHas(" in filters["events"]- assert "raw_sessions.team_id)" in filters["raw_sessions"]+ for key, column in [+ ("raw_sessions", "raw_sessions.team_id"),+ ("person_distinct_id_overrides", "person_distinct_id_overrides.team_id"),+ ("events", "e.team_id"),+ ]:+ assert filters[key].startswith(f"{column} GLOBAL IN (")+ assert "web_pre_aggregated_teams" in filters[key]+ assert "dictHas" not in filters[key]@pytest.mark.parametrize("granularity,expected_session_start,expected_event_start",diff --git a/products/web_analytics/dags/tests/test_web_preaggregated_team_selection.py b/products/web_analytics/dags/tests/test_web_preaggregated_team_selection.pyindex 19e8d3244c4d..ca513f797954 100644--- a/products/web_analytics/dags/tests/test_web_preaggregated_team_selection.py+++ b/products/web_analytics/dags/tests/test_web_preaggregated_team_selection.py@@ -263,19 +263,14 @@ class TestStoreTeamSelectionInClickhouse:def test_stores_team_selection_successfully(self):team_ids = [1, 2, 3]- # Mock successful operationsinsert_results = {"host1": True, "host2": True}- reload_results = {"host1": True, "host2": True}- self.mock_cluster.map_all_hosts.side_effect = [- Mock(result=Mock(return_value=insert_results)),- Mock(result=Mock(return_value=reload_results)),- ]+ self.mock_cluster.map_all_hosts.return_value = Mock(result=Mock(return_value=insert_results))result = store_team_selection_in_clickhouse(self.mock_context, team_ids, self.mock_cluster)assert result == team_ids- assert self.mock_cluster.map_all_hosts.call_count == 2+ assert self.mock_cluster.map_all_hosts.call_count == 1self.mock_context.log.info.assert_called()def test_handles_empty_team_ids_list(self):@@ -291,66 +286,24 @@ class TestStoreTeamSelectionInClickhouse:def test_raises_exception_on_insert_failure(self):team_ids = [1, 2, 3]- # Mock failed insert on one hostinsert_results = {"host1": True, "host2": False}- reload_results = {"host1": True, "host2": True}- self.mock_cluster.map_all_hosts.side_effect = [- Mock(result=Mock(return_value=insert_results)),- Mock(result=Mock(return_value=reload_results)),- ]+ self.mock_cluster.map_all_hosts.return_value = Mock(result=Mock(return_value=insert_results))with pytest.raises(Exception, match="Failed to insert team selection"):store_team_selection_in_clickhouse(self.mock_context, team_ids, self.mock_cluster)- def test_raises_exception_on_dictionary_reload_failure(self):- team_ids = [1, 2, 3]-- # Mock failed reload on one host- insert_results = {"host1": True, "host2": True}- reload_results = {"host1": True, "host2": False}-- self.mock_cluster.map_all_hosts.side_effect = [- Mock(result=Mock(return_value=insert_results)),- Mock(result=Mock(return_value=reload_results)),- ]-- with pytest.raises(Exception, match="Failed to reload dictionary"):- store_team_selection_in_clickhouse(self.mock_context, team_ids, self.mock_cluster)-def test_logs_appropriate_messages(self):team_ids = [1, 2, 3]- # Mock successful operationsinsert_results = {"host1": True, "host2": True}- reload_results = {"host1": True, "host2": True}- self.mock_cluster.map_all_hosts.side_effect = [- Mock(result=Mock(return_value=insert_results)),- Mock(result=Mock(return_value=reload_results)),- ]+ self.mock_cluster.map_all_hosts.return_value = Mock(result=Mock(return_value=insert_results))store_team_selection_in_clickhouse(self.mock_context, team_ids, self.mock_cluster)self.mock_context.log.info.assert_called_with(f"Storing {len(team_ids)} enabled team IDs in ClickHouse")- def test_calls_cluster_map_all_hosts_twice(self):- team_ids = [1, 2, 3]-- # Mock successful operations- insert_results = {"host1": True}- reload_results = {"host1": True}-- self.mock_cluster.map_all_hosts.side_effect = [- Mock(result=Mock(return_value=insert_results)),- Mock(result=Mock(return_value=reload_results)),- ]-- store_team_selection_in_clickhouse(self.mock_context, team_ids, self.mock_cluster)-- # Verify map_all_hosts was called twice (once for insert, once for reload)- assert self.mock_cluster.map_all_hosts.call_count == 2-class TestWebAnalyticsTeamSelectionAsset:def setup_method(self):diff --git a/products/web_analytics/dags/tests/test_web_preaggregated_utils.py b/products/web_analytics/dags/tests/test_web_preaggregated_utils.pyindex b999a3e1ad35..16563a88f578 100644--- a/products/web_analytics/dags/tests/test_web_preaggregated_utils.py+++ b/products/web_analytics/dags/tests/test_web_preaggregated_utils.py@@ -1,7 +1,9 @@import inspect-from unittest.mock import Mock+import pytest+from unittest.mock import Mock, patch+import dagsterfrom dagster import DagsterInstance, DagsterRunStatus, RunsFilter, SkipReason, job, op, scheduleimport products.web_analytics.dags.web_preaggregated as wp@@ -190,3 +192,15 @@ class TestWebPreaggregatedUtils:recreate_staging_table(context, cluster, "my_test_staging_table", mock_sql_func)context.log.info.assert_called_once_with("Recreating staging table my_test_staging_table")++ @patch.object(wp, "sync_execute", return_value=[(0,)])+ def test_pre_aggregation_fails_before_touching_tables_when_no_teams_are_selected(self, _mock_sync_execute):+ context = Mock(op_config={})+ sql_generator = Mock()+ cluster = Mock()++ with pytest.raises(dagster.Failure, match="No teams are selected"):+ wp.pre_aggregate_web_analytics_data(context, "web_pre_aggregated_stats", sql_generator, cluster)++ sql_generator.assert_not_called()+ cluster.map_all_hosts.assert_not_called()diff --git a/products/web_analytics/dags/web_preaggregated.py b/products/web_analytics/dags/web_preaggregated.pyindex 822e9492dcac..caa6260c0f78 100644--- a/products/web_analytics/dags/web_preaggregated.py+++ b/products/web_analytics/dags/web_preaggregated.py@@ -18,6 +18,7 @@ from posthog.models.web_preaggregated.sql import (WEB_BOUNCES_INSERT_SQL,WEB_STATS_INSERT_SQL,)+from posthog.models.web_preaggregated.team_selection import WEB_PRE_AGGREGATED_SELECTED_TEAMS_SQLfrom posthog.settings import DEBUG, TESTfrom products.web_analytics.dags.web_preaggregated_utils import (@@ -46,6 +47,12 @@ REPLACE_TEMPLATES_BY_STAGING_TABLE_NAME = {}+def count_selected_teams() -> int:+ with tags_context(product=ProductKey.WEB_ANALYTICS, feature=Feature.PREAGGREGATION):+ rows = sync_execute(f"SELECT count() FROM ({WEB_PRE_AGGREGATED_SELECTED_TEAMS_SQL()})")+ return rows[0][0]++def pre_aggregate_web_analytics_data(context: dagster.AssetExecutionContext,table_name: str,@@ -54,6 +61,9 @@ def pre_aggregate_web_analytics_data() -> None:config = context.op_configteam_ids = config.get("team_ids")+ # An empty selection would swap empty partitions over the existing data+ if not team_ids and count_selected_teams() == 0:+ raise dagster.Failure("No teams are selected for web analytics pre-aggregation")extra_settings = config.get("extra_clickhouse_settings", "")ch_settings = merge_clickhouse_settings(WEB_PRE_AGGREGATED_CLICKHOUSE_SETTINGS, extra_settings)@@ -87,7 +97,7 @@ def pre_aggregate_web_analytics_data()context.log.info(f"Populating staging table with hourly data from {date_start} to {date_end}")- context.log.info(f"Processing {len(team_ids) if team_ids else 0} team_ids: {team_ids}")+ context.log.info(f"Processing team_ids: {team_ids or 'all teams in the team selection table'}")context.log.info(insert_query)with tags_context(product=ProductKey.WEB_ANALYTICS, feature=Feature.PREAGGREGATION):sync_execute(insert_query)diff --git a/products/web_analytics/dags/web_preaggregated_team_selection.py b/products/web_analytics/dags/web_preaggregated_team_selection.pyindex a58c32ba6db8..f2edc99d2cb6 100644--- a/products/web_analytics/dags/web_preaggregated_team_selection.py+++ b/products/web_analytics/dags/web_preaggregated_team_selection.py@@ -12,7 +12,6 @@ from posthog.models.web_preaggregated.team_selection import (DEFAULT_ENABLED_TEAM_IDS,DEFAULT_WEEKLY_PAGEVIEWS_THRESHOLD,WEB_PRE_AGGREGATED_TEAM_SELECTION_DATA_SQL,- WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME,get_teams_by_weekly_pageviews_sql,)from posthog.models.web_preaggregated.team_selection_strategies import strategy_registry@@ -97,29 +96,11 @@ def store_team_selection_in_clickhouse(context.log.warning(f"Failed to insert team selection: {e}")return False- def reload_dict(client: Client) -> bool:- try:- client.execute(- f"SYSTEM RELOAD DICTIONARY {WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME}",- settings=settings_with_log_comment(context),- )- context.log.info("Successfully reloaded team selection dictionary")- return True- except Exception as e:- context.log.warning(f"Failed to reload team selection dictionary: {e}")- return False-- # Execute operations on all hostsinsert_results = cluster.map_all_hosts(insert).result()- reload_results = cluster.map_all_hosts(reload_dict).result()- # Check if all operations succeededif not all(insert_results.values()):raise Exception(f"Failed to insert team selection on some hosts: {insert_results}")- if not all(reload_results.values()):- raise Exception(f"Failed to reload dictionary on some hosts: {reload_results}")-return team_ids@@ -153,7 +134,7 @@ def web_analytics_team_selection() -> dagster.MaterializeResult:"""This manages which teams have access to web analytics pre-aggregated tables.- The selection is then stored in a ClickHouse dictionary for fast lookups.+ The selection is then stored in the web_pre_aggregated_teams ClickHouse table."""return _web_analytics_team_selection_impl(context, cluster)diff --git a/products/web_analytics/dags/web_preaggregated_utils.py b/products/web_analytics/dags/web_preaggregated_utils.pyindex cc6a50e329e8..3b1e61de3b8a 100644--- a/products/web_analytics/dags/web_preaggregated_utils.py+++ b/products/web_analytics/dags/web_preaggregated_utils.py@@ -168,7 +168,7 @@ WEB_ANALYTICS_CONFIG_SCHEMA = {"team_ids": Field(Array(int),is_required=False,- description="List of team IDs to process - if not provided, uses ClickHouse dictionary configuration",+ description="List of team IDs to process - if not provided, uses the teams in web_pre_aggregated_teams",),"extra_clickhouse_settings": Field(str,