: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): precompute language breakdown via two-level read (#62602)
Lucas Ricoy8a96ba7433f1
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.pyindex 5b0d4d62b7b1..b24ff2609c28 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@@ -38,6 +38,7 @@ PARITY_BREAKDOWNS = [("channel_type", WebStatsBreakdown.INITIAL_CHANNEL_TYPE),("initial_referring_domain", WebStatsBreakdown.INITIAL_REFERRING_DOMAIN),("initial_referring_url", WebStatsBreakdown.INITIAL_REFERRING_URL),+ ("language", WebStatsBreakdown.LANGUAGE),]@@ -66,6 +67,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):"$browser": "Chrome","$os": "Linux","$device_type": "Desktop",+ "$browser_language": "en-US","$geoip_country_code": "US","$geoip_subdivision_1_code": "US-CA","$geoip_subdivision_1_name": "California",@@ -114,6 +116,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):"$browser": "Firefox","$os": "Windows","$device_type": "Mobile",+ "$browser_language": "en-GB","$geoip_country_code": "GB","$geoip_subdivision_1_code": "GB-ENG","$geoip_subdivision_1_name": "England",@@ -316,14 +319,83 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):assert self._job_count() == 0@freeze_time("2024-01-15T12:00:00Z")- def test_language_breakdown_falls_through(self):- # LANGUAGE needs an extra topK aggregation column that can't be rebuilt- # from hourly states — it must fall through to the raw path.+ def test_language_breakdown_precomputes_and_groups_by_prefix(self):+ # LANGUAGE precomputes: the INSERT stores the full `$browser_language`+ # ("en-US"/"en-GB"); the read groups by the "en" prefix and labels it with+ # the most-common region (US wins on views), reproducing the raw two-level+ # query entirely on read. en-US (u1, 3 views) + en-GB (u2, 1 view) collapse+ # to one "en-US" row with 2 visitors / 4 views.self._seed()with self._enable_lazy():- self._run(self._build_query(breakdown_by=WebStatsBreakdown.LANGUAGE))+ response = self._run(self._build_query(breakdown_by=WebStatsBreakdown.LANGUAGE))- assert self._job_count() == 0+ assert self._job_count() > 0+ assert response.usedLazyPrecompute is True+ assert self._metrics(response) == [("en-US", (2.0, None), (4.0, None))]++ @freeze_time("2024-01-15T12:00:00Z")+ def test_language_breakdown_keeps_missing_value(self):+ # The raw LANGUAGE query keeps rows with no `$browser_language`+ # (outer_where_breakdown is None for LANGUAGE) so the tile total stays+ # consistent with the overview. The lazy read must do the same — assert+ # parity rather than a hardcoded label so it tracks whatever the raw path+ # renders for the missing bucket.+ self._seed()+ _create_person(team_id=self.team.pk, distinct_ids=["u3"], properties={"name": "u3"})+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="u3",+ timestamp="2024-01-05T08:00:00Z",+ properties=self._props(+ **{+ "$session_id": str(uuid7("2024-01-05")),+ "$host": "example.com",+ "$current_url": "https://example.com/a",+ "$pathname": "/a",+ "$browser_language": None,+ }+ ),+ )++ raw = self._metrics(self._run(self._build_query(breakdown_by=WebStatsBreakdown.LANGUAGE)))+ with self._enable_lazy():+ lazy_response = self._run(self._build_query(breakdown_by=WebStatsBreakdown.LANGUAGE))++ assert lazy_response.usedLazyPrecompute is True+ assert self._metrics(lazy_response) == raw++ @freeze_time("2024-01-15T12:00:00Z")+ def test_language_breakdown_three_part_tag_matches_raw(self):+ # 3-component BCP-47 tags (e.g. `zh-Hans-CN`) must split the same way as the+ # raw query, which uses `splitByChar('-', ..., 2)`. Assert parity against the+ # raw path rather than a hardcoded label so it holds under any cluster's+ # `splitby_max_substrings_includes_remaining_string` setting.+ self._seed()+ _create_person(team_id=self.team.pk, distinct_ids=["u4"], properties={"name": "u4"})+ for path, ts in (("/a", "2024-01-05T08:00:00Z"), ("/b", "2024-01-05T08:05:00Z")):+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="u4",+ timestamp=ts,+ properties=self._props(+ **{+ "$session_id": str(uuid7("2024-01-05")),+ "$host": "example.com",+ "$current_url": f"https://example.com{path}",+ "$pathname": path,+ "$browser_language": "zh-Hans-CN",+ }+ ),+ )++ raw = self._metrics(self._run(self._build_query(breakdown_by=WebStatsBreakdown.LANGUAGE)))+ with self._enable_lazy():+ lazy_response = self._run(self._build_query(breakdown_by=WebStatsBreakdown.LANGUAGE))++ assert lazy_response.usedLazyPrecompute is True+ assert self._metrics(lazy_response) == raw, f"raw={raw} lazy={self._metrics(lazy_response)}"@freeze_time("2024-01-15T12:00:00Z")def test_conversion_goal_falls_through(self):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.pyindex cb66c5e813a7..a8e82c24e129 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@@ -58,7 +58,7 @@ WEB_STATS_LAZY_FAILED = Counter(# expect to behave well under precompute. UTM/browser/OS/region/city values are# user-controlled at ingestion so cardinality is not strictly bounded, but in# practice they sit several orders of magnitude below the per-page breakdowns we-# deliberately route to the raw path (page/path, FRUSTRATION_METRICS, LANGUAGE).+# deliberately route to the raw path (page/path, FRUSTRATION_METRICS).# The failure mode for a pathological team is a slow precompute INSERT, not an# incorrect result — sort, pagination and HAVING all run in SQL so the read# returns exactly the page the user asked for regardless of total distinct@@ -73,6 +73,21 @@ WEB_STATS_LAZY_FAILED = Counter(# Tuple/float breakdowns (REGION, CITY, VIEWPORT, TIMEZONE) are supported: the# breakdown value is JSON-encoded into the `breakdown_value` String column and# decoded back to its native shape on read.+#+# LANGUAGE is supported but special: the raw query groups by the language prefix+# ("en" from "en-US") and labels each group with its most-common region via+# topK(1). The INSERT stores the full `$browser_language` ("en-US") as the+# breakdown_value; the read derives the prefix + most-common-region deterministically+# via a two-level aggregation (see `_LANGUAGE_READ_SQL_TEMPLATE`). The region label+# is window-dependent, so it must be computed on read, not baked into the per-hour+# INSERT. The raw `topK(1)` picks the region with the most sessions; the precompute+# stores no session-count state, so the read approximates it with `argMax` over+# pageviews — the closest stored signal (the dominant region almost always leads on+# both). Matching session-topK exactly would need a new stored state and is deferred+# since it only changes the displayed region (not any count) in rare ties. Missing+# `$browser_language` is kept (not filtered) to match the raw query's+# `outer_where_breakdown() is None` for LANGUAGE, so the tile total stays consistent+# with the overview.SUPPORTED_BREAKDOWNS: set[WebStatsBreakdown] = {WebStatsBreakdown.INITIAL_CHANNEL_TYPE,WebStatsBreakdown.INITIAL_REFERRING_DOMAIN,@@ -91,6 +106,7 @@ SUPPORTED_BREAKDOWNS: set[WebStatsBreakdown] = {WebStatsBreakdown.REGION,WebStatsBreakdown.CITY,WebStatsBreakdown.TIMEZONE,+ WebStatsBreakdown.LANGUAGE,}# Breakdowns whose value is a tuple — JSON-decoded as a list and converted back@@ -292,6 +308,56 @@ GROUP BY breakdown_value"""+# LANGUAGE read. The INSERT stores the full `$browser_language` ("en-US") as the+# JSON-encoded `breakdown_value`; here we reproduce the raw query's behaviour —+# group by the language prefix ("en") and label each group with its most-common+# region — entirely on read.+#+# `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 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+# kept (not filtered), matching the raw query's `outer_where_breakdown() is None` for+# LANGUAGE.+_LANGUAGE_READ_SQL_TEMPLATE = """+SELECT+ concat(m.lang_prefix, '-', r.top_region) AS breakdown_value,+ m.visitors AS visitors,+ m.previous_visitors AS previous_visitors,+ m.views AS views,+ m.previous_views AS previous_views,+ sum({sort_metric}) OVER () AS fill_total+FROM (+ SELECT+ arrayElement(splitByChar('-', JSONExtractString(breakdown_value), 2), 1) AS lang_prefix,+ uniqMergeIf(uniq_users_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS visitors,+ uniqMergeIf(uniq_users_state, and(time_window_start >= {prev_start}, time_window_start < {prev_end})) AS previous_visitors,+ sumMergeIf(sum_pageviews_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS views,+ sumMergeIf(sum_pageviews_state, and(time_window_start >= {prev_start}, time_window_start < {prev_end})) AS previous_views+ FROM posthog.web_stats_preaggregated+ WHERE and(team_id = {team_id}, job_id IN {job_ids}, breakdown_by = {breakdown_by})+ GROUP BY lang_prefix+) AS m+LEFT JOIN (+ SELECT lang_prefix, argMax(region, region_views) AS top_region+ FROM (+ SELECT+ arrayElement(splitByChar('-', JSONExtractString(breakdown_value), 2), 1) AS lang_prefix,+ arrayElement(splitByChar('-', JSONExtractString(breakdown_value), 2), 2) AS region,+ sumMergeIf(sum_pageviews_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS region_views+ FROM posthog.web_stats_preaggregated+ WHERE and(team_id = {team_id}, job_id IN {job_ids}, breakdown_by = {breakdown_by})+ GROUP BY lang_prefix, region+ )+ GROUP BY lang_prefix+) AS r ON m.lang_prefix = r.lang_prefix+"""++@dataclassclass LazyStatsRow:"""One breakdown value with its decoded value and current/previous metrics.@@ -375,6 +441,10 @@ def _decode_breakdown_value(breakdown_by: WebStatsBreakdown, raw: str) -> object# A non-nullable String column can surface a genuine NULL breakdown as# an empty string; treat it as the null breakdown value.return None+ if breakdown_by == WebStatsBreakdown.LANGUAGE:+ # The LANGUAGE read emits the final "lang-region" string directly+ # (concat of prefix + most-common region), not a JSON-wrapped value.+ return rawvalue = json.loads(raw)if breakdown_by in TUPLE_BREAKDOWNS and isinstance(value, list):return tuple(value)@@ -418,13 +488,19 @@ def execute_read_query("sort_metric": ast.Field(chain=[sort_metric]),}- parsed = parse_select(_READ_SQL_TEMPLATE, placeholders=placeholders)+ read_template = (+ _LANGUAGE_READ_SQL_TEMPLATE if runner.query.breakdownBy == WebStatsBreakdown.LANGUAGE else _READ_SQL_TEMPLATE+ )+ parsed = parse_select(read_template, placeholders=placeholders)assert isinstance(parsed, ast.SelectQuery)# Filter equivalent to the raw query's `outer_where_breakdown()`. Pushing# this to HAVING means ORDER BY + LIMIT downstream see the same row set the- # raw path's pagination operates on.- parsed.having = _breakdown_having_expr(runner.query.breakdownBy)+ # raw path's pagination operates on. LANGUAGE applies its breakdown filter in+ # the subquery WHERE instead — its outer SELECT has no GROUP BY, so a HAVING+ # there would be invalid.+ if runner.query.breakdownBy != WebStatsBreakdown.LANGUAGE:+ parsed.having = _breakdown_having_expr(runner.query.breakdownBy)direction: Literal["ASC", "DESC"] = "DESC" if descending else "ASC"secondary = "views" if sort_metric == "visitors" else "visitors"