Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(web-analytics): keep null breakdown rows in dimensional precompute reads (#65829)

Lucas Ricoyb94478137393
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
index 0d399209e609..07bef57bf55b 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
@@ -20,11 +20,14 @@ from posthog.schema import (
WebStatsTableQuery,
)
+from posthog.hogql import ast
+
from posthog.clickhouse.client import sync_execute
from posthog.models.utils import uuid7
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import _breakdown_having_expr
# Low-cardinality breakdowns with a generic seed that have data and are cheap to
# assert parity on. VIEWPORT is exercised separately — the raw query compares
@@ -235,6 +238,55 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy == raw, f"lazy/raw compare mismatch for {breakdown_by}: raw={raw}, lazy={lazy}"
+ @parameterized.expand(
+ [
+ ("browser", WebStatsBreakdown.BROWSER, "$browser"),
+ ("os", WebStatsBreakdown.OS, "$os"),
+ ("device_type", WebStatsBreakdown.DEVICE_TYPE, "$device_type"),
+ ]
+ )
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_lazy_keeps_null_breakdown_rows(self, _name: str, breakdown_by: WebStatsBreakdown, null_prop: str):
+ self._seed()
+ # One extra session whose breakdown property is absent -> a genuine NULL that
+ # both paths must surface as a "(none)" row rather than silently drop.
+ s = str(uuid7("2024-01-05"))
+ props = self._props(
+ **{"$session_id": s, "$host": "example.com", "$current_url": "https://example.com/n", "$pathname": "/n"}
+ )
+ props.pop(null_prop)
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="u1",
+ timestamp="2024-01-05T08:00:00Z",
+ properties=props,
+ )
+
+ raw = self._metrics(self._run(self._build_query(breakdown_by=breakdown_by)))
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query(breakdown_by=breakdown_by))
+ lazy = self._metrics(lazy_response)
+
+ # Guard against a silent fallback to raw making lazy==raw trivially true.
+ assert lazy_response.preComputeStrategy == WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
+ assert any(row[0] is None for row in raw), f"raw should surface a null {breakdown_by} row, got {raw}"
+ assert lazy == raw, f"lazy dropped/altered the null row for {breakdown_by}: raw={raw}, lazy={lazy}"
+
+ @parameterized.expand([(b.value, b) for b in WebStatsBreakdown])
+ def test_breakdown_having_matches_live_null_handling(self, _name: str, breakdown_by: WebStatsBreakdown):
+ # The lazy read's HAVING must keep/drop NULL breakdown rows exactly as the raw
+ # runner's outer_where_breakdown does, or precompute tiles gain/lose a "(none)"
+ # row relative to raw. `outer_where_breakdown() is None` means "keep nulls"; the
+ # lazy side encodes that as a bare `True` HAVING.
+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query(breakdown_by=breakdown_by))
+ live_keeps_null = runner.outer_where_breakdown() is None
+ having = _breakdown_having_expr(breakdown_by)
+ lazy_keeps_null = isinstance(having, ast.Constant) and having.value is True
+ assert lazy_keeps_null == live_keeps_null, (
+ f"{breakdown_by}: lazy keeps_null={lazy_keeps_null} but raw keeps_null={live_keeps_null}"
+ )
+
@freeze_time("2024-01-15T12:00:00Z")
def test_viewport_breakdown_lazy_runs(self):
# The raw VIEWPORT query compares viewport tuple elements against 0,
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
index 07f4e3fdedb2..77d61580de04 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
@@ -322,9 +322,12 @@ GROUP BY breakdown_value
#
# `m` computes the prefix-level visitor/view metrics: `uniqMergeIf` over a GROUP BY
# prefix dedups users across regions exactly (no double-count), matching the raw
-# query's prefix-level `uniq`. `r` derives the most-common region per prefix via
-# `argMax(region, region_views)` — the precompute-side equivalent of the raw query's
-# `topK(1)` over the region part. The `splitByChar('-', ..., 2)` limit mirrors the raw
+# query's prefix-level `uniq`. `r` derives the displayed region per prefix via
+# `argMax(region, region_views)` — a best-effort *approximation* of the raw query's
+# `topK(1)` over the region part, NOT an exact equivalent: `topK(1)` weights by session
+# count, which the precompute does not store, so the region *suffix* on a multi-region
+# language (e.g. `cs-CZ` vs `cs-`) can differ from raw. Counts are unaffected; see the
+# module-level LANGUAGE note above for why this is accepted. The `splitByChar('-', ..., 2)` limit mirrors the raw
# query's exact split signature so the prefix/region split stays identical to the raw
# path for multi-part BCP-47 tags (e.g. `zh-Hans-CN`) regardless of the cluster's
# `splitby_max_substrings_includes_remaining_string` setting. Empty/null languages are
@@ -406,6 +409,26 @@ def _resolve_sort_metric(query: WebStatsTableQuery) -> tuple[str, bool]:
return sort_metric, descending
+# Breakdowns where the raw query keeps NULL rows (surfaced as a "(none)" row) instead
+# of dropping them — must stay in lockstep with the `outer_where_breakdown() is None`
+# cases in `WebStatsTableQueryRunner`. `test_breakdown_having_matches_live_null_handling`
+# enforces the parity so the two can't drift.
+_KEEP_NULL_BREAKDOWNS = {
+ WebStatsBreakdown.COUNTRY,
+ WebStatsBreakdown.BROWSER,
+ WebStatsBreakdown.OS,
+ WebStatsBreakdown.DEVICE_TYPE,
+ WebStatsBreakdown.LANGUAGE,
+ WebStatsBreakdown.TIMEZONE,
+ WebStatsBreakdown.INITIAL_REFERRING_DOMAIN,
+ WebStatsBreakdown.INITIAL_UTM_SOURCE,
+ WebStatsBreakdown.INITIAL_UTM_CAMPAIGN,
+ WebStatsBreakdown.INITIAL_UTM_MEDIUM,
+ WebStatsBreakdown.INITIAL_UTM_TERM,
+ WebStatsBreakdown.INITIAL_UTM_CONTENT,
+}
+
+
def _breakdown_having_expr(breakdown_by: WebStatsBreakdown) -> ast.Expr:
"""HAVING-clause equivalent of the raw query's `outer_where_breakdown()` —
operates on the JSON-encoded `breakdown_value` column produced by the INSERT.
@@ -424,14 +447,10 @@ def _breakdown_having_expr(breakdown_by: WebStatsBreakdown) -> ast.Expr:
"JSONExtractRaw(breakdown_value, 1) NOT IN ('null', '0') "
"AND JSONExtractRaw(breakdown_value, 2) NOT IN ('null', '0')"
)
- if breakdown_by in {
- WebStatsBreakdown.INITIAL_UTM_SOURCE,
- WebStatsBreakdown.INITIAL_UTM_CAMPAIGN,
- WebStatsBreakdown.INITIAL_UTM_MEDIUM,
- WebStatsBreakdown.INITIAL_UTM_TERM,
- WebStatsBreakdown.INITIAL_UTM_CONTENT,
- }:
- # The raw query intentionally keeps null UTM values.
+ if breakdown_by in _KEEP_NULL_BREAKDOWNS:
+ # Mirror the raw query's `outer_where_breakdown() is None` set: missing data is
+ # real for these dimensions and surfaces as a "(none)" row, so it must not be
+ # dropped. Source of truth is `WebStatsTableQueryRunner.outer_where_breakdown`.
return ast.Constant(value=True)
if breakdown_by == WebStatsBreakdown.INITIAL_CHANNEL_TYPE:
# JSON scalars: 'null' is genuine null, '""' is empty string.