: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
fix(data-warehouse): Fail Bing Ads incremental syncs if a single chunk fails (#64197)
Luke Belton20a8848a3c86
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.pyindex 195e159785ca..d2a017da4cd5 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@@ -57,8 +57,7 @@ class TestBingAdsHelperFunctions:assert result[0]["Clicks"] is Noneassert result[1]["CampaignName"] is None- @patch("posthog.temporal.data_imports.sources.bing_ads.utils.logger")- def test_fetch_data_in_yearly_chunks_single_chunk(self, mock_logger):+ def test_fetch_data_in_yearly_chunks_single_chunk(self):"""Test fetching data within a single year."""mock_client = Mock()mock_client.get_data_by_resource.return_value = iter([[{"CampaignId": "123", "Clicks": "100"}]])@@ -85,8 +84,7 @@ class TestBingAdsHelperFunctions:BingAdsResumeConfig(next_start_date="2024-07-01", end_date=end_date.isoformat()))- @patch("posthog.temporal.data_imports.sources.bing_ads.utils.logger")- def test_fetch_data_in_yearly_chunks_multiple_chunks(self, mock_logger):+ def test_fetch_data_in_yearly_chunks_multiple_chunks(self):"""Test fetching data across multiple years."""mock_client = Mock()mock_client.get_data_by_resource.side_effect = [@@ -117,8 +115,7 @@ class TestBingAdsHelperFunctions:first_checkpoint = manager.save_state.call_args_list[0].args[0]assert first_checkpoint == BingAdsResumeConfig(next_start_date="2024-01-02", end_date=end_date.isoformat())- @patch("posthog.temporal.data_imports.sources.bing_ads.utils.logger")- def test_fetch_data_in_yearly_chunks_same_day(self, mock_logger):+ def test_fetch_data_in_yearly_chunks_same_day(self):mock_client = Mock()mock_client.get_data_by_resource.return_value = iter([[{"CampaignId": "123", "Clicks": "100"}]])@@ -145,9 +142,12 @@ class TestBingAdsHelperFunctions:end_date=dt.datetime.combine(today, dt.time.max),)- @patch("posthog.temporal.data_imports.sources.bing_ads.utils.logger")- def test_fetch_data_in_yearly_chunks_with_errors(self, mock_logger):- """Test fetching data with some chunks failing."""+ def test_fetch_data_in_yearly_chunks_failure_fails_sync(self):+ """A chunk failure propagates so the sync fails rather than completing with missing data.++ The checkpoint must not advance past the failed chunk, so a resume re-attempts it+ instead of leaving a permanent gap in the data.+ """mock_client = Mock()mock_client.get_data_by_resource.side_effect = [iter([[{"year": "2023"}]]),@@ -159,24 +159,27 @@ class TestBingAdsHelperFunctions:end_date = dt.date(2025, 6, 30)manager = _mock_resumable_manager()- result = list(- fetch_data_in_yearly_chunks(++ result: list[list[dict]] = []+ with pytest.raises(Exception, match="API Error"):+ for page in 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,- )- )+ ):+ result.append(page)- assert len(result) == 2- mock_logger.error.assert_called_once()- # Checkpoint advances even after the failed chunk so resume moves past it- assert manager.save_state.call_count == 3+ # Only the first chunk was yielded before the failure aborted the sync+ assert result == [[{"year": "2023"}]]+ # Checkpoint advanced only past the successful first chunk, not the failed one+ manager.save_state.assert_called_once_with(+ BingAdsResumeConfig(next_start_date="2024-01-02", end_date=end_date.isoformat())+ )- @patch("posthog.temporal.data_imports.sources.bing_ads.utils.logger")- def test_fetch_data_in_yearly_chunks_resumes_from_saved_state(self, mock_logger):+ 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()mock_client.get_data_by_resource.return_value = iter([[{"year": "2025"}]])diff --git a/posthog/temporal/data_imports/sources/bing_ads/utils.py b/posthog/temporal/data_imports/sources/bing_ads/utils.pyindex 48a8e0703f6c..f3baff1fd9db 100644--- a/posthog/temporal/data_imports/sources/bing_ads/utils.py+++ b/posthog/temporal/data_imports/sources/bing_ads/utils.py@@ -1,6 +1,5 @@import csvimport uuid-import typingimport zipfileimport datetime as dtimport tempfile@@ -9,7 +8,6 @@ from collections.abc import Iteratorfrom pathlib import Pathfrom typing import Any-import structlogfrom bingads.v13.reporting import ReportingDownloadParametersfrom dateutil.relativedelta import relativedelta@@ -31,8 +29,6 @@ class BingAdsResumeConfig:end_date: str-logger = structlog.get_logger(__name__)-ENVIRONMENT = "production"REPORT_POLL_INTERVAL_MS = 5000REPORT_TIMEOUT_MS = 360000@@ -73,7 +69,6 @@ def fetch_data_in_yearly_chunks(end_date = dt.date.fromisoformat(saved_state.end_date)current_start = start_date- errors: list[dict[str, typing.Any]] = []while current_start <= end_date:chunk_end = min(@@ -81,32 +76,22 @@ def fetch_data_in_yearly_chunks(end_date,)- 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),- )+ 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:- errors.append(- {- "start_date": current_start.isoformat(),- "end_date": chunk_end.isoformat(),- "error": str(e),- "error_type": type(e).__name__,- }- )+ for page in data_pages:+ if page:+ yield page# Move to the day after chunk_end to avoid duplicate dates at chunk boundariescurrent_start = chunk_end + dt.timedelta(days=1)- # Checkpoint after each chunk boundary (both success and error paths) so resume- # always advances past chunks we've already attempted.+ # Checkpoint only after a chunk has been fetched, so a resume re-attempts a failed+ # chunk rather than skipping past it.resumable_source_manager.save_state(BingAdsResumeConfig(next_start_date=current_start.isoformat(),@@ -114,13 +99,6 @@ def fetch_data_in_yearly_chunks())- if errors:- logger.error(- "Some data chunks failed to fetch",- failed_chunks=len(errors),- total_errors=errors,- )-def build_report_request(service_factory: Any,