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.

fix(meta_ads): catch requests' JSONDecodeError on truncated 200 bodies (#68463)

Tom Owersbfc6cd40ccfa
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py
index d6d3a18acf59..3cb9ccb8ccd5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py
@@ -9,6 +9,7 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from django.db import OperationalError, close_old_connections
from requests import Response
+from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, MetaAdsIntegration
@@ -218,11 +219,11 @@ PAGE_LIMIT_FALLBACK_SIZES = [500, 100, 50]
# Meta's Graph API intermittently returns HTTP 200 with a truncated/partial JSON
# body — a server-side serialization hiccup under load — so ``response.json()``
-# raises ``JSONDecodeError``. The body is fully received but unparseable, so the
-# only recovery is to re-issue the same request; a couple of immediate retries
-# almost always returns a complete body. If it stays malformed we let the error
-# propagate (it remains retryable, so Temporal re-runs the activity from saved
-# resume state) rather than silently dropping the page.
+# raises ``requests.exceptions.JSONDecodeError``. The body is fully received but
+# unparseable, so the only recovery is to re-issue the same request; a couple of
+# immediate retries almost always returns a complete body. If it stays malformed
+# we let the error propagate (it remains retryable, so Temporal re-runs the
+# activity from saved resume state) rather than silently dropping the page.
MALFORMED_JSON_MAX_ATTEMPTS = 3
@@ -379,10 +380,13 @@ def _iter_simple_pagination(
try:
response_payload = response.json()
- except json.JSONDecodeError:
+ except RequestsJSONDecodeError:
# Truncated 200 body — re-issue the same request. Re-fetching is safe
# (the initial request has yielded nothing yet, and a cursor points at
- # the start of the next not-yet-yielded page).
+ # the start of the next not-yet-yielded page). ``response.json()`` raises
+ # requests' own JSONDecodeError, which subclasses simplejson's (not the
+ # stdlib json's) when simplejson is installed — catching the stdlib type
+ # would miss it entirely.
malformed_json_attempts += 1
if malformed_json_attempts >= MALFORMED_JSON_MAX_ATTEMPTS:
raise
@@ -514,7 +518,7 @@ def _iter_time_range_pagination(
try:
response_payload = response.json()
- except json.JSONDecodeError:
+ except RequestsJSONDecodeError:
# Truncated 200 body — re-issue whichever request produced it. A
# cursor points at the start of the not-yet-yielded page and the
# initial chunk request has yielded nothing, so no rows are re-emitted.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
index 77e64d03c846..c7b4aac0d9e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py
@@ -8,6 +8,8 @@ from unittest import mock
from django.db import OperationalError
+from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads import meta_ads as meta_ads_module
@@ -42,10 +44,12 @@ def _mock_response(status: int, body: dict) -> mock.MagicMock:
def _mock_truncated_response() -> mock.MagicMock:
# Meta occasionally returns HTTP 200 with a truncated JSON body, so `.json()`
- # raises JSONDecodeError even though the status is healthy.
+ # raises JSONDecodeError even though the status is healthy. requests raises its
+ # own JSONDecodeError (subclass of simplejson's, not the stdlib json's, when
+ # simplejson is installed), so mirror that here rather than the stdlib type.
response = mock.MagicMock()
response.status_code = 200
- response.json.side_effect = json.JSONDecodeError("Unterminated string starting at", "{", 98254)
+ response.json.side_effect = RequestsJSONDecodeError("Unterminated string starting at", "{", 98254)
response.text = '{"data": [{"id": "1"'
return response
@@ -366,7 +370,7 @@ class TestSimplePaginationMalformedJson:
"products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session"
) as mock_get:
mock_get.return_value.get.side_effect = responses
- with pytest.raises(json.JSONDecodeError):
+ with pytest.raises(RequestsJSONDecodeError):
list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))
# Bounded: one attempt per allowed try, then it gives up (stays retryable upstream).
@@ -1003,7 +1007,7 @@ class TestTimeRangeMalformedJson:
"products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session"
) as mock_get:
mock_get.return_value.get.side_effect = responses
- with pytest.raises(json.JSONDecodeError):
+ with pytest.raises(RequestsJSONDecodeError):
list(
_iter_time_range_pagination(
self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager