: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
fix(marketing-analytics): share hogql database with previous-period compare runner (#66593)
Javier Bahamondesa0ee516d41bb
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.pyindex 7028b00acb98..ac7d2f126a19 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_aggregated_query_runner.py@@ -204,14 +204,16 @@ class MarketingAnalyticsAggregatedQueryRunner(date_to=previous_date_range.date_to().isoformat(),)- # Create a new runner for the previous period+ # user= is required: a user-less previous runner loses warehouse access (empties the cost) and runs RBAC user-less.previous_runner = MarketingAnalyticsAggregatedQueryRunner(query=previous_query,team=self.team,timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,+ user=self.user,)+ previous_runner.__dict__["_shared_hogql_database"] = self._shared_hogql_databaseprevious_period_query = previous_runner.to_query()current_period_query = self.to_query()diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.pyindex da985dfc2fcf..df130352926a 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py@@ -191,13 +191,14 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Markedate_to=previous_date_range.date_to().isoformat(),)- # Create a new runner for the previous period+ # user= is required: a user-less previous runner loses warehouse access and runs RBAC user-less.previous_runner = MarketingAnalyticsTableQueryRunner(query=previous_query,team=self.team,timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,+ user=self.user,)# Share the prebuilt HogQL database across both periods so the compare query pays the ~1s# Database.create_for once, not twice. Pre-populates the previous runner's cached_property.diff --git a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.pyindex da3771ec18fb..7335a4ab8640 100644--- a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py@@ -194,12 +194,14 @@ class NonIntegratedConversionsTableQueryRunner(date_to=previous_date_range.date_to().isoformat(),)+ # user= is required: a user-less previous runner loses warehouse access and runs RBAC user-less.previous_runner = NonIntegratedConversionsTableQueryRunner(query=previous_query,team=self.team,timings=self.timings,modifiers=self.modifiers,limit_context=self.limit_context,+ user=self.user,)# Share the prebuilt HogQL database across both periods so the compare query pays the ~1s# Database.create_for once, not twice. Pre-populates the previous runner's cached_property.diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_aggregated_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_aggregated_query_runner.pyindex dae03340be07..155098af2ca1 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_aggregated_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_aggregated_query_runner.py@@ -3,8 +3,9 @@ from typing import Optionalfrom posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import Mock, patch-from posthog.schema import BaseMathType, DateRange, MarketingAnalyticsAggregatedQuery, NodeKind+from posthog.schema import BaseMathType, CompareFilter, DateRange, MarketingAnalyticsAggregatedQuery, NodeKind+from posthog.hogql.database.database import Databasefrom posthog.hogql.parser import parse_selectfrom posthog.hogql.test.utils import pretty_print_in_tests@@ -78,3 +79,69 @@ class TestMarketingAnalyticsAggregatedQueryRunner(ClickhouseTestMixin, BaseTest)# Snapshot the queryassert pretty_print_in_tests(hogql, self.team.pk) == self.snapshot++ def test_compare_shares_database_across_periods(self):+ query = MarketingAnalyticsAggregatedQuery(+ dateRange=self.default_date_range,+ compareFilter=CompareFilter(compare=True),+ properties=[],+ )+ runner = self._create_query_runner(query)++ mock_adapter = Mock()+ mock_adapter.get_source_id.return_value = "test_source"+ mock_adapter.supports_level.return_value = True+ mock_adapter.build_query.return_value = parse_select(+ "SELECT 'Campaign' as campaign, 'id1' as id, 'google' as source, "+ "100 as impressions, 10 as clicks, 50.0 as cost, 5 as reported_conversion, "+ "25.0 as reported_conversion_value, 'Campaign' as match_key"+ )++ with (+ patch.object(+ MarketingAnalyticsAggregatedQueryRunner,+ "_get_marketing_source_adapters",+ return_value=[mock_adapter],+ ),+ patch.object(Database, "create_for", wraps=Database.create_for) as create_for_spy,+ ):+ runner.calculate_with_compare()++ assert create_for_spy.call_count == 1, (+ f"both periods must share one HogQL database (the previous runner has no user); "+ f"Database.create_for ran {create_for_spy.call_count} times"+ )++ def test_compare_previous_period_not_zeroed_under_user_scoped_adapters(self):+ # Adapters resolve only for a user-scoped runner (warehouse RBAC); a user-less previous runner+ # gets none, falls back to the empty cost source, and zeroes the previous period.+ query = MarketingAnalyticsAggregatedQuery(+ dateRange=self.default_date_range,+ compareFilter=CompareFilter(compare=True),+ properties=[],+ )+ runner = MarketingAnalyticsAggregatedQueryRunner(query=query, team=self.team, user=self.user)++ mock_adapter = Mock()+ mock_adapter.get_source_id.return_value = "test_source"+ mock_adapter.supports_level.return_value = True+ mock_adapter.build_query.return_value = parse_select(+ "SELECT 'Campaign' as campaign, 'id1' as id, 'google' as source, "+ "100 as impressions, 10 as clicks, 50.0 as cost, 5 as reported_conversion, "+ "25.0 as reported_conversion_value, 'Campaign' as match_key"+ )++ def rbac_adapters(runner_self, date_range):+ return [mock_adapter] if runner_self.user is not None else []++ with patch.object(+ MarketingAnalyticsAggregatedQueryRunner,+ "_get_marketing_source_adapters",+ autospec=True,+ side_effect=rbac_adapters,+ ):+ response = runner.calculate()++ cost = response.results["Cost"]+ assert cost.value == 50.0+ assert cost.previous == 50.0, f"previous fell back to the empty cost source (user-less runner): {cost.previous}"