: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): attribute PostHog goals to paid keywords (#116421)
Javier Bahamondese49524fa3f95
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.mdindex f3464589969d..b45f8e00f9f4 100644--- a/docs/internal/marketing-source-suggestions.md+++ b/docs/internal/marketing-source-suggestions.md@@ -50,12 +50,19 @@ Bing Ads connections need to sync `keyword_performance_report` or `destination_uOlder rows without placement data show no value.The Traffic and Conversions views both include spend when a paid source is ready.The first column stays visible while the metrics scroll horizontally.-In Landing pages → Conversions, the Ad performance Include conversion goals switch adds the first five supported event or action goals and their cost per conversion.+In Search performance → Conversions, the Ad performance Include conversion goals switch adds the first five supported event or action goals and their cost per conversion.Goals with missing actions are skipped with a warning before the five-goal limit is applied.If more goals are configured, a warning directs users to the attribution report for other goals.This limits each search request to five attribution queries, or ten with period comparison.+Search requests calculate credit for the configured model only, without the attribution report’s visitor counts, revenue, or footer totals.These conversions use the session attribution engine with the team's attribution model, lookback window, goal filters, and test-account exclusion setting.-Credit is matched by landing URL and search source after attribution, so other channels retain their share.+Credit is matched after attribution, so other channels retain their share.+Landing pages match by landing URL and search source.+Paid keywords match by the session entry `utm_term` and search source, ignoring case and surrounding whitespace.+Set `utm_term` to the keyword text in Google Ads or Bing Ads tracking URLs.+Click IDs identify the paid source but do not provide a keyword lookup.+Organic query rows do not receive PostHog conversion credit; use Landing pages for organic goals.+Keywords with multiple match types or currencies leave PostHog metrics empty because the same credit cannot be assigned to individual rows.URL query parameters and fragments are combined in this view.Opening a combined landing page preserves this URL matching in the organic query details without loading PostHog goals.With goals off, landing page details keep exact URL matching.@@ -63,12 +70,12 @@ Google organic search, paid Google search, and paid Bing search receive separateCanonical Google and Bing source names match regardless of capitalization.Paid Search sessions can also identify Google through `gclid` and Bing through `msclkid`.A click ID alone does not classify a session as search traffic; the session must have the Paid Search channel.-When `marketing-analytics-live-session-resolution` is enabled, eligible landing-page goals reuse shared live session resolution.+When `marketing-analytics-live-session-resolution` is enabled, eligible search goals reuse shared live session resolution.They do not read session or conversion precomputation tables.Organic rows have no cost per conversion, and pages with spend in multiple currencies leave PostHog metrics empty because credit cannot be assigned to individual ad accounts.-Data warehouse goals are not supported by landing-page attribution.+Data warehouse goals are not supported by search attribution.Turning the switch off removes PostHog goal columns and stops their queries while keeping platform-reported conversions.-The switch only loads search conversions in the Landing pages Conversions view; keyword detail views do not imply query-level PostHog attribution.+The switch only loads search conversions in the Conversions view; organic detail views do not imply query-level PostHog attribution.For Google Ads landing pages, enable `landing_page_stats` and wait for its first sync to finish.## X Adsdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c1b85bf81bc6..2627adbb5ed4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -12414,6 +12414,14 @@ snapshots:hash: v1.k794b7964.0abe2d58ee70ac24582205caacee0e0b09831b9f04687d5ee1d9ec28f7f99be8.23pCSt9pA4N6R0id0jXh6Z0GpGSmmifTz1Ur090dRnYscenes-app-marketing-analytics-search-performance--flag-off--light:hash: v1.k794b7964.9336af8fdbf0c10e0dadbdc398517b3856ad19eae7ff0f580ddd507e4202b57b.92lmvS4XqmLPpRq2h7e7R_7p8x2ZpdvIaIAKZRL4lQU+ scenes-app-marketing-analytics-search-performance--keyword-post-hog-conversions--dark:+ hash: v1.k794b7964.08352ca5f141186204085249a1318a5a204bb29eb19a9cc0c6ab6e5a11c86579.X0nJmEMQCBQMMcYzBquugAPlqyJksuG_LVrf7mZrXgQ+ scenes-app-marketing-analytics-search-performance--keyword-post-hog-conversions--light:+ hash: v1.k794b7964.454e2084c91cf62e426ba8e5ee8f75af354b3d4754dbe5080ed0784489165ad1.QM9Ibm39uqc7GW-ryAG3R5rXUNpBfUYuFHX2YBmk8Ho+ scenes-app-marketing-analytics-search-performance--keyword-post-hog-conversions-narrow--dark:+ hash: v1.k794b7964.b5585ebf1f1b8995e0a1cda32d0ea5ef2df888a606af4de2703361e7c48676dc.TPlbixQEfAu7fdXtCSGjE6MuDNYPWluKc5hIu3D9KQA+ scenes-app-marketing-analytics-search-performance--keyword-post-hog-conversions-narrow--light:+ hash: v1.k794b7964.38e817cd8019c0b63e9fee8723b8f5f44889d74a47ce18cec52650ead801ce34.lmCYjwMaUVsFAMyKz3JGA1UUIsRTpdusdGIenK1zqp8scenes-app-marketing-analytics-search-performance--landing-pages--dark:hash: v1.k794b7964.883fc81c04f8d867edbbf6d690a2cb767634ecc425a732f27963de3a08882e90.ctIgKeFriNwBZiNHsJaadrL7l1YmYvkJwJ46ROY72H0scenes-app-marketing-analytics-search-performance--landing-pages--light:@@ -12475,9 +12483,9 @@ snapshots:scenes-app-marketing-analytics-search-performance--position-metrics--light:hash: v1.k794b7964.91cdd0e2715b472259b9fd736ae5936926266e5ee8766c5c63581fa604cab234.T59PyJwwDMDgLMD2lg4sR2t0x0CaQ5Eoxzgue-uoauwscenes-app-marketing-analytics-search-performance--post-hog-conversions--dark:- hash: v1.k794b7964.249f05547429e97576a6990a000058a01b2feadf917438665b3d2a6e46d6a2b3.bQIiR1aQpeVJwqEvrrlnr3t6hgiZDJyBkNIfrHYJNpk+ hash: v1.k794b7964.7bc1d18e05ac3fad8c8ec8bd3f2c9fb76cfae53e9e298d251896b34a4bfa3150.Lg7OKWnTCXmr991lNWnkATCK4jBVyjbYq_24o-3PtIsscenes-app-marketing-analytics-search-performance--post-hog-conversions--light:- hash: v1.k794b7964.7dbc5975e28e15b3ee3ef65dc551e6c890e3b4d1404407b1b8d637f16fe15ae2.2dlK5ffDvGkQMWxTTnJqvw4OmlWSmEGCQgLQIFO4xjE+ hash: v1.k794b7964.e5af1ad6e00fce36b1e06ba792eae272df295629a62e418ab747b4b4d07ee94e.AYNfKxuWzaZpjn66KaOUaCPs0JY8cGlhZyLal6djFCkscenes-app-marketing-analytics-search-performance--post-hog-conversions-error--dark:hash: v1.k794b7964.d887d7afb260af6ed8265f4693a3915f864b1c16629c87cac27ce955dfe73a47.cIFh7HaMEIWwOvOvLSRtUQvaWlvYeGAhVC5A8oLXNiMscenes-app-marketing-analytics-search-performance--post-hog-conversions-error--light:@@ -12487,9 +12495,9 @@ snapshots:scenes-app-marketing-analytics-search-performance--post-hog-conversions-loading--light:hash: v1.k794b7964.fbe875f837dafae033a34c62b2e02a83abc417fdd92d3efd2f3bfdb815076400.QJEcGZfq7bWLCEgkEXkhmiC-esnncvY-HFBHYMcR2wIscenes-app-marketing-analytics-search-performance--post-hog-conversions-narrow--dark:- hash: v1.k794b7964.a628c3106347fb2deaac48251d66f5f6b2ad09444afa06aca50e8018d341b069.7dk89PqQyxbgTB8XwnJtLS0oXVw8Ygo0TSMrpeSgK5w+ hash: v1.k794b7964.dfa6431f9864e646d4e62d4d98bfdf9b065cb5a649ae18a0722bba570baf680d.lQLoYyChZ9Jeil1O_VefkquqxWpWp13Uzgo8ujDvI_Yscenes-app-marketing-analytics-search-performance--post-hog-conversions-narrow--light:- hash: v1.k794b7964.c4148ba91a03733146b72a0802b8a62016f18fd1c52bdd0a0851654a71915955.5pQDycNPMC4B9SUe6epR-HD_9tJRvC2R4U3U-a9qIOE+ hash: v1.k794b7964.1c54630da5d7dbd9539fd140b1a84d384189e1a09ae83352958bd21caadc4692.XWOAX1CCLyHrktMB5IIzhp4vZpXcnZ610_7Qk5YbnS0scenes-app-marketing-analytics-search-performance--query-error--dark:hash: v1.k794b7964.3a11f95ed8775f2d45568ac1e4a5938f1f2e924bfc1d86c02165b659dc93e4ce.opQL0vSr8S9E7lYNq-f59RcmiOU-CQ_gZmyERtxEYa4scenes-app-marketing-analytics-search-performance--query-error--light:diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.tsindex a3c6b060027e..607d9a2302a6 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts@@ -370,6 +370,50 @@ describe('marketingAnalyticsLogic', () => {expect(logic.values.includeConversionGoals).toBe(true)search.actions.setMetrics('conversions')expect(search.values.query.includePostHogConversions).toBe(false)+ for (const sourceType of ['GoogleAds', 'BingAds'] as const) {+ await expectLogic(logic, () =>+ logic.actions.loadSourcesSuccess({+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: 'search-ads',+ source_type: sourceType,+ source_id: 'example-account',+ connection_id: 'example-search',+ status: ExternalDataJobStatus.Completed,+ prefix: null,+ description: 'Example search ads',+ created_via: 'web',+ latest_error: null,+ sync_frequency: '24hour',+ job_inputs: {},+ user_access_level: AccessControlLevel.Admin,+ revenue_analytics_config: { enabled: false, include_invoiceless_charges: false },+ schemas: (sourceType === 'GoogleAds'+ ? ['keyword', 'keyword_stats']+ : ['keyword_performance_report']+ ).map(+ (name) =>+ ({+ id: name,+ name,+ should_sync: true,+ status: ExternalDataSchemaStatus.Completed,+ last_synced_at: dayjs(),+ table: { name, hogql_name: name },+ }) as ExternalDataSourceSchema+ ),+ } as ExternalDataSource,+ ],+ })+ ).toFinishAllListeners()+ expect(search.values.query.includePostHogConversions).toBe(true)+ logic.actions.setAdPerformanceConversionGoals(false)+ expect(search.values.query.includePostHogConversions).toBe(false)+ logic.actions.setAdPerformanceConversionGoals(true)+ }search.actions.setBreakdown('page')expect(search.values.query.includePostHogConversions).toBe(true)search.actions.selectRow({diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.pyindex 60e5e5f10306..5ab7ba397270 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_table_query_runner.py@@ -131,8 +131,8 @@ class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[Marketgroup_by=[ast.Field(chain=[_BREAKDOWN_VALUE])],)- def _build_per_conversion_select(self) -> ast.SelectQuery:- """(D) One row per conversion, carrying all five weight arrays.+ def _build_per_conversion_select(self, model: AttributionMode | None = None) -> ast.SelectQuery:+ """(D) One row per conversion, carrying the requested weight arrays.Every builder maps over the same `ts`, so all five arrays have identical length — that is whatlets (E) explode them with a single shared ARRAY JOIN instead of five.@@ -190,6 +190,15 @@ class MarketingAnalyticsAttributionQueryRunner(AttributionQueryRunnerBase[Marketast.Alias(alias=_WEIGHT_ALIASES[AttributionMode.POSITION_BASED], expr=build_position_based_weights(ts)),]+ if model is not None:+ select = [+ expr+ for expr in select+ if not isinstance(expr, ast.Alias)+ or expr.alias not in _WEIGHT_ALIASES.values()+ or expr.alias == _WEIGHT_ALIASES[model]+ ]+return ast.SelectQuery(select=select,select_from=ast.JoinExpr(table=ast.Field(chain=[PERSON_ARRAYS_CTE])),diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.pyindex 423bd6a70950..6f1ac3578d0b 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_search_query_runner.py@@ -129,7 +129,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic@propertydef include_posthog_conversions(self) -> bool:- return bool(self.query.includePostHogConversions and self.query.breakdown == "page" and not self.query.keyword)+ return bool(self.query.includePostHogConversions and not self.query.keyword and not self.query.page)def get_cache_key_variant(self) -> str:variant = super().get_cache_key_variant()@@ -345,7 +345,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticreturn parse_select("""SELECT keyword, page, platform, matchType, currency,- {currency_count} AS currency_count,+ {attribution_row_count} AS attribution_row_count,coalesce(sumIf(click_count, period = 0), 0) AS clicks, coalesce(sumIf(impression_count, period = 0), 0) AS impressions,if(platform = 'GoogleSearchConsole', NULL, coalesce(sumIf(total_cost, period = 0), 0)) AS cost,if(platform = 'GoogleSearchConsole', NULL, coalesce(sumIf(conversion_count, period = 0), 0)) AS conversions,@@ -374,20 +374,33 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticplaceholders={"sources": sources,"search": ast.Constant(value=(self.query.search or "").strip()),- "currency_count": parse_expr("uniqExact(ifNull(currency, '')) OVER (PARTITION BY page, platform)")+ "attribution_row_count": parse_expr("count() OVER (PARTITION BY keyword, page, platform)")if self.include_posthog_conversionselse ast.Constant(value=1),},)+ def _conversion_key(self, row: MarketingAnalyticsSearchRow) -> str | None:+ value = row.page if self.query.breakdown == "page" else row.keyword+ if not value or (self.query.breakdown != "page" and row.platform == "GoogleSearchConsole"):+ return None+ return SearchConversionQueryRunner.row_key(value, row.platform)+def _add_posthog_conversions(self, response: MarketingAnalyticsSearchQueryResponse, ambiguous_keys: set[str]) -> None:- keys = [SearchConversionQueryRunner.row_key(row.page, row.platform) for row in response.results if row.page]+ keys = list(+ dict.fromkeys(+ key for row in response.results if (key := self._conversion_key(row)) and key not in ambiguous_keys+ )+ )+ breakdown = (+ MarketingAnalyticsAttributionBreakdown.LANDING_PAGE+ if self.query.breakdown == "page"+ else MarketingAnalyticsAttributionBreakdown.TERM+ )goal_runner = SearchConversionQueryRunner(- query=MarketingAnalyticsAttributionQuery(- properties=[], conversionGoalId="", breakdownBy=MarketingAnalyticsAttributionBreakdown.LANDING_PAGE- ),+ query=MarketingAnalyticsAttributionQuery(properties=[], conversionGoalId="", breakdownBy=breakdown),team=self.team,user=self.user,modifiers=self.modifiers,@@ -422,11 +435,13 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticresponse.posthogAttributionMode = goal_runner.config.attribution_modeif len(event_goals) != len(goals):warnings.append(- "Landing page attribution supports event and action goals. Data warehouse goals are not included."+ "Search performance supports event and action goals. Data warehouse goals are not included.")if ambiguous_keys:warnings.append("PostHog conversions are unavailable for pages with spend in multiple currencies because conversion credit cannot be split by ad account."+ if self.query.breakdown == "page"+ else "PostHog conversions are unavailable for keywords with multiple match types or currencies because conversion credit cannot be split between those rows.")response.posthogConversionsWarning = " ".join(warnings) or Nonefor row in response.results:@@ -443,7 +458,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticquery=MarketingAnalyticsAttributionQuery(properties=[],conversionGoalId=goal.conversion_goal_id,- breakdownBy=MarketingAnalyticsAttributionBreakdown.LANDING_PAGE,+ breakdownBy=breakdown,dateRange=DateRange(date_from=date_range.date_from().isoformat(),date_to=date_range.date_to().isoformat(),@@ -460,18 +475,13 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticrunner.search_keys = keys# Share one HogQL database across goals and periods, so the request pays Database.create_for once.runner.__dict__["_shared_hogql_database"] = goal_runner._shared_hogql_database- periods.append(- {- row.breakdownValue: next(- cell.conversions for cell in row.models if cell.model == response.posthogAttributionMode- )- for row in runner.calculate().results- }- )+ periods.append(runner.calculate_conversions())for row in response.results:- key = SearchConversionQueryRunner.row_key(row.page, row.platform)- current = periods[0].get(key, 0.0) if row.page and key not in ambiguous_keys else None- previous = periods[1].get(key, 0.0) if current is not None and self.comparison_date_range else None+ key = self._conversion_key(row)+ current = periods[0].get(key, 0.0) if key and key not in ambiguous_keys else None+ previous = (+ periods[1].get(key, 0.0) if key and current is not None and self.comparison_date_range else None+ )assert row.posthogConversions is not Nonerow.posthogConversions.append(MarketingAnalyticsSearchConversion(@@ -503,8 +513,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticambiguous_keys: set[str] = set()for row in result.results:values = dict(zip(result.columns or [], row))- if values.pop("currency_count") > 1:- ambiguous_keys.add(SearchConversionQueryRunner.row_key(values.get("page"), values["platform"]))+ attribution_row_count = values.pop("attribution_row_count")previous = {metric: values.pop(f"previous_{metric}") for metric in MarketingAnalyticsSearchMetrics.model_fields}@@ -514,6 +523,8 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticprevious=MarketingAnalyticsSearchMetrics(**previous) if self.comparison_date_range else None,))+ if attribution_row_count > 1 and (key := self._conversion_key(rows[-1])):+ ambiguous_keys.add(key)response = MarketingAnalyticsSearchQueryResponse(results=rows, placementUnavailable=bool(self.unavailable_placement_tables))diff --git a/products/marketing_analytics/backend/hogql_queries/search_conversion_query_runner.py b/products/marketing_analytics/backend/hogql_queries/search_conversion_query_runner.pyindex bf6ef8015355..70b79f8602a7 100644--- a/products/marketing_analytics/backend/hogql_queries/search_conversion_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/search_conversion_query_runner.py@@ -1,9 +1,13 @@-from posthog.schema import NativeMarketingSource+from posthog.schema import MarketingAnalyticsAttributionBreakdown, NativeMarketingSourcefrom posthog.hogql import ast-from posthog.hogql.parser import parse_expr+from posthog.hogql.constants import LimitContext+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.query import execute_hogql_query-from .attribution_table_query_runner import MarketingAnalyticsAttributionQueryRunner+from .attribution_base import PERSON_ARRAYS_CTE+from .attribution_sessions_read import session_ctes+from .attribution_table_query_runner import _WEIGHT_ALIASES, MarketingAnalyticsAttributionQueryRunnerfrom .constants import INTEGRATION_PRIMARY_SOURCE@@ -11,8 +15,8 @@ class SearchConversionQueryRunner(MarketingAnalyticsAttributionQueryRunner):search_keys: list[str]@staticmethod- def row_key(page: str | None, platform: str) -> str:- return f"{platform}:{page or ''}"+ def row_key(value: str | None, platform: str) -> str:+ return f"{platform}:{value or ''}"def additional_session_columns(self) -> set[str]:return {"channel_type", "utm_source", "referring_domain", "entry_url", "has_gclid", "has_msclkid"}@@ -31,17 +35,23 @@ class SearchConversionQueryRunner(MarketingAnalyticsAttributionQueryRunner):"notEmpty(ifNull(events.session.$entry_msclkid, '')) OR notEmpty(extractURLParameter(ifNull({url}, ''), 'msclkid'))",placeholders={"url": url},)+ by_keyword = self.query.breakdownBy == MarketingAnalyticsAttributionBreakdown.TERM+ value = (+ parse_expr("lower(trim(ifNull({term}, '')))", placeholders={"term": field("utm_term", "$entry_utm_term")})+ if by_keyword+ else parse_expr("cutQueryStringAndFragment(ifNull({url}, ''))", placeholders={"url": url})+ )return parse_expr("""concat(multiIf({channel} = 'Paid Search' AND ({source} = {google} OR {has_gclid}), 'GoogleAds',{channel} = 'Paid Search' AND ({source} = {bing} OR {has_msclkid}), 'BingAds',- {channel} = 'Organic Search' AND NOT {has_msclkid}+ {include_organic} AND {channel} = 'Organic Search' AND NOT {has_msclkid}AND match(lower(ifNull({referrer}, '')), {google_domain}), 'GoogleSearchConsole',''),- ':', cutQueryStringAndFragment(ifNull({url}, ''))+ ':', {value})""",placeholders={@@ -55,7 +65,8 @@ class SearchConversionQueryRunner(MarketingAnalyticsAttributionQueryRunner):"has_msclkid": has_msclkid,"referrer": field("referring_domain", "$entry_referring_domain"),"google_domain": ast.Constant(value=r"(^|\.)google\.[a-z.]+$"),- "url": url,+ "include_organic": ast.Constant(value=not by_keyword),+ "value": value,},)@@ -73,3 +84,42 @@ class SearchConversionQueryRunner(MarketingAnalyticsAttributionQueryRunner):placeholders={"keys": ast.Tuple(exprs=[ast.Constant(value=key) for key in self.search_keys])},)return query++ def to_conversion_query(self) -> ast.SelectQuery:+ model = self.config.attribution_mode+ query = parse_select(+ """+ SELECT credit.1 AS breakdown_value, sum(credit.2) AS conversions+ FROM {conversions}+ ARRAY JOIN arrayZip(dims, {weights}) AS credit+ WHERE credit.1 IN {keys}+ GROUP BY breakdown_value+ """,+ placeholders={+ "conversions": self._build_per_conversion_select(model=model),+ "weights": ast.Field(chain=[_WEIGHT_ALIASES[model]]),+ "keys": ast.Tuple(exprs=[ast.Constant(value=key) for key in self.search_keys]),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ query.ctes = session_ctes(self, self.query_date_range)+ query.ctes[PERSON_ARRAYS_CTE] = ast.CTE(+ name=PERSON_ARRAYS_CTE, expr=self._person_arrays_select(self.query_date_range), cte_type="subquery"+ )+ return query++ def calculate_conversions(self) -> dict[str, float]:+ # Search needs credit only; visitor reach and report totals would add unused event scans.+ query = self.to_conversion_query()+ response = execute_hogql_query(+ query_type="marketing_analytics_search_conversions_query",+ query=query,+ team=self.team,+ user=self.user,+ timings=self.timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context or LimitContext.QUERY,+ context=self._shared_hogql_context,+ settings=self.get_query_settings(),+ )+ return {str(key): float(conversions) for key, conversions in response.results or []}diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_search_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_search_query_runner.pyindex f09cff499e27..d9b543f9b1b6 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_search_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_search_query_runner.py@@ -38,6 +38,7 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTablefrom products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csvfrom .marketing_search_query_runner import MarketingAnalyticsSearchQueryRunner+from .search_conversion_query_runner import SearchConversionQueryRunnerclass TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):@@ -619,6 +620,209 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):assert result.posthogConversionGoals is Noneassert all(row.posthogConversions is None for row in result.results)+ @parameterized.expand(+ [+ (AttributionMode.LAST_TOUCH, 1, False),+ (AttributionMode.LAST_TOUCH, 1, True),+ (AttributionMode.FIRST_TOUCH, 2, True),+ (AttributionMode.LINEAR, 1.5, True),+ (AttributionMode.POSITION_BASED, 1.5, True),+ (AttributionMode.TIME_DECAY, 1 + 1 / (1 + 2 ** (1 / 42)), True),+ ]+ )+ def test_keyword_goals_match_paid_terms_without_duplicating_credit(+ self, model: AttributionMode, google_count: float, shared_sessions: bool+ ) -> None:+ self.team.modifiers = {"sessionTableVersion": SessionTableVersion.V3}+ self.team._ma_multi_touch_flag = True # type: ignore[attr-defined]+ self.team._ma_precompute_flags = {"conversion": False, "costs": False, "live_sessions": shared_sessions} # type: ignore[attr-defined]+ config = self.team.marketing_analytics_config+ config.attribution_mode = model+ config.attribution_window_days = 7+ config.conversion_goals = [+ ConversionGoalFilter1(+ kind="EventsNode",+ event="purchase",+ name="Purchases",+ conversion_goal_id="purchase",+ conversion_goal_name="Purchases",+ schema_map={},+ math=BaseMathType.TOTAL,+ properties=[EventPropertyFilter(key="qualified", value=True, operator=PropertyOperator.EXACT)],+ ).model_dump()+ ]+ config.save()+ keywords = self._table(+ "goal_keywords",+ {+ "customer_id": "Int64",+ "campaign_id": "Int64",+ "ad_group_id": "Int64",+ "ad_group_criterion_criterion_id": "Int64",+ "ad_group_criterion_keyword_text": "String",+ "ad_group_criterion_keyword_match_type": "String",+ },+ "customer_id,campaign_id,ad_group_id,ad_group_criterion_criterion_id,ad_group_criterion_keyword_text,ad_group_criterion_keyword_match_type\n"+ "1,10,100,1,Hedgehog,EXACT\n1,10,100,2,Multiple matches,EXACT\n"+ "1,10,100,3,Multiple matches,PHRASE\n1,10,100,4,Multiple currencies,EXACT\n",+ )+ google = self._table(+ "goal_google_stats",+ {+ "customer_id": "Int64",+ "campaign_id": "Int64",+ "ad_group_id": "Int64",+ "ad_group_criterion_criterion_id": "Int64",+ "customer_currency_code": "String",+ "metrics_clicks": "Float64",+ "metrics_impressions": "Float64",+ "metrics_cost_micros": "Float64",+ "metrics_conversions": "Float64",+ "segments_date": "Date",+ "segments_ad_network_type": "String",+ },+ "customer_id,campaign_id,ad_group_id,ad_group_criterion_criterion_id,customer_currency_code,metrics_clicks,metrics_impressions,metrics_cost_micros,metrics_conversions,segments_date,segments_ad_network_type\n"+ "1,10,100,1,USD,10,100,30000000,7,2023-01-10,SEARCH\n"+ "1,10,100,1,USD,5,50,8000000,2,2022-12-15,SEARCH\n"+ "1,10,100,2,USD,1,10,1000000,1,2023-01-10,SEARCH\n"+ "1,10,100,3,USD,1,10,1000000,1,2023-01-10,SEARCH\n"+ "1,10,100,4,USD,1,10,1000000,1,2023-01-10,SEARCH\n"+ "1,10,100,4,EUR,1,10,1000000,1,2023-01-10,SEARCH\n"+ "1,10,100,99,USD,1,10,1000000,1,2023-01-10,SEARCH\n",+ )+ bing = self._table(+ "goal_bing_stats",+ {+ "keyword": "String",+ "bid_match_type": "String",+ "currency_code": "String",+ "clicks": "Float64",+ "impressions": "Float64",+ "spend": "Float64",+ "conversions": "Float64",+ "time_period": "Date",+ },+ "keyword,bid_match_type,currency_code,clicks,impressions,spend,conversions,time_period\n"+ "Hedgehog,Exact,USD,5,50,20,4,2023-01-10\n",+ )+ organic = self._table(+ "goal_organic_queries",+ {"query": "String", "clicks": "Float64", "impressions": "Float64", "position": "Float64", "date": "Date"},+ "query,clicks,impressions,position,date\nHedgehog,20,200,2,2023-01-10\n",+ )+ for person, source, term, day, qualified in [+ ("google", "Google", " HEDGEHOG ", "2023-01-09", True),+ ("bing", "Bing", "hedgehog", "2023-01-09", True),+ ("journey", "google", "hedgehog", "2023-01-09", True),+ ("missing-term", "google", "", "2023-01-09", True),+ ("filtered", "google", "hedgehog", "2023-01-09", False),+ ("expired", "google", "hedgehog", "2022-12-20", True),+ ("previous", "google", "hedgehog", "2022-12-15", True),+ ("organic", "", "hedgehog", "2023-01-09", True),+ ("match-types", "google", "multiple matches", "2023-01-09", True),+ ("currencies", "google", "multiple currencies", "2023-01-09", True),+ ]:+ create_person(team_id=self.team.pk, distinct_ids=[person])+ at = f"{day}T10:00:00Z"+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id=person,+ timestamp=at,+ properties={+ "$session_id": str(uuid7(at)),+ "$current_url": "https://example.com/pricing",+ "utm_source": source,+ "utm_medium": "cpc" if source else "",+ "utm_term": term,+ "gclid": "example-click" if source == "google" else "",+ "$referring_domain": "$direct" if source else "www.google.com",+ },+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=person,+ timestamp=f"{'2023-01-09' if person == 'expired' else day}T13:00:00Z",+ properties={"qualified": qualified},+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="journey",+ timestamp="2023-01-09T11:00:00Z",+ properties={+ "$session_id": str(uuid7("2023-01-09T11:00:00Z")),+ "$current_url": "https://example.com/pricing",+ "utm_source": "newsletter",+ "utm_medium": "email",+ },+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="google",+ timestamp="2023-01-09T11:00:00Z",+ properties={+ "$session_id": str(uuid7("2023-01-09T11:00:00Z")),+ "$current_url": "https://example.com/pricing",+ "utm_source": "Google",+ "utm_medium": "cpc",+ "utm_term": "hedgehog",+ },+ )+ flush_persons_and_events()+ query = MarketingAnalyticsSearchQuery(+ sources=[+ MarketingAnalyticsSearchSource(sourceType="GoogleAds", statsTable=google, keywordTable=keywords),+ MarketingAnalyticsSearchSource(sourceType="BingAds", statsTable=bing),+ MarketingAnalyticsSearchSource(sourceType="GoogleSearchConsole", statsTable=organic),+ ],+ breakdown="keyword",+ includePostHogConversions=True,+ compareFilter=CompareFilter(compare=True),+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),+ )+ result = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate()++ def full_report_conversions(runner: SearchConversionQueryRunner) -> dict[str, float]:+ return {+ row.breakdownValue: next(cell.conversions for cell in row.models if cell.model == model)+ for row in runner.calculate().results+ }++ with patch.object(SearchConversionQueryRunner, "calculate_conversions", full_report_conversions):+ full_report = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate()+ for row, reference in zip(result.results, full_report.results, strict=True):+ assert row.model_dump(exclude={"posthogConversions"}) == reference.model_dump(+ exclude={"posthogConversions"}+ )+ assert row.posthogConversions is not None and reference.posthogConversions is not None+ for goal, reference_goal in zip(row.posthogConversions, reference.posthogConversions, strict=True):+ assert goal.model_dump() == pytest.approx(reference_goal.model_dump()), (row.platform, row.keyword)+ assert result.posthogAttributionMode == model+ assert (+ result.posthogConversionsWarning+ and "multiple match types or currencies" in result.posthogConversionsWarning+ )+ for row in result.results:+ assert row.posthogConversions is not None+ goal = row.posthogConversions[0]+ if row.keyword == "hedgehog" and row.platform != "GoogleSearchConsole":+ expected = google_count if row.platform == "GoogleAds" else 1+ assert goal.conversions == pytest.approx(expected), row.platform+ assert goal.costPerConversion == pytest.approx((30 if row.platform == "GoogleAds" else 20) / expected)+ assert goal.previousConversions == (1 if row.platform == "GoogleAds" else 0)+ assert goal.previousCostPerConversion == (8 if row.platform == "GoogleAds" else None)+ assert row.conversions == (7 if row.platform == "GoogleAds" else 4)+ else:+ assert goal.conversions is None and goal.costPerConversion is None+ assert goal.previousConversions is None and goal.previousCostPerConversion is None+ query.includePostHogConversions = False+ result = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate()+ assert result.posthogConversionGoals is None+ assert all(row.posthogConversions is None for row in result.results)+class TestMarketingSearchConversionBudget(BaseTest):@parameterized.expand([(3, 3), (6, 5)])@@ -652,7 +856,7 @@ class TestMarketingSearchConversionBudget(BaseTest):warehouse_row = {"page": "https://example.com/pricing","platform": "GoogleSearchConsole",- "currency_count": 1,+ "attribution_row_count": 1,**metrics,**{f"previous_{key}": value for key, value in metrics.items()},}@@ -662,7 +866,7 @@ class TestMarketingSearchConversionBudget(BaseTest):return_value=HogQLQueryResponse(columns=list(warehouse_row), results=[list(warehouse_row.values())]),),patch(- "products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner.execute_hogql_query",+ "products.marketing_analytics.backend.hogql_queries.search_conversion_query_runner.execute_hogql_query",return_value=HogQLQueryResponse(results=[]),) as execute_attribution,patch.object(Database, "create_for", wraps=Database.create_for) as create_database,diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsxindex 44b87e553169..0d2687fb8990 100644--- a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx@@ -240,32 +240,34 @@ const MOCKS: Mocks = {).map((row) => ({...row,- posthogConversions: query.includePostHogConversions- ? [- {- id: 'signup',- name: 'Signups',- conversions: 24,- costPerConversion: row.cost == null ? null : row.cost / 24,- previousConversions: query.compareFilter?.compare ? 20 : null,- previousCostPerConversion:- query.compareFilter?.compare && row.cost != null- ? (row.cost * 1.1) / 20- : null,- },- {- id: 'purchase',- name: 'Purchases',- conversions: 6,- costPerConversion: row.cost == null ? null : row.cost / 6,- previousConversions: query.compareFilter?.compare ? 8 : null,- previousCostPerConversion:- query.compareFilter?.compare && row.cost != null- ? (row.cost * 1.1) / 8- : null,- },- ]- : undefined,+ posthogConversions:+ query.includePostHogConversions &&+ (query.breakdown === 'page' || row.platform !== 'GoogleSearchConsole')+ ? [+ {+ id: 'signup',+ name: 'Signups',+ conversions: 24,+ costPerConversion: row.cost == null ? null : row.cost / 24,+ previousConversions: query.compareFilter?.compare ? 20 : null,+ previousCostPerConversion:+ query.compareFilter?.compare && row.cost != null+ ? (row.cost * 1.1) / 20+ : null,+ },+ {+ id: 'purchase',+ name: 'Purchases',+ conversions: 6,+ costPerConversion: row.cost == null ? null : row.cost / 6,+ previousConversions: query.compareFilter?.compare ? 8 : null,+ previousCostPerConversion:+ query.compareFilter?.compare && row.cost != null+ ? (row.cost * 1.1) / 8+ : null,+ },+ ]+ : undefined,previous: query.compareFilter?.compare? {clicks: row.clicks * 0.8,@@ -829,6 +831,22 @@ export const PostHogConversionsNarrow: Story = {],}+export const KeywordPostHogConversions: Story = {+ ...PostHogConversions,+ play: async (context) => {+ await PostHogConversions.play?.(context)+ const canvas = within(context.canvasElement)+ await userEvent.click(canvas.getByRole('button', { name: 'Keywords and queries' }))+ await expect(canvas.findByText(/Paid keywords are matched/)).resolves.toBeVisible()+ await expect(canvas.findByRole('columnheader', { name: /Cost per Purchases/ })).resolves.toBeVisible()+ },+}++export const KeywordPostHogConversionsNarrow: Story = {+ ...KeywordPostHogConversions,+ decorators: PostHogConversionsNarrow.decorators,+}+function conversionLoadingMock(state: 'loading' | 'error'): MockSignature {return async (info) => {const { query } = (await info.request.clone().json()) as { query: MarketingAnalyticsSearchQuery }diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsxindex d3f6530943fc..2823caa92c52 100644--- a/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx@@ -122,8 +122,12 @@ export function SearchPerformanceTable({}>{goals.length === 0- ? 'Add an event or action conversion goal in Marketing analytics settings to see PostHog conversions by landing page.'- : `PostHog conversions use ${conversionsResponse.posthogAttributionMode?.replaceAll('_', ' ') ?? 'your configured'} attribution, matched by landing URL and search source. URL query parameters and fragments are combined. Organic rows have no cost per conversion.`}+ ? 'Add an event or action conversion goal in Marketing analytics settings to see PostHog conversions.'+ : `PostHog conversions use ${conversionsResponse.posthogAttributionMode?.replaceAll('_', ' ') ?? 'your configured'} attribution. ${+ query.breakdown === 'page'+ ? 'Conversions are matched by landing URL and search source. URL query parameters and fragments are combined. Organic rows have no cost per conversion.'+ : 'Paid keywords are matched to the session’s utm_term and search source. Set utm_term to the keyword in your ad links. Organic query conversions are only available by landing page.'+ }`}{conversionsResponse.posthogConversionsWarning && (<p className="mb-0 mt-1">{conversionsResponse.posthogConversionsWarning}</p>)}diff --git a/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts b/products/marketing_analytics/frontend/search/searchPerformanceLogic.tsindex b6ab1f181c78..4ba10eb9689b 100644--- a/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts+++ b/products/marketing_analytics/frontend/search/searchPerformanceLogic.ts@@ -221,7 +221,7 @@ export const searchPerformanceLogic = kea<searchPerformanceLogicType>([s.displayMetrics,],(- sources,+ sources: MarketingAnalyticsSearchSource[],dateFilter,search,compareFilter,@@ -233,7 +233,10 @@ export const searchPerformanceLogic = kea<searchPerformanceLogicType>([sources,breakdown,compareFilter,- includePostHogConversions: breakdown === 'page' && metrics === 'conversions' && includeConversionGoals,+ includePostHogConversions:+ metrics === 'conversions' &&+ includeConversionGoals &&+ (breakdown === 'page' || sources.some((source) => source.sourceType !== 'GoogleSearchConsole')),dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },search,}),