: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(meta_ads): retry truncated JSON responses from the Graph API (#64736)
Tom Owersd77d0c37d303
diff --git a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.pyindex ef9c44ebb2e8..335814e20894 100644--- a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py+++ b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py@@ -184,6 +184,15 @@ TIME_RANGE_CHUNK_SIZES = [30, 7, 1]# ``limit`` as a query param on cursor URLs.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.+MALFORMED_JSON_MAX_ATTEMPTS = 3+def _override_limit(url: str, limit: int) -> str:"""Return ``url`` with its ``limit`` query parameter overridden.@@ -321,6 +330,7 @@ def _iter_simple_pagination(return make_tracked_session().get(initial_url, params=params)response = _issue()+ malformed_json_attempts = 0while True:if response.status_code != 200:@@ -335,7 +345,19 @@ def _iter_simple_pagination(continue_raise_meta_api_error(response)- response_payload = response.json()+ try:+ response_payload = response.json()+ except json.JSONDecodeError:+ # 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).+ malformed_json_attempts += 1+ if malformed_json_attempts >= MALFORMED_JSON_MAX_ATTEMPTS:+ raise+ response = _issue()+ continue+ malformed_json_attempts = 0+yield response_payload.get("data", [])next_url = response_payload.get("paging", {}).get("next")@@ -415,6 +437,9 @@ def _iter_time_range_pagination(# The most recent cursor URL we tried (without a limit override applied),# used to retry-with-smaller-limit if a mid-chunk request times out.last_paging_url: str | None = None+ # Params of the initial chunk request, kept so a truncated 200 body can be+ # re-fetched. Only set on the non-resume path; unused once we're on a cursor.+ chunk_params: dict | None = Noneif pending_next_url:# Mid-chunk resume: re-attach a fresh access_token at request time@@ -440,6 +465,7 @@ def _iter_time_range_pagination(continue_raise_meta_api_error(response)+ malformed_json_attempts = 0while True:if response.status_code != 200:# Mid-chunk timeout: retry the same cursor URL with a smaller@@ -454,7 +480,26 @@ def _iter_time_range_pagination(continue_raise_meta_api_error(response)- response_payload = response.json()+ try:+ response_payload = response.json()+ except json.JSONDecodeError:+ # 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.+ malformed_json_attempts += 1+ if malformed_json_attempts >= MALFORMED_JSON_MAX_ATTEMPTS:+ raise+ if last_paging_url is not None:+ response = _fetch_paging_url(_override_limit(last_paging_url, current_limit), access_token)+ elif chunk_params is not None:+ response = make_tracked_session().get(url, params=chunk_params)+ else:+ # Unreachable: on the non-resume path chunk_params is always+ # set, and on the resume path last_paging_url is always set.+ raise RuntimeError("Cannot retry truncated JSON: no cursor and no initial chunk params")+ continue+ malformed_json_attempts = 0+yield response_payload.get("data", [])next_url = response_payload.get("paging", {}).get("next")diff --git a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.pyindex 425b35dad861..7c27b14104fc 100644--- a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py+++ b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py@@ -10,6 +10,7 @@ from posthog.temporal.data_imports.sources.common.resumable import ResumableSourfrom posthog.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfigfrom posthog.temporal.data_imports.sources.meta_ads import meta_ads as meta_ads_modulefrom posthog.temporal.data_imports.sources.meta_ads.meta_ads import (+ MALFORMED_JSON_MAX_ATTEMPTS,META_ADS_MAX_HISTORY_DAYS,META_AUTH_ERROR_MESSAGE,PAGE_LIMIT_FALLBACK_SIZES,@@ -37,6 +38,16 @@ def _mock_response(status: int, body: dict) -> mock.MagicMock:return response+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.+ response = mock.MagicMock()+ response.status_code = 200+ response.json.side_effect = json.JSONDecodeError("Unterminated string starting at", "{", 98254)+ response.text = '{"data": [{"id": "1"'+ return response++def _build_manager(*, can_resume: bool = False, state: MetaAdsResumeConfig | None = None) -> mock.MagicMock:manager = mock.MagicMock(spec=ResumableSourceManager)manager.can_resume.return_value = can_resume@@ -284,6 +295,62 @@ class TestSimplePaginationLimitFallback:assert mock_get.return_value.get.call_count == 1+class TestSimplePaginationMalformedJson:+ INITIAL_URL = "https://graph.facebook.com/v20/act_123/campaigns"+ PARAMS: dict[str, Any] = {"fields": "id,name", "limit": 500, "access_token": "tok"}++ def test_initial_truncated_body_reissues_same_request(self) -> None:+ manager = _build_manager()+ responses = [+ # Initial request comes back 200 but with a truncated JSON body.+ _mock_truncated_response(),+ # Re-issuing the same request returns a complete body.+ _mock_response(200, {"data": [{"id": "1"}], "paging": {}}),+ ]++ with mock.patch("posthog.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session") as mock_get:+ mock_get.return_value.get.side_effect = responses+ batches = list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))++ assert batches == [[{"id": "1"}]]+ # Re-issue targets the same initial URL (no rows were yielded before the retry).+ assert mock_get.return_value.get.call_count == 2+ assert mock_get.return_value.get.call_args_list[1].args[0] == self.INITIAL_URL++ def test_cursor_truncated_body_reissues_same_cursor(self) -> None:+ manager = _build_manager()+ responses = [+ _mock_response(+ 200,+ {"data": [{"id": "1"}], "paging": {"next": "https://graph.facebook.com/v20/next?after=p1"}},+ ),+ # The cursor page returns a truncated body, then succeeds on re-issue.+ _mock_truncated_response(),+ _mock_response(200, {"data": [{"id": "2"}], "paging": {}}),+ ]++ with mock.patch("posthog.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session") as mock_get:+ mock_get.return_value.get.side_effect = responses+ batches = list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))++ # The already-yielded first page is not re-emitted; the cursor is re-fetched.+ assert batches == [[{"id": "1"}], [{"id": "2"}]]+ assert mock_get.return_value.get.call_args_list[1].args[0] == "https://graph.facebook.com/v20/next?after=p1"+ assert mock_get.return_value.get.call_args_list[2].args[0] == "https://graph.facebook.com/v20/next?after=p1"++ def test_persistently_truncated_body_raises(self) -> None:+ manager = _build_manager()+ responses = [_mock_truncated_response() for _ in range(MALFORMED_JSON_MAX_ATTEMPTS)]++ with mock.patch("posthog.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):+ list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))++ # Bounded: one attempt per allowed try, then it gives up (stays retryable upstream).+ assert mock_get.return_value.get.call_count == MALFORMED_JSON_MAX_ATTEMPTS++class TestTimeRangePagination:URL = "https://graph.facebook.com/v20/act_1/insights"PARAMS: dict[str, Any] = {"fields": "ad_id", "limit": 500, "level": "ad", "access_token": "tok"}@@ -774,6 +841,126 @@ class TestMidChunkLimitFallback:assert mock_get.return_value.get.call_count == 2+class TestTimeRangeMalformedJson:+ URL = "https://graph.facebook.com/v20/act_1/insights"+ PARAMS: dict[str, Any] = {"fields": "ad_id", "limit": 500, "level": "ad", "access_token": "tok"}++ def test_initial_chunk_truncated_body_reissues_chunk_request(self) -> None:+ manager = _build_manager()+ responses = [+ # Initial chunk request returns a truncated 200 body.+ _mock_truncated_response(),+ # Re-issuing the same chunk request returns a complete body.+ _mock_response(200, {"data": [{"ad_id": "a"}], "paging": {}}),+ ]++ with mock.patch("posthog.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session") as mock_get:+ mock_get.return_value.get.side_effect = responses+ batches = list(+ _iter_time_range_pagination(+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager+ )+ )++ assert batches == [[{"ad_id": "a"}]]+ # Both calls are the same initial chunk request, carrying the time_range param.+ assert mock_get.return_value.get.call_count == 2+ for call in mock_get.return_value.get.call_args_list:+ assert call.args[0] == self.URL+ assert json.loads(call.kwargs["params"]["time_range"]) == {"since": "2026-04-21", "until": "2026-04-21"}++ def test_cursor_truncated_body_reissues_same_cursor(self) -> None:+ manager = _build_manager()+ responses = [+ _mock_response(+ 200,+ {+ "data": [{"ad_id": "a"}],+ "paging": {"next": "https://graph.facebook.com/v20/act_1/insights?after=p1"},+ },+ ),+ # The cursor page returns a truncated body, then succeeds on re-issue.+ _mock_truncated_response(),+ _mock_response(200, {"data": [{"ad_id": "b"}], "paging": {}}),+ ]++ with mock.patch("posthog.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session") as mock_get:+ mock_get.return_value.get.side_effect = responses+ batches = list(+ _iter_time_range_pagination(+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager+ )+ )++ # Already-yielded first page is not re-emitted; the cursor is re-fetched at the same limit.+ assert batches == [[{"ad_id": "a"}], [{"ad_id": "b"}]]+ assert (+ mock_get.return_value.get.call_args_list[1].args[0]+ == "https://graph.facebook.com/v20/act_1/insights?after=p1&limit=500"+ )+ assert (+ mock_get.return_value.get.call_args_list[2].args[0]+ == "https://graph.facebook.com/v20/act_1/insights?after=p1&limit=500"+ )++ def test_resumed_cursor_truncated_body_reissues_same_cursor(self) -> None:+ # Mid-chunk resume: pending_next_url comes from a saved MetaAdsResumeConfig,+ # so chunk_params stays None and recovery must go through the last_paging_url branch.+ resumed_cursor = "https://graph.facebook.com/v20/act_1/insights?after=resumed"+ manager = _build_manager(+ can_resume=True,+ state=MetaAdsResumeConfig(+ end_date="2026-04-21",+ chunk_since="2026-04-21",+ chunk_size_days=1,+ chunk_next_url=resumed_cursor,+ ),+ )+ responses = [+ # The resumed cursor page returns a truncated body, then succeeds on re-issue.+ _mock_truncated_response(),+ _mock_response(200, {"data": [{"ad_id": "b"}], "paging": {}}),+ ]++ with mock.patch("posthog.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session") as mock_get:+ mock_get.return_value.get.side_effect = responses+ batches = list(+ _iter_time_range_pagination(+ self.URL,+ self.PARAMS,+ {"since": "2026-04-21", "until": "2026-04-21"},+ MetaAdsResumeConfig(+ end_date="2026-04-21",+ chunk_since="2026-04-21",+ chunk_size_days=1,+ chunk_next_url=resumed_cursor,+ ),+ manager,+ )+ )++ assert batches == [[{"ad_id": "b"}]]+ # Both calls re-fetch the same resumed cursor at the default limit; no initial chunk request.+ assert mock_get.return_value.get.call_count == 2+ for call in mock_get.return_value.get.call_args_list:+ assert call.args[0] == f"{resumed_cursor}&limit=500"++ def test_persistently_truncated_body_raises(self) -> None:+ manager = _build_manager()+ responses = [_mock_truncated_response() for _ in range(MALFORMED_JSON_MAX_ATTEMPTS)]++ with mock.patch("posthog.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):+ list(+ _iter_time_range_pagination(+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager+ )+ )++ assert mock_get.return_value.get.call_count == MALFORMED_JSON_MAX_ATTEMPTS++class TestNonRetryableErrors:@pytest.mark.parametrize("error_message",