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): cap paths precompute per day and raise top-k to 100k (#65842)

Lucas Ricoy60de185f5a0b
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
index 8cce89cf4579..99393f0d4132 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
@@ -1,4 +1,5 @@
import uuid
+import dataclasses
import unittest
from freezegun import freeze_time
@@ -462,6 +463,47 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"capped insert top-level columns must all be aliased for _build_manual_insert_sql"
)
+ def test_capped_insert_caps_per_day_not_per_window(self):
+ # The cap must be computed PER DAY, not over the whole job window. The read path
+ # decomposes a request into daily windows and can serve one of them from a wider
+ # covering job (`filter_overlapping_jobs`), so a path in a single day's top-K must
+ # be stored even if it falls outside the job window's overall top-K — a per-window
+ # cap silently drops it. Guards against a revert to per-window capping.
+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query())
+ placeholders: dict = {
+ "events_session_id": _events_session_id_expr(runner),
+ "breakdown_value_expr": _breakdown_value_expr(runner),
+ "entry_breakdown_value_expr": _entry_breakdown_value_expr(runner),
+ "event_type_filter": runner.event_type_expr,
+ "user_filter": host_filter_expr(runner.query.properties or [], team=runner.team),
+ "test_account_filter": _test_account_filter_expr(
+ test_account_filters=runner._test_account_filters, team=runner.team
+ ),
+ "pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
+ "top_k_metric": _top_k_ranking_expr(runner),
+ "time_window_min": ast.Constant(value="__MIN__"),
+ "time_window_max": ast.Constant(value="__MAX__"),
+ }
+ parsed = parse_select(INSERT_QUERY_TEMPLATE_CAPPED, placeholders=placeholders)
+
+ rank_windows: list[ast.WindowExpr] = []
+
+ def walk(node: object) -> None:
+ if isinstance(node, ast.WindowFunction) and node.name == "dense_rank" and node.over_expr:
+ rank_windows.append(node.over_expr)
+ if dataclasses.is_dataclass(node) and not isinstance(node, type):
+ for field in dataclasses.fields(node):
+ walk(getattr(node, field.name, None))
+ elif isinstance(node, list | tuple):
+ for item in node:
+ walk(item)
+
+ walk(parsed)
+ assert rank_windows, "capped insert must rank breakdowns with a windowed dense_rank()"
+ assert all(w.partition_by and "day_bucket" in str(w.partition_by) for w in rank_windows), (
+ f"the top-K rank must partition by the day bucket, got: {[w.partition_by for w in rank_windows]}"
+ )
+
@freeze_time("2024-01-15T12:00:00Z")
def test_uuid_session_mode_falls_through(self):
query = self._build_query()
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
index a08bf6207025..cac701316a61 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
@@ -249,16 +249,16 @@ def _entry_breakdown_value_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr:
return runner._apply_path_cleaning(path)
-# Cap on stored breakdown rows per job: only the top-K paths by the query's sort
+# Cap on stored breakdown rows: only the top-K paths PER DAY by the query's sort
# metric. The PATHS tile shows a paginated top-N and the read's `LIMIT` can't prune
# the scan (it must aggregate every path to find the top), so the long tail — paths
-# that never reach the display — is pure dead weight. On a high-cardinality team the
-# top ~1k cleaned paths already cover ~98% of pageviews, so a generous K is lossless
-# for the display while shrinking the stored set by orders of magnitude. K is large
-# enough to absorb pagination and the sub-range-read case (a job window wider than
-# the read's) — a path displayable in any sub-range is virtually always within the
-# job's top-K.
-PATHS_TOP_K = 10000
+# that never reach the display — is pure dead weight. K is sized so that the vast
+# majority of teams (fleet-wide, >99% of active teams have fewer distinct cleaned
+# paths per week than this) store their full path set and only extreme-cardinality
+# outliers (typically one-path-per-pageview instrumentation) get truncated. Capping
+# per day rather than per job window keeps sub-range reads correct — see
+# `INSERT_QUERY_TEMPLATE_CAPPED`.
+PATHS_TOP_K = 100_000
# The per-(hour, breakdown) state aggregation — shared by the capped and uncapped
# inserts. The lazy_computation framework substitutes the placeholders (incl.
@@ -314,10 +314,13 @@ GROUP BY time_window_start, breakdown_value
# Uncapped insert — current behaviour, used for ASC sorts (see `_top_k_ranking_expr`).
INSERT_QUERY_TEMPLATE = _PER_WINDOW_AGG_SQL
-# Capped insert — keep only the top-K `breakdown_value`s by `{top_k_metric}` (the
-# query's sort metric, merged over the job's window), then store all their per-hour
-# rows. `{top_k_metric}` is in the AST so the sort dimension joins the job hash —
-# each sort variant gets its own correctly-capped job.
+# Capped insert — keep the top-K `breakdown_value`s by `{top_k_metric}` (the query's
+# sort metric) computed PER DAY, then store all per-hour rows of any path that reaches
+# a day's top-K. Capping per day (not over the whole job window) is what keeps the cap
+# correct for sub-range reads: the read path decomposes a request into daily windows and
+# can serve any one of them from a wider covering job (`filter_overlapping_jobs` in the
+# lazy executor), so a path in a single day's top-K must be stored even if it falls
+# outside the job window's overall top-K — a per-window cap silently drops it.
#
# `per_window` is referenced exactly ONCE: the top-K membership is computed inline with
# window functions instead of a re-scanning `breakdown_value IN (SELECT … FROM per_window)`
@@ -326,9 +329,12 @@ INSERT_QUERY_TEMPLATE = _PER_WINDOW_AGG_SQL
# filter-only `mat_*` columns (e.g. `$raw_user_agent` bot filters) out from under the filter
# that still referenced them → `Code 47 UNKNOWN_IDENTIFIER`. A single reference can't be
# pruned inconsistently. `{top_k_metric}` is the sort metric merged across the breakdown's
-# windows via `… OVER (PARTITION BY breakdown_value)`; `dense_rank()` over it (constant per
-# breakdown) ranks distinct breakdowns, so `<= PATHS_TOP_K` keeps the top-K breakdowns and
-# all their per-hour rows. The metric stays in the AST, so each sort variant gets its own job.
+# hourly rows within each day via `… OVER (PARTITION BY breakdown_value, day_bucket)`;
+# `dense_rank()` over it, partitioned by day (constant per breakdown within a day, ties
+# broken by `breakdown_value ASC`), ranks distinct breakdowns within each day, so
+# `<= PATHS_TOP_K` keeps the union of daily top-Ks. (HogQL parses `LIMIT n BY` but the
+# printer can't emit it, so the cap ranks with window functions.) The metric stays in the
+# AST, so each sort variant gets its own job.
INSERT_QUERY_TEMPLATE_CAPPED = (
"WITH per_window AS ("
+ _PER_WINDOW_AGG_SQL
@@ -346,7 +352,10 @@ FROM (
uniq_users_state AS uniq_users_state,
sum_pageviews_state AS sum_pageviews_state,
avg_bounce_state AS avg_bounce_state,
- dense_rank() OVER (ORDER BY breakdown_rank_metric DESC, breakdown_value ASC) AS breakdown_rank
+ dense_rank() OVER (
+ PARTITION BY day_bucket
+ ORDER BY breakdown_rank_metric DESC, breakdown_value ASC
+ ) AS breakdown_rank
FROM (
SELECT
time_window_start AS time_window_start,
@@ -354,6 +363,7 @@ FROM (
uniq_users_state AS uniq_users_state,
sum_pageviews_state AS sum_pageviews_state,
avg_bounce_state AS avg_bounce_state,
+ toStartOfDay(time_window_start) AS day_bucket,
{top_k_metric} AS breakdown_rank_metric
FROM per_window
)
@@ -374,27 +384,35 @@ def _top_k_ranking_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr | None:
`WebStatsTableQueryRunner._resolve_sort_field`. Bounce NaN (paths with no entry
sessions) ranks last via the `-1.0` sentinel, matching the read's NULLS-LAST.
- The metric is merged across the breakdown's per-hour rows via
- `OVER (PARTITION BY breakdown_value)` so the capped template can rank breakdowns in a
- single pass over `per_window` (see `INSERT_QUERY_TEMPLATE_CAPPED`)."""
+ The metric is merged across the breakdown's per-hour rows within each day via
+ `OVER (PARTITION BY breakdown_value, toStartOfDay(time_window_start))` so the capped
+ template can rank breakdowns per day in a single pass over `per_window` (see
+ `INSERT_QUERY_TEMPLATE_CAPPED`)."""
order_by = runner.query.orderBy or []
# A missing direction (single-element or empty orderBy) defaults to DESC, matching
# `_resolve_sort_field`'s fallback — so we still cap rather than storing the full set.
direction = order_by[1] if len(order_by) > 1 else WebAnalyticsOrderByDirection.DESC
if direction != WebAnalyticsOrderByDirection.DESC:
return None
- # The `OVER (PARTITION BY breakdown_value)` window merges the metric across the
- # breakdown's per-hour rows so the capped template can rank in one pass. Fully static
- # SQL — no interpolation, no user input.
+ # The `OVER (PARTITION BY breakdown_value, toStartOfDay(time_window_start))` window
+ # merges the metric across the breakdown's per-hour rows within a day so the capped
+ # template can rank per day in one pass. Fully static SQL — no interpolation, no
+ # user input.
field = order_by[0] if order_by else WebAnalyticsOrderByFields.VISITORS
if field == WebAnalyticsOrderByFields.VIEWS:
- return parse_expr("sumMerge(sum_pageviews_state) OVER (PARTITION BY breakdown_value)")
+ return parse_expr(
+ "sumMerge(sum_pageviews_state) OVER (PARTITION BY breakdown_value, toStartOfDay(time_window_start))"
+ )
if field == WebAnalyticsOrderByFields.BOUNCE_RATE:
return parse_expr(
- "if(isNaN(avgMerge(avg_bounce_state) OVER (PARTITION BY breakdown_value)), -1.0, "
- "avgMerge(avg_bounce_state) OVER (PARTITION BY breakdown_value))"
+ "if(isNaN(avgMerge(avg_bounce_state) "
+ "OVER (PARTITION BY breakdown_value, toStartOfDay(time_window_start))), -1.0, "
+ "avgMerge(avg_bounce_state) "
+ "OVER (PARTITION BY breakdown_value, toStartOfDay(time_window_start)))"
)
- return parse_expr("uniqMerge(uniq_users_state) OVER (PARTITION BY breakdown_value)")
+ return parse_expr(
+ "uniqMerge(uniq_users_state) OVER (PARTITION BY breakdown_value, toStartOfDay(time_window_start))"
+ )
def ensure_web_stats_paths_precomputed(