: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(linkedin_ads): retry non-JSON API responses instead of crashing (#65071)
Tom Owers5357344861a7
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/client.py b/posthog/temporal/data_imports/sources/linkedin_ads/client.pyindex 0d79a8bf0c79..4e7b0aba5b6a 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/client.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/client.py@@ -7,6 +7,7 @@ from typing import Any, Optionalimport requestsimport structlogfrom linkedin_api.clients.restli.client import RestliClient+from linkedin_api.common.errors import ResponseFormattingErrorfrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom .schemas import (@@ -285,13 +286,20 @@ class LinkedinAdsClient:so we fail fast instead of burning the remaining budget on doomed retries. Short-window429s stay retryable and honour the Retry-After header when present."""- response = self.client.finder(- resource_path=resource_path,- finder_name=finder,- access_token=self.access_token,- query_params=params,- version_string=self.api_version,- )+ try:+ response = self.client.finder(+ resource_path=resource_path,+ finder_name=finder,+ access_token=self.access_token,+ query_params=params,+ version_string=self.api_version,+ )+ except ResponseFormattingError as e:+ # The Restli client parses the body as JSON before returning, so a non-JSON response+ # (an empty payload or an HTML error page from a 5xx gateway/proxy) raises here as a+ # wrapped JSONDecodeError rather than a status code we can branch on below. These are+ # transient edge responses — retry them like the 5xx path instead of failing the sync.+ raise LinkedinAdsRetryableError(f"LinkedIn API returned a malformed (non-JSON) response: {e}") from eif response.status_code == 429:body = response.response.textdiff --git a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.pyindex 0e63ced7cf07..f4e495d15bd4 100644--- a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py+++ b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py@@ -5,6 +5,7 @@ import pytestfrom unittest import mockimport requests+from linkedin_api.common.errors import ResponseFormattingErrorfrom structlog.testing import capture_logsfrom posthog.temporal.data_imports.sources.linkedin_ads.client import (@@ -346,6 +347,11 @@ class TestLinkedinAdsClient:2,id="http_429",),+ pytest.param(+ lambda: ResponseFormattingError("Expecting value: line 1 column 1 (char 0)"),+ 3,+ id="non_json_response",+ ),],)@mock.patch("tenacity.nap.time.sleep", return_value=None)@@ -492,6 +498,21 @@ class TestLinkedinAdsClient:assert mock_sleep.call_count == 1assert mock_sleep.call_args[0][0] >= 0+ @mock.patch("tenacity.nap.time.sleep", return_value=None)+ @mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.client.RestliClient")+ def test_non_json_response_exhausts_retries_as_retryable_error(self, mock_restli_client, _mock_sleep):+ """A persistently non-JSON response is retried, then reraised as LinkedinAdsRetryableError+ rather than crashing the sync with a bare JSONDecodeError from the Restli client."""+ mock_client_instance = mock_restli_client.return_value+ mock_client_instance.finder.side_effect = ResponseFormattingError("Expecting value: line 1 column 1 (char 0)")++ client = LinkedinAdsClient(self.access_token)++ with pytest.raises(LinkedinAdsRetryableError, match="malformed \\(non-JSON\\) response"):+ client.get_accounts()++ assert mock_client_instance.finder.call_count == 5+def test_retryable_error_is_exported(self):assert issubclass(LinkedinAdsRetryableError, Exception)assert issubclass(LinkedinAdsDailyRateLimitError, Exception)