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.

feat(web-analytics): serve bounce-less page breakdowns from paths precompute (#102024)

Lucas Ricoy21272f92473d
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index a43b268c7f7c..6818be858afd 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -259,8 +259,10 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
Mirrors the family-level branches of `_get_strategy` above, deliberately not its join
variants: those pick how a family runs the query, not which family owns it. The two
- taxonomies diverge in one place. INITIAL_PAGE with bounce rate is a simple breakdown with an
- entry-pathname override on the live path, but the paths family is what precomputes it.
+ taxonomies diverge where the live path treats a pathname breakdown as simple: INITIAL_PAGE
+ (with or without bounce) and bounce-less PAGE run as simple breakdowns live, but the paths
+ family is what precomputes every pathname shape — its buckets store bounce state either
+ way, and the response just omits the column when the query didn't ask for it.
The families are disjoint, so asking only the owner loses no precompute hit: PAGE,
INITIAL_PAGE and FRUSTRATION_METRICS are all absent from the simple family's
@@ -271,14 +273,7 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
if breakdown == WebStatsBreakdown.FRUSTRATION_METRICS:
return "frustration"
- if (
- breakdown == WebStatsBreakdown.PAGE
- and not self.query.conversionGoal
- and (self.query.includeAvgTimeOnPage or self.query.includeBounceRate)
- ):
- return "paths"
-
- if breakdown == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:
+ if breakdown in (WebStatsBreakdown.PAGE, WebStatsBreakdown.INITIAL_PAGE) and not self.query.conversionGoal:
return "paths"
return "simple"
@@ -288,7 +283,10 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
direction: Literal["ASC", "DESC"] = "DESC"
if self.query.orderBy:
field = cast(WebAnalyticsOrderByFields, self.query.orderBy[0])
- direction = cast(WebAnalyticsOrderByDirection, self.query.orderBy[1]).value
+ # The schema does not bound orderBy's length, so an API caller can send
+ # just the field; a missing direction defaults to DESC everywhere.
+ if len(self.query.orderBy) > 1:
+ direction = cast(WebAnalyticsOrderByDirection, self.query.orderBy[1]).value
if field == WebAnalyticsOrderByFields.VISITORS:
column = "context.columns.visitors"
@@ -692,6 +690,10 @@ WHERE and(
this just renames fields and applies the `limit + 1` → `hasMore`
truncation."""
include_previous = bool(self.query_compare_to_date_range)
+ # The SQL always computes bounce (the stored buckets carry it either way);
+ # the response only carries it when the query asked, so a bounce-less read
+ # (weekly digest, API callers) keeps the same column set as the live path.
+ include_bounce = bool(self.query.includeBounceRate)
has_more = len(rows) > limit
page = rows[:limit]
@@ -712,22 +714,22 @@ WHERE and(
# in case a future schema change reintroduces a NaN path.
bounce_rate = _none_if_nan(bounce_rate)
prev_bounce_rate = _none_if_nan(prev_bounce_rate)
- results.append(
- [
- breakdown_value,
- (visitors, prev_visitors if include_previous else None),
- (views, prev_views if include_previous else None),
- (bounce_rate, prev_bounce_rate if include_previous else None),
- float(fill_fraction) if fill_fraction is not None else 0.0,
- "", # cross_sell placeholder
- ]
- )
+ result_row = [
+ breakdown_value,
+ (visitors, prev_visitors if include_previous else None),
+ (views, prev_views if include_previous else None),
+ ]
+ if include_bounce:
+ result_row.append((bounce_rate, prev_bounce_rate if include_previous else None))
+ result_row.append(float(fill_fraction) if fill_fraction is not None else 0.0)
+ result_row.append("") # cross_sell placeholder
+ results.append(result_row)
columns = [
"context.columns.breakdown_value",
"context.columns.visitors",
"context.columns.views",
- "context.columns.bounce_rate",
+ *(["context.columns.bounce_rate"] if include_bounce else []),
"context.columns.ui_fill_fraction",
"context.columns.cross_sell",
]
@@ -753,8 +755,9 @@ WHERE and(
field = "visitors"
if self.query.orderBy:
order_field = cast(WebAnalyticsOrderByFields, self.query.orderBy[0])
- order_dir = cast(WebAnalyticsOrderByDirection, self.query.orderBy[1])
- direction = cast(Literal["ASC", "DESC"], order_dir.value)
+ if len(self.query.orderBy) > 1:
+ order_dir = cast(WebAnalyticsOrderByDirection, self.query.orderBy[1])
+ direction = cast(Literal["ASC", "DESC"], order_dir.value)
if order_field == WebAnalyticsOrderByFields.VISITORS:
field = "visitors"
elif order_field == WebAnalyticsOrderByFields.VIEWS:
diff --git a/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py
index e2a9745ff7c0..32b415d06c32 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py
@@ -582,7 +582,8 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)
column = None
direction: Literal["ASC", "DESC"] = "DESC"
field = cast(WebAnalyticsOrderByFields, self.runner.query.orderBy[0])
- direction = cast(WebAnalyticsOrderByDirection, self.runner.query.orderBy[1]).value
+ if len(self.runner.query.orderBy) > 1:
+ direction = cast(WebAnalyticsOrderByDirection, self.runner.query.orderBy[1]).value
if field == WebAnalyticsOrderByFields.VISITORS:
column = "context.columns.visitors"
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
index 9b60f1e71cb4..eb69634ad92d 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
@@ -264,7 +264,7 @@ class TestOwningLazyPrecomputeFamily(BaseTest):
WebStatsTableQuery(
dateRange=DateRange(date_from="-7d"), properties=[], breakdownBy=WebStatsBreakdown.PAGE
),
- "simple",
+ "paths",
),
(
"page with a conversion goal",
@@ -292,7 +292,7 @@ class TestOwningLazyPrecomputeFamily(BaseTest):
WebStatsTableQuery(
dateRange=DateRange(date_from="-7d"), properties=[], breakdownBy=WebStatsBreakdown.INITIAL_PAGE
),
- "simple",
+ "paths",
),
(
"frustration metrics",
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 ccb35a514c4e..5c0dc9226771 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
@@ -366,20 +366,14 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert self._job_count() == 0, "extra metrics are not precomputed — must fall through to raw"
- @parameterized.expand(
- [
- ("page", WebStatsBreakdown.PAGE),
- ("initial_page", WebStatsBreakdown.INITIAL_PAGE),
- ("exit_click", WebStatsBreakdown.EXIT_CLICK),
- ]
- )
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
- def test_high_cardinality_breakdown_falls_through(self, _name: str, breakdown_by: WebStatsBreakdown):
- # Page/path breakdowns are intentionally excluded — handled by the
- # dedicated paths lazy precompute. They fall through to raw here.
+ def test_high_cardinality_breakdown_falls_through(self):
+ # Pathname breakdowns (PAGE/INITIAL_PAGE) are owned by the paths lazy
+ # precompute — bounce or not — and are covered in its test suite.
+ # EXIT_CLICK belongs to no family and must stay on the raw path.
self._seed()
with self._enable_lazy():
- self._run(self._build_query(breakdown_by=breakdown_by))
+ self._run(self._build_query(breakdown_by=WebStatsBreakdown.EXIT_CLICK))
assert self._job_count() == 0
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 f4f9bdd07fb8..7e8dd5276fbe 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
@@ -48,6 +48,7 @@ from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precomput
_entry_breakdown_value_expr,
_events_session_id_expr,
_top_k_ranking_expr,
+ can_use_lazy_precompute,
)
@@ -359,9 +360,73 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
)
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
- def test_missing_include_bounce_rate_falls_through(self):
+ def test_bounce_less_read_shares_buckets(self):
+ """A PAGE read without bounce rate (the weekly digest's shape) must take the
+ lazy path and resolve the SAME jobs as the dashboard's bounce read — not fall
+ through to live, and not mint a second bucket namespace."""
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ no_bounce_query = self._build_query(include_bounce_rate=False)
+ runner = WebStatsTableQueryRunner(team=self.team, query=no_bounce_query)
+ assert runner._owning_lazy_precompute_family() == "paths"
+ assert can_use_lazy_precompute(runner)
+
+ self._run(no_bounce_query)
+ no_bounce_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+ assert no_bounce_hashes, "bounce-less read should create precompute jobs"
+
+ self._run(self._build_query())
+ bounce_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ assert bounce_hashes == no_bounce_hashes, (
+ "bounce and bounce-less reads must share one bucket namespace, "
+ f"got extra hashes: {bounce_hashes ^ no_bounce_hashes}"
+ )
+
+ @parameterized.expand(
+ [
+ ("with_bounce", True),
+ ("without_bounce", False),
+ ]
+ )
+ def test_lazy_response_bounce_column_follows_query(self, _name: str, include_bounce: bool) -> None:
+ # One row in the executor's 8-tuple wire shape; the builder must emit the
+ # bounce column only when the query asked for it.
+ rows = [("/a", 3, 1, 5, 2, 0.5, 0.25, 0.8)]
+ runner = WebStatsTableQueryRunner(
+ team=self.team,
+ query=self._build_query(include_bounce_rate=include_bounce, compare=True),
+ )
+ response = runner._build_response_from_lazy_rows(rows, limit=10, offset=0)
+
+ expected_columns = [
+ "context.columns.breakdown_value",
+ "context.columns.visitors",
+ "context.columns.views",
+ *(["context.columns.bounce_rate"] if include_bounce else []),
+ "context.columns.ui_fill_fraction",
+ "context.columns.cross_sell",
+ ]
+ assert response.columns == expected_columns
+ expected_row = [
+ "/a",
+ (3, 1),
+ (5, 2),
+ *([(0.5, 0.25)] if include_bounce else []),
+ 0.8,
+ "",
+ ]
+ assert response.results == [expected_row]
+
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_bounce_less_read_with_bounce_sort_falls_through(self):
with self._enable_lazy():
- self._run(self._build_query(include_bounce_rate=False))
+ self._run(
+ self._build_query(
+ include_bounce_rate=False,
+ order_by=[WebAnalyticsOrderByFields.BOUNCE_RATE, WebAnalyticsOrderByDirection.DESC],
+ )
+ )
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
@@ -650,6 +715,16 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
self._run(self._build_query(order_by=[field, WebAnalyticsOrderByDirection.DESC]))
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_single_element_orderby_defaults_direction(self) -> None:
+ # The schema does not bound orderBy's length, so an API caller can send just
+ # the field. The query must complete with DESC defaulted, not IndexError on
+ # the missing direction — on the lazy sort resolution and the raw path alike.
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ response = self._run(self._build_query(order_by=[WebAnalyticsOrderByFields.VISITORS]))
+ assert response.results is not None
+
@parameterized.expand(
[
("visitors_asc", WebAnalyticsOrderByFields.VISITORS, WebAnalyticsOrderByDirection.ASC),
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 bcdf42451f89..7869a49ee7f2 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
@@ -417,10 +417,10 @@ def _resolve_sort_metric(query: WebStatsTableQuery) -> tuple[str, bool]:
descending = True
if query.orderBy:
field = query.orderBy[0]
- direction = query.orderBy[1]
if field == WebAnalyticsOrderByFields.VIEWS:
sort_metric = "views"
- descending = direction != WebAnalyticsOrderByDirection.ASC
+ if len(query.orderBy) > 1:
+ descending = query.orderBy[1] != WebAnalyticsOrderByDirection.ASC
return sort_metric, descending
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 02d7202701df..17f560a832b1 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
@@ -106,10 +106,6 @@ class WrongBreakdown(LazyPrecomputeIneligible):
pass
-class MissingBounceRate(LazyPrecomputeIneligible):
- pass
-
-
class AvgTimeOnPageUnsupported(LazyPrecomputeIneligible):
pass
@@ -153,8 +149,10 @@ def _check_eligible(runner: "WebStatsTableQueryRunner") -> None:
# allows overview/paths to opt in independently per query.
if query.breakdownBy not in (WebStatsBreakdown.PAGE, WebStatsBreakdown.INITIAL_PAGE):
raise WrongBreakdown(f"breakdownBy={query.breakdownBy!r}")
- if not query.includeBounceRate:
- raise MissingBounceRate()
+ # `includeBounceRate` is deliberately NOT a gate: the precompute stores bounce
+ # state regardless, so a bounce-less read (the weekly digest, API callers)
+ # resolves the same jobs as the dashboard's bounce read and the response
+ # builder simply omits the bounce column.
if query.includeAvgTimeOnPage:
raise AvgTimeOnPageUnsupported()
if query.includeScrollDepth:
@@ -166,6 +164,11 @@ def _check_eligible(runner: "WebStatsTableQueryRunner") -> None:
order_field = query.orderBy[0]
if order_field not in SUPPORTED_ORDER_BY_FIELDS:
raise UnsupportedOrderBy(order_field)
+ # A bounce-less read sorted by bounce would order rows by a column the
+ # response (and the live fallback) does not have — refuse so both paths
+ # keep identical ordering semantics.
+ if order_field == WebAnalyticsOrderByFields.BOUNCE_RATE and not query.includeBounceRate:
+ raise UnsupportedOrderBy(order_field)
check_common_eligibility(
team=runner.team,