Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(marketing): restore google ads keyword placement reporting (#114619)

Javier Bahamondes8669774ec707
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.md
index f67d948625f3..a22c6a1375a7 100644
--- a/docs/internal/marketing-source-suggestions.md
+++ b/docs/internal/marketing-source-suggestions.md
@@ -16,12 +16,20 @@ These counts guide connection suggestions; they do not change report attribution
Spend and conversions require a synced ad platform source in the current search filters.
Google Search Console reports organic traffic metrics only.
The Traffic view always includes the Position column when Google Search Console, Google Ads, or Bing Ads is ready.
-The Position cell shows the organic average position for Google Search Console, or top and first-position impression percentages for Google Ads or Bing Ads.
+The Position cell shows the organic average position for Google Search Console, or top and first-position impression percentages for Google Ads keywords and Bing Ads.
Hover over each label or value, or focus it with the keyboard, for its definition.
-Google Ads percentages use Google Search impressions with placement data, weighted by impressions; Search partners are excluded.
+Google Ads keyword placement comes from the `keyword_placement_stats` table, selected by default for new connections.
+For existing connections, enable it in the Google Ads source settings and wait for its first successful sync to see Top and First percentages.
+These percentages use Google Search impressions, weighted by impressions, and exclude Search partners.
+The placement table does not include click-type segmentation, which Google Ads does not allow with these metrics.
+Clicks, spend, conversions, and total impressions continue to come from `keyword_stats`.
+When keyword traffic tables are ready but placement data is unavailable, a separate notice explains how to enable or restore `keyword_placement_stats`.
+Traffic remains visible while placement data is pending.
+If the placement table is missing or the user cannot access it, the report omits its placement data and shows an access notice.
+Google Ads landing page breakdowns show no placement percentages because Google Ads does not support these metrics for the landing page resource.
+Historical placement columns in `keyword_stats` and `landing_page_stats` are ignored.
Bing Ads percentages use Microsoft Advertising report values, weighted by impressions.
They do not identify second or third position, or the search results page.
-Existing Google Ads connections need to sync `keyword_stats` or `landing_page_stats` to import the new fields.
Bing Ads connections need to sync `keyword_performance_report` or `destination_url_performance_report`.
Older rows without placement data show no value.
When no paid source is ready, the disabled control directs users to check their source settings or filters.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 197e884a8216..e27442865db1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -12292,6 +12292,10 @@ snapshots:
hash: v1.k794b7964.335e317721a8c9048bb23873444f0e217a3a1c16c7f5df90a6e7e9b56eccc17e.MTtJBu_VnIKhamkJogojTo0n82UPnRL2ooBj1pmu9g4
scenes-app-marketing-analytics-search-performance--pagination--light:
hash: v1.k794b7964.0aadfd41174c836d09256ecb4b2b2b14262da464c649ad906911d014f4756f69.aJLdwc-ThHLyjpXcx_LBTqvitPN4bYvRNZ8Hv91zBsQ
+ scenes-app-marketing-analytics-search-performance--placement-unavailable--dark:
+ hash: v1.k794b7964.ac0cf62eb7903ae36235e10f7c4e57fc8e0ee211f859a56dda230be27bfcb372.eKKQR7_MYNn080QaTtvEloqmqRG3-PeQrOmBIJ8PL_g
+ scenes-app-marketing-analytics-search-performance--placement-unavailable--light:
+ hash: v1.k794b7964.7330e79c678922a08b9e7efb722a0353db7df0669e8f701fdf856f44042f7d7b.Vaaa8TSebVIautTnKqz5k-a8RyHh3i2YSUJuqPrDFFs
scenes-app-marketing-analytics-search-performance--position-metrics--dark:
hash: v1.k794b7964.3757126e384ddc22242bce51a71f1f2556530e576885ca5cbd315163d73a3465.GTDt8Kt1dD6av9gY0MiCCLOZU7eeqEpYLwNjzfFYXBY
scenes-app-marketing-analytics-search-performance--position-metrics--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 6039036d56fd..d249ca5f6652 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -13098,6 +13098,9 @@
"format": "date-time",
"type": "string"
},
+ "placementUnavailable": {
+ "type": "boolean"
+ },
"posthogAttributionMode": {
"anyOf": [
{
@@ -36711,6 +36714,9 @@
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
},
+ "placementUnavailable": {
+ "type": "boolean"
+ },
"posthogAttributionMode": {
"anyOf": [
{
@@ -36883,6 +36889,9 @@
"keywordTable": {
"type": "string"
},
+ "placementTable": {
+ "type": "string"
+ },
"queryPageTable": {
"type": "boolean"
},
@@ -45201,6 +45210,9 @@
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
},
+ "placementUnavailable": {
+ "type": "boolean"
+ },
"posthogAttributionMode": {
"anyOf": [
{
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index b6df024916cc..e9ae86194841 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -8264,6 +8264,7 @@ export interface MarketingAnalyticsSearchSource {
sourceType: 'GoogleAds' | 'BingAds' | 'GoogleSearchConsole'
statsTable: string
keywordTable?: string
+ placementTable?: string
queryPageTable?: boolean
}
@@ -8318,6 +8319,7 @@ export interface MarketingAnalyticsSearchRow extends MarketingAnalyticsSearchMet
}
export interface MarketingAnalyticsSearchQueryResponse extends AnalyticsQueryResponseBase {
+ placementUnavailable?: boolean
results: MarketingAnalyticsSearchRow[]
posthogConversionGoals?: MarketingAnalyticsSearchConversionGoal[] | null
posthogConversionsWarning?: string | null
diff --git a/posthog/schema.py b/posthog/schema.py
index 9c67dd67733c..4458d0647884 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2161,6 +2161,7 @@ class MarketingAnalyticsSearchSource(BaseModel):
extra="forbid",
)
keywordTable: str | None = None
+ placementTable: str | None = None
queryPageTable: bool | None = None
sourceType: SourceType
statsTable: str
@@ -14399,6 +14400,7 @@ class CachedMarketingAnalyticsSearchQueryResponse(BaseModel):
last_refresh: AwareDatetime
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
next_allowed_client_refresh: AwareDatetime
+ placementUnavailable: bool | None = None
posthogAttributionMode: AttributionMode | None = None
posthogConversionGoals: list[MarketingAnalyticsSearchConversionGoal] | None = None
posthogConversionsWarning: str | None = None
@@ -20360,6 +20362,7 @@ 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")
+ placementUnavailable: bool | None = None
posthogAttributionMode: AttributionMode | None = None
posthogConversionGoals: list[MarketingAnalyticsSearchConversionGoal] | None = None
posthogConversionsWarning: str | None = None
@@ -22269,6 +22272,7 @@ 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")
+ placementUnavailable: bool | None = None
posthogAttributionMode: AttributionMode | None = None
posthogConversionGoals: list[MarketingAnalyticsSearchConversionGoal] | None = None
posthogConversionsWarning: str | None = None
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.py
index 1cf0be2590ff..423bd6a70950 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
@@ -87,26 +87,46 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic
def _placement_fields(self, source: MarketingAnalyticsSearchSource) -> dict[str, ast.Expr]:
table = self.hogql_database.get_table(source.statsTable.split("."))
fields = (
- (
- ("top_rate", "metrics_top_impression_percentage"),
- ("absolute_top_rate", "metrics_absolute_top_impression_percentage"),
- )
- if source.sourceType == "GoogleAds"
- else (
- ("top_rate", "top_impression_rate_percent"),
- ("absolute_top_rate", "absolute_top_impression_rate_percent"),
- )
+ ("top_rate", "top_impression_rate_percent"),
+ ("absolute_top_rate", "absolute_top_impression_rate_percent"),
)
result: dict[str, ast.Expr] = {}
for name, field in fields:
value: ast.Expr = ast.Field(chain=["s", field]) if table.has_field(field) else ast.Constant(value=None)
result[name] = (
parse_expr("toFloatOrNull(replaceAll(toString({value}), '%', '')) / 100", placeholders={"value": value})
- if source.sourceType == "BingAds" and table.has_field(field)
+ if table.has_field(field)
else value
)
return result
+ @cached_property
+ def unavailable_placement_tables(self) -> set[str]:
+ if self.query.breakdown == "page":
+ return set()
+ return {
+ source.placementTable
+ for source in self.query.sources
+ if source.sourceType == "GoogleAds"
+ and source.placementTable
+ and (
+ self.hogql_database.is_table_access_denied(source.placementTable)
+ or not self.hogql_database.has_table(source.placementTable)
+ )
+ }
+
+ def _google_keywords(self, keyword_table: str) -> ast.SelectQuery | ast.SelectSetQuery:
+ return parse_select(
+ """
+ SELECT customer_id, campaign_id, ad_group_id, ad_group_criterion_criterion_id,
+ any(ad_group_criterion_keyword_text) AS keyword,
+ any(ad_group_criterion_keyword_match_type) AS match_type
+ FROM {keywords}
+ GROUP BY customer_id, campaign_id, ad_group_id, ad_group_criterion_criterion_id
+ """,
+ placeholders={"keywords": ast.Field(chain=[*keyword_table.split(".")])},
+ )
+
@property
def include_posthog_conversions(self) -> bool:
return bool(self.query.includePostHogConversions and self.query.breakdown == "page" and not self.query.keyword)
@@ -134,7 +154,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic
"date_from": ast.Constant(value=date_range.date_from()),
"date_to": ast.Constant(value=date_range.date_to()),
}
- if source.sourceType in ("GoogleAds", "BingAds"):
+ if source.sourceType == "BingAds":
placeholders.update(self._placement_fields(source))
if source.sourceType == "GoogleSearchConsole":
if (self.query.keyword is not None or self.query.page is not None) and not source.queryPageTable:
@@ -215,10 +235,8 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic
sum(toFloat(metrics_impressions)) AS impression_count,
sum(toFloat(metrics_cost_micros)) / 1000000 AS total_cost,
sum(toFloat(metrics_conversions)) AS conversion_count, 0 AS position_total,
- sumIf(toFloat({top_rate}) * toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH') AS top_impressions,
- sumIf(toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH' AND {top_rate} IS NOT NULL) AS top_eligible_impressions,
- sumIf(toFloat({absolute_top_rate}) * toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH') AS absolute_top_impressions,
- sumIf(toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH' AND {absolute_top_rate} IS NOT NULL) AS absolute_top_eligible_impressions
+ NULL AS top_impressions, 0 AS top_eligible_impressions,
+ NULL AS absolute_top_impressions, 0 AS absolute_top_eligible_impressions
FROM {stats} AS s
WHERE toDate(segments_date) >= toDate({date_from})
AND toDate(segments_date) <= toDate({date_to})
@@ -230,7 +248,7 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic
if source.sourceType == "GoogleAds":
if not source.keywordTable:
raise ValueError("Google Ads requires a synced keyword table")
- placeholders["keywords"] = ast.Field(chain=[*source.keywordTable.split(".")])
+ placeholders["keywords"] = self._google_keywords(source.keywordTable)
return parse_select(
"""
SELECT {period} AS period, nullIf(lower(trim(k.keyword)), '') AS keyword, NULL AS page, 'GoogleAds' AS platform,
@@ -240,18 +258,10 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic
sum(toFloat(s.metrics_impressions)) AS impression_count,
sum(toFloat(s.metrics_cost_micros)) / 1000000 AS total_cost,
sum(toFloat(s.metrics_conversions)) AS conversion_count, 0 AS position_total,
- sumIf(toFloat({top_rate}) * toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH') AS top_impressions,
- sumIf(toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH' AND {top_rate} IS NOT NULL) AS top_eligible_impressions,
- sumIf(toFloat({absolute_top_rate}) * toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH') AS absolute_top_impressions,
- sumIf(toFloat(s.metrics_impressions), s.segments_ad_network_type = 'SEARCH' AND {absolute_top_rate} IS NOT NULL) AS absolute_top_eligible_impressions
+ NULL AS top_impressions, 0 AS top_eligible_impressions,
+ NULL AS absolute_top_impressions, 0 AS absolute_top_eligible_impressions
FROM {stats} AS s
- LEFT JOIN (
- SELECT customer_id, campaign_id, ad_group_id, ad_group_criterion_criterion_id,
- any(ad_group_criterion_keyword_text) AS keyword,
- any(ad_group_criterion_keyword_match_type) AS match_type
- FROM {keywords}
- GROUP BY customer_id, campaign_id, ad_group_id, ad_group_criterion_criterion_id
- ) AS k ON s.customer_id = k.customer_id AND s.campaign_id = k.campaign_id
+ LEFT JOIN {keywords} AS k ON s.customer_id = k.customer_id AND s.campaign_id = k.campaign_id
AND s.ad_group_id = k.ad_group_id
AND s.ad_group_criterion_criterion_id = k.ad_group_criterion_criterion_id
WHERE toDate(s.segments_date) >= toDate({date_from})
@@ -278,12 +288,59 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic
placeholders=placeholders,
)
+ def _google_placement_query(
+ self, source: MarketingAnalyticsSearchSource, date_range: QueryDateRange, period: int
+ ) -> ast.SelectQuery | ast.SelectSetQuery:
+ if not source.placementTable or not source.keywordTable:
+ raise ValueError("Google Ads placement requires synced keyword and keyword placement tables")
+ # Name keywords from the keyword table, as traffic does, so a criterion it lacks does not split into two rows.
+ return parse_select(
+ """
+ SELECT {period} AS period,
+ nullIf(lower(trim(k.keyword)), '') AS keyword,
+ NULL AS page, 'GoogleAds' AS platform,
+ nullIf(lower(k.match_type), '') AS matchType,
+ nullIf(upper(p.customer_currency_code), '') AS currency,
+ 0 AS click_count, 0 AS impression_count, 0 AS total_cost,
+ 0 AS conversion_count, 0 AS position_total,
+ sum(toFloat(p.metrics_top_impression_percentage) * toFloat(p.metrics_impressions)) AS top_impressions,
+ sumIf(toFloat(p.metrics_impressions), p.metrics_top_impression_percentage IS NOT NULL) AS top_eligible_impressions,
+ sum(toFloat(p.metrics_absolute_top_impression_percentage) * toFloat(p.metrics_impressions)) AS absolute_top_impressions,
+ sumIf(toFloat(p.metrics_impressions), p.metrics_absolute_top_impression_percentage IS NOT NULL) AS absolute_top_eligible_impressions
+ FROM {placement} AS p
+ LEFT JOIN {keywords} AS k ON p.customer_id = k.customer_id AND p.campaign_id = k.campaign_id
+ AND p.ad_group_id = k.ad_group_id
+ AND p.ad_group_criterion_criterion_id = k.ad_group_criterion_criterion_id
+ WHERE toDate(p.segments_date) >= toDate({date_from})
+ AND toDate(p.segments_date) <= toDate({date_to})
+ AND p.segments_ad_network_type = 'SEARCH'
+ GROUP BY keyword, matchType, currency
+ """,
+ placeholders={
+ "period": ast.Constant(value=period),
+ "placement": ast.Field(chain=[*source.placementTable.split(".")]),
+ "keywords": self._google_keywords(source.keywordTable),
+ "date_from": ast.Constant(value=date_range.date_from()),
+ "date_to": ast.Constant(value=date_range.date_to()),
+ },
+ )
+
def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
source_queries = [self._source_query(source, self.query_date_range, 0) for source in self.query.sources]
if self.comparison_date_range:
source_queries.extend(
self._source_query(source, self.comparison_date_range, 1) for source in self.query.sources
)
+ if self.query.breakdown != "page":
+ for source in self.query.sources:
+ if (
+ source.sourceType == "GoogleAds"
+ and source.placementTable
+ and source.placementTable not in self.unavailable_placement_tables
+ ):
+ source_queries.append(self._google_placement_query(source, self.query_date_range, 0))
+ if self.comparison_date_range:
+ source_queries.append(self._google_placement_query(source, self.comparison_date_range, 1))
sources = ast.SelectSetQuery.create_from_queries(source_queries, "UNION ALL")
return parse_select(
"""
@@ -457,7 +514,9 @@ class MarketingAnalyticsSearchQueryRunner(AnalyticsQueryRunner[MarketingAnalytic
previous=MarketingAnalyticsSearchMetrics(**previous) if self.comparison_date_range else None,
)
)
- response = MarketingAnalyticsSearchQueryResponse(results=rows)
+ response = MarketingAnalyticsSearchQueryResponse(
+ results=rows, placementUnavailable=bool(self.unavailable_placement_tables)
+ )
if self.include_posthog_conversions:
self._add_posthog_conversions(response, ambiguous_keys)
return response
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.py
index 15cec6166265..f09cff499e27 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
@@ -34,6 +34,7 @@ from posthog.models.utils import uuid7
from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
from .marketing_search_query_runner import MarketingAnalyticsSearchQueryRunner
@@ -50,7 +51,9 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
self.addCleanup(cleanup)
return table.name
- def test_combines_platforms_without_multiplying_metrics_or_mixing_currencies(self) -> None:
+ @parameterized.expand([("absent",), ("ready",), ("denied",), ("missing",)])
+ def test_combines_platforms_without_multiplying_metrics_or_mixing_currencies(self, placement_status: str) -> None:
+ with_placement = placement_status == "ready"
keywords = self._table(
"search_keywords",
{
@@ -90,8 +93,62 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
"1,10,100,7,USD,900,9000,90000000,9,2023-01-10,CONTENT,0.99,0.99\n"
"1,10,100,7,USD,20,200,30000000,1.25,2022-12-15,SEARCH,0.6,0.2\n"
"1,10,100,7,USD,8,80,16000000,2,2022-01-10,SEARCH,0.6,0.2\n"
- "2,20,200,7,USD,3,100,6000000,1,2023-01-10,SEARCH,0.6,0.2\n",
+ "2,20,200,7,USD,3,100,6000000,1,2023-01-10,SEARCH,0.6,0.2\n"
+ "1,10,100,8,USD,7,70,14000000,1,2023-01-10,SEARCH,0.5,0.5\n",
)
+ placement = None
+ if placement_status in {"ready", "denied"}:
+ placement = self._table(
+ "search_google_placement",
+ {
+ "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_currency_code": "String",
+ "segments_date": "Date",
+ "segments_ad_network_type": "String",
+ "metrics_impressions": "Float64",
+ "metrics_top_impression_percentage": "Float64",
+ "metrics_absolute_top_impression_percentage": "Float64",
+ },
+ "customer_id,campaign_id,ad_group_id,ad_group_criterion_criterion_id,ad_group_criterion_keyword_text,ad_group_criterion_keyword_match_type,customer_currency_code,segments_date,segments_ad_network_type,metrics_impressions,metrics_top_impression_percentage,metrics_absolute_top_impression_percentage\n"
+ "1,10,100,7,Hedgehog,EXACT,USD,2023-01-10,SEARCH,40,0.8,0.4\n"
+ "1,10,100,7,Hedgehog,EXACT,USD,2023-01-11,SEARCH,60,0.3,0.1\n"
+ "1,10,100,7,Hedgehog,EXACT,USD,2023-01-11,SEARCH_PARTNERS,900,0.99,0.99\n"
+ "1,10,100,7,Hedgehog,EXACT,EUR,2023-01-10,SEARCH,100,0.6,0.2\n"
+ "1,10,100,7,Hedgehog,EXACT,USD,2023-01-10,CONTENT,9000,0.99,0.99\n"
+ "1,10,100,7,Hedgehog,EXACT,USD,2022-12-15,SEARCH,200,0.6,0.2\n"
+ "1,10,100,7,Hedgehog,EXACT,USD,2022-01-10,SEARCH,80,0.6,0.2\n"
+ "2,20,200,7,Other keyword,PHRASE,USD,2023-01-10,SEARCH,100,0.6,0.2\n"
+ "1,10,100,8,Unsynced keyword,BROAD,USD,2023-01-10,SEARCH,70,0.5,0.5\n",
+ )
+ if placement_status == "denied":
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ placement_table = DataWarehouseTable.objects.get(team=self.team, name=placement)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_table",
+ resource_id=str(placement_table.id),
+ access_level="none",
+ organization_member=self.organization_membership,
+ )
+ flag = patch(
+ "posthog.hogql.database.database.feature_enabled_or_false",
+ side_effect=lambda key, *args, **kwargs: key == "hogql-warehouse-access-control",
+ )
+ flag.start()
+ self.addCleanup(flag.stop)
+ elif placement_status == "missing":
+ placement = "missing_keyword_placement_stats"
bing_stats = self._table(
"search_bing_stats",
{
@@ -116,12 +173,19 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
query = MarketingAnalyticsSearchQuery(
dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"),
sources=[
- MarketingAnalyticsSearchSource(sourceType="GoogleAds", statsTable=google_stats, keywordTable=keywords),
+ MarketingAnalyticsSearchSource(
+ sourceType="GoogleAds", statsTable=google_stats, keywordTable=keywords, placementTable=placement
+ ),
MarketingAnalyticsSearchSource(sourceType="BingAds", statsTable=bing_stats),
],
)
- rows = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
- assert len(rows) == 6
+ response = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate()
+ assert response.placementUnavailable == (placement_status in {"denied", "missing"})
+ rows = response.results
+ assert len(rows) == 7
+ unsynced = next(row for row in rows if row.platform == "GoogleAds" and row.keyword is None)
+ assert unsynced.clicks == 7 and unsynced.impressions == 70
+ assert unsynced.topImpressionRate == (pytest.approx(0.5) if with_placement else None)
google = next(
row for row in rows if row.platform == "GoogleAds" and row.currency == "USD" and row.keyword == "hedgehog"
)
@@ -129,8 +193,8 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
"keyword": "hedgehog",
"page": None,
"position": None,
- "topImpressionRate": 0.5,
- "absoluteTopImpressionRate": pytest.approx(0.22),
+ "topImpressionRate": pytest.approx(0.5) if with_placement else None,
+ "absoluteTopImpressionRate": pytest.approx(0.22) if with_placement else None,
"platform": "GoogleAds",
"matchType": "exact",
"currency": "USD",
@@ -163,7 +227,7 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
query.search = None
query.compareFilter = CompareFilter(compare=True)
compared = MarketingAnalyticsSearchQueryRunner(query=query, team=self.team, user=self.user).calculate().results
- assert len(compared) == 7
+ assert len(compared) == 8
google_compared = next(
row
for row in compared
@@ -180,8 +244,8 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
"cpc": 1.5,
"cpa": 24,
"position": None,
- "topImpressionRate": 0.6,
- "absoluteTopImpressionRate": 0.2,
+ "topImpressionRate": pytest.approx(0.6) if with_placement else None,
+ "absoluteTopImpressionRate": pytest.approx(0.2) if with_placement else None,
}
previous_only = next(row for row in compared if row.keyword == "previous only")
assert previous_only.clicks == 0
@@ -303,8 +367,8 @@ class TestMarketingAnalyticsSearchQueryRunner(ClickhouseTestMixin, BaseTest):
assert usd.page == "https://example.com/a" and usd.keyword is None
assert usd.clicks == 15 and usd.impressions == 150
assert usd.cost == 30 and usd.conversions == 2.5 and usd.position is None
- assert usd.topImpressionRate == (0.8 if placement_available else None)
- assert usd.absoluteTopImpressionRate == (0.4 if placement_available else None)
+ assert usd.topImpressionRate == (0.8 if platform == "BingAds" and placement_available else None)
+ assert usd.absoluteTopImpressionRate == (0.4 if platform == "BingAds" and placement_available else None)
@parameterized.expand([(False,), (True,)])
def test_organic_positions_are_weighted_and_details_keep_query_page_filters(self, normalize_urls: bool) -> None:
diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
index 72a9aba4695d..8c4dba96cd00 100644
--- a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
@@ -28,17 +28,22 @@ const SOURCES = [
description: 'Example Google Ads',
prefix: 'example',
status: 'Completed',
- schemas: ['campaign', 'campaign_overview_stats', 'keyword', 'keyword_stats', 'landing_page_stats'].map(
- (name) => ({
- id: `example-${name}`,
- name,
- should_sync: true,
- sync_frequency: '24hour',
- last_synced_at: '2025-02-14T12:00:00Z',
- status: 'Completed',
- table: { name: `example_${name}`, hogql_name: `example.${name}` },
- })
- ),
+ schemas: [
+ 'campaign',
+ 'campaign_overview_stats',
+ 'keyword',
+ 'keyword_stats',
+ 'keyword_placement_stats',
+ 'landing_page_stats',
+ ].map((name) => ({
+ id: `example-${name}`,
+ name,
+ should_sync: true,
+ sync_frequency: '24hour',
+ last_synced_at: '2025-02-14T12:00:00Z',
+ status: 'Completed',
+ table: { name: `example_${name}`, hogql_name: `example.${name}` },
+ })),
},
{
id: 'example-bing',
@@ -513,6 +518,29 @@ export const OnlyGoogleAds: Story = {
},
},
}
+export const PlacementUnavailable: Story = {
+ parameters: {
+ msw: {
+ mocks: {
+ post: {
+ '/api/environments/:team_id/query/MarketingAnalyticsSearchQuery/': {
+ results: ROWS.map((row) =>
+ row.platform === 'GoogleAds'
+ ? { ...row, topImpressionRate: null, absoluteTopImpressionRate: null }
+ : row
+ ),
+ placementUnavailable: true,
+ },
+ },
+ },
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await expect(canvas.findByText(/Some Google Ads position data is unavailable/)).resolves.toBeVisible()
+ expect((await canvas.findAllByRole('button', { name: 'product analytics' })).length).toBeGreaterThan(0)
+ },
+}
export const Empty: Story = {
parameters: {
msw: {
diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx
index 7f31c30fa6c9..132ef9837ad9 100644
--- a/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx
+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTable.tsx
@@ -3,7 +3,7 @@ import './SearchPerformanceTable.scss'
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
-import { LemonButton, LemonTable } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonTable } from '@posthog/lemon-ui'
import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'
@@ -45,7 +45,8 @@ export function SearchPerformanceTable({
})
const { response, responseLoading, responseError, responseErrorObject, queryId } = useValues(logic)
const { loadData } = useActions(logic)
- const rows = (response as MarketingAnalyticsSearchQueryResponse | undefined)?.results ?? []
+ const searchResponse = response as MarketingAnalyticsSearchQueryResponse | undefined
+ const rows = searchResponse?.results ?? []
const hasPaidSources = query.sources.some((source) => source.sourceType !== 'GoogleSearchConsole')
const hasPositionSources = query.sources.some((source) =>
['GoogleSearchConsole', 'GoogleAds', 'BingAds'].includes(source.sourceType)
@@ -80,6 +81,12 @@ export function SearchPerformanceTable({
<Reload />
<ElapsedTime />
</div>
+ {!responseLoading && searchResponse?.placementUnavailable && (
+ <LemonBanner type="info">
+ Some Google Ads position data is unavailable. Check your access to keyword_placement_stats or ask a
+ project admin for help. Traffic data is available.
+ </LemonBanner>
+ )}
<LemonTable<MarketingAnalyticsSearchRow>
size="small"
tableLayout="fixed"
diff --git a/products/marketing_analytics/frontend/search/searchPerformance.test.ts b/products/marketing_analytics/frontend/search/searchPerformance.test.ts
index 45b04e42c120..13aaece68244 100644
--- a/products/marketing_analytics/frontend/search/searchPerformance.test.ts
+++ b/products/marketing_analytics/frontend/search/searchPerformance.test.ts
@@ -22,6 +22,21 @@ describe('search performance sources', () => {
[schema('keyword'), schema('keyword_stats')],
{ sourceType: 'GoogleAds', keywordTable: 'example.keyword', statsTable: 'example.keyword_stats' },
],
+ [
+ 'GoogleAds',
+ [schema('keyword'), schema('keyword_stats'), schema('keyword_placement_stats')],
+ {
+ sourceType: 'GoogleAds',
+ keywordTable: 'example.keyword',
+ statsTable: 'example.keyword_stats',
+ placementTable: 'example.keyword_placement_stats',
+ },
+ ],
+ [
+ 'GoogleAds',
+ [schema('keyword'), schema('keyword_stats'), schema('keyword_placement_stats', false)],
+ { sourceType: 'GoogleAds', keywordTable: 'example.keyword', statsTable: 'example.keyword_stats' },
+ ],
['GoogleAds', [schema('keyword'), schema('keyword_stats', false)], null],
['GoogleAds', [schema('keyword', true, false), schema('keyword_stats')], null],
['GoogleAds', [schema('search_term_stats')], null],
@@ -105,6 +120,35 @@ describe('search performance sources', () => {
expect(searchPerformanceSourceNotice(source)).toContain(message)
})
+ it.each([
+ ['disabled', { should_sync: false }, 'Enable keyword_placement_stats'],
+ ['pending', { last_synced_at: undefined }, 'first sync of keyword_placement_stats'],
+ ['failed', { status: ExternalDataSchemaStatus.Failed }, 'failed'],
+ ['paused', { status: ExternalDataSchemaStatus.Paused }, 'Resume it'],
+ ['billing', { status: 'Billing limits' as ExternalDataSchemaStatus }, 'billing limit'],
+ ['stale', { last_synced_at: dayjs('2025-02-10T12:00:00Z') }, 'out of date'],
+ ])('keeps traffic available when placement is %s', (_, overrides, message) => {
+ const source = {
+ source_type: 'GoogleAds',
+ schemas: [
+ schema('keyword'),
+ schema('keyword_stats'),
+ { ...schema('keyword_placement_stats'), ...overrides },
+ schema('landing_page_stats'),
+ ],
+ } as ExternalDataSource
+ expect(searchPerformanceSource(source)).toEqual({
+ sourceType: 'GoogleAds',
+ keywordTable: 'example.keyword',
+ statsTable: 'example.keyword_stats',
+ })
+ expect(searchPerformanceSourceNotice(source)).toContain(message)
+ expect(searchPerformanceSourceNotice(source)).toContain('Traffic data is available.')
+ expect(searchPerformanceSourceNotice(source, 'page')).toBeNull()
+ source.schemas[2] = schema('keyword_placement_stats')
+ expect(searchPerformanceSourceNotice(source)).toBeNull()
+ })
+
it.each(['keyword', 'page'] as const)('uses fresh query-page data instead of a stale %s aggregate', (breakdown) => {
const source = {
source_type: 'GoogleSearchConsole',
diff --git a/products/marketing_analytics/frontend/search/searchPerformance.ts b/products/marketing_analytics/frontend/search/searchPerformance.ts
index fc4a7f2f9cba..44ea93c87ff3 100644
--- a/products/marketing_analytics/frontend/search/searchPerformance.ts
+++ b/products/marketing_analytics/frontend/search/searchPerformance.ts
@@ -86,7 +86,14 @@ export function searchPerformanceSource(
? {
sourceType: 'GoogleAds',
statsTable: tables[tables.length - 1]!,
- ...(breakdown === 'keyword' ? { keywordTable: tables[0] } : {}),
+ ...(breakdown === 'keyword'
+ ? {
+ keywordTable: tables[0],
+ ...(table('keyword_placement_stats')
+ ? { placementTable: table('keyword_placement_stats') }
+ : {}),
+ }
+ : {}),
}
: { sourceType: 'BingAds', statsTable: tables[0]! }
}
@@ -99,6 +106,21 @@ export function searchPerformanceSourceNotice(
const querySource = searchPerformanceSource(source, breakdown, detail)
const fallback = querySource?.queryPageTable && !detail
if (querySource && !fallback) {
+ if (source.source_type === 'GoogleAds' && breakdown === 'keyword' && !querySource.placementTable) {
+ const status = searchTableStatus(source.schemas.find((schema) => schema.name === 'keyword_placement_stats'))
+ const message = {
+ disabled: 'Enable keyword_placement_stats in the source settings to see Top and First percentages.',
+ pending: 'Position data will appear after the first sync of keyword_placement_stats finishes.',
+ failed: 'The sync of keyword_placement_stats failed. Retry it in the source settings to see position data.',
+ billing:
+ 'A billing limit is blocking keyword_placement_stats. Check the source settings to restore position data.',
+ paused: 'Syncing has stopped for keyword_placement_stats. Resume it in the source settings to restore position data.',
+ stale: 'Position data in keyword_placement_stats is out of date. Sync it again in the source settings.',
+ ready: '',
+ }[status]
+ const label = source.description || SEARCH_PLATFORM_LABELS.GoogleAds
+ return `${label}: ${message} Traffic data is available.`
+ }
return null
}
const names = searchTableNames(source, breakdown, detail)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py
index e5513556f1f3..69d3e6c2945e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/canonical_descriptions.py
@@ -222,6 +222,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"campaign_criterion_user_list_user_list": "Resource name of the user list, when the criterion is a user list.",
},
},
+ "keyword_placement_stats": {
+ "description": "Daily keyword impression placement without click-type segmentation.",
+ "columns": {
+ **_IDS,
+ "ad_group_criterion_criterion_id": "The keyword criterion ID.",
+ "ad_group_criterion_keyword_text": "The keyword text.",
+ "ad_group_criterion_keyword_match_type": "The keyword match type.",
+ "segments_date": "The date the impressions are reported for.",
+ "segments_ad_network_type": "The ad network where the impressions were shown.",
+ "metrics_impressions": "Number of times the ad was shown.",
+ "metrics_top_impression_percentage": "Fraction of impressions shown among the top ads.",
+ "metrics_absolute_top_impression_percentage": "Fraction of impressions shown as the first ad.",
+ },
+ },
"keyword_stats": {
"description": "Daily performance metrics for keywords (keyword_view), segmented by date, device, and network.",
"docs_url": "https://developers.google.com/google-ads/api/fields/v17/keyword_view",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py
index dfe0699e3a7d..49ea62053cdc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/schemas.py
@@ -542,6 +542,33 @@ RESOURCE_SCHEMAS: dict[str, dict[str, Any]] = {
"campaign.percent_cpc.enhanced_cpc_enabled",
],
},
+ "keyword_placement_stats": {
+ "resource_name": "keyword_view",
+ "should_sync_default": True,
+ "filter_field_names": [("segments.date", IncrementalFieldType.Date)],
+ "primary_key": [
+ "customer.id",
+ "campaign.id",
+ "ad_group.id",
+ "ad_group_criterion.criterion_id",
+ "segments.date",
+ "segments.ad_network_type",
+ ],
+ "field_names": [
+ "customer.id",
+ "customer.currency_code",
+ "campaign.id",
+ "ad_group.id",
+ "ad_group_criterion.criterion_id",
+ "ad_group_criterion.keyword.text",
+ "ad_group_criterion.keyword.match_type",
+ "segments.date",
+ "segments.ad_network_type",
+ "metrics.impressions",
+ "metrics.top_impression_percentage",
+ "metrics.absolute_top_impression_percentage",
+ ],
+ },
"keyword_stats": {
"resource_name": "keyword_view",
"filter_field_names": [("segments.date", IncrementalFieldType.Date)],
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 88a9e78f2ff5..709360a76fad 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55903,6 +55903,7 @@ export namespace Schemas {
hogql?: string | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
+ placementUnavailable?: boolean | null;
posthogAttributionMode?: AttributionMode | null;
posthogConversionGoals?: MarketingAnalyticsSearchConversionGoal[] | null;
posthogConversionsWarning?: string | null;
@@ -55932,6 +55933,7 @@ export namespace Schemas {
export interface MarketingAnalyticsSearchSource {
keywordTable?: string | null;
+ placementTable?: string | null;
queryPageTable?: boolean | null;
sourceType: SourceType;
statsTable: string;
@@ -91079,6 +91081,7 @@ export namespace Schemas {
hogql?: string | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
+ placementUnavailable?: boolean | null;
posthogAttributionMode?: AttributionMode | null;
posthogConversionGoals?: MarketingAnalyticsSearchConversionGoal[] | null;
posthogConversionsWarning?: string | null;