: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(marketing-analytics): add a ROAS column driven by revenue conversion goals (#83263)
Javier Bahamondesd423db23c091
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex de07b2eb8d0c..eebe311f8b64 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -388,6 +388,7 @@ export const FEATURE_FLAGS = {MARKETING_ANALYTICS_MCP: 'marketing-analytics-mcp', // owner: @jabahamondes #team-web-analytics — gates MCP tool exposure (read-only marketing-analytics tools)MARKETING_ANALYTICS_MULTI_TOUCH_ATTRIBUTION: 'marketing-analytics-multi-touch-attribution', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_NEW_DASHBOARD: 'new-marketing-analytics-dashboard', // owner: @jabahamondes #team-web-analytics — gates the WIP redesigned dashboard tab+ MARKETING_ANALYTICS_RETURN_METRICS: 'marketing-analytics-return-metrics', // owner: @jabahamondes #team-web-analytics — gates the ROAS columnMARKETING_ANALYTICS_SETUP: 'marketing-analytics-setup', // owner: @jabahamondes #team-web-analytics — gates the Setup tab and its setup_plan / apply_setup_ops endpointsMARKETING_ANALYTICS_UTM_AUDIT: 'marketing-analytics-utm-audit', // owner: @jabahamondes #team-web-analyticsMAX_AI_INSIGHT_SEARCH: 'max-ai-insight-search', // owner: #team-posthog-aidiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex f63f113b252d..870e5456bafa 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -33380,7 +33380,7 @@"type": "object"},"MarketingAnalyticsConstants": {- "enum": ["Goal", "Cost per", "const:"],+ "enum": ["Goal", "Cost per", "ROAS", "const:"],"type": "string"},"MarketingAnalyticsDrillDownConfig": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 15427dbb6444..42da182af908 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -7496,6 +7496,7 @@ export function getEffectiveExcludedColumns(export enum MarketingAnalyticsConstants {Goal = 'Goal',CostPer = 'Cost per',+ Roas = 'ROAS',ConstantValuePrefix = 'const:',}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.tsindex 275c92e00378..f175bad73bdc 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTableLogic.ts@@ -1,6 +1,8 @@import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'import { actionToUrl, urlToAction } from 'kea-router'+import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { isNotNil } from 'lib/utils/guards'import {@@ -43,6 +45,7 @@ export type NativeSource = {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface marketingAnalyticsTableLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogicconversion_goals: ConversionGoalFilter[] // marketingAnalyticsLogicdraftConversionGoal: ConversionGoalFilter | null // marketingAnalyticsLogicdrillDownLevel: MarketingAnalyticsDrillDownLevel // marketingAnalyticsLogic@@ -66,7 +69,8 @@ export interface marketingAnalyticsTableLogicMeta {__keaTypeGenInternalSelectorTypes: {defaultColumns: (conversion_goals: ConversionGoalFilter[],- drillDownLevel: MarketingAnalyticsDrillDownLevel+ drillDownLevel: MarketingAnalyticsDrillDownLevel,+ featureFlags: FeatureFlagsSet) => string[]sortedColumns: (defaultColumns: string[], query: DataTableNode | null) => string[]}@@ -82,7 +86,12 @@ export type marketingAnalyticsTableLogicType = MakeLogicType<export const marketingAnalyticsTableLogic = kea<marketingAnalyticsTableLogicType>([path(['scenes', 'marketingAnalytics', 'marketingAnalyticsTableLogic']),connect(() => ({- values: [marketingAnalyticsLogic, ['conversion_goals', 'draftConversionGoal', 'drillDownLevel']],+ values: [+ marketingAnalyticsLogic,+ ['conversion_goals', 'draftConversionGoal', 'drillDownLevel'],+ featureFlagLogic,+ ['featureFlags'],+ ],actions: [marketingAnalyticsLogic, ['setDraftConversionGoal']],})),actions({@@ -98,8 +107,12 @@ export const marketingAnalyticsTableLogic = kea<marketingAnalyticsTableLogicType}),selectors({defaultColumns: [- (s) => [s.conversion_goals, s.drillDownLevel],- (conversionGoals: ConversionGoalFilter[], drillDownLevel: MarketingAnalyticsDrillDownLevel) => {+ (s) => [s.conversion_goals, s.drillDownLevel, s.featureFlags],+ (+ conversionGoals: ConversionGoalFilter[],+ drillDownLevel: MarketingAnalyticsDrillDownLevel,+ featureFlags: FeatureFlagsSet+ ) => {const config = MARKETING_ANALYTICS_DRILL_DOWN_CONFIG[drillDownLevel]// Hierarchy columns are auto-excluded outside AD_GROUP / AD — see// getEffectiveExcludedColumns. Routing on the user-config (config.excludedBaseColumns)@@ -144,7 +157,17 @@ export const marketingAnalyticsTableLogic = kea<marketingAnalyticsTableLogicType).flat()- const selectColumns = [...baseColumns, ...conversionGoalColumns].filter(isNotNil)+ // ROAS divides revenue-goal value by spend, so it needs both a revenue goal and a+ // Cost column at this drill-down level.+ const roasColumn =+ featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_RETURN_METRICS] &&+ costAvailable &&+ !config.excludesConversionGoals &&+ conversionGoals.some((goal) => goal.counts_as_revenue)+ ? [MarketingAnalyticsConstants.Roas]+ : []++ const selectColumns = [...baseColumns, ...conversionGoalColumns, ...roasColumn].filter(isNotNil)return selectColumns},],diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 1faabbff09ba..e20c336c0ef2 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3088,6 +3088,7 @@ class MarketingAnalyticsColumnsSchemaNames(StrEnum):class MarketingAnalyticsConstants(StrEnum):GOAL = "Goal"COST_PER = "Cost per"+ ROAS = "ROAS"CONST_ = "const:"diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_adapters.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_adapters.ambrindex 7ad6d9d4b7ca..9b0b1e1b0682 100644--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_adapters.ambr+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_adapters.ambr@@ -52,7 +52,7 @@# name: TestMarketingAnalyticsAdapters.test_google_ads_query_generation_with_clp_currency'''- SELECT toString(google_campaign.campaign_name) AS match_key, toString(google_campaign.campaign_name) AS campaign, toString(google_campaign.campaign_id) AS id, toString('google') AS source, toFloat(SUM(ifNull(toFloat(google_stats.metrics_impressions), 0))) AS impressions, toFloat(SUM(ifNull(toFloat(google_stats.metrics_clicks), 0))) AS clicks, SUM(toFloat(convertCurrency(coalesce(google_stats.customer_currency_code, 'CLP'), 'CLP', toFloat(divide(google_stats.metrics_cost_micros, 1000000))))) AS cost, toFloat(SUM(ifNull(toFloat(google_stats.metrics_conversions), 0))) AS reported_conversion, SUM(toFloat(convertCurrency(coalesce(google_stats.customer_currency_code, 'CLP'), 'CLP', ifNull(toFloat(google_stats.metrics_conversions_value), 0)))) AS reported_conversion_value+ SELECT toString(google_campaign.campaign_name) AS match_key, toString(google_campaign.campaign_name) AS campaign, toString(google_campaign.campaign_id) AS id, toString('google') AS source, toFloat(SUM(ifNull(toFloat(google_stats.metrics_impressions), 0))) AS impressions, toFloat(SUM(ifNull(toFloat(google_stats.metrics_clicks), 0))) AS clicks, SUM(toFloat(convertCurrency(coalesce(google_stats.customer_currency_code, 'CLP'), 'CLP', toFloat(divide(google_stats.metrics_cost_micros, 1000000)), coalesce(toDate(google_stats.segments_date), today())))) AS cost, toFloat(SUM(ifNull(toFloat(google_stats.metrics_conversions), 0))) AS reported_conversion, SUM(toFloat(convertCurrency(coalesce(google_stats.customer_currency_code, 'CLP'), 'CLP', ifNull(toFloat(google_stats.metrics_conversions_value), 0), coalesce(toDate(google_stats.segments_date), today())))) AS reported_conversion_valueFROM google_campaign LEFT JOIN google_stats ON equals(toString(google_campaign.campaign_id), toString(google_stats.campaign_id))WHERE and(greaterOrEquals(toDateTime(google_stats.segments_date), toDateTime('2024-01-01 00:00:00')), lessOrEquals(toDateTime(google_stats.segments_date), toDateTime('2024-12-31 23:59:59')))GROUP BY toString(google_campaign.campaign_name), toString(google_campaign.campaign_id)diff --git a/products/marketing_analytics/backend/hogql_queries/adapters/base.py b/products/marketing_analytics/backend/hogql_queries/adapters/base.pyindex 6c2cb2a8364f..94d851dcbc0f 100644--- a/products/marketing_analytics/backend/hogql_queries/adapters/base.py+++ b/products/marketing_analytics/backend/hogql_queries/adapters/base.py@@ -745,8 +745,12 @@ class MarketingSourceAdapter(ABC, Generic[ConfigType]):) -> ast.Expr | None:"""Wrap value_expr with currency conversion if the currency column exists in the table.- Returns toFloat(convertCurrency(coalesce(currency_col, base_currency), base_currency, value_expr))- or None if the column doesn't exist or can't be checked.+ Converts at the row's own stats date. Without a date `convertCurrency` falls back to+ `today()`, which both reprices past spend every time the page loads and puts cost on a+ different rate than conversion revenue, which converts at the event's timestamp.++ Returns toFloat(convertCurrency(coalesce(currency_col, base_currency), base_currency,+ value_expr, stats_date)) or None if the column doesn't exist or can't be checked."""if not self._table_has_column(table, currency_column):return None@@ -754,9 +758,25 @@ class MarketingSourceAdapter(ABC, Generic[ConfigType]):currency_with_fallback = ast.Call(name="coalesce", args=[currency_field, ast.Constant(value=self.context.base_currency)])+ # Warehouse date columns read back nullable, and `convertCurrency` resolves the rate+ # through `dictGetOrDefault`, which rejects a Nullable(Date) key outright rather than+ # returning the default. Falling back to today() for a row with no date is the old+ # behaviour, kept only for those rows.+ stats_date = ast.Call(+ name="coalesce",+ args=[+ ast.Call(name="toDate", args=[ast.Field(chain=[table_name, self._stats_date_column])]),+ ast.Call(name="today", args=[]),+ ],+ )converted = ast.Call(name="convertCurrency",- args=[currency_with_fallback, ast.Constant(value=self.context.base_currency), value_expr],+ args=[+ currency_with_fallback,+ ast.Constant(value=self.context.base_currency),+ value_expr,+ stats_date,+ ],)return ast.Call(name="toFloat", args=[converted])diff --git a/products/marketing_analytics/backend/hogql_queries/constants.py b/products/marketing_analytics/backend/hogql_queries/constants.pyindex 9679cfedf4b5..9ccd361cb12b 100644--- a/products/marketing_analytics/backend/hogql_queries/constants.py+++ b/products/marketing_analytics/backend/hogql_queries/constants.py@@ -88,6 +88,10 @@ SESSIONS_COLUMN_ALIAS = "Sessions"# enum so the sides can't drift apart and split one row in two.UNKNOWN_CHANNEL = DefaultChannelTypes.UNKNOWN.value+# Revenue from goals marked counts_as_revenue over the channel's spend. Distinct from+# REPORTED_ROAS, the platform's own figure. Not a base column: it needs the goals CTE.+ROAS_COLUMN = MarketingAnalyticsConstants.ROAS.value+# What `$entry_referring_domain` holds when a session arrived with no referrer at all. Stored as a# sentinel rather than an empty string, so anything asking "does this session name a referrer?" has# to test for it explicitly. Matches the literal the channel-type classifier keys off indiff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex 22658a8a820e..be2ffdb9004f 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -207,7 +207,9 @@ class SharedTouchpointsPrecompute:return self._result-@dataclass+# Mutable by design: `precompute_stale` is set while building the query, and each+# processor owns a `timings` clone the runner merges back after the pool joins.+@dataclass(frozen=False)class ConversionGoalProcessor:"""Processes conversion goals for marketing analytics queries.@@ -274,13 +276,22 @@ class ConversionGoalProcessor:return self.goal.schema_map.get(field.schema_map_key, field.event_property)return field.event_property+ def sums_a_property(self) -> bool:+ """Whether this goal's column holds a summed property value rather than a conversion count.++ Anything dividing by a goal's column needs to tell the two apart, so this shares the branch+ with `get_select_field` rather than re-deriving it from `math`.+ """+ math_type = self.goal.math+ return math_type in ["sum", PropertyMathType.SUM] or str(math_type).endswith("_sum")+def get_select_field(self) -> ast.Expr:"""Build select field expression based on math aggregation type"""math_type = self.goal.mathif math_type in [BaseMathType.DAU, "dau"]:return self._build_dau_select()- elif math_type in ["sum", PropertyMathType.SUM] or str(math_type).endswith("_sum"):+ elif self.sums_a_property():return self._build_sum_select()else:return ast.Call(name="count", args=[ast.Constant(value="*")])diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.pyindex 678023430e1f..41a64c026a94 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py@@ -11,6 +11,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.settings import TESTfrom products.marketing_analytics.backend.hogql_queries.constants import (+ ROAS_COLUMN,UNIFIED_CONVERSION_GOALS_CTE_ALIAS,UNKNOWN_CHANNEL,)@@ -399,8 +400,49 @@ class ConversionGoalsAggregator:)columns[f"{self.config.cost_per_prefix} {goal_name}"] = cost_per_goal_alias+ # Needs campaign_costs joined, since spend is the denominator. A flagged goal only+ # contributes if its column holds money — a counting one would render 200 signups against+ # $100 of spend as "ROAS 2.0".+ if include_cost_per:+ revenue_processors = [p for p in self.processors if p.goal.counts_as_revenue and p.sums_a_property()]+ if revenue_processors:+ columns[ROAS_COLUMN] = self._build_roas_column(revenue_processors)+return columns+ def _build_roas_column(self, revenue_processors: list[ConversionGoalProcessor]) -> ast.Alias:+ total_revenue = self._sum_conversion_values(revenue_processors)+ total_cost = ast.Field(chain=self.config.get_campaign_cost_field_chain(self.config.total_cost_field))+ return ast.Alias(+ alias=ROAS_COLUMN,+ expr=ast.Call(+ name="round",+ args=[+ ast.ArithmeticOperation(+ left=total_revenue,+ op=ast.ArithmeticOperationOp.Div,+ right=ast.Call(name="nullif", args=[total_cost, ast.Constant(value=0)]),+ ),+ ast.Constant(value=2),+ ],+ ),+ )++ def _sum_conversion_values(self, processors: list[ConversionGoalProcessor]) -> ast.Expr:+ """Sum the unified-CTE value columns of the given goals into one expression."""+ fields = [+ ast.Field(+ chain=self.config.get_unified_conversion_field_chain(+ self.config.get_conversion_goal_column_name(p.index)+ )+ )+ for p in processors+ ]+ total: ast.Expr = fields[0]+ for field in fields[1:]:+ total = ast.ArithmeticOperation(left=total, op=ast.ArithmeticOperationOp.Add, right=field)+ return total+def get_coalesce_fallback_columns(self, campaign_costs_joined: bool = True) -> dict[str, ast.Expr]:"""Get COALESCE columns that fall back to unified conversion goals for campaign/id/source.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 418cf9189758..a52d785d1ed5 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@@ -19,6 +19,7 @@ from .constants import (BASE_COLUMN_MAPPING,HIERARCHY_BASE_COLUMNS,HIERARCHY_DRILL_DOWN_LEVELS,+ ROAS_COLUMN,UNIFIED_CONVERSION_GOALS_CTE_ALIAS,to_marketing_analytics_data,)@@ -117,9 +118,12 @@ class MarketingAnalyticsAggregatedQueryRunner(# Add conversion goal columns using the aggregatorif conversion_aggregator:conversion_columns = conversion_aggregator.get_conversion_goal_columns()- # We exclude the `Cost per` conversion goal columns from the mapping because we'll recalculate them later+ # A sum of per-row ratios isn't the ratio of the totals, so rate-shaped columns can't+ # ride the generic SUM() wrapper.conversion_columns = {- k: v for k, v in conversion_columns.items() if not k.startswith(MarketingAnalyticsConstants.COST_PER)+ k: v+ for k, v in conversion_columns.items()+ if not k.startswith(MarketingAnalyticsConstants.COST_PER) and k != ROAS_COLUMN}all_columns.update(conversion_columns)diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.pyindex decd43ce93be..5d94fbcafa63 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py@@ -42,6 +42,7 @@ from products.analytics_platform.backend.lazy_computation.stale_policy import isfrom products.marketing_analytics.backend.hogql_queries.constants import (CHANNEL_SESSIONS_CTE_NAME,DRILL_DOWN_LEVEL_CONFIG,+ ROAS_COLUMN,TOTAL_SESSIONS_FIELD,UNIFIED_CONVERSION_GOALS_CTE_ALIAS,UNKNOWN_CHANNEL,@@ -854,11 +855,15 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,) -> list:"""Create conversion goal processors for reuse across different methods"""processors = []+ # Needed even when the goals' own columns are hidden, or the ratio changes value as+ # columns are added or removed.+ roas_selected = self.query.select is not None and ROAS_COLUMN in self.query.selectfor index, conversion_goal in enumerate(conversion_goals):# Create processor if select is None (all columns) or if conversion goal columns are explicitly selectedshould_create = self.query.select is None or (conversion_goal.conversion_goal_name in self.query.selector f"{MarketingAnalyticsConstants.COST_PER} {conversion_goal.conversion_goal_name}" in self.query.select+ or (roas_selected and conversion_goal.counts_as_revenue))if should_create:processor = ConversionGoalProcessor(diff --git a/products/marketing_analytics/backend/hogql_queries/test_adapters.py b/products/marketing_analytics/backend/hogql_queries/test_adapters.pyindex 013107be4d83..572e544adefa 100644--- a/products/marketing_analytics/backend/hogql_queries/test_adapters.py+++ b/products/marketing_analytics/backend/hogql_queries/test_adapters.py@@ -2713,3 +2713,22 @@ class TestMarketingAnalyticsAdapters(ClickhouseTestMixin, BaseTest):hogql_query = query.to_hogql()assert "convertCurrency" in hogql_queryassert expected_in_query in hogql_query++ def test_currency_conversion_date_cannot_be_null(self):+ # `convertCurrency` resolves its rate through `dictGetOrDefault`, which rejects a+ # Nullable(Date) key outright rather than returning its default — and warehouse date+ # columns read back nullable. A bare toDate() here fails the entire cost query.+ stats_table = self._create_mock_table("google_stats", "GoogleAds")+ stats_table.columns = {"customer_currency_code": True}+ config = GoogleAdsConfig(+ campaign_table=self._create_mock_table("google_campaign", "GoogleAds"),+ stats_table=stats_table,+ source_type="GoogleAds",+ source_id="google_ads",+ )+ query = GoogleAdsAdapter(config=config, context=self.context).build_query()+ assert query is not None+ hogql_query = query.to_hogql()++ assert "convertCurrency" in hogql_query+ assert "coalesce(toDate(google_stats.segments_date), today())" in hogql_querydiff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.pyindex b90de5a0f070..68d9654e89ee 100644--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py@@ -15,6 +15,7 @@ from posthog.schema import (ConversionGoalFilter2,DateRange,MarketingAnalyticsBaseColumns,+ PropertyMathType,)from posthog.hogql import ast@@ -33,6 +34,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu)from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from .constants import ROAS_COLUMNfrom .conversion_goal_processor import ConversionGoalProcessor, SharedTouchpointsPrecomputefrom .conversion_goals_aggregator import ConversionGoalsAggregator, _map_in_caller_contextfrom .marketing_analytics_config import MarketingAnalyticsConfig@@ -99,8 +101,9 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):goal_id: str,goal_name: str,event_name: str | None = None,- math: BaseMathType = BaseMathType.TOTAL,+ math: BaseMathType | PropertyMathType = BaseMathType.TOTAL,math_property: str | None = None,+ counts_as_revenue: bool | None = None,) -> ConversionGoalFilter1:return ConversionGoalFilter1(kind="EventsNode",@@ -109,6 +112,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):conversion_goal_name=goal_name,math=math,math_property=math_property,+ counts_as_revenue=counts_as_revenue,schema_map={"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},)@@ -314,6 +318,67 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):assert isinstance(division_expr, ast.ArithmeticOperation)assert division_expr.op == ast.ArithmeticOperationOp.Div+ def test_roas_column_absent_when_no_goal_is_revenue(self):+ goal = self._create_test_conversion_goal("plain", "Plain Goal")+ aggregator = ConversionGoalsAggregator(processors=[self._create_test_processor(goal, 0)], config=self.config)++ columns = aggregator.get_conversion_goal_columns()++ assert ROAS_COLUMN not in columns++ def test_roas_column_absent_without_campaign_costs(self):+ goal = self._create_test_conversion_goal(+ "rev", "Revenue Goal", math=PropertyMathType.SUM, math_property="revenue", counts_as_revenue=True+ )+ aggregator = ConversionGoalsAggregator(processors=[self._create_test_processor(goal, 0)], config=self.config)++ columns = aggregator.get_conversion_goal_columns(include_cost_per=False)++ assert ROAS_COLUMN not in columns++ def test_roas_numerator_sums_only_the_revenue_goals(self):+ goals = [+ self._create_test_conversion_goal("g0", "Signups"),+ self._create_test_conversion_goal(+ "g1", "Purchases", math=PropertyMathType.SUM, math_property="revenue", counts_as_revenue=True+ ),+ self._create_test_conversion_goal(+ "g2", "Subscriptions", math=PropertyMathType.SUM, math_property="mrr", counts_as_revenue=True+ ),+ ]+ processors = [self._create_test_processor(goal, i) for i, goal in enumerate(goals)]+ aggregator = ConversionGoalsAggregator(processors=processors, config=self.config)++ roas = aggregator.get_conversion_goal_columns()[ROAS_COLUMN].expr.to_hogql()++ # Revenue goals sit at indices 1 and 2, the plain signup goal at 0 must not be in the numerator+ assert self.config.get_conversion_goal_column_name(1) in roas+ assert self.config.get_conversion_goal_column_name(2) in roas+ assert self.config.get_conversion_goal_column_name(0) not in roas+ assert self.config.total_cost_field in roas++ def test_roas_numerator_skips_revenue_goals_that_count_instead_of_summing(self):+ goals = [+ # Flagged as revenue but counts conversions, so its column holds a count, not money.+ self._create_test_conversion_goal("g0", "Signups", counts_as_revenue=True),+ self._create_test_conversion_goal(+ "g1", "Purchases", math=PropertyMathType.SUM, math_property="revenue", counts_as_revenue=True+ ),+ ]+ processors = [self._create_test_processor(goal, i) for i, goal in enumerate(goals)]+ aggregator = ConversionGoalsAggregator(processors=processors, config=self.config)++ roas = aggregator.get_conversion_goal_columns()[ROAS_COLUMN].expr.to_hogql()++ assert self.config.get_conversion_goal_column_name(1) in roas+ assert self.config.get_conversion_goal_column_name(0) not in roas++ def test_roas_column_absent_when_every_revenue_goal_counts_instead_of_summing(self):+ goal = self._create_test_conversion_goal("g0", "Signups", counts_as_revenue=True)+ aggregator = ConversionGoalsAggregator(processors=[self._create_test_processor(goal, 0)], config=self.config)++ assert ROAS_COLUMN not in aggregator.get_conversion_goal_columns()+def test_coalesce_fallback_columns(self):goal = self._create_test_conversion_goal("fallback_test", "Fallback Test")processor = self._create_test_processor(goal, 0)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 155098af2ca1..097afc8b33d0 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@@ -80,6 +80,41 @@ class TestMarketingAnalyticsAggregatedQueryRunner(ClickhouseTestMixin, BaseTest)# Snapshot the queryassert pretty_print_in_tests(hogql, self.team.pk) == self.snapshot+ def test_roas_column_is_excluded_from_the_generic_sum_wrapper(self):+ # A per-row ratio: in the aggregated mapping SUM() gives sum-of-ratios, not the total.+ self.team.marketing_analytics_config.conversion_goals = [+ {+ "kind": NodeKind.EVENTS_NODE,+ "event": "purchase",+ "conversion_goal_id": "revenue_goal",+ "conversion_goal_name": "Revenue",+ "name": "purchase",+ "math": "sum",+ "math_property": "revenue",+ "counts_as_revenue": True,+ "schema_map": {"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"},+ }+ ]+ self.team.marketing_analytics_config.save()++ runner = self._create_query_runner()++ mock_adapter = Mock()+ mock_adapter.get_source_id.return_value = "test_source"+ 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, "+ "'Campaign' as match_key"+ )++ with patch.object(runner, "_get_marketing_source_adapters", return_value=[mock_adapter]):+ query = runner.to_query()++ hogql = query.to_hogql()++ assert "AS ROAS" not in hogql, f"ROAS must not be emitted (and summed) by the aggregated runner. Got: {hogql}"+ assert "AS Revenue" in hogql, f"the revenue goal column itself should still be summed. Got: {hogql}"+def test_compare_shares_database_across_periods(self):query = MarketingAnalyticsAggregatedQuery(dateRange=self.default_date_range,