: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(bing_ads): avoid working-directory race in report downloads (#69663)
Tom Owers4fe7f6c781b6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.pyindex 56487c08cd08..9ada63736ad9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py@@ -1,3 +1,4 @@+import tempfilefrom collections.abc import Generatorfrom datetime import datetimefrom typing import Any@@ -178,29 +179,35 @@ class BingAdsClient:self.authorization_data.customer_id = customer_idtry:- reporting_service_manager = reporting.ReportingServiceManager(- authorization_data=self.authorization_data,- poll_interval_in_milliseconds=REPORT_POLL_INTERVAL_MS,- environment=ENVIRONMENT,- )+ # The SDK otherwise defaults every manager to a shared /tmp/BingAdsSDKPython and creates it+ # with a check-then-makedirs that isn't atomic; two report fetches running concurrently on the+ # same worker race and one dies with FileExistsError. Give each manager a private, already-created+ # working directory so the SDK skips that creation path entirely.+ with tempfile.TemporaryDirectory(prefix="bing_ads_sdk_") as working_directory:+ reporting_service_manager = reporting.ReportingServiceManager(+ authorization_data=self.authorization_data,+ poll_interval_in_milliseconds=REPORT_POLL_INTERVAL_MS,+ environment=ENVIRONMENT,+ working_directory=working_directory,+ )- # 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 ediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.pyindex 447fa309c81e..c3c9eeab4004 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py@@ -1,4 +1,7 @@+import osimport types+import datetime as dt+import tempfileimport pytestfrom unittest import mock@@ -9,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.cBingAdsClient,extract_webfault_detail,)+from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.schemas import BingAdsResourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.source import BingAdsSource@@ -184,6 +188,47 @@ class TestBingAdsClient:non_retryable_patterns = BingAdsSource().get_non_retryable_errors()assert not any(pattern in message for pattern in non_retryable_patterns)+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.download_and_extract_report_csv"+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.build_report_request")+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.reporting")+ def test_get_performance_report_gives_sdk_private_existing_working_directory(+ self, mock_reporting, _mock_build_request, mock_download+ ):+ """The bingads SDK defaults every ReportingServiceManager to a shared /tmp/BingAdsSDKPython that it+ creates with a non-atomic check-then-makedirs; concurrent report fetches race and one dies with+ FileExistsError. get_performance_report must hand the SDK a private directory that already exists so+ the SDK never runs that creation path.+ """+ shared_default = os.path.join(tempfile.gettempdir(), "BingAdsSDKPython")+ captured: dict[str, object] = {}++ def fake_manager(authorization_data, poll_interval_in_milliseconds, environment, working_directory=None):+ # Mirror the SDK's own working-directory handling to prove our fix bypasses it.+ resolved = working_directory if working_directory is not None else shared_default+ captured["working_directory"] = resolved+ captured["created_by_sdk"] = not os.path.exists(resolved)+ if captured["created_by_sdk"]:+ os.makedirs(resolved)+ return mock.MagicMock()++ mock_reporting.ReportingServiceManager.side_effect = fake_manager+ mock_download.return_value = ""++ client = BingAdsClient(self.access_token, self.refresh_token, self.developer_token)+ client.get_performance_report(+ resource=BingAdsResource.AD_PERFORMANCE_REPORT,+ account_id=self.account_id,+ customer_id=self.customer_id,+ start_date=dt.datetime(2024, 1, 1),+ end_date=dt.datetime(2024, 12, 31),+ )++ # A private, already-existing directory means the SDK's racy makedirs never runs.+ assert captured["working_directory"] != shared_default+ assert captured["created_by_sdk"] is False+@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.ServiceClient")def test_get_campaigns_success(self, mock_service_client):"""Test successful campaigns retrieval."""