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.

feat(bing_ads): treat failed customer ID fetch as non-retryable (#56488)

Tom Owersf4e02ba4bb84
diff --git a/posthog/temporal/data_imports/sources/bing_ads/client.py b/posthog/temporal/data_imports/sources/bing_ads/client.py
index 112a464417eb..d2c031bfcd1f 100644
--- a/posthog/temporal/data_imports/sources/bing_ads/client.py
+++ b/posthog/temporal/data_imports/sources/bing_ads/client.py
@@ -46,7 +46,7 @@ class BingAdsClient:
authentication=self.oauth,
)
- def get_customer_id(self) -> int | None:
+ def get_customer_id(self) -> int:
if self._customer_id is not None:
return self._customer_id
@@ -60,10 +60,15 @@ class BingAdsClient:
user = service_client.GetUser(UserId=None).User
self._customer_id = user.CustomerId
- return self._customer_id
except Exception as e:
logger.warning("Failed to fetch customer ID", error=str(e), error_type=type(e).__name__)
- return None
+ # 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
+
+ return self._customer_id
def get_campaigns(self, account_id: int, customer_id: int) -> Generator[list[dict[str, Any]], None, None]:
self.authorization_data.account_id = account_id
@@ -147,8 +152,6 @@ class BingAdsClient:
end_date: datetime | None = None,
) -> Generator[list[dict[str, Any]], None, None]:
customer_id = self.get_customer_id()
- if customer_id is None:
- raise ValueError("Failed to fetch customer ID")
if resource == BingAdsResource.CAMPAIGNS:
yield from self.get_campaigns(account_id, customer_id)
diff --git a/posthog/temporal/data_imports/sources/bing_ads/source.py b/posthog/temporal/data_imports/sources/bing_ads/source.py
index 655f131d29f2..74e236801a4c 100644
--- a/posthog/temporal/data_imports/sources/bing_ads/source.py
+++ b/posthog/temporal/data_imports/sources/bing_ads/source.py
@@ -34,6 +34,33 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], O
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BINGADS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Match only on auth/permission failures that retrying cannot recover from.
+ # Transient SDK errors (network, Bing outage, rate limits) propagate as their
+ # original exception class and stay retryable — see BingAdsClient.get_customer_id,
+ # which wraps the underlying error as `ValueError("Failed to fetch customer ID: <ExcType>: <msg>")`.
+ auth_friendly = (
+ "PostHog could not authenticate with Bing Ads. The connected account's OAuth credentials "
+ "are revoked, expired, or no longer have access. Please reconnect your Bing Ads integration."
+ )
+ return {
+ # OAuth grant rejection by Microsoft (the bingads SDK raises OAuthTokenRequestException
+ # whose str() format is "<error_code> <error_description>").
+ "OAuthTokenRequestException": auth_friendly,
+ "invalid_grant": auth_friendly,
+ "invalid_client": auth_friendly,
+ "unauthorized_client": auth_friendly,
+ # Bing Ads service-level auth error codes surfaced via suds.WebFault details.
+ "AuthenticationTokenExpired": auth_friendly,
+ "AuthenticationFailed": auth_friendly,
+ "InvalidCredentials": auth_friendly,
+ "OAuthTokenExpired": auth_friendly,
+ # 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.",
+ "Bing Ads developer token not configured": None,
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
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.py
index 2f4ecd1f3dfc..0be536580992 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,6 +1,8 @@
+import pytest
from unittest import mock
from posthog.temporal.data_imports.sources.bing_ads.client import BingAdsClient
+from posthog.temporal.data_imports.sources.bing_ads.source import BingAdsSource
class TestBingAdsClient:
@@ -33,6 +35,50 @@ class TestBingAdsClient:
assert client._customer_id == self.customer_id
mock_client_instance.GetUser.assert_called_once_with(UserId=None)
+ @mock.patch("posthog.temporal.data_imports.sources.bing_ads.client.ServiceClient")
+ def test_get_customer_id_preserves_underlying_exception_details(self, mock_service_client):
+ """Underlying exception's class name and message must be embedded in the raised ValueError so
+ the retry framework can selectively match auth-related substrings as non-retryable while
+ keeping transient SDK errors (network/timeouts) retryable.
+ """
+
+ class OAuthTokenRequestException(Exception):
+ pass
+
+ mock_client_instance = mock_service_client.return_value
+ mock_client_instance.GetUser.side_effect = OAuthTokenRequestException(
+ "invalid_grant The provided authorization grant has expired or been revoked."
+ )
+
+ 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
+ assert "OAuthTokenRequestException" in message
+ assert "invalid_grant" in message
+ # __cause__ preserves the original exception for stack traces / logging.
+ assert isinstance(exc_info.value.__cause__, OAuthTokenRequestException)
+
+ @mock.patch("posthog.temporal.data_imports.sources.bing_ads.client.ServiceClient")
+ def test_get_customer_id_transient_failure_message_has_no_auth_substring(self, mock_service_client):
+ """A network/timeout failure must not coincidentally match the non-retryable auth patterns."""
+ mock_client_instance = mock_service_client.return_value
+ mock_client_instance.GetUser.side_effect = ConnectionError(
+ "HTTPSConnectionPool(host='bingads.microsoft.com', port=443): Max retries exceeded"
+ )
+
+ 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 "ConnectionError" in message
+
+ 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.py
index 40a3274315c5..bae96488cb2f 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
@@ -231,6 +231,56 @@ class TestBingAdsSource:
with pytest.raises(ValueError, match="Bing Ads refresh token not found for job test-job-id"):
self.source.source_for_pipeline(self.valid_config, resumable_manager, inputs)
+ @pytest.mark.parametrize(
+ "pattern,raised_message",
+ [
+ # Auth-specific substrings — wrapped by BingAdsClient.get_customer_id as
+ # `ValueError("Failed to fetch customer ID: <ExcType>: <msg>")`, so the substring
+ # must appear inside that combined message.
+ (
+ "OAuthTokenRequestException",
+ "Failed to fetch customer ID: OAuthTokenRequestException: invalid_grant ...",
+ ),
+ (
+ "invalid_grant",
+ "Failed to fetch customer ID: OAuthTokenRequestException: invalid_grant ...",
+ ),
+ (
+ "AuthenticationTokenExpired",
+ "Failed to fetch customer ID: WebFault: ... AuthenticationTokenExpired ...",
+ ),
+ (
+ "InvalidCredentials",
+ "Failed to fetch customer ID: WebFault: ... InvalidCredentials ...",
+ ),
+ # Deterministic credential/config errors raised in source_for_pipeline.
+ ("Bing Ads access token not found", "Bing Ads access token not found for job abc"),
+ ("Bing Ads refresh token not found", "Bing Ads refresh token not found for job abc"),
+ ("Bing Ads developer token not configured", "Bing Ads developer token not configured"),
+ ],
+ )
+ def test_get_non_retryable_errors_pattern_recognised(self, pattern, raised_message):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+
+ assert pattern in non_retryable_errors
+ assert pattern in raised_message
+
+ @pytest.mark.parametrize(
+ "transient_message",
+ [
+ # Plain transport-level failures — must NOT match any non-retryable pattern,
+ # otherwise the schema would be disabled after the first few transient failures.
+ "Failed to fetch customer ID: ConnectionError: HTTPSConnectionPool(host='bingads.microsoft.com', port=443): Max retries exceeded",
+ "Failed to fetch customer ID: TimeoutError: The read operation timed out",
+ "Failed to fetch customer ID: WebFault: Server raised fault: 'Internal Error'",
+ "Failed to fetch customer ID: HTTPError: 503 Server Error: Service Unavailable",
+ ],
+ )
+ def test_get_non_retryable_errors_does_not_match_transient_failures(self, transient_message):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+
+ assert not any(pattern in transient_message for pattern in non_retryable_errors)
+
def test_get_resumable_source_manager(self):
"""Test that get_resumable_source_manager returns a manager that round-trips BingAdsResumeConfig."""
inputs = mock.MagicMock()