: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 Meta's transient server errors inline (#72172)
Tom Owersfe11b5de64b0
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.pyindex 26790c0725a8..6cc15916bf9d 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@@ -101,7 +101,7 @@ def _fetch_paging_url(url: str, access_token: str) -> Response:Saved URLs have ``access_token`` stripped; we pass it via ``params`` atrequest time so the token never persists in Redis or debug logs."""- return make_tracked_session().get(url, params={"access_token": access_token})+ return _get_with_transient_retry(lambda: make_tracked_session().get(url, params={"access_token": access_token}))def _clean_account_id(s: str | None) -> str | None:@@ -286,6 +286,53 @@ def _is_timeout_error(response: Response) -> bool:return False+# Meta flags momentary server-side failures with ``error.is_transient`` and asks callers to retry+# (the dominant case is code 2, "An unexpected error has occurred. Please retry your request later.").+# The request itself is fine, so a couple of immediate retries with a short backoff usually clears+# it — keeping a self-recovering blip from failing the whole activity (and surfacing as error-tracking+# noise) while still letting it propagate, and Temporal retry from saved resume state, if it persists.+META_TRANSIENT_ERROR_MAX_ATTEMPTS = 4+++def _is_transient_error(response: Response) -> bool:+ """Return True for Meta errors Meta itself flags transient via ``error.is_transient``.++ Distinct from the too-much-data timeout (``_is_timeout_error``), which has its own+ limit-shrinking recovery; a transient error is retried with the request unchanged.+ """+ try:+ error = response.json().get("error", {})+ except (ValueError, AttributeError):+ return False+ return error.get("is_transient") is True+++def _get_with_transient_retry(issue: collections.abc.Callable[[], Response]) -> Response:+ """Issue a request, absorbing Meta's transient server errors with a short backoff.++ Re-issuing the same request is safe: a transiently-failed request yielded no rows. Too-much-data+ timeouts are left for the caller's limit-shrinking path. If it stays transient past the bound the+ last response is returned unchanged, so the caller raises it as usual (staying retryable upstream).+ """+ response = issue()+ attempt = 1+ while (+ attempt < META_TRANSIENT_ERROR_MAX_ATTEMPTS+ and response.status_code != 200+ and _is_transient_error(response)+ and not _is_timeout_error(response)+ ):+ _backoff_sleep(attempt)+ response = issue()+ attempt += 1+ return response+++def _get_initial_request(url: str, params: dict) -> Response:+ """Issue a first (non-cursor) Graph API request, absorbing Meta's transient server errors."""+ return _get_with_transient_retry(lambda: make_tracked_session().get(url, params=params))++# Meta error codes that indicate a permanent auth or permission problem — the# only fix is for the user to re-authorize the integration, so retrying the job# is pointless. We key off the numeric ``code`` rather than the error ``type``:@@ -470,8 +517,8 @@ def _iter_simple_pagination()return _fetch_paging_url(url, access_token)if current_limit != PAGE_LIMIT_FALLBACK_SIZES[0]:- return make_tracked_session().get(initial_url, params={**params, "limit": current_limit})- return make_tracked_session().get(initial_url, params=params)+ return _get_initial_request(initial_url, {**params, "limit": current_limit})+ return _get_initial_request(initial_url, params)response = _issue()malformed_json_attempts = 0@@ -601,7 +648,7 @@ def _iter_time_range_pagination(}chunk_params = {**params, "limit": current_limit, "time_range": json.dumps(chunk_time_range)}- response = make_tracked_session().get(url, params=chunk_params)+ response = _get_initial_request(url, chunk_params)if response.status_code != 200:# Fallback only happens on the initial chunk request (before any data is yielded).@@ -639,7 +686,7 @@ def _iter_time_range_pagination(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)+ response = _get_initial_request(url, 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.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.pyindex 795e3ecbb094..e7fe05f87a19 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@@ -22,12 +22,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mMAX_AD_ACCOUNT_PAGES,META_ADS_MAX_HISTORY_DAYS,META_AUTH_ERROR_MESSAGE,+ META_TRANSIENT_ERROR_MAX_ATTEMPTS,PAGE_LIMIT_FALLBACK_SIZES,MetaAdsAuthError,MetaAdsResumeConfig,_earliest_supported_since,_fetch_integration_row,_is_permanent_auth_error,+ _is_transient_error,_iter_simple_pagination,_iter_time_range_pagination,_next_smaller_limit,@@ -384,6 +386,76 @@ class TestSimplePaginationMalformedJson:assert mock_get.return_value.get.call_count == MALFORMED_JSON_MAX_ATTEMPTS+class TestIsTransientError:+ @pytest.mark.parametrize(+ "body,expected",+ [+ ({"error": {"is_transient": True, "code": 2}}, True),+ ({"error": {"code": 190}}, False),+ ({"data": []}, False),+ ],+ )+ def test_reads_transient_flag(self, body: dict, expected: bool) -> None:+ assert _is_transient_error(_mock_response(500, body)) is expected++ def test_non_json_body_is_not_transient(self) -> None:+ # A proxy/gateway can return a non-JSON error page; the flag check must not crash on it.+ response = mock.MagicMock()+ response.status_code = 500+ response.json.side_effect = RequestsJSONDecodeError("Expecting value", "<html>", 0)+ assert _is_transient_error(response) is False+++class TestTransientErrorRetry:+ INITIAL_URL = "https://graph.facebook.com/v20/act_123/campaigns"+ PARAMS: dict[str, Any] = {"fields": "id,name", "limit": 500, "access_token": "tok"}+ # Meta's own body for a self-recovering server hiccup: 500, code 2, is_transient true.+ TRANSIENT_BODY: dict[str, Any] = {+ "error": {+ "message": "An unexpected error has occurred. Please retry your request later.",+ "type": "OAuthException",+ "is_transient": True,+ "code": 2,+ }+ }++ def test_transient_error_reissues_same_request_then_succeeds(self, monkeypatch) -> None:+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)+ manager = _build_manager()+ responses = [+ _mock_response(500, self.TRANSIENT_BODY),+ _mock_response(200, {"data": [{"id": "1"}], "paging": {}}),+ ]++ with mock.patch(+ "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+ batches = list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))++ assert batches == [[{"id": "1"}]]+ assert mock_get.return_value.get.call_count == 2+ # Retry re-issues the SAME request at the SAME limit — a transient blip is not a+ # too-much-data timeout, so the page limit is left untouched.+ assert mock_get.return_value.get.call_args_list[1].args[0] == self.INITIAL_URL+ assert mock_get.return_value.get.call_args_list[1].kwargs["params"]["limit"] == 500++ def test_persistent_transient_error_raises_after_bounded_attempts(self, monkeypatch) -> None:+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)+ manager = _build_manager()+ responses = [_mock_response(500, self.TRANSIENT_BODY) for _ in range(META_TRANSIENT_ERROR_MAX_ATTEMPTS)]++ with mock.patch(+ "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+ # Still surfaces the raw failure so it stays retryable at the Temporal layer.+ with pytest.raises(Exception, match="Meta API request failed: 500"):+ list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))++ assert mock_get.return_value.get.call_count == META_TRANSIENT_ERROR_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"}