: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): align dimensional backfill with legacy pre-aggregation (#117339)
Lucas Ricoy9db00e841023
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 7e37f3871102..714868a634d8 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -3,7 +3,7 @@ import jsonimport timeimport uuidimport hashlib-from collections.abc import Callable+from collections.abc import Callable, Mappingfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom enum import StrEnum@@ -175,7 +175,13 @@ LAZY_COMPUTATION_JOB_CREATE_CONFLICTS_TOTAL = Counter()-def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False, read_after_write: bool = True) -> dict:+def _get_insert_settings(+ team_id: int,+ *,+ spill_to_disk: bool = False,+ read_after_write: bool = True,+ overrides: Mapping[str, int | str] | None = None,+) -> dict:"""Build ClickHouse settings for preaggregation INSERT queries.Starts from the same HogQLGlobalSettings defaults that execute_hogql_query@@ -218,6 +224,8 @@ def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False, read_afte# build hash tables past the cluster memory limit and fail with# MEMORY_LIMIT_EXCEEDED.settings["max_bytes_before_external_group_by"] = MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY+ if overrides:+ settings.update(overrides)return settings@@ -1617,6 +1625,7 @@ def ensure_precomputed(cache_key_context: dict[str, str] | None = None,read_after_write: bool = True,database: "Database | None" = None,+ insert_settings: Mapping[str, int | str] | None = None,) -> LazyComputationResult:"""Ensure lazy-computed data exists for the given query and time range.@@ -1701,6 +1710,9 @@ def ensure_precomputed(and CPU per job. A caller that ensures many windows for one team shouldbuild it once, userless with warehouse access control bypassed and withthe same `modifiers`, and pass it here.+ insert_settings: ClickHouse settings applied last to every INSERT, over the defaults+ and `spill_to_disk`. For a precompute kind whose INSERT needs more+ memory or time than the defaults allow.Returns:ComputationResult with job_ids that can be used to query the data@@ -1789,7 +1801,12 @@ def ensure_precomputed(sync_execute(insert_sql,values,- settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk, read_after_write=read_after_write),+ settings=_get_insert_settings(+ t.id,+ spill_to_disk=spill_to_disk,+ read_after_write=read_after_write,+ overrides=insert_settings,+ ),))# Splits the job's insert_duration_ms: printing builds the team's HogQL database, which can costdiff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.pyindex 267e42c76568..1094c8673b0d 100644--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py@@ -3555,11 +3555,23 @@ class TestInsertSettingsAppliedToInserts(BaseTest):@parameterized.expand([- ("default_read_after_write", {}, "auto"),- ("background_no_quorum", {"read_after_write": False}, 0),+ ("default_read_after_write", {}, "auto", {}),+ ("background_no_quorum", {"read_after_write": False}, 0, {}),+ # Caller overrides must win over the defaults and over spill_to_disk's threshold.+ (+ "caller_settings_override_defaults",+ {+ "spill_to_disk": True,+ "insert_settings": {"max_memory_usage": 7, "max_bytes_before_external_group_by": 3},+ },+ "auto",+ {"max_memory_usage": 7, "max_bytes_before_external_group_by": 3},+ ),])- def test_manual_insert_path_passes_insert_settings_to_clickhouse(self, _name, extra_kwargs, expected_quorum):+ def test_manual_insert_path_passes_insert_settings_to_clickhouse(+ self, _name, extra_kwargs, expected_quorum, expected_overrides+ ):# The quorum constant is patched to its production value because TEST forces# it to 0, which would make both parameter rows assert the same settings.with (@@ -3578,7 +3590,12 @@ class TestInsertSettingsAppliedToInserts(BaseTest):time_range_end=datetime(2024, 1, 2, tzinfo=UTC),**extra_kwargs,)- expected_settings = _get_insert_settings(self.team.pk, **extra_kwargs)+ expected_settings = _get_insert_settings(+ self.team.pk,+ spill_to_disk=extra_kwargs.get("spill_to_disk", False),+ read_after_write=extra_kwargs.get("read_after_write", True),+ overrides=extra_kwargs.get("insert_settings"),+ )assert result.ready is True# Bind the assertion to the INSERT specifically, so the test doesn't break (or silently@@ -3587,6 +3604,7 @@ class TestInsertSettingsAppliedToInserts(BaseTest):assert len(insert_calls) == 1 # one missing range -> one INSERTassert insert_calls[0].kwargs["settings"] == expected_settingsassert insert_calls[0].kwargs["settings"]["insert_quorum"] == expected_quorum+ assert insert_calls[0].kwargs["settings"].items() >= expected_overrides.items()# The coverage landed in this call, so quorum-skipping callers must not read it yet.assert result.freshly_built is Truediff --git a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.pyindex d8c24b9b7013..a4dbabc05941 100644--- a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py@@ -302,6 +302,17 @@ def _base_placeholders() -> dict[str, ast.Expr]:}+# Same ceilings as the legacy pre-aggregation job (`WEB_PRE_AGGREGATED_CLICKHOUSE_SETTINGS`), whose+# tables these replace. One UTC day of a very large team's events, grouped by every fixed dimension,+# outgrows the default 42 GiB limit in the step that merges the shards' partial aggregates.+DIMENSIONAL_INSERT_SETTINGS: dict[str, int | str] = {+ "max_memory_usage": 140 * 1024**3,+ "max_bytes_before_external_group_by": 70 * 1024**3,+ "distributed_aggregation_memory_efficient": 1,+ "max_execution_time": 2200,+}++def ensure_web_stats_dimensional_precomputed(team: Team,time_range_start: datetime,@@ -317,7 +328,7 @@ def ensure_web_stats_dimensional_precomputed(placeholders=_base_placeholders(),query_type="web_stats_dimensional_insert",read_after_write=False,- spill_to_disk=True, # GROUP BY over every fixed dimension; a large team's day outgrows the memory limit+ insert_settings=DIMENSIONAL_INSERT_SETTINGS,)@@ -336,5 +347,5 @@ def ensure_web_bounces_dimensional_precomputed(placeholders=_base_placeholders(),query_type="web_bounces_dimensional_insert",read_after_write=False,- spill_to_disk=True, # session-level GROUP BY over every fixed dimension; same memory profile as stats+ insert_settings=DIMENSIONAL_INSERT_SETTINGS,)diff --git a/products/web_analytics/dags/tests/test_web_dimensional_precompute.py b/products/web_analytics/dags/tests/test_web_dimensional_precompute.pyindex 9dec9ba6f905..283b4947f473 100644--- a/products/web_analytics/dags/tests/test_web_dimensional_precompute.py+++ b/products/web_analytics/dags/tests/test_web_dimensional_precompute.py@@ -1,6 +1,7 @@import osfrom datetime import UTC, datetime+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -121,10 +122,18 @@ class TestEnsureWebDimensionalPrecomputeOp(APIBaseTest):# 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}"}):+ with (+ time_machine.travel("2026-10-14T20:21:00Z", tick=False),+ 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))+ chunks = [(s, e) for _t, s, e in (c.args for c in stats_mock.call_args_list)]+ assert len(chunks) > 1+ assert all((e - s).days <= 7 for s, e in chunks)+ # A chunk that straddles UTC midnight makes the framework merge two missing days into one+ # INSERT, so every boundary must sit on a UTC midnight even when the run starts mid-day.+ assert all(b == b.replace(hour=0, minute=0, second=0, microsecond=0) for chunk in chunks for b in chunk)@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")diff --git a/products/web_analytics/dags/web_dimensional_precompute.py b/products/web_analytics/dags/web_dimensional_precompute.pyindex e56f214b5bde..bedb01eef5cf 100644--- a/products/web_analytics/dags/web_dimensional_precompute.py+++ b/products/web_analytics/dags/web_dimensional_precompute.py@@ -136,7 +136,10 @@ def _ensure_for_team(@dagster.opdef 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)+ # chunk_ranges slices backwards from `end`, so ending on a UTC midnight makes every chunk one UTC+ # day. The framework builds one job per UTC day, and a chunk that straddles midnight merges two+ # missing days into a single INSERT that reads twice the data.+ end = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)team_ids = get_selected_team_ids()