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(data-warehouse): cap bing ads report lookback to bing's retention (#65668)

Javier Bahamondesa2a32b9e3d5d
diff --git a/posthog/temporal/data_imports/sources/bing_ads/bing_ads.py b/posthog/temporal/data_imports/sources/bing_ads/bing_ads.py
index 987bc1b861dd..fa6f28977cd4 100644
--- a/posthog/temporal/data_imports/sources/bing_ads/bing_ads.py
+++ b/posthog/temporal/data_imports/sources/bing_ads/bing_ads.py
@@ -4,6 +4,7 @@ import collections.abc
from dataclasses import dataclass
import structlog
+from dateutil.relativedelta import relativedelta
from posthog.settings import integrations
from posthog.temporal.data_imports.naming_convention import NamingConvention
@@ -19,6 +20,11 @@ from .utils import BingAdsResumeConfig, fetch_data_in_yearly_chunks
logger = structlog.get_logger()
+# Microsoft Advertising retains daily-aggregated performance report data for 36 months. Requesting an
+# end date older than that is rejected with InvalidCustomDateRangeEnd, so don't look back past it —
+# older data simply doesn't exist to fetch.
+BING_ADS_REPORT_RETENTION = relativedelta(months=36)
+
@dataclass
class BingAdsSchema:
@@ -116,7 +122,7 @@ def bing_ads_source(
is_first_sync = db_incremental_field_last_value is None
if is_first_sync:
- start_date = today - dt.timedelta(days=365 * 5)
+ start_date = today - BING_ADS_REPORT_RETENTION
else:
last_value = db_incremental_field_last_value
@@ -138,7 +144,7 @@ def bing_ads_source(
resumable_source_manager=resumable_source_manager,
)
else:
- start_date = today - dt.timedelta(days=365 * 5)
+ start_date = today - BING_ADS_REPORT_RETENTION
yield from fetch_data_in_yearly_chunks(
client=client,
resource=resource,
diff --git a/posthog/temporal/data_imports/sources/bing_ads/client.py b/posthog/temporal/data_imports/sources/bing_ads/client.py
index 4d6d297478c8..2cb6eaa1a766 100644
--- a/posthog/temporal/data_imports/sources/bing_ads/client.py
+++ b/posthog/temporal/data_imports/sources/bing_ads/client.py
@@ -60,6 +60,27 @@ def extract_webfault_detail(fault: Any) -> str:
return "; ".join(parts)
+def _wrap_with_fault_detail(e: Exception, context: str) -> ValueError:
+ """Wrap a bingads SDK error so the SOAP fault detail the generic faultstring hides reaches
+ both the logs and the retry classifier. Every Bing Ads SOAP call should funnel its errors
+ through here — otherwise the real, stable code (``InvalidReportColumn``, ``InvalidCredentials``,
+ etc.) is lost behind the opaque "Invalid client data..." umbrella message.
+
+ Preserves the underlying exception's type and message — plus any SOAP fault detail — so the
+ retry framework can selectively recognise auth/config failures as non-retryable while transient
+ SDK errors (network, Bing outage, rate limits) keep their original signature and stay retryable.
+ """
+ fault_detail = extract_webfault_detail(e.fault) if isinstance(e, WebFault) else ""
+ logger.warning(
+ context,
+ error=str(e),
+ error_type=type(e).__name__,
+ fault_detail=fault_detail,
+ )
+ detail_suffix = f" ({fault_detail})" if fault_detail else ""
+ return ValueError(f"{context}: {type(e).__name__}: {e}{detail_suffix}")
+
+
class BingAdsClient:
def __init__(self, access_token: str, refresh_token: str, developer_token: str):
self.developer_token = developer_token
@@ -101,21 +122,7 @@ class BingAdsClient:
user = service_client.GetUser(UserId=None).User
self._customer_id = user.CustomerId
except Exception as e:
- # For SOAP faults the str(e) is a generic umbrella message ("Invalid client data...");
- # the actionable error code lives in the fault detail, so surface it explicitly.
- fault_detail = extract_webfault_detail(e.fault) if isinstance(e, WebFault) else ""
- logger.warning(
- "Failed to fetch customer ID",
- error=str(e),
- error_type=type(e).__name__,
- fault_detail=fault_detail,
- )
- # Preserve the underlying exception's type and message — plus any SOAP fault detail —
- # so the retry framework can selectively recognise auth-related failures as
- # non-retryable while transient SDK errors (network, Bing outage, rate limits) keep
- # their original signature and remain retryable.
- detail_suffix = f" ({fault_detail})" if fault_detail else ""
- raise ValueError(f"Failed to fetch customer ID: {type(e).__name__}: {e}{detail_suffix}") from e
+ raise _wrap_with_fault_detail(e, "Failed to fetch customer ID") from e
return self._customer_id
@@ -167,29 +174,32 @@ class BingAdsClient:
self.authorization_data.account_id = account_id
self.authorization_data.customer_id = customer_id
- reporting_service_manager = reporting.ReportingServiceManager(
- authorization_data=self.authorization_data,
- poll_interval_in_milliseconds=REPORT_POLL_INTERVAL_MS,
- environment=ENVIRONMENT,
- )
+ try:
+ reporting_service_manager = reporting.ReportingServiceManager(
+ authorization_data=self.authorization_data,
+ poll_interval_in_milliseconds=REPORT_POLL_INTERVAL_MS,
+ environment=ENVIRONMENT,
+ )
- # Build report request using SDK's factory pattern
- report_request = build_report_request(
- service_factory=reporting_service_manager._service_client.factory,
- report_config=report_config,
- field_names=schema["field_names"],
- account_id=account_id,
- start_date=start_date,
- end_date=end_date,
- )
+ # Build report request using SDK's factory pattern
+ report_request = build_report_request(
+ service_factory=reporting_service_manager._service_client.factory,
+ report_config=report_config,
+ field_names=schema["field_names"],
+ account_id=account_id,
+ start_date=start_date,
+ end_date=end_date,
+ )
- # Download and extract CSV from ZIP
- csv_data = download_and_extract_report_csv(
- reporting_service_manager=reporting_service_manager,
- report_request=report_request,
- report_type=report_config["report_type"],
- account_id=account_id,
- )
+ # Download and extract CSV from ZIP
+ csv_data = download_and_extract_report_csv(
+ reporting_service_manager=reporting_service_manager,
+ report_request=report_request,
+ report_type=report_config["report_type"],
+ account_id=account_id,
+ )
+ except Exception as e:
+ raise _wrap_with_fault_detail(e, f"Failed to generate {resource.value} report") from e
return parse_csv_to_dicts(csv_data)
diff --git a/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py b/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py
index d2a017da4cd5..6acb0fe79a13 100644
--- a/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py
+++ b/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py
@@ -6,10 +6,11 @@ from unittest.mock import MagicMock, Mock, patch
from parameterized import parameterized
-from posthog.temporal.data_imports.sources.bing_ads.bing_ads import bing_ads_source
+from posthog.temporal.data_imports.sources.bing_ads.bing_ads import BING_ADS_REPORT_RETENTION, bing_ads_source
from posthog.temporal.data_imports.sources.bing_ads.schemas import BingAdsResource
from posthog.temporal.data_imports.sources.bing_ads.utils import (
BingAdsResumeConfig,
+ download_and_extract_report_csv,
fetch_data_in_yearly_chunks,
parse_csv_to_dicts,
)
@@ -179,6 +180,55 @@ class TestBingAdsHelperFunctions:
BingAdsResumeConfig(next_start_date="2024-01-02", end_date=end_date.isoformat())
)
+ def test_fetch_data_in_yearly_chunks_skips_out_of_retention_chunk(self):
+ # A chunk rejected with InvalidCustomDateRangeEnd (older than Bing's 36-month retention) is
+ # skipped and its checkpoint advanced, so the sync keeps the in-retention chunks instead of
+ # aborting. Any other error stays fatal — see test_fetch_data_in_yearly_chunks_failure_fails_sync.
+ mock_client = Mock()
+ mock_client.get_data_by_resource.side_effect = [
+ Exception(
+ "Failed to generate campaign_performance_report report: WebFault: Server raised fault: "
+ "'Invalid client data...' (InvalidCustomDateRangeEnd: The specified report time contains "
+ "an invalid custom date range end.)"
+ ),
+ iter([[{"year": "2024"}]]),
+ iter([[{"year": "2025"}]]),
+ ]
+
+ start_date = dt.date(2023, 1, 1)
+ end_date = dt.date(2025, 6, 30)
+
+ manager = _mock_resumable_manager()
+ result = list(
+ fetch_data_in_yearly_chunks(
+ client=mock_client,
+ resource=BingAdsResource.CAMPAIGN_PERFORMANCE_REPORT,
+ account_id=12345,
+ start_date=start_date,
+ end_date=end_date,
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert result == [[{"year": "2024"}], [{"year": "2025"}]]
+ # The skipped chunk still advances the checkpoint, so all three chunks are accounted for
+ assert manager.save_state.call_count == 3
+
+ def test_download_and_extract_report_csv_no_file_returns_empty(self):
+ # Bing returns no file (download_file -> None) when a report has zero rows for the range;
+ # treat it as an empty report instead of crashing on Path(None).
+ manager = Mock()
+ manager.download_file.return_value = None
+
+ result = download_and_extract_report_csv(
+ reporting_service_manager=manager,
+ report_request=Mock(),
+ report_type="CampaignPerformanceReportRequest",
+ account_id=12345,
+ )
+
+ assert result == ""
+
def test_fetch_data_in_yearly_chunks_resumes_from_saved_state(self):
"""When resume state exists, the loop starts at the saved chunk boundary and does not re-fetch earlier chunks."""
mock_client = Mock()
@@ -327,6 +377,35 @@ class TestBingAdsSource:
assert call_args.kwargs["start_date"] <= dt.date.today()
assert call_args.kwargs["resumable_source_manager"] is manager
+ @patch("posthog.temporal.data_imports.sources.bing_ads.bing_ads.fetch_data_in_yearly_chunks")
+ @patch("posthog.temporal.data_imports.sources.bing_ads.bing_ads.BingAdsClient")
+ @patch("posthog.temporal.data_imports.sources.bing_ads.bing_ads.integrations")
+ def test_bing_ads_source_first_sync_caps_lookback_to_retention(
+ self, mock_integrations, mock_client_class, mock_fetch_chunks
+ ):
+ # On the first sync (no prior incremental value) the lookback is capped to Bing's 36-month
+ # retention window rather than reaching years back for data Bing no longer retains.
+ mock_integrations.BING_ADS_DEVELOPER_TOKEN = "test_dev_token"
+ mock_client_class.return_value = Mock()
+ mock_fetch_chunks.return_value = iter([[{"CampaignId": "123"}]])
+
+ result = bing_ads_source(
+ account_id=self.account_id,
+ resource_name="campaign_performance_report",
+ access_token=self.access_token,
+ refresh_token=self.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,
+ )
+ items = result.items()
+ assert isinstance(items, Iterable)
+ list(items)
+
+ assert mock_fetch_chunks.call_args.kwargs["start_date"] == dt.date.today() - BING_ADS_REPORT_RETENTION
+
@patch("posthog.temporal.data_imports.sources.bing_ads.bing_ads.integrations")
def test_bing_ads_source_missing_developer_token(self, mock_integrations):
"""Test source function raises error when developer token is missing."""
diff --git a/posthog/temporal/data_imports/sources/bing_ads/utils.py b/posthog/temporal/data_imports/sources/bing_ads/utils.py
index f3baff1fd9db..6af48c871313 100644
--- a/posthog/temporal/data_imports/sources/bing_ads/utils.py
+++ b/posthog/temporal/data_imports/sources/bing_ads/utils.py
@@ -8,6 +8,7 @@ from collections.abc import Iterator
from pathlib import Path
from typing import Any
+import structlog
from bingads.v13.reporting import ReportingDownloadParameters
from dateutil.relativedelta import relativedelta
@@ -15,6 +16,8 @@ from posthog.temporal.data_imports.sources.common.resumable import ResumableSour
from .schemas import BingAdsResource
+logger = structlog.get_logger(__name__)
+
@dataclasses.dataclass
class BingAdsResumeConfig:
@@ -76,16 +79,29 @@ def fetch_data_in_yearly_chunks(
end_date,
)
- data_pages = client.get_data_by_resource(
- resource=resource,
- account_id=account_id,
- start_date=dt.datetime.combine(current_start, dt.time.min),
- end_date=dt.datetime.combine(chunk_end, dt.time.max),
- )
-
- for page in data_pages:
- if page:
- yield page
+ try:
+ data_pages = client.get_data_by_resource(
+ resource=resource,
+ account_id=account_id,
+ start_date=dt.datetime.combine(current_start, dt.time.min),
+ end_date=dt.datetime.combine(chunk_end, dt.time.max),
+ )
+ for page in data_pages:
+ if page:
+ yield page
+ except Exception as e:
+ # Bing's 36-month retention boundary moves day by day, so the oldest chunk can land just
+ # outside it and get rejected with InvalidCustomDateRangeEnd. That rejection is
+ # deterministic — skip the out-of-retention chunk (advancing the checkpoint below) instead
+ # of failing the whole sync. Any other error stays fatal so it can retry.
+ if "InvalidCustomDateRangeEnd" not in str(e):
+ raise
+ logger.warning(
+ "Skipping Bing Ads report chunk outside the 36-month retention window",
+ resource=resource.value,
+ chunk_start=current_start.isoformat(),
+ chunk_end=chunk_end.isoformat(),
+ )
# Move to the day after chunk_end to avoid duplicate dates at chunk boundaries
current_start = chunk_end + dt.timedelta(days=1)
@@ -178,6 +194,12 @@ def download_and_extract_report_csv(
result_file_path = reporting_service_manager.download_file(download_params)
+ # Bing returns no file when the report completes with zero rows for the requested range
+ # (e.g. a date window with no campaign activity). Treat that as an empty report instead of
+ # crashing on Path(None).
+ if result_file_path is None:
+ return ""
+
result_path = Path(result_file_path)
with zipfile.ZipFile(result_path, "r") as zip_file:
csv_files = [name for name in zip_file.namelist() if name.endswith(".csv")]