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): retry generic Meta backend blips and stop tracking them as bugs (#73142)

Tom Owersf77e629345a0
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 f036ce5a3d91..43aab815c846 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
@@ -293,16 +293,21 @@ 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's error-code reference documents code 1 ("API Unknown" — an unexplained backend hiccup
+# that usually clears in 1-2 retries) and code 2 ("API Service" — temporary downtime/overload) as
+# retry-recommended: https://developers.facebook.com/docs/graph-api/guides/error-handling. Meta
+# also flags some of these transient via ``error.is_transient``, but that flag isn't set
+# consistently — code 2 "Service temporarily unavailable" has been observed with
+# ``is_transient: false`` — so the documented codes are trusted over the flag. 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
+META_TRANSIENT_ERROR_CODES = {1, 2}
def _is_transient_error(response: Response) -> bool:
- """Return True for Meta errors Meta itself flags transient via ``error.is_transient``.
+ """Return True for Meta errors that are momentary backend blips worth retrying immediately.
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.
@@ -311,7 +316,7 @@ def _is_transient_error(response: Response) -> bool:
error = response.json().get("error", {})
except (ValueError, AttributeError):
return False
- return error.get("is_transient") is True
+ return error.get("is_transient") is True or error.get("code") in META_TRANSIENT_ERROR_CODES
# Meta's connection occasionally resets mid-response — `requests` raises these while decoding the
@@ -418,11 +423,18 @@ def _raise_meta_api_error(response: Response) -> typing.NoReturn:
Permanent auth/permission failures raise a clean, user-actionable message
that ``MetaAdsSource.get_non_retryable_errors`` matches on, so the job fails
- fast instead of burning retries. The raw response is appended for debugging.
+ fast instead of burning retries. A momentary backend blip (see
+ ``_is_transient_error``) that has already exhausted its in-process retries is
+ tagged so ``MetaAdsSource.get_retryable_errors`` can keep the self-recovering
+ failure out of error tracking once Temporal retries the activity — excluding
+ the too-much-data timeout, which has its own non-retryable classification since
+ plain retries never resolve it. The raw response is appended for debugging.
Everything else raises the raw response and stays retryable.
"""
if _is_permanent_auth_error(response):
raise Exception(f"{META_AUTH_ERROR_MESSAGE} (Meta API response: {response.status_code} - {response.text})")
+ if _is_transient_error(response) and not _is_timeout_error(response):
+ raise Exception(f"Meta API request failed (retryable): {response.status_code} - {response.text}")
raise Exception(f"Meta API request failed: {response.status_code} - {response.text}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.py
index 09ae90a85b06..d79c9c46411d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/source.py
@@ -134,6 +134,13 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], O
"Please reduce the amount of data you're asking for": None,
}
+ def get_retryable_errors(self) -> set[str]:
+ # Meta error codes 1 ("API Unknown") and 2 ("API Service") are momentary backend blips
+ # Meta's own docs recommend simply retrying. `meta_ads._raise_meta_api_error` tags them
+ # with this marker once `_get_with_transient_retry`'s in-process retries are exhausted, so
+ # the eventual Temporal-level retry doesn't page us as a bug.
+ return {"Meta API request failed (retryable)"}
+
def get_schemas(
self,
config: MetaAdsSourceConfig,
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 c0564a0d27fc..9c559e600bcb 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
@@ -39,6 +39,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.m
_iter_time_range_pagination,
_next_smaller_limit,
_override_limit,
+ _raise_meta_api_error,
_strip_access_token,
get_integration,
list_ad_accounts,
@@ -316,8 +317,9 @@ class TestSimplePaginationLimitFallback:
def test_non_timeout_error_does_not_retry(self) -> None:
manager = _build_manager()
- # Transient service error (code 2) — not a too-much-data error, so no limit fallback.
- responses = [_mock_response(500, {"error": {"message": "Service temporarily unavailable", "code": 2}})]
+ # A generic application error outside Meta's documented transient codes (1, 2) — not a
+ # too-much-data error either, so neither the limit fallback nor the transient retry apply.
+ responses = [_mock_response(500, {"error": {"message": "Something else went wrong", "code": 100}})]
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session"
@@ -396,11 +398,17 @@ class TestIsTransientError:
"body,expected",
[
({"error": {"is_transient": True, "code": 2}}, True),
+ # Meta doesn't always set `is_transient` for code 2 ("API Service") or code 1 ("API
+ # Unknown") — both are documented as momentary backend blips regardless of the flag,
+ # so the code alone must classify these as transient.
+ ({"error": {"code": 2}}, True),
+ ({"error": {"code": 1}}, True),
+ ({"error": {"is_transient": False, "code": 2}}, True),
({"error": {"code": 190}}, False),
({"data": []}, False),
],
)
- def test_reads_transient_flag(self, body: dict, expected: bool) -> None:
+ def test_reads_transient_flag_or_code(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:
@@ -454,12 +462,33 @@ class TestTransientErrorRetry:
"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"):
+ # Still surfaces the raw failure, tagged retryable, so it stays retryable at the
+ # Temporal layer without also re-tracking as a bug (see MetaAdsSource.get_retryable_errors).
+ with pytest.raises(Exception, match=r"Meta API request failed \(retryable\): 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
+ def test_transient_error_without_is_transient_flag_still_retries(self, monkeypatch) -> None:
+ # Real-world Meta responses have been observed sending code 2 "Service temporarily
+ # unavailable" without `is_transient` set true — the documented code alone must still
+ # trigger the in-process retry, not just the flag.
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ responses = [
+ _mock_response(500, {"error": {"message": "Service temporarily unavailable", "code": 2}}),
+ _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
+
class TestNetworkTransientRetry:
INITIAL_URL = "https://graph.facebook.com/v20/act_123/campaigns"
@@ -959,9 +988,10 @@ class TestMidChunkLimitFallback:
"paging": {"next": "https://graph.facebook.com/v20/act_1/insights?after=p1"},
},
),
- # Transient service error (code 2) — not a timeout and not an auth error, so it
- # neither retries-with-smaller-limit nor gets reclassified as permanent.
- _mock_response(500, {"error": {"message": "Service temporarily unavailable", "code": 2}}),
+ # A generic application error outside Meta's documented transient codes (1, 2) — not a
+ # timeout and not an auth error, so it neither retries-with-smaller-limit, retries
+ # transiently, nor gets reclassified as permanent.
+ _mock_response(500, {"error": {"message": "Something else went wrong", "code": 100}}),
]
with mock.patch(
@@ -1193,6 +1223,38 @@ class TestNonRetryableErrors:
assert _is_permanent_auth_error(_mock_response(400, body)) is expected
+class TestRetryableErrors:
+ @pytest.mark.parametrize(
+ "body",
+ [
+ # Real-world Meta responses: code 2 "Service temporarily unavailable" with an
+ # explicit is_transient: false, and a generic code 1 "unknown error" with no flag.
+ {"error": {"message": "Service temporarily unavailable", "code": 2, "is_transient": False}},
+ {"error": {"message": "An unknown error has occurred.", "code": 1}},
+ ],
+ )
+ def test_transient_error_message_matches_retryable_pattern(self, body: dict) -> None:
+ patterns = MetaAdsSource().get_retryable_errors()
+ with pytest.raises(Exception) as exc_info:
+ _raise_meta_api_error(_mock_response(500, body))
+ assert any(pattern in str(exc_info.value) for pattern in patterns)
+
+ def test_too_much_data_timeout_does_not_match_retryable_pattern(self) -> None:
+ # The too-much-data timeout keeps its own non-retryable classification (adaptive chunking
+ # already exhausted) — plain retries never resolve it, so it must not also be tagged
+ # retryable, which would contradict `get_non_retryable_errors`.
+ body = {
+ "error": {
+ "code": 1,
+ "message": "Please reduce the amount of data you're asking for, then retry your request",
+ }
+ }
+ patterns = MetaAdsSource().get_retryable_errors()
+ with pytest.raises(Exception) as exc_info:
+ _raise_meta_api_error(_mock_response(500, body))
+ assert not any(pattern in str(exc_info.value) for pattern in patterns)
+
+
@freeze_time("2026-06-16")
class TestTimeRangeClamping:
"""Meta rejects insights time ranges starting beyond ~37 months (error 3018).