: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): attribute search landing page goals (#113947)
Javier Bahamondes2202098cbdaf
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.mdindex aea5e055f35e..59f28b353f6a 100644--- a/docs/internal/marketing-attribution-session-precompute.md+++ b/docs/internal/marketing-attribution-session-precompute.md@@ -15,6 +15,8 @@ A materialized CTE selects pageview session IDs and current person IDs once perThe raw-session lookup filters to those IDs before merging entry properties and classifying channels.Reach and credit share the resolved session rows and conversion aggregation within the query.Table and paths reports execute separate queries.+Search performance landing-page goals use this route too, with normalized full entry URLs, source and referrer, and Google/Bing click-ID presence.+Each goal and comparison period runs its own query; raw click IDs are not part of the resolved dimensions.Clickable conversion metrics use the same spacing, typography, and comparison backgrounds as other Marketing analytics table cells.The cell accepts an optional click handler and uses a native button for keyboard activation.diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex facacc8b3afe..6039036d56fd 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -13098,6 +13098,32 @@"format": "date-time","type": "string"},+ "posthogAttributionMode": {+ "anyOf": [+ {+ "$ref": "#/definitions/AttributionMode"+ },+ {+ "type": "null"+ }+ ]+ },+ "posthogConversionGoals": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/definitions/MarketingAnalyticsSearchConversionGoal"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ },+ "posthogConversionsWarning": {+ "type": ["string", "null"]+ },"query_metadata": {"type": "object"},@@ -36537,6 +36563,44 @@"enum": ["string", "integer", "number", "float", "datetime", "date", "boolean"],"type": "string"},+ "MarketingAnalyticsSearchConversion": {+ "additionalProperties": false,+ "properties": {+ "conversions": {+ "type": ["number", "null"]+ },+ "costPerConversion": {+ "type": ["number", "null"]+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "previousConversions": {+ "type": ["number", "null"]+ },+ "previousCostPerConversion": {+ "type": ["number", "null"]+ }+ },+ "required": ["conversions", "costPerConversion", "id", "name"],+ "type": "object"+ },+ "MarketingAnalyticsSearchConversionGoal": {+ "additionalProperties": false,+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ }+ },+ "required": ["id", "name"],+ "type": "object"+ },"MarketingAnalyticsSearchMetrics": {"additionalProperties": false,"properties": {@@ -36589,6 +36653,9 @@"dateRange": {"$ref": "#/definitions/DateRange"},+ "includePostHogConversions": {+ "type": "boolean"+ },"keyword": {"type": "string"},@@ -36600,6 +36667,9 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "normalizePageUrls": {+ "type": "boolean"+ },"page": {"type": "string"},@@ -36641,6 +36711,32 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "posthogAttributionMode": {+ "anyOf": [+ {+ "$ref": "#/definitions/AttributionMode"+ },+ {+ "type": "null"+ }+ ]+ },+ "posthogConversionGoals": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/definitions/MarketingAnalyticsSearchConversionGoal"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ },+ "posthogConversionsWarning": {+ "type": ["string", "null"]+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."@@ -36738,6 +36834,19 @@"position": {"type": ["number", "null"]},+ "posthogConversions": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/definitions/MarketingAnalyticsSearchConversion"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ },"previous": {"anyOf": [{@@ -45092,6 +45201,32 @@"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"},+ "posthogAttributionMode": {+ "anyOf": [+ {+ "$ref": "#/definitions/AttributionMode"+ },+ {+ "type": "null"+ }+ ]+ },+ "posthogConversionGoals": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/definitions/MarketingAnalyticsSearchConversionGoal"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ]+ },+ "posthogConversionsWarning": {+ "type": ["string", "null"]+ },"query_status": {"$ref": "#/definitions/QueryStatus","description": "Query status indicates whether next to the provided data, a query is still running."diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex f871c16a0204..b6df024916cc 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -8276,6 +8276,8 @@ export interface MarketingAnalyticsSearchQuery extends DataNode<MarketingAnalytibreakdown?: 'keyword' | 'page'keyword?: stringpage?: string+ normalizePageUrls?: boolean+ includePostHogConversions?: boolean}export interface MarketingAnalyticsSearchMetrics {@@ -8293,6 +8295,18 @@ export interface MarketingAnalyticsSearchMetrics {absoluteTopImpressionRate?: number | null}+export interface MarketingAnalyticsSearchConversionGoal {+ id: string+ name: string+}++export interface MarketingAnalyticsSearchConversion extends MarketingAnalyticsSearchConversionGoal {+ conversions: number | null+ costPerConversion: number | null+ previousConversions?: number | null+ previousCostPerConversion?: number | null+}+export interface MarketingAnalyticsSearchRow extends MarketingAnalyticsSearchMetrics {keyword: string | nullpage?: string | null@@ -8300,10 +8314,14 @@ export interface MarketingAnalyticsSearchRow extends MarketingAnalyticsSearchMetmatchType: string | nullcurrency: string | nullprevious?: MarketingAnalyticsSearchMetrics | null+ posthogConversions?: MarketingAnalyticsSearchConversion[] | null}export interface MarketingAnalyticsSearchQueryResponse extends AnalyticsQueryResponseBase {results: MarketingAnalyticsSearchRow[]+ posthogConversionGoals?: MarketingAnalyticsSearchConversionGoal[] | null+ posthogConversionsWarning?: string | null+ posthogAttributionMode?: AttributionMode | null}export type CachedMarketingAnalyticsSearchQueryResponse = CachedQueryResponse<MarketingAnalyticsSearchQueryResponse>diff --git a/posthog/schema.py b/posthog/schema.pyindex 63e7ca750f28..9c67dd67733c 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -2085,6 +2085,26 @@ class MarketingAnalyticsDrillDownConfig(BaseModel):excludesConversionGoals: bool | None = None+class MarketingAnalyticsSearchConversion(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ conversions: float | None = None+ costPerConversion: float | None = None+ id: str+ name: str+ previousConversions: float | None = None+ previousCostPerConversion: float | None = None+++class MarketingAnalyticsSearchConversionGoal(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ id: str+ name: str++class MarketingAnalyticsSearchMetrics(BaseModel):model_config = ConfigDict(extra="forbid",@@ -2128,6 +2148,7 @@ class MarketingAnalyticsSearchRow(BaseModel):page: str | None = Noneplatform: Platformposition: float | None = None+ posthogConversions: list[MarketingAnalyticsSearchConversion] | None = Noneprevious: MarketingAnalyticsSearchMetrics | None = NonetopImpressionRate: float | None = Field(default=None,@@ -14378,6 +14399,9 @@ class CachedMarketingAnalyticsSearchQueryResponse(BaseModel):last_refresh: AwareDatetimemodifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetime+ posthogAttributionMode: AttributionMode | None = None+ posthogConversionGoals: list[MarketingAnalyticsSearchConversionGoal] | None = None+ posthogConversionsWarning: str | None = Nonequery_metadata: dict[str, Any] | None = Nonequery_scan: QueryScanSummary | None = Field(default=None,@@ -20336,6 +20360,9 @@ class MarketingAnalyticsSearchQueryResponse(BaseModel):)hogql: str | None = Field(default=None, description="Generated HogQL query.")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ posthogAttributionMode: AttributionMode | None = None+ posthogConversionGoals: list[MarketingAnalyticsSearchConversionGoal] | None = None+ posthogConversionsWarning: str | None = Nonequery_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -22242,6 +22269,9 @@ class QueryResponseAlternative38(BaseModel):)hogql: str | None = Field(default=None, description="Generated HogQL query.")modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ posthogAttributionMode: AttributionMode | None = None+ posthogConversionGoals: list[MarketingAnalyticsSearchConversionGoal] | None = None+ posthogConversionsWarning: str | None = Nonequery_status: QueryStatus | None = Field(default=None,description=("Query status indicates whether next to the provided data, a query is still running."),@@ -29068,9 +29098,11 @@ class MarketingAnalyticsSearchQuery(BaseModel):breakdown: Breakdown1 | None = NonecompareFilter: CompareFilter | None = NonedateRange: DateRange | None = None+ includePostHogConversions: bool | None = Nonekeyword: str | None = Nonekind: Literal["MarketingAnalyticsSearchQuery"] = "MarketingAnalyticsSearchQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ normalizePageUrls: bool | None = Nonepage: str | None = Noneresponse: MarketingAnalyticsSearchQueryResponse | None = Nonesearch: str | None = Nonediff --git a/products/marketing_analytics/backend/hogql_queries/attribution_base.py b/products/marketing_analytics/backend/hogql_queries/attribution_base.pyindex e9aae6b4176a..aaaad69a3361 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_base.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_base.py@@ -60,6 +60,12 @@ class AttributionQueryRunnerBase(MarketingSessionBreakdownQueryRunnerBase[Respon# Narrower than the session-breakdown base's union: everything below reads attribution-only fields.query: MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery+ def additional_session_columns(self) -> set[str]:+ return set()++ def resolved_breakdown_expr(self) -> ast.Expr | None:+ return None+def get_query_settings(self) -> HogQLGlobalSettings:# Extra aggregation threads create more partial states and spill files for the same sessions.return HogQLGlobalSettings(diff --git a/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.pyindex 4ece6b5aaab3..0646f61cb3d4 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_session_dimensions.py@@ -29,6 +29,9 @@ _DIMENSION_FIELDS = {}+SEARCH_SESSION_COLUMNS = ("entry_url", "has_gclid", "has_msclkid")++def _raw_session_source(modifiers: HogQLQueryModifiers) -> tuple[str, ast.Expr]:is_v3 = modifiers.sessionTableVersion == SessionTableVersion.V3table = "raw_sessions_v3" if is_v3 else "raw_sessions"@@ -53,6 +56,12 @@ def _raw_dimensions("$end_timestamp",*[field for column, field in _DIMENSION_FIELDS.items() if column in columns],]+ if "entry_url" in columns or "has_msclkid" in columns:+ fields.append("$entry_current_url")+ if "has_gclid" in columns:+ fields.append("$entry_gclid")+ if "has_msclkid" in columns:+ fields.append("$entry_msclkid")context = HogQLContext(modifiers=modifiers)select_sessions = (select_from_sessions_table_v3@@ -96,6 +105,14 @@ def _raw_dimensions(dimensions.append(parse_expr("toString(ifNull({field}, ''))", placeholders={"field": ast.Field(chain=[field])}))+ search_dimensions = {+ "entry_url": parse_expr("cutQueryStringAndFragment(ifNull($entry_current_url, ''))"),+ "has_gclid": parse_expr("notEmpty(ifNull($entry_gclid, ''))"),+ "has_msclkid": parse_expr(+ "notEmpty(ifNull($entry_msclkid, '')) OR notEmpty(extractURLParameter(ifNull($entry_current_url, ''), 'msclkid'))"+ ),+ }+ dimensions.extend(search_dimensions[column] for column in SEARCH_SESSION_COLUMNS if column in columns)query = parse_select("""SELECT session_id_v7, {dimensions} AS dimensions, now() AS computed_at, 1 AS source_prioritydiff --git a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.pyindex 9eb29481b727..836b475e789e 100644--- a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py+++ b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py@@ -23,7 +23,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.access_control.backend.facade.api import team_has_property_access_rulesfrom .attribution_base import MAX_CONVERSIONS_PER_PERSON, MAX_TOUCHPOINTS_PER_PERSON, PERSON_CONVERSION_COUNT-from .attribution_session_dimensions import session_dimensions+from .attribution_session_dimensions import SEARCH_SESSION_COLUMNS, session_dimensionsfrom .constants import UNKNOWN_CHANNELfrom .session_breakdown_base import UNATTRIBUTED_SESSION_VALUES@@ -194,7 +194,7 @@ def _session_identities(start: datetime, end: datetime) -> ast.SelectQuery:return query-def _read_sessions(dimensions: ast.SelectQuery) -> ast.SelectQuery:+def _read_sessions(dimensions: ast.SelectQuery, columns: set[str]) -> ast.SelectQuery:query = parse_select("""WITH dimensions AS (SELECT * FROM {dimensions}), identities AS ({identities})@@ -212,6 +212,10 @@ def _read_sessions(dimensions: ast.SelectQuery) -> ast.SelectQuery:},)assert isinstance(query, ast.SelectQuery)+ for index, column in enumerate((column for column in SEARCH_SESSION_COLUMNS if column in columns), start=11):+ query.select.append(+ ast.Alias(alias=column, expr=ast.TupleAccess(tuple=ast.Field(chain=["d", "latest"]), index=index))+ )return query@@ -287,6 +291,9 @@ def _exclusions(runner: "AttributionQueryRunnerBase", table_alias: Optional[str]def _breakdown_expr(runner: "AttributionQueryRunnerBase") -> ast.Expr:+ resolved = runner.resolved_breakdown_expr()+ if resolved is not None:+ return resolvedcolumn = _field(BREAKDOWN_COLUMNS[runner.breakdown])if runner.breakdown == MarketingAnalyticsAttributionBreakdown.CHANNEL:return runner._non_empty_or(column, UNKNOWN_CHANNEL)@@ -388,7 +395,7 @@ def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRangif not _eligible(runner, date_range):return {}read = window(runner, date_range)- columns = {BREAKDOWN_COLUMNS[runner.breakdown]}+ columns = {BREAKDOWN_COLUMNS[runner.breakdown]} | runner.additional_session_columns()if runner.breakdown == MarketingAnalyticsAttributionBreakdown.CAMPAIGN:columns.add("utm_source")if runner.query.excludeDirectTraffic:@@ -399,7 +406,7 @@ def session_ctes(runner: "AttributionQueryRunnerBase", date_range: QueryDateRangread.start,read.end,)- sessions = _read_sessions(dimensions)+ sessions = _read_sessions(dimensions, columns)ctes: dict[str, ast.CTE] = {}ctes["attribution_session_identities"] = ast.CTE(name="attribution_session_identities",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 f5e6cf241efa..1cf0be2590ff 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@@ -3,6 +3,11 @@ from functools import cached_propertyfrom posthog.schema import (CachedMarketingAnalyticsSearchQueryResponse,+ DateRange,+ MarketingAnalyticsAttributionBreakdown,+ MarketingAnalyticsAttributionQuery,+ MarketingAnalyticsSearchConversion,+ MarketingAnalyticsSearchConversionGoal,MarketingAnalyticsSearchMetrics,MarketingAnalyticsSearchQuery,MarketingAnalyticsSearchQueryResponse,@@ -21,6 +26,13 @@ from posthog.hogql_queries.utils.query_compare_to_date_range import QueryComparefrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange+from .attribution_base import ConversionGoal+from .conversion_goal_conditions import conversion_goal_match_expr+from .marketing_analytics_config import MarketingAnalyticsConfig+from .search_conversion_query_runner import SearchConversionQueryRunner++MAX_POSTHOG_CONVERSION_GOALS = 5+class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticsSearchQueryResponse]):query: MarketingAnalyticsSearchQuery@@ -95,6 +107,24 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic)return result+ @property+ def include_posthog_conversions(self) -> bool:+ return bool(self.query.includePostHogConversions and self.query.breakdown == "page" and not self.query.keyword)++ def get_cache_key_variant(self) -> str:+ variant = super().get_cache_key_variant()+ if (+ self.include_posthog_conversions+ and MarketingAnalyticsConfig.from_team(self.team).live_session_resolution_enabled+ ):+ return f"{variant}_live_session_resolution"+ return variant++ def _page_expr(self, page: ast.Expr) -> ast.Expr:+ if self.include_posthog_conversions or self.query.normalizePageUrls:+ return ast.Call(name="cutQueryStringAndFragment", args=[page])+ return page+def _source_query(self, source: MarketingAnalyticsSearchSource, date_range: QueryDateRange, period: int) -> ast.SelectQuery | ast.SelectSetQuery:@@ -114,7 +144,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic"keyword_value": ast.Constant(value=None)if self.query.breakdown == "page"else parse_expr("nullIf(lower(trim(s.query)), '')"),- "page_value": ast.Field(chain=["s", "page"])+ "page_value": self._page_expr(parse_expr("s.page"))if self.query.breakdown == "page"else ast.Constant(value=None),"keyword_filter": parse_expr(@@ -124,7 +154,11 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticif self.query.keyword is not Noneelse ast.Constant(value=True),"page_filter": parse_expr(- "s.page = {page}", placeholders={"page": ast.Constant(value=self.query.page)}+ "{page_value} = {page}",+ placeholders={+ "page_value": self._page_expr(parse_expr("s.page")),+ "page": self._page_expr(ast.Constant(value=self.query.page)),+ },)if self.query.page is not Noneelse ast.Constant(value=True),@@ -147,9 +181,10 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticplaceholders=placeholders,)if self.query.breakdown == "page" and source.sourceType == "BingAds":+ placeholders["page_value"] = self._page_expr(parse_expr("destination_url"))return parse_select("""- SELECT {period} AS period, NULL AS keyword, nullIf(destination_url, '') AS page,+ SELECT {period} AS period, NULL AS keyword, nullIf({page_value}, '') AS page,'BingAds' AS platform, NULL AS matchType,nullIf(upper(currency_code), '') AS currency,sum(toFloat(clicks)) AS click_count, sum(toFloat(impressions)) AS impression_count,@@ -169,10 +204,11 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticif self.query.breakdown == "page":if source.sourceType != "GoogleAds":raise ValueError("Landing pages are supported by Google Ads and Google Search Console")+ placeholders["page_value"] = self._page_expr(parse_expr("landing_page_view_unexpanded_final_url"))return parse_select("""SELECT {period} AS period, NULL AS keyword,- nullIf(landing_page_view_unexpanded_final_url, '') AS page,+ nullIf({page_value}, '') AS page,'GoogleAds' AS platform, NULL AS matchType,nullIf(upper(customer_currency_code), '') AS currency,sum(toFloat(metrics_clicks)) AS click_count,@@ -252,6 +288,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticreturn parse_select("""SELECT keyword, page, platform, matchType, currency,+ {currency_count} AS currency_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,@@ -277,8 +314,120 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticORDER BY clicks DESC, impressions DESC, previous_clicks DESC, platform, keyword, page, matchType, currencyLIMIT 100""",- placeholders={"sources": sources, "search": ast.Constant(value=(self.query.search or "").strip())},+ placeholders={+ "sources": sources,+ "search": ast.Constant(value=(self.query.search or "").strip()),+ "currency_count": parse_expr("uniqExact(ifNull(currency, '')) OVER (PARTITION BY page, platform)")+ if self.include_posthog_conversions+ else ast.Constant(value=1),+ },+ )++ 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]+ goal_runner = SearchConversionQueryRunner(+ query=MarketingAnalyticsAttributionQuery(+ properties=[], conversionGoalId="", breakdownBy=MarketingAnalyticsAttributionBreakdown.LANDING_PAGE+ ),+ team=self.team,+ user=self.user,+ modifiers=self.modifiers,+ timings=self.timings,+ limit_context=self.limit_context,)+ goal_runner.__dict__["_shared_hogql_database"] = self.hogql_database+ goals = goal_runner._get_team_conversion_goals()+ event_goals: list[ConversionGoal] = [goal for goal in goals if goal.kind != "DataWarehouseNode"]+ filtered_goals, skipped_goals = goal_runner._filter_invalid_conversion_goals(event_goals)+ warnings = [goal.message for goal in skipped_goals]+ # The attribution runner raises on a goal whose action was deleted, so skip it before the goal cap.+ valid_goals: list[ConversionGoal] = []+ for goal in filtered_goals:+ if conversion_goal_match_expr(goal, self.team) is None:+ warnings.append(+ f"Conversion goal '{goal.conversion_goal_name}' skipped: its action no longer exists. "+ "Update the goal in Marketing analytics settings."+ )+ else:+ valid_goals.append(goal)+ if len(valid_goals) > MAX_POSTHOG_CONVERSION_GOALS:+ warnings.append(+ f"Search performance shows the first {MAX_POSTHOG_CONVERSION_GOALS} supported PostHog goals. "+ "Use the attribution report to view other goals."+ )+ valid_goals = valid_goals[:MAX_POSTHOG_CONVERSION_GOALS]+ response.posthogConversionGoals = [+ MarketingAnalyticsSearchConversionGoal(id=goal.conversion_goal_id, name=goal.conversion_goal_name)+ for goal in valid_goals+ ]+ response.posthogAttributionMode = goal_runner.config.attribution_mode+ if len(event_goals) != len(goals):+ warnings.append(+ "Landing page attribution 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."+ )+ response.posthogConversionsWarning = " ".join(warnings) or None+ for row in response.results:+ row.posthogConversions = []+ if not keys:+ return+ for goal in valid_goals:+ periods: list[dict[str, float]] = []+ for date_range in [self.query_date_range, self.comparison_date_range]:+ if date_range is None:+ periods.append({})+ continue+ runner = SearchConversionQueryRunner(+ query=MarketingAnalyticsAttributionQuery(+ properties=[],+ conversionGoalId=goal.conversion_goal_id,+ breakdownBy=MarketingAnalyticsAttributionBreakdown.LANDING_PAGE,+ dateRange=DateRange(+ date_from=date_range.date_from().isoformat(),+ date_to=date_range.date_to().isoformat(),+ explicitDate=True,+ ),+ limit=len(keys),+ ),+ team=self.team,+ user=self.user,+ modifiers=self.modifiers,+ timings=self.timings,+ limit_context=self.limit_context,+ )+ runner.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+ }+ )+ 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+ assert row.posthogConversions is not None+ row.posthogConversions.append(+ MarketingAnalyticsSearchConversion(+ id=goal.conversion_goal_id,+ name=goal.conversion_goal_name,+ conversions=current,+ costPerConversion=row.cost / current if row.cost is not None and current else None,+ previousConversions=previous,+ previousCostPerConversion=row.previous.cost / previous+ if row.previous and row.previous.cost is not None and previous+ else None,+ )+ )def _calculate(self) -> MarketingAnalyticsSearchQueryResponse:if not self.query.sources:@@ -293,9 +442,12 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticmodifiers=self.modifiers,limit_context=self.limit_context,)- rows = []+ rows: list[MarketingAnalyticsSearchRow] = []+ ambiguous_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"]))previous = {metric: values.pop(f"previous_{metric}") for metric in MarketingAnalyticsSearchMetrics.model_fields}@@ -305,4 +457,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalyticprevious=MarketingAnalyticsSearchMetrics(**previous) if self.comparison_date_range else None,))- return MarketingAnalyticsSearchQueryResponse(results=rows)+ response = MarketingAnalyticsSearchQueryResponse(results=rows)+ if self.include_posthog_conversions:+ self._add_posthog_conversions(response, ambiguous_keys)+ return responsediff --git a/products/marketing_analytics/backend/hogql_queries/search_conversion_query_runner.py b/products/marketing_analytics/backend/hogql_queries/search_conversion_query_runner.pynew file mode 100644index 000000000000..bf6ef8015355--- /dev/null+++ b/products/marketing_analytics/backend/hogql_queries/search_conversion_query_runner.py@@ -0,0 +1,75 @@+from posthog.schema import NativeMarketingSource++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr++from .attribution_table_query_runner import MarketingAnalyticsAttributionQueryRunner+from .constants import INTEGRATION_PRIMARY_SOURCE+++class SearchConversionQueryRunner(MarketingAnalyticsAttributionQueryRunner):+ search_keys: list[str]++ @staticmethod+ def row_key(page: str | None, platform: str) -> str:+ return f"{platform}:{page or ''}"++ def additional_session_columns(self) -> set[str]:+ return {"channel_type", "utm_source", "referring_domain", "entry_url", "has_gclid", "has_msclkid"}++ def _search_breakdown_expr(self, *, resolved: bool) -> ast.Expr:+ def field(column: str, session_field: str) -> ast.Expr:+ return ast.Field(chain=[column] if resolved else ["events", "session", session_field])++ url = field("entry_url", "$entry_current_url")+ if resolved:+ has_gclid: ast.Expr = ast.Field(chain=["has_gclid"])+ has_msclkid: ast.Expr = ast.Field(chain=["has_msclkid"])+ else:+ has_gclid = parse_expr("notEmpty(ifNull(events.session.$entry_gclid, ''))")+ has_msclkid = parse_expr(+ "notEmpty(ifNull(events.session.$entry_msclkid, '')) OR notEmpty(extractURLParameter(ifNull({url}, ''), 'msclkid'))",+ 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}+ AND match(lower(ifNull({referrer}, '')), {google_domain}), 'GoogleSearchConsole',+ ''+ ),+ ':', cutQueryStringAndFragment(ifNull({url}, ''))+ )+ """,+ placeholders={+ "channel": field("channel_type", "$channel_type"),+ "source": self._normalized_source_expr(+ ast.Call(name="lower", args=[field("utm_source", "$entry_utm_source")])+ ),+ "google": ast.Constant(value=INTEGRATION_PRIMARY_SOURCE[NativeMarketingSource.GOOGLE_ADS]),+ "bing": ast.Constant(value=INTEGRATION_PRIMARY_SOURCE[NativeMarketingSource.BING_ADS]),+ "has_gclid": has_gclid,+ "has_msclkid": has_msclkid,+ "referrer": field("referring_domain", "$entry_referring_domain"),+ "google_domain": ast.Constant(value=r"(^|\.)google\.[a-z.]+$"),+ "url": url,+ },+ )++ def _breakdown_expr(self) -> ast.Expr:+ return self._search_breakdown_expr(resolved=False)++ def resolved_breakdown_expr(self) -> ast.Expr:+ return self._search_breakdown_expr(resolved=True)++ def _build_outer_select(self) -> ast.SelectQuery:+ query = super()._build_outer_select()+ # Filter after attribution so other channels keep their share of conversion credit.+ query.where = parse_expr(+ "breakdown_value IN {keys}",+ placeholders={"keys": ast.Tuple(exprs=[ast.Constant(value=key) for key in self.search_keys])},+ )+ return querydiff --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 d966686e8a7a..15cec6166265 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@@ -2,22 +2,36 @@ from pathlib import Pathfrom tempfile import TemporaryDirectoryimport pytest-from posthog.test.base import BaseTest, ClickhouseTestMixin+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patchfrom django.core.cache import cachefrom parameterized import parameterizedfrom posthog.schema import (+ AttributionMode,+ BaseMathType,Breakdown1,CompareFilter,+ ConversionGoalFilter1,+ ConversionGoalFilter2,DateRange,+ EventPropertyFilter,+ HogQLQueryResponse,+ MarketingAnalyticsSearchMetrics,MarketingAnalyticsSearchQuery,MarketingAnalyticsSearchSource,+ PropertyOperator,+ SessionTableVersion,)+from posthog.hogql.database.database import Database+from posthog.constants import AvailableFeaturefrom posthog.models.organization import OrganizationMembership+from posthog.models.utils import uuid7+from posthog.test.persons import create_personfrom products.access_control.backend.models.access_control import AccessControlfrom products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv@@ -128,6 +142,7 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):"cpc": 1.5,"cpa": 24,"previous": None,+ "posthogConversions": None,}bing = next(row for row in rows if row.platform == "BingAds" and row.matchType == "exact" and row.keyword == "hedgehog"@@ -291,7 +306,8 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):assert usd.topImpressionRate == (0.8 if placement_available else None)assert usd.absoluteTopImpressionRate == (0.4 if placement_available else None)- def test_organic_positions_are_weighted_and_details_keep_query_page_filters(self) -> None:+ @parameterized.expand([(False,), (True,)])+ def test_organic_positions_are_weighted_and_details_keep_query_page_filters(self, normalize_urls: bool) -> None:table = self._table("organic_query_pages",{@@ -305,7 +321,7 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):"date,query,page,clicks,impressions,position\n""2023-01-10,Analytics,https://example.com/a,10,100,1\n""2023-01-10,Analytics,https://example.com/b,90,900,9\n"- "2023-01-10,Other,https://example.com/a,5,50,2\n"+ "2023-01-10,Other,https://example.com/a?variant=example#plans,5,50,2\n""2022-12-15,Analytics,https://example.com/a,8,200,4\n",)query = MarketingAnalyticsSearchQuery(@@ -328,15 +344,290 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):assert sum(row.clicks for row in pages) == 100query.breakdown = Breakdown1.KEYWORDquery.keyword = None- query.page = "https://example.com/a"- queries = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results- assert {row.keyword for row in queries} == {"analytics", "other"}- assert sum(row.clicks for row in queries) == 15+ query.page = "https://example.com/a?campaign=example#details" if normalize_urls else "https://example.com/a"+ query.normalizePageUrls = normalize_urls+ query.includePostHogConversions = False+ result = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate()+ assert {row.keyword for row in result.results} == ({"analytics", "other"} if normalize_urls else {"analytics"})+ assert sum(row.clicks for row in result.results) == (15 if normalize_urls else 10)+ assert result.posthogConversionGoals is Nonequery.page = "https://example.com/a' OR 1=1 --"assert (MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results == [])+ @parameterized.expand(+ [+ (AttributionMode.LAST_TOUCH, 2, 1, False, SessionTableVersion.V2, False),+ (AttributionMode.LAST_TOUCH, 2, 1, False, SessionTableVersion.V2, True),+ (AttributionMode.LAST_TOUCH, 2, 1, False, SessionTableVersion.V3, False),+ (AttributionMode.LAST_TOUCH, 2, 1, False, SessionTableVersion.V3, True),+ (AttributionMode.FIRST_TOUCH, 3, 0, False, SessionTableVersion.V3, True),+ (AttributionMode.LAST_TOUCH, None, 1, True, SessionTableVersion.V2, True),+ ]+ )+ def test_posthog_landing_page_conversions_respect_source_model_filters_and_comparison(+ self,+ model: AttributionMode,+ paid_count: int | None,+ organic_count: int,+ multiple_currencies: bool,+ version: SessionTableVersion,+ shared_sessions: bool,+ ) -> None:+ self.team.modifiers = {"sessionTableVersion": version}+ 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-goal",+ conversion_goal_name="Purchases",+ schema_map={},+ math=BaseMathType.TOTAL,+ properties=[EventPropertyFilter(key="qualified", value=True, operator=PropertyOperator.EXACT)],+ ).model_dump()+ ]+ config.save()+ paid = self._table(+ "search_conversion_paid",+ {+ "landing_page_view_unexpanded_final_url": "String",+ "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",+ },+ "landing_page_view_unexpanded_final_url,customer_currency_code,metrics_clicks,metrics_impressions,metrics_cost_micros,metrics_conversions,segments_date,segments_ad_network_type\n"+ "https://example.com/pricing?utm_campaign=spring,USD,20,100,40000000,5,2023-01-10,SEARCH\n"+ "https://example.com/pricing,USD,10,50,20000000,2,2023-01-10,SEARCH\n"+ "https://example.com/pricing,USD,5,20,8000000,1,2022-12-15,SEARCH\n"+ + ("https://example.com/pricing,EUR,3,10,6000000,1,2023-01-10,SEARCH\n" if multiple_currencies else ""),+ )+ organic = self._table(+ "search_conversion_organic",+ {+ "page": "String",+ "clicks": "Float64",+ "impressions": "Float64",+ "position": "Float64",+ "date": "Date",+ },+ "page,clicks,impressions,position,date\nhttps://example.com/pricing,40,200,2,2023-01-10\n",+ )+ bing = self._table(+ "search_conversion_bing",+ {+ "destination_url": "String",+ "currency_code": "String",+ "clicks": "Float64",+ "impressions": "Float64",+ "spend": "Float64",+ "conversions_qualified": "Float64",+ "time_period": "Date",+ "ad_distribution": "String",+ },+ "destination_url,currency_code,clicks,impressions,spend,conversions_qualified,time_period,ad_distribution\n"+ "https://example.com/pricing?utm_source=bing,USD,10,100,12,3,2023-01-10,Search\n"+ "https://example.com/pricing#plans,USD,5,50,8,2,2023-01-10,Search\n"+ "https://example.com/pricing,USD,3,30,6,1,2022-12-15,Search\n",+ )+ for person, day, url, medium, referrer, qualified in [+ ("paid", "2023-01-09", "https://example.com/pricing?utm_campaign=spring", "cpc", "$direct", True),+ ("journey", "2023-01-08", "https://example.com/pricing", "cpc", "$direct", True),+ ("other-host", "2023-01-09", "https://other.example.com/pricing", "cpc", "$direct", True),+ ("bing", "2023-01-09", "https://example.com/pricing", "", "www.bing.com", True),+ (+ "auto-tagged",+ "2023-01-09",+ "https://example.com/pricing?gclid=example-click",+ "cpc",+ "www.google.com",+ True,+ ),+ ("bing-paid", "2023-01-09", "https://example.com/pricing?utm_source=bing", "cpc", "www.bing.com", True),+ ("bing-previous", "2022-12-15", "https://example.com/pricing", "cpc", "www.bing.com", True),+ (+ "bing-auto-tagged",+ "2023-01-09",+ "https://example.com/pricing?msclkid=example-click",+ "cpc",+ "www.bing.com",+ True,+ ),+ ("bing-stored-click", "2022-12-15", "https://example.com/pricing", "cpc", "www.bing.com", True),+ ("excluded", "2023-01-09", "https://example.com/pricing", "cpc", "$direct", False),+ ("previous", "2022-12-15", "https://example.com/pricing", "cpc", "$direct", 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": url,+ "$pathname": "/pricing",+ "utm_source": (+ "Google"+ if person == "paid"+ else "Bing"+ if person == "bing-previous"+ else "microsoft"+ if person == "bing-paid"+ else "google"+ if medium and person not in ("auto-tagged", "bing-auto-tagged", "bing-stored-click")+ else ""+ ),+ "gclid": "example-click" if person == "auto-tagged" else "",+ "msclkid": "example-click" if person == "bing-stored-click" else "",+ "utm_medium": medium,+ "$referring_domain": referrer,+ },+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=person,+ timestamp=f"{day}T13:00:00Z",+ properties={"qualified": qualified},+ )+ # The later organic touch earns last-touch credit, but not first-touch credit.+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="journey",+ timestamp="2023-01-08T11:00:00Z",+ properties={+ "$session_id": str(uuid7("2023-01-08T11:00:00Z")),+ "$current_url": "https://example.com/pricing#plans",+ "$pathname": "/pricing",+ "$referring_domain": "www.google.com",+ },+ )+ flush_persons_and_events()+ query = MarketingAnalyticsSearchQuery(+ sources=[+ MarketingAnalyticsSearchSource(sourceType="GoogleAds", statsTable=paid),+ MarketingAnalyticsSearchSource(sourceType="BingAds", statsTable=bing),+ MarketingAnalyticsSearchSource(sourceType="GoogleSearchConsole", statsTable=organic),+ ],+ breakdown="page",+ 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()+ assert len(result.results) == (4 if multiple_currencies else 3)+ assert bool(result.posthogConversionsWarning) == multiple_currencies+ assert result.posthogAttributionMode == model+ paid_row = next(row for row in result.results if row.platform == "GoogleAds" and row.currency == "USD")+ organic_row = next(row for row in result.results if row.platform == "GoogleSearchConsole")+ assert paid_row.conversions == 7+ assert paid_row.cost == 60+ assert paid_row.posthogConversions is not None+ assert paid_row.posthogConversions[0].conversions == paid_count+ assert paid_row.posthogConversions[0].costPerConversion == (60 / paid_count if paid_count else None)+ assert paid_row.posthogConversions[0].previousConversions == (None if multiple_currencies else 1)+ assert paid_row.posthogConversions[0].previousCostPerConversion == (None if multiple_currencies else 8)+ assert organic_row.posthogConversions is not None+ assert organic_row.posthogConversions[0].conversions == organic_count+ assert organic_row.posthogConversions[0].costPerConversion is None+ bing_row = next(row for row in result.results if row.platform == "BingAds")+ assert bing_row.page == "https://example.com/pricing"+ assert bing_row.cost == 20 and bing_row.conversions == 5+ assert bing_row.posthogConversions is not None+ assert bing_row.posthogConversions[0].conversions == 2+ assert bing_row.posthogConversions[0].costPerConversion == 10+ assert bing_row.posthogConversions[0].previousConversions == 2+ assert bing_row.posthogConversions[0].previousCostPerConversion == 3+ 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)])+ def test_bounds_goal_queries_and_reports_excluded_goals(self, goal_count: int, expected_count: int) -> None:+ config = self.team.marketing_analytics_config+ goals = [+ ConversionGoalFilter1(+ kind="EventsNode",+ event=None if index == 0 else "purchase",+ name=f"Goal {index}",+ conversion_goal_id=f"goal-{index}",+ conversion_goal_name=f"Goal {index}",+ schema_map={},+ ).model_dump()+ for index in range(goal_count + 1)+ ]+ goals.insert(+ 1,+ ConversionGoalFilter2(+ kind="ActionsNode",+ id=999999,+ name="Deleted action",+ conversion_goal_id="deleted-action",+ conversion_goal_name="Deleted action",+ schema_map={},+ ).model_dump(),+ )+ config.conversion_goals = goals+ config.save()+ metrics = MarketingAnalyticsSearchMetrics(clicks=1, impressions=10).model_dump()+ warehouse_row = {+ "page": "https://example.com/pricing",+ "platform": "GoogleSearchConsole",+ "currency_count": 1,+ **metrics,+ **{f"previous_{key}": value for key, value in metrics.items()},+ }+ with (+ patch(+ "products.marketing_analytics.backend.hogql_queries.marketing_search_query_runner.execute_hogql_query",+ 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",+ return_value=HogQLQueryResponse(results=[]),+ ) as execute_attribution,+ patch.object(Database, "create_for", wraps=Database.create_for) as create_database,+ ):+ result = MarketingAnalyticsSearchQueryRunner(+ query=MarketingAnalyticsSearchQuery(+ sources=[MarketingAnalyticsSearchSource(sourceType="GoogleSearchConsole", statsTable="pages")],+ breakdown="page",+ includePostHogConversions=True,+ compareFilter=CompareFilter(compare=True),+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),+ ),+ team=self.team,+ user=self.user,+ ).calculate()+ assert execute_attribution.call_count == expected_count * 2+ assert create_database.call_count == 1+ assert result.posthogConversionGoals is not None+ assert [goal.id for goal in result.posthogConversionGoals] == [+ f"goal-{index}" for index in range(1, expected_count + 1)+ ]+ conversions = result.results[0].posthogConversions+ assert conversions is not None and len(conversions) == expected_count+ assert all(goal.conversions == 0 and goal.previousConversions == 0 for goal in conversions)+ assert result.posthogConversionsWarning is not None+ assert "'All Events' cannot be used" in result.posthogConversionsWarning+ assert "'Deleted action' skipped: its action no longer exists" in result.posthogConversionsWarning+ assert ("first 5 supported PostHog goals" in result.posthogConversionsWarning) == (goal_count > expected_count)+@pytest.mark.eeclass TestMarketingSearchCacheAccessControl(BaseTest):@@ -351,6 +642,20 @@ class TestMarketingSearchCacheAccessControl(BaseTest):self.organization_membership.save()self.addCleanup(cache.clear)+ @parameterized.expand([True, False])+ def test_live_resolution_rollout_partitions_search_conversion_cache(self, include_conversions: bool) -> None:+ query = MarketingAnalyticsSearchQuery(+ sources=[], breakdown="page", includePostHogConversions=include_conversions+ )+ keys = []+ for enabled in (False, True, False):+ self.team._ma_precompute_flags = {"conversion": False, "costs": False, "live_sessions": enabled} # type: ignore[attr-defined]+ keys.append(+ MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).get_cache_key()+ )+ assert (keys[0] != keys[1]) == include_conversions+ assert keys[0] == keys[2]+@parameterized.expand([("warehouse_objects", {"warehouse_table", "warehouse_view"}),diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 084b8b81098d..367732b44a74 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55564,6 +55564,11 @@ export namespace Schemas {version?: number | null;}+ export interface MarketingAnalyticsSearchConversionGoal {+ id: string;+ name: string;+ }+export type Platform = typeof Platform[keyof typeof Platform];@@ -55573,6 +55578,15 @@ export namespace Schemas {GoogleSearchConsole: 'GoogleSearchConsole',} as const;+ export interface MarketingAnalyticsSearchConversion {+ conversions?: number | null;+ costPerConversion?: number | null;+ id: string;+ name: string;+ previousConversions?: number | null;+ previousCostPerConversion?: number | null;+ }+export interface MarketingAnalyticsSearchMetrics {/** Fraction of Google Search ad impressions shown as the first ad. */absoluteTopImpressionRate?: number | null;@@ -55604,6 +55618,7 @@ export namespace Schemas {page?: string | null;platform: Platform;position?: number | null;+ posthogConversions?: MarketingAnalyticsSearchConversion[] | null;previous?: MarketingAnalyticsSearchMetrics | null;/** Fraction of Google Search ad impressions shown among the top ads. */topImpressionRate?: number | null;@@ -55616,6 +55631,9 @@ export namespace Schemas {hogql?: string | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ posthogAttributionMode?: AttributionMode | null;+ posthogConversionGoals?: MarketingAnalyticsSearchConversionGoal[] | null;+ posthogConversionsWarning?: string | null;/** Query status indicates whether next to the provided data, a query is still running. */query_status?: QueryStatus | null;/** The resolved previous/comparison period date range, when comparing against another period */@@ -55651,10 +55669,12 @@ export namespace Schemas {breakdown?: Breakdown1 | null;compareFilter?: CompareFilter | null;dateRange?: DateRange | null;+ includePostHogConversions?: boolean | null;keyword?: string | null;kind?: 'MarketingAnalyticsSearchQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ normalizePageUrls?: boolean | null;page?: string | null;response?: MarketingAnalyticsSearchQueryResponse | null;search?: string | null;@@ -90545,6 +90565,9 @@ export namespace Schemas {hogql?: string | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;+ posthogAttributionMode?: AttributionMode | null;+ posthogConversionGoals?: MarketingAnalyticsSearchConversionGoal[] | null;+ posthogConversionsWarning?: string | null;/** Query status indicates whether next to the provided data, a query is still running. */query_status?: QueryStatus | null;/** The resolved previous/comparison period date range, when comparing against another period */