: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): cap paths precompute to top-k by sort key (#65664)
Lucas Ricoy2925593f202a
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.pyindex ccf482845e53..8cce89cf4579 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@@ -25,14 +25,27 @@ from posthog.schema import (WebStatsTableQuery,)+from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.models.utils import uuid7from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResultfrom products.analytics_platform.backend.models.preaggregation_job import PreaggregationJobfrom products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner++# Aliased so pytest doesn't collect this `test_`-prefixed helper as a test case.+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ SESSION_FORWARD_PAD_MINUTES,+ host_filter_expr,+ test_account_filter_expr as _test_account_filter_expr,+)from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import (+ INSERT_QUERY_TEMPLATE_CAPPED,_breakdown_value_expr,_entry_breakdown_value_expr,+ _events_session_id_expr,+ _top_k_ranking_expr,)@@ -384,6 +397,71 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):f"doPathCleaning on/off must produce distinct cache keys, got overlap: {raw_hashes & cleaned_hashes}")+ @parameterized.expand(+ [+ # Descending sorts cap by the matching merge metric; default is visitors DESC.+ ("default_visitors", None, "uniqMerge"),+ ("views_desc", [WebAnalyticsOrderByFields.VIEWS, WebAnalyticsOrderByDirection.DESC], "sumMerge"),+ ("bounce_desc", [WebAnalyticsOrderByFields.BOUNCE_RATE, WebAnalyticsOrderByDirection.DESC], "avgMerge"),+ # Ascending sorts are not capped (the "top" is a tied long tail) → store full set.+ ("visitors_asc", [WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.ASC], None),+ ]+ )+ def test_top_k_ranking_expr_matches_sort(self, _name: str, order_by, expected_metric):+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query(order_by=order_by))+ expr = _top_k_ranking_expr(runner)+ if expected_metric is None:+ assert expr is None+ else:+ assert expected_metric in repr(expr)++ @freeze_time("2024-01-15T12:00:00Z")+ def test_sort_key_gets_distinct_cache_entry(self):+ # The cap metric is in the insert AST, so different sort keys map to distinct+ # capped jobs. This also exercises that the capped insert template parses/builds.+ self._seed_two_sessions()+ with self._enable_lazy():+ self._run(+ self._build_query(order_by=[WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.DESC])+ )+ visitors_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()++ self._run(self._build_query(order_by=[WebAnalyticsOrderByFields.VIEWS, WebAnalyticsOrderByDirection.DESC]))+ views_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}++ assert visitors_hashes, "expected visitors-sorted run to create at least one job"+ assert views_hashes, "expected views-sorted run to create at least one job"+ assert visitors_hashes.isdisjoint(views_hashes), (+ f"different sort keys must produce distinct capped jobs, got overlap: {visitors_hashes & views_hashes}"+ )++ def test_capped_insert_top_level_columns_are_aliased(self):+ # Regression: the framework's `_build_manual_insert_sql` builds the INSERT+ # column list from top-level aliases — bare columns raise, silently failing+ # the capped insert so the tile falls back to raw. Parse the capped template+ # (the path every descending sort takes) and assert all columns are aliased.+ 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)+ assert isinstance(parsed, ast.SelectQuery)+ assert parsed.select and all(isinstance(e, ast.Alias) for e in parsed.select), (+ "capped insert top-level columns must all be aliased for _build_manual_insert_sql"+ )+@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.pyindex b0f23a9ca637..9282c5d892c8 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@@ -20,10 +20,15 @@ from django.conf import settingsimport structlogfrom prometheus_client import Counter, Histogram-from posthog.schema import HogQLQueryModifiers, WebAnalyticsOrderByFields, WebStatsBreakdown+from posthog.schema import (+ HogQLQueryModifiers,+ WebAnalyticsOrderByDirection,+ WebAnalyticsOrderByFields,+ WebStatsBreakdown,+)from posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client import sync_execute@@ -244,16 +249,23 @@ def _entry_breakdown_value_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr:return runner._apply_path_cleaning(path)-# HogQL template for the precompute INSERT. The lazy_computation framework-# substitutes the listed placeholders (including `time_window_min`/`time_window_max`),-# parses the result, and INSERTs into `web_stats_paths_preaggregated`.-# Framework auto-prepends `team_id`, `job_id` and appends `expires_at`.-#-# `event_type_filter` is a placeholder even though it's a constant today — so-# a future extension that admits additional event kinds (e.g. `$autocapture`)-# automatically rotates the cache key instead of silently colliding on the-# existing precomputed rows.-INSERT_QUERY_TEMPLATE = """+# Cap on stored breakdown rows per job: only the top-K paths 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++# The per-(hour, breakdown) state aggregation — shared by the capped and uncapped+# inserts. The lazy_computation framework substitutes the placeholders (incl.+# `time_window_min`/`time_window_max`) and prepends `team_id`/`job_id` + appends+# `expires_at`. `event_type_filter` is a placeholder even though constant today so a+# future event-kind extension rotates the cache key instead of colliding.+_PER_WINDOW_AGG_SQL = """SELECTtoStartOfHour(start_timestamp) AS time_window_start,breakdown_value AS breakdown_value,@@ -299,6 +311,60 @@ FROM (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. NOTE: `per_window` is+# referenced twice, so ClickHouse re-evaluates the events aggregation once for the+# top-K selection and once for the output; acceptable for the background insert, a+# candidate for a single-pass window-function rewrite if it proves too heavy.+INSERT_QUERY_TEMPLATE_CAPPED = (+ "WITH per_window AS ("+ + _PER_WINDOW_AGG_SQL+ + """)+SELECT+ time_window_start AS time_window_start,+ breakdown_value AS breakdown_value,+ uniq_users_state AS uniq_users_state,+ sum_pageviews_state AS sum_pageviews_state,+ avg_bounce_state AS avg_bounce_state+FROM per_window+WHERE breakdown_value IN (+ SELECT breakdown_value FROM per_window+ GROUP BY breakdown_value+ ORDER BY {top_k_metric} DESC, breakdown_value ASC+ LIMIT """+ + str(PATHS_TOP_K)+ + "\n)"+)+++def _top_k_ranking_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr | None:+ """Ranking expression for the insert top-K cap, mirroring the read's sort.++ Returns the metric to rank by (DESC, top-K kept) for a descending sort — the+ common, displayable case (the eager warmer's default is `visitors DESC`). Returns+ `None` for an ascending sort: there the "top" is a huge tied long tail (e.g. all+ 1-visit paths), so a cap would be unstable and shrink nothing — we store the full+ set uncapped instead. Field/direction default to `visitors DESC`, matching+ `WebStatsTableQueryRunner._resolve_sort_field`. Bounce NaN (paths with no entry+ sessions) ranks last via the `-1.0` sentinel, matching the read's NULLS-LAST."""+ 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+ field = order_by[0] if order_by else WebAnalyticsOrderByFields.VISITORS+ if field == WebAnalyticsOrderByFields.VIEWS:+ return parse_expr("sumMerge(sum_pageviews_state)")+ if field == WebAnalyticsOrderByFields.BOUNCE_RATE:+ return parse_expr("if(isNaN(avgMerge(avg_bounce_state)), -1.0, avgMerge(avg_bounce_state))")+ return parse_expr("uniqMerge(uniq_users_state)")+def ensure_web_stats_paths_precomputed(runner: "WebStatsTableQueryRunner",@@ -317,9 +383,18 @@ def ensure_web_stats_paths_precomputed("pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),}+ # Cap to the displayable top-K for descending sorts; store the full set otherwise.+ # The metric goes into the INSERT AST, so the sort dimension joins the job hash.+ ranking_expr = _top_k_ranking_expr(runner)+ if ranking_expr is not None:+ insert_query = INSERT_QUERY_TEMPLATE_CAPPED+ placeholders["top_k_metric"] = ranking_expr+ else:+ insert_query = INSERT_QUERY_TEMPLATE+return web_ensure_precomputed(team=runner.team,- insert_query=INSERT_QUERY_TEMPLATE,+ insert_query=insert_query,time_range_start=time_range_start,time_range_end=time_range_end,ttl_seconds=LAZY_TTL_SECONDS,