: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
refactor(web-analytics): split web analytics stats table queries into multiple strategies (#57707)
Lucas Ricoyd367c573514e
diff --git a/posthog/hogql_queries/web_analytics/stats_table.py b/posthog/hogql_queries/web_analytics/stats_table.pyindex 8a0c15af614b..42060d33accf 100644--- a/posthog/hogql_queries/web_analytics/stats_table.py+++ b/posthog/hogql_queries/web_analytics/stats_table.py@@ -14,7 +14,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import LimitContext-from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.parser import parse_exprfrom posthog.hogql.property import (get_property_key,get_property_operator,@@ -25,13 +25,14 @@ from posthog.hogql.property import (from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.web_analytics.events_prefilter import PrefilterHogQLHasMorePaginator-from posthog.hogql_queries.web_analytics.query_constants.stats_table_queries import (- FRUSTRATION_METRICS_INNER_QUERY,- MAIN_INNER_QUERY,- PATH_BOUNCE_AND_AVG_TIME_QUERY,- PATH_BOUNCE_QUERY,-)from posthog.hogql_queries.web_analytics.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilder+from posthog.hogql_queries.web_analytics.stats_table_strategies import (+ FrustrationMetricsStrategy,+ MainQueryStrategy,+ PathBounceAvgTimeStrategy,+ PathBounceStrategy,+ StatsTableQueryStrategy,+)from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner, map_columnsfrom posthog.settings.data_stores import is_web_analytics_events_prefilter_team@@ -87,238 +88,24 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryResponsself.used_preaggregated_tables = Truereturn self.preaggregated_query_builder.get_query()- if self.query.breakdownBy == WebStatsBreakdown.PAGE:- if self.query.conversionGoal:- return self.to_main_query(self._counts_breakdown_value())- elif self.query.includeAvgTimeOnPage:- return self.to_path_bounce_and_avg_time_query()- elif self.query.includeBounceRate:- return self.to_path_bounce_query()-- if self.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE:- if self.query.includeBounceRate:- return self.to_entry_bounce_query()+ return self._get_strategy().build_query()+ def _get_strategy(self) -> StatsTableQueryStrategy:if self.query.breakdownBy == WebStatsBreakdown.FRUSTRATION_METRICS:- return self.to_frustration_metrics_query()-- return self.to_main_query(self._counts_breakdown_value())-- def to_main_query(self, breakdown) -> ast.SelectQuery:- with self.timings.measure("stats_table_query"):- # Base selects, always returns the breakdown value, and the total number of visitors- selects = [- ast.Alias(alias="context.columns.breakdown_value", expr=self._processed_breakdown_value()),- self._period_comparison_tuple("filtered_person_id", "context.columns.visitors", "uniq"),- ]-- if self.query.conversionGoal is not None:- selects.extend(- [- self._period_comparison_tuple("conversion_count", "context.columns.total_conversions", "sum"),- self._period_comparison_tuple(- "conversion_person_id", "context.columns.unique_conversions", "uniq"- ),- ast.Alias(- alias="context.columns.conversion_rate",- expr=ast.Tuple(- exprs=[- parse_expr(- "if(`context.columns.visitors`.1 = 0, NULL, `context.columns.unique_conversions`.1 / `context.columns.visitors`.1)"- ),- parse_expr(- "if(`context.columns.visitors`.2 = 0, NULL, `context.columns.unique_conversions`.2 / `context.columns.visitors`.2)"- ),- ]- ),- ),- ]- )- else:- selects.append(- self._period_comparison_tuple("filtered_pageview_count", "context.columns.views", "sum"),- )-- if self._include_extra_aggregation_value():- selects.append(self._extra_aggregation_value())-- if self.query.includeBounceRate:- selects.append(self._period_comparison_tuple("is_bounce", "context.columns.bounce_rate", "avg"))-- order_by = self._order_by(columns=[select.alias for select in selects])- fill_fraction_expr = self._fill_fraction(order_by)- if fill_fraction_expr:- selects.append(fill_fraction_expr)-- query = ast.SelectQuery(- select=selects,- select_from=ast.JoinExpr(table=self._main_inner_query(breakdown)),- group_by=[ast.Field(chain=["context.columns.breakdown_value"])],- order_by=order_by,- having=self.outer_where_breakdown(),- )-- return query-- def to_path_bounce_and_avg_time_query(self) -> ast.SelectQuery:- if self.query.breakdownBy not in [WebStatsBreakdown.PAGE, WebStatsBreakdown.INITIAL_PAGE]:- raise NotImplementedError("Time on page is only supported for page breakdowns")-- with self.timings.measure("stats_table_time_on_page_query"):- query = parse_select(- PATH_BOUNCE_AND_AVG_TIME_QUERY,- timings=self.timings,- placeholders={- "breakdown_value": self._counts_breakdown_value(),- "session_properties": self._session_properties(),- "event_properties": self._event_properties(),- "time_on_page_event_properties": self._event_properties_for_scroll(),- "time_on_page_breakdown_value": self._scroll_prev_pathname_breakdown(),- "bounce_event_properties": self._event_properties_for_bounce_rate(),- "bounce_breakdown_value": self._bounce_entry_pathname_breakdown(),- "current_period": self._current_period_expression(),- "previous_period": self._previous_period_expression(),- "avg_current_period": self._current_period_expression("timestamp"),- "avg_previous_period": self._previous_period_expression("timestamp"),- "inside_periods": self._periods_expression(),- },- )- assert isinstance(query, ast.SelectQuery)-- columns = [select.alias for select in query.select if isinstance(select, ast.Alias)]- query.order_by = self._order_by(columns)-- fill_fraction = self._fill_fraction(query.order_by)- if fill_fraction:- query.select.append(fill_fraction)-- return query-- def to_entry_bounce_query(self) -> ast.SelectQuery:- query = self.to_main_query(self._bounce_entry_pathname_breakdown())- return query-- def to_path_bounce_query(self) -> ast.SelectQuery:- if self.query.breakdownBy not in [WebStatsBreakdown.INITIAL_PAGE, WebStatsBreakdown.PAGE]:- raise NotImplementedError("Bounce rate is only supported for page breakdowns")-- with self.timings.measure("stats_table_scroll_query"):- query = parse_select(- PATH_BOUNCE_QUERY,- timings=self.timings,- placeholders={- "breakdown_value": self._counts_breakdown_value(),- "session_properties": self._session_properties(),- "event_properties": self._event_properties(),- "bounce_event_properties": self._event_properties_for_bounce_rate(),- "bounce_breakdown_value": self._bounce_entry_pathname_breakdown(),- "current_period": self._current_period_expression(),- "previous_period": self._previous_period_expression(),- "inside_periods": self._periods_expression(),- },- )- assert isinstance(query, ast.SelectQuery)-- # Compute query order based on the columns we're selecting- columns = [select.alias for select in query.select if isinstance(select, ast.Alias)]- query.order_by = self._order_by(columns)-- fill_fraction = self._fill_fraction(query.order_by)- if fill_fraction:- query.select.append(fill_fraction)-- return query-- def to_frustration_metrics_query(self) -> ast.SelectQuery:- with self.timings.measure("frustration_metrics_query"):- # Base selects, always returns the breakdown value, and the total number of visitors- selects = [- ast.Alias(alias="context.columns.breakdown_value", expr=self._processed_breakdown_value()),- self._period_comparison_tuple("rage_clicks_count", "context.columns.rage_clicks", "sum"),- self._period_comparison_tuple("dead_clicks_count", "context.columns.dead_clicks", "sum"),- self._period_comparison_tuple("errors_count", "context.columns.errors", "sum"),- ]+ return FrustrationMetricsStrategy(self)- having_exprs = [self._frustration_metrics_having()]- outer_breakdown = self.outer_where_breakdown()- if outer_breakdown:- having_exprs.append(outer_breakdown)-- query = ast.SelectQuery(- select=selects,- select_from=ast.JoinExpr(table=self._frustration_metrics_inner_query()),- group_by=[ast.Field(chain=["context.columns.breakdown_value"])],- having=ast.And(exprs=having_exprs),- order_by=self._frustration_metrics_order_by(),- )-- return query-- def _frustration_metrics_inner_query(self):- query = parse_select(- FRUSTRATION_METRICS_INNER_QUERY,- timings=self.timings,- placeholders={- "breakdown_value": self._counts_breakdown_value(),- "event_where": parse_expr(- "events.event IN ('$pageview', '$screen', '$rageclick', '$dead_click', '$exception')"- ),- "all_properties": self._all_properties(),- "inside_periods": self._periods_expression(),- },- )-- assert isinstance(query, ast.SelectQuery)- return query-- def _frustration_metrics_having(self) -> ast.Expr:- zero_tuple = ast.Tuple(exprs=[ast.Constant(value=0), ast.Constant(value=0)])- return ast.Or(- exprs=[- ast.CompareOperation(- op=ast.CompareOperationOp.Gt,- left=ast.Field(chain=["context.columns.rage_clicks"]),- right=zero_tuple,- ),- ast.CompareOperation(- op=ast.CompareOperationOp.Gt,- left=ast.Field(chain=["context.columns.dead_clicks"]),- right=zero_tuple,- ),- ast.CompareOperation(- op=ast.CompareOperationOp.Gt,- left=ast.Field(chain=["context.columns.errors"]),- right=zero_tuple,- ),- ]- )-- def _frustration_metrics_order_by(self) -> list[ast.OrderExpr] | None:- return [- ast.OrderExpr(expr=ast.Field(chain=["context.columns.errors"]), order="DESC"),- ast.OrderExpr(expr=ast.Field(chain=["context.columns.rage_clicks"]), order="DESC"),- ast.OrderExpr(expr=ast.Field(chain=["context.columns.dead_clicks"]), order="DESC"),- ]-- def _main_inner_query(self, breakdown):- query = parse_select(- MAIN_INNER_QUERY,- timings=self.timings,- placeholders={- "breakdown_value": breakdown,- "event_where": self.event_type_expr,- "all_properties": self._all_properties(),- "inside_periods": self._periods_expression(),- },- )-- assert isinstance(query, ast.SelectQuery)+ if self.query.breakdownBy == WebStatsBreakdown.PAGE:+ if self.query.conversionGoal:+ return MainQueryStrategy(self)+ if self.query.includeAvgTimeOnPage:+ return PathBounceAvgTimeStrategy(self)+ if self.query.includeBounceRate:+ return PathBounceStrategy(self)- if self.conversion_count_expr and self.conversion_person_id_expr:- query.select.append(ast.Alias(alias="conversion_count", expr=self.conversion_count_expr))- query.select.append(ast.Alias(alias="conversion_person_id", expr=self.conversion_person_id_expr))+ if self.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:+ return MainQueryStrategy(self, breakdown_override=self._bounce_entry_pathname_breakdown())- return query+ return MainQueryStrategy(self)def _order_by(self, columns: list[str]) -> list[ast.OrderExpr] | None:column = Nonediff --git a/posthog/hogql_queries/web_analytics/stats_table_strategies.py b/posthog/hogql_queries/web_analytics/stats_table_strategies.pynew file mode 100644index 000000000000..5925616cfc46--- /dev/null+++ b/posthog/hogql_queries/web_analytics/stats_table_strategies.py@@ -0,0 +1,264 @@+from __future__ import annotations++from abc import ABC, abstractmethod+from typing import TYPE_CHECKING++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr, parse_select++from posthog.hogql_queries.web_analytics.query_constants.stats_table_queries import (+ FRUSTRATION_METRICS_INNER_QUERY,+ MAIN_INNER_QUERY,+ PATH_BOUNCE_AND_AVG_TIME_QUERY,+ PATH_BOUNCE_QUERY,+)++if TYPE_CHECKING:+ from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner+++class StatsTableQueryStrategy(ABC):+ """Each subclass represents a distinct SQL query structure.++ The runner delegates to the strategy returned by ``_get_strategy()``.+ Strategies call back into ``self.runner`` for shared helpers (breakdown+ values, property filters, period expressions, ordering, fill fractions).+ """++ def __init__(self, runner: WebStatsTableQueryRunner) -> None:+ self.runner = runner++ @abstractmethod+ def build_query(self) -> ast.SelectQuery: ...++ def _finalize_query(self, query: ast.SelectQuery) -> ast.SelectQuery:+ columns = [select.alias for select in query.select if isinstance(select, ast.Alias)]+ query.order_by = self.runner._order_by(columns)+ fill_fraction = self.runner._fill_fraction(query.order_by)+ if fill_fraction:+ query.select.append(fill_fraction)+ return query+++class MainQueryStrategy(StatsTableQueryStrategy):+ """Default query for most breakdown types.++ Used by all UTM / device / browser / OS / geo / language / timezone+ breakdowns, PAGE with conversion goals or without special metrics,+ and INITIAL_PAGE with bounce rate (via *breakdown_override*).+ """++ def __init__(+ self,+ runner: WebStatsTableQueryRunner,+ breakdown_override: ast.Expr | None = None,+ ) -> None:+ super().__init__(runner)+ self.breakdown_override = breakdown_override++ def build_query(self) -> ast.SelectQuery:+ breakdown = self.breakdown_override or self.runner._counts_breakdown_value()++ with self.runner.timings.measure("stats_table_query"):+ selects: list[ast.Expr] = [+ ast.Alias(alias="context.columns.breakdown_value", expr=self.runner._processed_breakdown_value()),+ self.runner._period_comparison_tuple("filtered_person_id", "context.columns.visitors", "uniq"),+ ]++ if self.runner.query.conversionGoal is not None:+ selects.extend(+ [+ self.runner._period_comparison_tuple(+ "conversion_count", "context.columns.total_conversions", "sum"+ ),+ self.runner._period_comparison_tuple(+ "conversion_person_id", "context.columns.unique_conversions", "uniq"+ ),+ ast.Alias(+ alias="context.columns.conversion_rate",+ expr=ast.Tuple(+ exprs=[+ parse_expr(+ "if(`context.columns.visitors`.1 = 0, NULL, `context.columns.unique_conversions`.1 / `context.columns.visitors`.1)"+ ),+ parse_expr(+ "if(`context.columns.visitors`.2 = 0, NULL, `context.columns.unique_conversions`.2 / `context.columns.visitors`.2)"+ ),+ ]+ ),+ ),+ ]+ )+ else:+ selects.append(+ self.runner._period_comparison_tuple("filtered_pageview_count", "context.columns.views", "sum"),+ )++ if self.runner._include_extra_aggregation_value():+ selects.append(self.runner._extra_aggregation_value())++ if self.runner.query.includeBounceRate:+ selects.append(+ self.runner._period_comparison_tuple("is_bounce", "context.columns.bounce_rate", "avg")+ )++ order_by = self.runner._order_by(+ columns=[select.alias for select in selects if isinstance(select, ast.Alias)]+ )+ fill_fraction_expr = self.runner._fill_fraction(order_by)+ if fill_fraction_expr:+ selects.append(fill_fraction_expr)++ query = ast.SelectQuery(+ select=selects,+ select_from=ast.JoinExpr(table=self._inner_query(breakdown)),+ group_by=[ast.Field(chain=["context.columns.breakdown_value"])],+ order_by=order_by,+ having=self.runner.outer_where_breakdown(),+ )++ return query++ def _inner_query(self, breakdown: ast.Expr) -> ast.SelectQuery:+ query = parse_select(+ MAIN_INNER_QUERY,+ timings=self.runner.timings,+ placeholders={+ "breakdown_value": breakdown,+ "event_where": self.runner.event_type_expr,+ "all_properties": self.runner._all_properties(),+ "inside_periods": self.runner._periods_expression(),+ },+ )++ assert isinstance(query, ast.SelectQuery)++ if self.runner.conversion_count_expr and self.runner.conversion_person_id_expr:+ query.select.append(ast.Alias(alias="conversion_count", expr=self.runner.conversion_count_expr))+ query.select.append(ast.Alias(alias="conversion_person_id", expr=self.runner.conversion_person_id_expr))++ return query+++class PathBounceStrategy(StatsTableQueryStrategy):+ """PAGE breakdown with bounce rate (no scroll depth or avg time)."""++ def build_query(self) -> ast.SelectQuery:+ with self.runner.timings.measure("stats_table_path_bounce_query"):+ query = parse_select(+ PATH_BOUNCE_QUERY,+ timings=self.runner.timings,+ placeholders={+ "breakdown_value": self.runner._counts_breakdown_value(),+ "session_properties": self.runner._session_properties(),+ "event_properties": self.runner._event_properties(),+ "bounce_event_properties": self.runner._event_properties_for_bounce_rate(),+ "bounce_breakdown_value": self.runner._bounce_entry_pathname_breakdown(),+ "current_period": self.runner._current_period_expression(),+ "previous_period": self.runner._previous_period_expression(),+ "inside_periods": self.runner._periods_expression(),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return self._finalize_query(query)+++class PathBounceAvgTimeStrategy(StatsTableQueryStrategy):+ """PAGE breakdown with average time on page and bounce rate."""++ def build_query(self) -> ast.SelectQuery:+ with self.runner.timings.measure("stats_table_time_on_page_query"):+ query = parse_select(+ PATH_BOUNCE_AND_AVG_TIME_QUERY,+ timings=self.runner.timings,+ placeholders={+ "breakdown_value": self.runner._counts_breakdown_value(),+ "session_properties": self.runner._session_properties(),+ "event_properties": self.runner._event_properties(),+ "time_on_page_event_properties": self.runner._event_properties_for_scroll(),+ "time_on_page_breakdown_value": self.runner._scroll_prev_pathname_breakdown(),+ "bounce_event_properties": self.runner._event_properties_for_bounce_rate(),+ "bounce_breakdown_value": self.runner._bounce_entry_pathname_breakdown(),+ "current_period": self.runner._current_period_expression(),+ "previous_period": self.runner._previous_period_expression(),+ "avg_current_period": self.runner._current_period_expression("timestamp"),+ "avg_previous_period": self.runner._previous_period_expression("timestamp"),+ "inside_periods": self.runner._periods_expression(),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return self._finalize_query(query)+++class FrustrationMetricsStrategy(StatsTableQueryStrategy):+ """FRUSTRATION_METRICS breakdown: rage clicks, dead clicks, errors."""++ def build_query(self) -> ast.SelectQuery:+ with self.runner.timings.measure("frustration_metrics_query"):+ selects: list[ast.Expr] = [+ ast.Alias(alias="context.columns.breakdown_value", expr=self.runner._processed_breakdown_value()),+ self.runner._period_comparison_tuple("rage_clicks_count", "context.columns.rage_clicks", "sum"),+ self.runner._period_comparison_tuple("dead_clicks_count", "context.columns.dead_clicks", "sum"),+ self.runner._period_comparison_tuple("errors_count", "context.columns.errors", "sum"),+ ]++ having_exprs: list[ast.Expr] = [self._having()]+ outer_breakdown = self.runner.outer_where_breakdown()+ if outer_breakdown:+ having_exprs.append(outer_breakdown)++ query = ast.SelectQuery(+ select=selects,+ select_from=ast.JoinExpr(table=self._inner_query()),+ group_by=[ast.Field(chain=["context.columns.breakdown_value"])],+ having=ast.And(exprs=having_exprs),+ order_by=self._order_by(),+ )++ return query++ def _inner_query(self) -> ast.SelectQuery:+ query = parse_select(+ FRUSTRATION_METRICS_INNER_QUERY,+ timings=self.runner.timings,+ placeholders={+ "breakdown_value": self.runner._counts_breakdown_value(),+ "event_where": parse_expr(+ "events.event IN ('$pageview', '$screen', '$rageclick', '$dead_click', '$exception')"+ ),+ "all_properties": self.runner._all_properties(),+ "inside_periods": self.runner._periods_expression(),+ },+ )++ assert isinstance(query, ast.SelectQuery)+ return query++ def _having(self) -> ast.Expr:+ zero_tuple = ast.Tuple(exprs=[ast.Constant(value=0), ast.Constant(value=0)])+ return ast.Or(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Field(chain=["context.columns.rage_clicks"]),+ right=zero_tuple,+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Field(chain=["context.columns.dead_clicks"]),+ right=zero_tuple,+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Field(chain=["context.columns.errors"]),+ right=zero_tuple,+ ),+ ]+ )++ def _order_by(self) -> list[ast.OrderExpr]:+ return [+ ast.OrderExpr(expr=ast.Field(chain=["context.columns.errors"]), order="DESC"),+ ast.OrderExpr(expr=ast.Field(chain=["context.columns.rage_clicks"]), order="DESC"),+ ast.OrderExpr(expr=ast.Field(chain=["context.columns.dead_clicks"]), order="DESC"),+ ]diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambr b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambrindex 8e775c6d5fe0..7adfbcff881e 100644--- a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambr+++ b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambr@@ -1102,6 +1102,64 @@LIMIT 50000'''+# ---+# name: TestSampleWebAnalyticsQueries.test_web_stats_initial_page_with_bounce_rate_snapshot+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,+ tuple(avg(is_bounce), NULL) AS `context.columns.bounce_rate`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT any(person_id) AS filtered_person_id,+ count() AS filtered_pageview_count,+ session.$entry_pathname AS breakdown_value,+ session.session_id AS session_id,+ any(session.$is_bounce) AS is_bounce,+ min(session.$start_timestamp) AS start_timestamp+ FROM events+ WHERE and(or(and(greaterOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59')))), false), or(equals(event, '$pageview'), equals(event, '$screen')), 1)+ GROUP BY session_id,+ breakdown_value)+ GROUP BY `context.columns.breakdown_value`+ HAVING notEquals(`context.columns.breakdown_value`, NULL)+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 50000+ '''++# ---+# name: TestSampleWebAnalyticsQueries.test_web_stats_page_with_conversion_goal_snapshot+ '''+ SELECT breakdown_value AS `context.columns.breakdown_value`,+ tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,+ tuple(sum(conversion_count), NULL) AS `context.columns.total_conversions`,+ tuple(uniq(conversion_person_id), NULL) AS `context.columns.unique_conversions`,+ tuple(if(equals(`context.columns.visitors`.1, 0), NULL, divide(`context.columns.unique_conversions`.1, `context.columns.visitors`.1)), if(equals(`context.columns.visitors`.2, 0), NULL, divide(`context.columns.unique_conversions`.2, `context.columns.visitors`.2))) AS `context.columns.conversion_rate`,+ divide(`context.columns.unique_conversions`.1, sum(`context.columns.unique_conversions`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT any(person_id) AS filtered_person_id,+ count() AS filtered_pageview_count,+ events.properties.$pathname AS breakdown_value,+ session.session_id AS session_id,+ any(session.$is_bounce) AS is_bounce,+ min(session.$start_timestamp) AS start_timestamp,+ countIf(equals(events.event, 'signup')) AS conversion_count,+ any(if(equals(events.event, 'signup'), events.person_id, NULL)) AS conversion_person_id+ FROM events+ WHERE and(or(and(greaterOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59')))), false), or(equals(event, '$pageview'), equals(event, '$screen'), equals(events.event, 'signup')), 1)+ GROUP BY session_id,+ breakdown_value)+ GROUP BY `context.columns.breakdown_value`+ HAVING notEquals(`context.columns.breakdown_value`, NULL)+ ORDER BY `context.columns.unique_conversions` DESC,+ `context.columns.total_conversions` DESC,+ `context.columns.visitors` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 50000+ '''+# ---# name: TestSampleWebAnalyticsQueries.test_web_stats_paths_with_bounce_rate_snapshot'''@@ -1147,6 +1205,62 @@LIMIT 50000'''+# ---+# name: TestSampleWebAnalyticsQueries.test_web_stats_with_avg_time_on_page_snapshot+ '''+ SELECT counts.breakdown_value AS `context.columns.breakdown_value`,+ tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,+ tuple(counts.views, counts.previous_views) AS `context.columns.views`,+ tuple(coalesce(time_on_page.avg_time_on_page, 0), coalesce(time_on_page.previous_avg_time_on_page, 0)) AS `context.columns.avg_time_on_page`,+ tuple(coalesce(bounce.bounce_rate, 0), coalesce(bounce.previous_bounce_rate, 0)) AS `context.columns.bounce_rate`,+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`+ FROM+ (SELECT breakdown_value,+ uniqIf(filtered_person_id, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59'))))) AS visitors,+ uniqIf(filtered_person_id, false) AS previous_visitors,+ sumIf(filtered_pageview_count, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59'))))) AS views,+ sumIf(filtered_pageview_count, false) AS previous_views+ FROM+ (SELECT any(person_id) AS filtered_person_id,+ count() AS filtered_pageview_count,+ events.properties.$pathname AS breakdown_value,+ session.session_id AS session_id,+ min(session.$start_timestamp) AS start_timestamp+ FROM events+ WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59')))), false), 1, 1)+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS counts+ LEFT JOIN+ (SELECT events.properties.$prev_pageview_pathname AS breakdown_value,+ quantileIf(0.9)(least(toFloat(events.properties.$prev_pageview_duration), 86400),+ and(greaterOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59'))))) AS avg_time_on_page,+ quantileIf(0.9)(least(toFloat(events.properties.$prev_pageview_duration), 86400),+ false) AS previous_avg_time_on_page+ FROM events+ WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$pageleave'), equals(events.event, '$screen')), notEquals(events.properties.$prev_pageview_pathname, NULL), notEquals(events.properties.$prev_pageview_duration, NULL), or(and(greaterOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59')))), false), 1, 1)+ GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)+ LEFT JOIN+ (SELECT breakdown_value,+ avgIf(is_bounce, and(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59'))))) AS bounce_rate,+ avgIf(is_bounce, false) AS previous_bounce_rate+ FROM+ (SELECT session.$entry_pathname AS breakdown_value,+ any(session.$is_bounce) AS is_bounce,+ session.session_id AS session_id,+ min(session.$start_timestamp) AS start_timestamp+ FROM events+ WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00'))), lessOrEquals(timestamp, assumeNotNull(toDateTime('2024-01-31 23:59:59')))), false), 1, 1)+ GROUP BY session_id,+ breakdown_value)+ GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)+ WHERE notEquals(counts.breakdown_value, NULL)+ ORDER BY `context.columns.visitors` DESC,+ `context.columns.views` DESC,+ `context.columns.breakdown_value` ASC+ LIMIT 50000+ '''+# ---# name: TestSampleWebAnalyticsQueries.test_web_stats_with_bounce_rate_snapshot'''diff --git a/posthog/hogql_queries/web_analytics/test/test_sample_web_analytics_queries.py b/posthog/hogql_queries/web_analytics/test/test_sample_web_analytics_queries.pyindex 67bcfb54d758..ba759277231f 100644--- a/posthog/hogql_queries/web_analytics/test/test_sample_web_analytics_queries.py+++ b/posthog/hogql_queries/web_analytics/test/test_sample_web_analytics_queries.py@@ -22,6 +22,7 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_hogql_qfrom posthog.schema import (BaseMathType,ChartDisplayType,+ CustomEventConversionGoal,DateRange,EventPropertyFilter,EventsNode,@@ -265,6 +266,60 @@ class TestSampleWebAnalyticsQueries(ClickhouseTestMixin, APIBaseTest):runner = WebStatsTableQueryRunner(team=self.team, query=query)runner.calculate()+ def test_web_stats_with_avg_time_on_page_snapshot(self):+ """+ Paths breakdown with average time on page query example.++ Triggers the path-bounce-and-avg-time strategy, joining bounce rate with+ average time-on-page. Pins the SQL shape produced by the avg-time query+ template so future strategy changes surface in this snapshot.+ """+ query = WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),+ properties=[],+ breakdownBy=WebStatsBreakdown.PAGE,+ includeAvgTimeOnPage=True,+ limit=10,+ )+ runner = WebStatsTableQueryRunner(team=self.team, query=query)+ runner.calculate()++ def test_web_stats_initial_page_with_bounce_rate_snapshot(self):+ """+ Initial-page (entry-page) breakdown with bounce rate.++ Triggers the main strategy with an entry-pathname breakdown override,+ producing bounce metrics keyed on the session's first pageview rather+ than every pageview. Pins the entry-bounce override path.+ """+ query = WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),+ properties=[],+ breakdownBy=WebStatsBreakdown.INITIAL_PAGE,+ includeBounceRate=True,+ limit=10,+ )+ runner = WebStatsTableQueryRunner(team=self.team, query=query)+ runner.calculate()++ def test_web_stats_page_with_conversion_goal_snapshot(self):+ """+ Page breakdown combined with a conversion goal.++ When a conversion goal is set on a PAGE breakdown the runner falls+ back to the main strategy (no bounce/avg-time templates). Pins the+ conversion-rate column shape that downstream consumers depend on.+ """+ query = WebStatsTableQuery(+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-31"),+ properties=[],+ breakdownBy=WebStatsBreakdown.PAGE,+ conversionGoal=CustomEventConversionGoal(customEventName="signup"),+ limit=10,+ )+ runner = WebStatsTableQueryRunner(team=self.team, query=query)+ runner.calculate()+def test_web_trends_unique_users_snapshot(self):"""Web analytics trends query for unique visitors over time.