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): split MainQueryStrategy into SimpleBreakdown and ChannelType strategies (#59078)

Lucas Ricoyddc5294682cc
diff --git a/posthog/hogql_queries/web_analytics/stats_table.py b/posthog/hogql_queries/web_analytics/stats_table.py
index 49ba24688c92..0110cba227e5 100644
--- a/posthog/hogql_queries/web_analytics/stats_table.py
+++ b/posthog/hogql_queries/web_analytics/stats_table.py
@@ -29,10 +29,11 @@ from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.web_analytics.events_prefilter import PrefilterHogQLHasMorePaginator
from posthog.hogql_queries.web_analytics.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilder
from posthog.hogql_queries.web_analytics.stats_table_strategies import (
+ ChannelTypeStrategy,
FrustrationMetricsStrategy,
- MainQueryStrategy,
PathBounceAvgTimeStrategy,
PathBounceStrategy,
+ SimpleBreakdownStrategy,
StatsTableQueryStrategy,
)
from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner, map_columns
@@ -134,15 +135,18 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
return "stats_table_path_bounce_and_avg_time"
if isinstance(strategy, PathBounceStrategy):
return "stats_table_path_bounce"
+ # ChannelTypeStrategy must be checked before SimpleBreakdownStrategy since it's a subclass.
+ if isinstance(strategy, ChannelTypeStrategy):
+ return "stats_table_channel_type"
if (
- isinstance(strategy, MainQueryStrategy)
+ isinstance(strategy, SimpleBreakdownStrategy)
and self.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE
and self.query.includeBounceRate
):
return "stats_table_entry_bounce"
- return "stats_table_main"
+ return "stats_table_simple_breakdown"
def _get_strategy(self) -> StatsTableQueryStrategy:
if self.query.breakdownBy == WebStatsBreakdown.FRUSTRATION_METRICS:
@@ -150,16 +154,19 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
if self.query.breakdownBy == WebStatsBreakdown.PAGE:
if self.query.conversionGoal:
- return MainQueryStrategy(self)
+ return SimpleBreakdownStrategy(self)
if self.query.includeAvgTimeOnPage:
return PathBounceAvgTimeStrategy(self)
if self.query.includeBounceRate:
return PathBounceStrategy(self)
if self.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:
- return MainQueryStrategy(self, breakdown_override=self._bounce_entry_pathname_breakdown())
+ return SimpleBreakdownStrategy(self, breakdown_override=self._bounce_entry_pathname_breakdown())
- return MainQueryStrategy(self)
+ if self.query.breakdownBy == WebStatsBreakdown.INITIAL_CHANNEL_TYPE:
+ return ChannelTypeStrategy(self)
+
+ return SimpleBreakdownStrategy(self)
def _order_by(self, columns: list[str]) -> list[ast.OrderExpr] | None:
column = None
diff --git a/posthog/hogql_queries/web_analytics/stats_table_strategies.py b/posthog/hogql_queries/web_analytics/stats_table_strategies.py
index 47b6262d2f79..4d02cf44d623 100644
--- a/posthog/hogql_queries/web_analytics/stats_table_strategies.py
+++ b/posthog/hogql_queries/web_analytics/stats_table_strategies.py
@@ -40,12 +40,16 @@ class StatsTableQueryStrategy(ABC):
return query
-class MainQueryStrategy(StatsTableQueryStrategy):
- """Default query for most breakdown types.
+class SimpleBreakdownStrategy(StatsTableQueryStrategy):
+ """Default query for simple-dimension breakdowns.
- Used by all UTM / device / browser / OS / geo / language / timezone
+ Used by 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*).
+
+ INITIAL_CHANNEL_TYPE has its own ``ChannelTypeStrategy`` subclass so
+ the query tag can be attributed separately even though the SQL shape
+ is identical.
"""
def __init__(
@@ -140,6 +144,22 @@ class MainQueryStrategy(StatsTableQueryStrategy):
return query
+class ChannelTypeStrategy(SimpleBreakdownStrategy):
+ """INITIAL_CHANNEL_TYPE breakdown.
+
+ Shares the ``MAIN_INNER_QUERY`` skeleton with ``SimpleBreakdownStrategy``,
+ but the breakdown value ``session.$channel_type`` is NOT a single field
+ lookup. In ``sessions_v2.py`` it unfolds via ``create_channel_type_expr``
+ into a multi-input case expression composing ten entry-level session
+ fields (``$entry_utm_{campaign,medium,source}``,
+ ``$entry_{current_url,hostname,pathname,referring_domain,gad_source}``,
+ plus ``isNotNull`` on ``$entry_{gclid,fbclid}``) and applies any
+ ``customChannelTypeRules`` from the query modifiers. That makes
+ per-row work materially heavier than other simple breakdowns, which
+ is why this gets its own tag for attribution even though the outer
+ SQL is the same template."""
+
+
class PathBounceStrategy(StatsTableQueryStrategy):
"""PAGE breakdown with bounce rate (no scroll depth or avg time)."""
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_analytics_metrics.py b/posthog/hogql_queries/web_analytics/test/test_web_analytics_metrics.py
index d3632009cf4d..ba8c6cf6c7c9 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_analytics_metrics.py
+++ b/posthog/hogql_queries/web_analytics/test/test_web_analytics_metrics.py
@@ -87,11 +87,11 @@ class TestWebAnalyticsMetrics(TestCase):
None,
{
"query_kind": "WebStatsTableQuery",
- "query_strategy": "stats_table_main",
+ "query_strategy": "stats_table_simple_breakdown",
"breakdown": "Page",
"has_conversion_goal": "false",
},
- "stats_table_main",
+ "stats_table_simple_breakdown",
),
(
"overview",
@@ -113,11 +113,11 @@ class TestWebAnalyticsMetrics(TestCase):
MagicMock(),
{
"query_kind": "WebStatsTableQuery",
- "query_strategy": "stats_table_main",
+ "query_strategy": "stats_table_channel_type",
"breakdown": "InitialChannelType",
"has_conversion_goal": "true",
},
- "stats_table_main",
+ "stats_table_channel_type",
),
(
"trends",
@@ -161,7 +161,7 @@ class TestWebAnalyticsMetrics(TestCase):
runner = _make_runner(
query_kind="WebStatsTableQuery",
breakdown=WebStatsBreakdown.BROWSER,
- query_strategy="stats_table_main",
+ query_strategy="stats_table_simple_breakdown",
)
with patch.object(WebAnalyticsQueryRunner.__mro__[1], "calculate", side_effect=ValueError("boom")):
@@ -170,7 +170,7 @@ class TestWebAnalyticsMetrics(TestCase):
error_filter = {
"query_kind": "WebStatsTableQuery",
- "query_strategy": "stats_table_main",
+ "query_strategy": "stats_table_simple_breakdown",
"breakdown": "Browser",
"error_type": "ValueError",
}
@@ -178,7 +178,7 @@ class TestWebAnalyticsMetrics(TestCase):
counter_filter = {
"query_kind": "WebStatsTableQuery",
- "query_strategy": "stats_table_main",
+ "query_strategy": "stats_table_simple_breakdown",
"used_preaggregated": "unknown",
}
assert _get_counter_value(WEB_ANALYTICS_QUERY_COUNTER, counter_filter) == 1.0
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_analytics_query_runner.py b/posthog/hogql_queries/web_analytics/test/test_web_analytics_query_runner.py
index 524172945d4e..a9459963780e 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_analytics_query_runner.py
+++ b/posthog/hogql_queries/web_analytics/test/test_web_analytics_query_runner.py
@@ -122,7 +122,15 @@ class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- ("main", WebStatsBreakdown.PAGE, False, False, None, "stats_table_main_query"),
+ ("simple_breakdown", WebStatsBreakdown.PAGE, False, False, None, "stats_table_simple_breakdown_query"),
+ (
+ "channel_type",
+ WebStatsBreakdown.INITIAL_CHANNEL_TYPE,
+ False,
+ False,
+ None,
+ "stats_table_channel_type_query",
+ ),
("path_bounce", WebStatsBreakdown.PAGE, True, False, None, "stats_table_path_bounce_query"),
(
"path_bounce_and_avg_time",