: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): stop retrying invalid-client-data auth faults (#63794)
Tom Owers928cfabb5a1a
diff --git a/posthog/temporal/data_imports/sources/bing_ads/client.py b/posthog/temporal/data_imports/sources/bing_ads/client.pyindex 90cb1d43442b..4d6d297478c8 100644--- a/posthog/temporal/data_imports/sources/bing_ads/client.py+++ b/posthog/temporal/data_imports/sources/bing_ads/client.py@@ -5,6 +5,7 @@ from typing import Anyimport structlogfrom bingads import AuthorizationData, OAuthTokens, OAuthWebAuthCodeGrant, ServiceClientfrom bingads.v13 import reporting+from suds import WebFaultfrom posthog.settings import integrations@@ -20,6 +21,45 @@ from .utils import (logger = structlog.get_logger(__name__)+def _as_list(value: Any) -> list[Any]:+ if value is None:+ return []+ return value if isinstance(value, list) else [value]+++def extract_webfault_detail(fault: Any) -> str:+ """Pull the actionable error codes/messages out of a Bing Ads suds ``WebFault``.++ The top-level ``faultstring`` is intentionally generic (e.g. "Invalid client data. Check the+ SOAP fault details for more information."). The real, stable error codes — ``InvalidCredentials``,+ ``AuthenticationTokenExpired``, ``WorkIdentityNotAvailable``, etc. — live in the SOAP fault+ detail. Surfacing them lets the retry framework recognise auth/credential failures as+ non-retryable and gives operators a real cause instead of the opaque umbrella message.++ Detail shape mirrors the bingads SDK (see ``bingads.util.errorcode_of_exception``):+ ``AdApiFaultDetail.Errors.AdApiError[]`` for auth/general errors and+ ``ApiFaultDetail.OperationErrors.OperationError[]`` for operation-level errors.+ """+ detail = getattr(fault, "detail", None)+ if detail is None:+ return ""++ ad_api_errors = getattr(getattr(getattr(detail, "AdApiFaultDetail", None), "Errors", None), "AdApiError", None)+ operation_errors = getattr(+ getattr(getattr(detail, "ApiFaultDetail", None), "OperationErrors", None), "OperationError", None+ )++ parts: list[str] = []+ for err in _as_list(ad_api_errors) + _as_list(operation_errors):+ code = getattr(err, "ErrorCode", None) or getattr(err, "Code", None)+ message = getattr(err, "Message", None)+ fragment = ": ".join(str(p) for p in (code, message) if p)+ if fragment:+ parts.append(fragment)++ return "; ".join(parts)++class BingAdsClient:def __init__(self, access_token: str, refresh_token: str, developer_token: str):self.developer_token = developer_token@@ -61,12 +101,21 @@ class BingAdsClient:user = service_client.GetUser(UserId=None).Userself._customer_id = user.CustomerIdexcept Exception as e:- logger.warning("Failed to fetch customer ID", error=str(e), error_type=type(e).__name__)- # Preserve the underlying exception's type and message 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.- raise ValueError(f"Failed to fetch customer ID: {type(e).__name__}: {e}") from 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 ereturn self._customer_iddiff --git a/posthog/temporal/data_imports/sources/bing_ads/source.py b/posthog/temporal/data_imports/sources/bing_ads/source.pyindex cd05c095bb96..6bf8e3fa6d91 100644--- a/posthog/temporal/data_imports/sources/bing_ads/source.py+++ b/posthog/temporal/data_imports/sources/bing_ads/source.py@@ -64,7 +64,8 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], O"invalid_grant": auth_friendly,"invalid_client": auth_friendly,"unauthorized_client": auth_friendly,- # Bing Ads service-level auth error codes surfaced via suds.WebFault details.+ # Bing Ads service-level auth error codes surfaced via suds.WebFault details+ # (see BingAdsClient.get_customer_id / extract_webfault_detail)."AuthenticationTokenExpired": auth_friendly,"AuthenticationFailed": auth_friendly,"InvalidCredentials": auth_friendly,@@ -74,6 +75,19 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], O# the id is volatile, so match only the stable prefix. Retrying can't recreate the row —# the customer has to reconnect."Integration not found": "The linked Bing Ads integration no longer exists. Please reconnect your Bing Ads integration.",+ # CustomerManagementService.GetUser returns the generic SOAP fault "Invalid client data.+ # Check the SOAP fault details for more information." when the connected account can't be+ # used — revoked/expired credentials, a work/school identity instead of a personal Microsoft+ # account (WorkIdentityNotAvailable), or no access to the Microsoft Advertising account.+ # GetUser takes no request parameters, so this is never a malformed-request bug on our side;+ # retrying can't recover it. When the specific code above is present in the fault detail it+ # matches first; this catches the generic umbrella message otherwise.+ "Invalid client data": (+ "PostHog could not use the connected Bing Ads account (Microsoft returned 'Invalid client data'). "+ "This usually means the account's credentials are no longer valid, or the Microsoft account does not "+ "have access to the Microsoft Advertising account. Please reconnect your Bing Ads integration and make "+ "sure the signed-in account can access the account in Microsoft Advertising."+ ),# Deterministic credential/config errors raised in source_for_pipeline."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.",diff --git a/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py b/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.pyindex 0be536580992..22194f6bb57d 100644--- a/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py+++ b/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py@@ -1,10 +1,68 @@+import types+import pytestfrom unittest import mock-from posthog.temporal.data_imports.sources.bing_ads.client import BingAdsClient+from suds import WebFault++from posthog.temporal.data_imports.sources.bing_ads.client import BingAdsClient, extract_webfault_detailfrom posthog.temporal.data_imports.sources.bing_ads.source import BingAdsSource+def _make_webfault(faultstring: str, detail: object | None) -> WebFault:+ """Build a suds WebFault mirroring the shape the bingads SDK produces.++ str(WebFault) is the generic faultstring; the actionable error codes live on fault.detail.+ """+ fault = types.SimpleNamespace(faultstring=faultstring, detail=detail)+ return WebFault(fault, None)+++def _ad_api_fault_detail(error_code: str, message: str, code: int = 105) -> object:+ error = types.SimpleNamespace(Code=code, ErrorCode=error_code, Message=message)+ return types.SimpleNamespace(AdApiFaultDetail=types.SimpleNamespace(Errors=types.SimpleNamespace(AdApiError=error)))+++def _operation_fault_detail(*errors: tuple[object, str]) -> object:+ """Build an ``ApiFaultDetail.OperationErrors.OperationError[]`` detail.++ OperationError carries ``Code``/``Message`` (no ``ErrorCode``); pass a single error or many.+ """+ operation_errors = [types.SimpleNamespace(Code=code, Message=message) for code, message in errors]+ payload = operation_errors[0] if len(operation_errors) == 1 else operation_errors+ return types.SimpleNamespace(+ ApiFaultDetail=types.SimpleNamespace(OperationErrors=types.SimpleNamespace(OperationError=payload))+ )+++ "detail,expected",+ [+ # No detail at all -> empty string, nothing to surface.+ (None, ""),+ # AdApiFaultDetail single error: ErrorCode wins over numeric Code.+ (+ _ad_api_fault_detail("InvalidCredentials", "The user is not authenticated."),+ "InvalidCredentials: The user is not authenticated.",+ ),+ # ApiFaultDetail single OperationError: falls back to numeric Code when no ErrorCode.+ (+ _operation_fault_detail((114, "Campaign service operation failed.")),+ "114: Campaign service operation failed.",+ ),+ # ApiFaultDetail with multiple OperationErrors are all surfaced, joined by "; ".+ (+ _operation_fault_detail((114, "First failure."), (116, "Second failure.")),+ "114: First failure.; 116: Second failure.",+ ),+ ],+)+def test_extract_webfault_detail(detail, expected):+ """extract_webfault_detail must parse both AdApiFaultDetail and ApiFaultDetail shapes."""+ fault = types.SimpleNamespace(detail=detail)+ assert extract_webfault_detail(fault) == expected++class TestBingAdsClient:"""Test suite for BingAdsClient."""@@ -79,6 +137,50 @@ class TestBingAdsClient:non_retryable_patterns = BingAdsSource().get_non_retryable_errors()assert not any(pattern in message for pattern in non_retryable_patterns)+ @mock.patch("posthog.temporal.data_imports.sources.bing_ads.client.ServiceClient")+ def test_get_customer_id_surfaces_soap_fault_detail(self, mock_service_client):+ """The generic 'Invalid client data' faultstring hides the real error code in the SOAP fault+ detail. get_customer_id must surface that code so the retry framework can recognise it and+ operators can see the real cause — matching an existing non-retryable auth pattern.+ """+ webfault = _make_webfault(+ "Invalid client data. Check the SOAP fault details for more information. TrackingId: abc-123.",+ _ad_api_fault_detail("InvalidCredentials", "The user is not authenticated."),+ )+ mock_client_instance = mock_service_client.return_value+ mock_client_instance.GetUser.side_effect = webfault++ client = BingAdsClient(self.access_token, self.refresh_token, self.developer_token)+ with pytest.raises(ValueError) as exc_info:+ client.get_customer_id()++ message = str(exc_info.value)+ assert "Failed to fetch customer ID" in message+ # The detail error code is surfaced alongside the generic umbrella message.+ assert "InvalidCredentials" in message+ assert "Invalid client data" in message+ # The surfaced detail makes the failure match a non-retryable pattern.+ non_retryable_patterns = BingAdsSource().get_non_retryable_errors()+ assert any(pattern in message for pattern in non_retryable_patterns)++ @mock.patch("posthog.temporal.data_imports.sources.bing_ads.client.ServiceClient")+ def test_get_customer_id_webfault_without_detail_keeps_generic_message(self, mock_service_client):+ """A WebFault with no parseable detail must not crash extraction — it just keeps the faultstring."""+ webfault = _make_webfault("Internal Error", detail=None)+ mock_client_instance = mock_service_client.return_value+ mock_client_instance.GetUser.side_effect = webfault++ client = BingAdsClient(self.access_token, self.refresh_token, self.developer_token)+ with pytest.raises(ValueError) as exc_info:+ client.get_customer_id()++ message = str(exc_info.value)+ assert "Failed to fetch customer ID: WebFault" in message+ assert "Internal Error" in message+ # No detail to surface, so no auth pattern should be matched (stays retryable).+ non_retryable_patterns = BingAdsSource().get_non_retryable_errors()+ assert not any(pattern in message for pattern in non_retryable_patterns)+@mock.patch("posthog.temporal.data_imports.sources.bing_ads.client.ServiceClient")def test_get_campaigns_success(self, mock_service_client):"""Test successful campaigns retrieval."""diff --git a/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py b/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.pyindex c51d852a9ef4..9351f986d50e 100644--- a/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py+++ b/posthog/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_source.py@@ -253,6 +253,13 @@ class TestBingAdsSource:"InvalidCredentials","Failed to fetch customer ID: WebFault: ... InvalidCredentials ...",),+ # Generic SOAP fault returned by GetUser when the connected account's credentials/identity+ # can't be used. GetUser takes no request params, so this is never our bug — stop retrying.+ (+ "Invalid client data",+ "Failed to fetch customer ID: WebFault: Server raised fault: 'Invalid client data. "+ "Check the SOAP fault details for more information. TrackingId: abc-123.'",+ ),# Specific Azure AD code — tenant missing service principal for the Microsoft Advertising API.("AADSTS650052",