: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(warehouse-sources): add Bing Ads keyword performance report (#79884)
posthog[bot]e46b1ca44a7d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.mdindex 3141811ce889..e42ffe0fc10a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md@@ -531,11 +531,11 @@ Nine hardcoded tables for what is fundamentally a schemaless CRM.### Bing Ads (Microsoft Advertising) — needs confirmation-Four tables: `campaigns` plus three performance reports.+Five tables: `campaigns` plus four performance reports.No ad group, ad, or keyword entity tables at all, which is unusual relative to our other ad sources.- [ ] `ad_groups` and `ads` as entity tables. Today the ad group and ad performance reports reference IDs with nothing to join to.-- [ ] `keywords` and `keyword_performance_report`.+- [x] `keyword_performance_report` — daily performance by keyword. Still missing the `keywords` entity table, so `keyword_id` has nothing to join to.- [ ] `search_query_performance_report` — search terms, one of the main reasons to export Bing data.- [ ] `accounts` — currency and timezone.- [ ] `geographic_performance_report`, `user_location_performance_report`.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/canonical_descriptions.pyindex 7c1f02faf737..8ccc6a6556b4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/canonical_descriptions.py@@ -95,4 +95,21 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"ad_type": "Type of the ad (e.g. TextAd, ResponsiveSearchAd, ProductAd).",},},+ "keyword_performance_report": {+ "description": "Daily performance metrics broken down by keyword, including quality score components.",+ "docs_url": "https://learn.microsoft.com/en-us/advertising/reporting-service/keywordperformancereportrequest",+ "columns": {+ **_REPORT_METRICS,+ "ad_group_id": "Identifier of the ad group the keyword belongs to.",+ "ad_group_name": "Name of the ad group the keyword belongs to.",+ "keyword": "The keyword text that triggered the ad.",+ "keyword_id": "Identifier of the keyword the row belongs to.",+ "keyword_status": "Keyword status (e.g. Active, Paused).",+ "bid_match_type": "Match type set on the keyword (e.g. Broad, Phrase, Exact).",+ "quality_score": "Microsoft's measure of how competitive the keyword is.",+ "expected_ctr": "Expected click-through rate component of quality score.",+ "ad_relevance": "Ad relevance component of quality score.",+ "landing_page_experience": "Landing page experience component of quality score.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/schemas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/schemas.pyindex 33ced38450cc..712817c85c4a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/schemas.py@@ -8,6 +8,7 @@ class BingAdsResource(str, Enum):CAMPAIGN_PERFORMANCE_REPORT = "campaign_performance_report"AD_GROUP_PERFORMANCE_REPORT = "ad_group_performance_report"AD_PERFORMANCE_REPORT = "ad_performance_report"+ KEYWORD_PERFORMANCE_REPORT = "keyword_performance_report"REPORT_CONFIG: dict[BingAdsResource, dict] = {@@ -32,6 +33,13 @@ REPORT_CONFIG: dict[BingAdsResource, dict] = {"scope_type": "AccountThroughAdGroupReportScope","report_name": "Ad Performance Report",},+ BingAdsResource.KEYWORD_PERFORMANCE_REPORT: {+ "report_type": "KeywordPerformanceReportRequest",+ "column_array_type": "ArrayOfKeywordPerformanceReportColumn",+ "column_field": "KeywordPerformanceReportColumn",+ "scope_type": "AccountThroughAdGroupReportScope",+ "report_name": "Keyword Performance Report",+ },}@@ -168,4 +176,46 @@ RESOURCE_SCHEMAS: dict[BingAdsResource, dict] = {"partition_size": 1,"filter_field_names": [("TimePeriod", IncrementalFieldType.Date)],},+ BingAdsResource.KEYWORD_PERFORMANCE_REPORT: {+ "resource_name": "keyword_performance_report",+ # KeywordId encodes the keyword text and its match type, so one keyword yields one row per+ # day. DeliveredMatchType is intentionally excluded from the columns below — requesting it+ # would split a keyword-day into one row per served match type and break this grain.+ "primary_key": ["KeywordId", "TimePeriod"],+ "field_names": [+ "AccountName",+ "AdGroupId",+ "AdGroupName",+ "AdRelevance",+ "Assists",+ "AverageCpc",+ "AverageCpm",+ "BidMatchType",+ "CampaignId",+ "CampaignName",+ "Clicks",+ "ConversionRate",+ "Conversions",+ "CostPerConversion",+ "Ctr",+ "CurrencyCode",+ "ExpectedCtr",+ "Impressions",+ "Keyword",+ "KeywordId",+ "KeywordStatus",+ "LandingPageExperience",+ "QualityScore",+ "ReturnOnAdSpend",+ "Revenue",+ "Spend",+ "TimePeriod",+ ],+ "partition_keys": ["TimePeriod"],+ "partition_mode": "datetime",+ "partition_format": "month",+ "is_stats": True,+ "partition_size": 1,+ "filter_field_names": [("TimePeriod", IncrementalFieldType.Date)],+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.pyindex 8c2f3dc6dc4b..9dd2f1b8b3b1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py@@ -138,6 +138,12 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], O"Bing Ads access token not found": "Bing Ads OAuth access token is missing. Please reconnect your Bing Ads integration.","Bing Ads refresh token not found": "Bing Ads OAuth refresh token is missing. Please reconnect your Bing Ads integration.","Bing Ads developer token not configured": None,+ # A report request that names a column not valid for its report type comes back as a coded+ # WebFault (InvalidReportColumn), surfaced by _wrap_with_fault_detail. This is deterministic —+ # retrying re-sends the same bad column list forever — and only a fix to a resource's+ # field_names in schemas.py can resolve it, so it's internal config (None message), not+ # customer-actionable.+ "InvalidReportColumn": None,# PostHog's Bing Ads OAuth application credentials aren't configured — an empty client_id makes# Microsoft reject the token request with AADSTS900144. Internal config, not customer-actionable."Bing Ads OAuth application credentials not configured": None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.pyindex 476e12be4415..f4879dd7cab0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py@@ -10,7 +10,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.bBING_ADS_REPORT_RETENTION,bing_ads_source,)-from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.schemas import BingAdsResource+from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.schemas import (+ REPORT_CONFIG,+ RESOURCE_SCHEMAS,+ BingAdsResource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.utils import (BingAdsResumeConfig,download_and_extract_report_csv,@@ -262,6 +266,58 @@ class TestBingAdsHelperFunctions:)+class TestKeywordPerformanceReport:+ """The keyword performance report rides the generic report path, so these guard the two+ ways it can be mis-wired without any live call catching it."""++ def test_keyword_report_wired_through_report_path(self):+ # get_data_by_resource routes a resource through the report path only if it's in REPORT_CONFIG;+ # adding the enum member but forgetting the config would raise "Unsupported resource" at sync time.+ assert BingAdsResource.KEYWORD_PERFORMANCE_REPORT in REPORT_CONFIG+ assert BingAdsResource.KEYWORD_PERFORMANCE_REPORT in RESOURCE_SCHEMAS++ def test_keyword_report_grain_is_keyword_per_day(self):+ # KeywordId + TimePeriod is the intended one-row-per-keyword-per-day grain. DeliveredMatchType+ # would split a keyword-day into one row per served match type; if it slips into the column list+ # the merge dedup on this primary key silently drops rows, so lock both facts down together.+ schema = RESOURCE_SCHEMAS[BingAdsResource.KEYWORD_PERFORMANCE_REPORT]+ assert schema["primary_key"] == ["KeywordId", "TimePeriod"]+ assert "DeliveredMatchType" not in schema["field_names"]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.bing_ads.fetch_data_in_yearly_chunks"+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.bing_ads.BingAdsClient")+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.bing_ads.integrations")+ def test_keyword_report_source_is_incremental_stats(self, mock_integrations, mock_client_class, mock_fetch_chunks):+ # The keyword report is a stats report: bing_ads_source must treat it as incremental (chunked over+ # TimePeriod) rather than the one-shot campaigns path, and expose the keyword-per-day primary key.+ mock_integrations.BING_ADS_DEVELOPER_TOKEN = "test_dev_token"+ mock_client_class.return_value = Mock()+ mock_fetch_chunks.return_value = iter([[{"KeywordId": "1", "TimePeriod": "2024-01-01"}]])++ result = bing_ads_source(+ account_id="12345",+ resource_name="keyword_performance_report",+ access_token="test_access_token",+ refresh_token="test_refresh_token",+ resumable_source_manager=_mock_resumable_manager(),+ should_use_incremental_field=True,+ incremental_field="TimePeriod",+ incremental_field_type=IncrementalFieldType.Date,+ db_incremental_field_last_value=None,+ )++ assert result.name == "keyword_performance_report"+ assert result.primary_keys == ["KeywordId", "TimePeriod"]+ assert result.partition_mode == "datetime"++ items = result.items()+ assert isinstance(items, Iterable)+ list(items)+ mock_fetch_chunks.assert_called_once()++class TestBingAdsSource:"""Test suite for main Bing Ads source function."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.pyindex ae8ec063c3eb..f8580a8c25d6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py@@ -306,6 +306,13 @@ class TestBingAdsSource:"Bing Ads OAuth application credentials not configured","Bing Ads OAuth application credentials not configured",),+ # A column not valid for a report type comes back as a coded WebFault; retrying re-sends the+ # same bad field list forever, so it must be non-retryable.+ (+ "InvalidReportColumn",+ "Failed to generate keyword_performance_report report: WebFault: Server raised fault: "+ "'Invalid client data...' (InvalidReportColumn: ...)",+ ),],)def test_get_non_retryable_errors_pattern_recognised(self, pattern, raised_message):