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): tolerate a doubled error body when classifying Meta API failures (#106876)

Tom Owersb19469cd0750
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 bf05ffa79bea..7ea556db1e55 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
@@ -323,18 +323,14 @@ def _is_timeout_error(response: Response) -> bool:
shrink ladders instead of spending retries on a request Meta has already
told us is too big.
"""
- try:
- error = response.json().get("error", {})
-
- if error.get("error_subcode") in META_TIMEOUT_ERROR_SUBCODES:
- return True
+ error = _meta_error_body(response)
+ if _meta_error_subcode(response) in META_TIMEOUT_ERROR_SUBCODES:
+ return True
- # This check is a bit fragile, but the Meta API has been observed to return a 500 response like this:
- # {"error":{"code":1,"message":"Please reduce the amount of data you're asking for, then retry your request"}}
- message = str(error.get("message") or "").lower()
- return error.get("code") == 1 and "reduce the amount of data" in message
- except (ValueError, KeyError, AttributeError):
- return False
+ # This check is a bit fragile, but the Meta API has been observed to return a 500 response like this:
+ # {"error":{"code":1,"message":"Please reduce the amount of data you're asking for, then retry your request"}}
+ message = str(error.get("message") or "").lower()
+ return error.get("code") == 1 and "reduce the amount of data" in message
def _should_shrink_request(response: Response) -> bool:
@@ -347,7 +343,7 @@ def _should_shrink_request(response: Response) -> bool:
"""
if _is_timeout_error(response):
return True
- return _meta_error_body(response).get("error_subcode") in META_HEAVY_QUERY_ERROR_SUBCODES
+ return _meta_error_subcode(response) in META_HEAVY_QUERY_ERROR_SUBCODES
# Meta's error-code reference documents code 1 ("API Unknown" — an unexplained backend hiccup
@@ -369,13 +365,15 @@ def _is_transient_error(response: Response) -> bool:
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):
+ payload = _parse_json_leniently(response)
+ if payload is None:
# A 5xx with no parseable body (occasionally a completely empty response) carries no
# error code to classify by, but a bare server-side failure is itself the signature of
# a momentary blip — unlike a 4xx, which more likely reflects a bad request of ours.
return response.status_code >= 500
+ error = payload.get("error", {})
+ if not isinstance(error, dict):
+ return response.status_code >= 500
return error.get("is_transient") is True or error.get("code") in META_TRANSIENT_ERROR_CODES
@@ -473,12 +471,34 @@ META_INVALID_CURSOR_ERROR_MESSAGE = "Meta's pagination cursor for this sync beca
SHRINK_EXHAUSTED_ERROR_MESSAGE = "Meta could not return this data even at the smallest request size"
-def _meta_error_body(response: Response) -> dict:
- """The ``error`` object of a Meta error response, or an empty dict if it carries none."""
+def _parse_json_leniently(response: Response) -> dict | None:
+ """Parse a Meta API response body as JSON, tolerating trailing garbage after it.
+
+ Meta's backend occasionally appends a second, unrelated error object right after the
+ real one in the same body — the same kind of serialization glitch already handled for
+ truncated 200 bodies elsewhere in this module (see ``MALFORMED_JSON_MAX_ATTEMPTS``).
+ ``response.json()`` rejects the extra data outright ("Extra data" ``JSONDecodeError``),
+ which would otherwise make every classifier below treat an error that is actually
+ classifiable as completely unparseable. Recovering just the leading JSON value keeps
+ classification working for that case. Returns ``None``, same as a genuinely unparseable
+ body, when even the leading value can't be recovered.
+ """
try:
- error = response.json().get("error", {})
+ payload = response.json()
except (ValueError, AttributeError):
- return {}
+ payload = None
+ if payload is None:
+ try:
+ payload, _ = json.JSONDecoder().raw_decode(response.text.lstrip())
+ except (ValueError, TypeError, AttributeError):
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def _meta_error_body(response: Response) -> dict:
+ """The ``error`` object of a Meta error response, or an empty dict if it carries none."""
+ payload = _parse_json_leniently(response)
+ error = payload.get("error", {}) if isinstance(payload, dict) else {}
return error if isinstance(error, dict) else {}
@@ -488,6 +508,17 @@ def _meta_error_code(response: Response) -> int | None:
return code if isinstance(code, int) else None
+def _meta_error_subcode(response: Response) -> int | None:
+ """The numeric ``error.error_subcode`` of a Meta error body, or None if it carries no parseable one.
+
+ Guards against a non-numeric value (Meta's error bodies are not contractually typed) before
+ the callers below test it for set membership, which raises ``TypeError`` on an unhashable
+ value like a list.
+ """
+ subcode = _meta_error_body(response).get("error_subcode")
+ return subcode if isinstance(subcode, int) else None
+
+
def _is_permanent_auth_error(response: Response) -> bool:
"""Return True for Meta errors that only re-authorization can fix.
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 a19e63af6416..fdcf5000daad 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
@@ -42,6 +42,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.m
_fetch_integration_row,
_is_invalid_cursor_error,
_is_permanent_auth_error,
+ _is_timeout_error,
_is_transient_error,
_iter_simple_pagination,
_iter_time_range_pagination,
@@ -49,6 +50,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.m
_next_smaller_limit,
_override_limit,
_raise_meta_api_error,
+ _should_shrink_request,
_strip_access_token,
get_integration,
get_schemas as get_meta_ads_schemas,
@@ -84,6 +86,18 @@ def _mock_truncated_response() -> mock.MagicMock:
return response
+def _mock_response_with_trailing_garbage(status: int, body: dict) -> mock.MagicMock:
+ # Meta has been observed appending a second, unrelated error object right after the real
+ # one in the same error response body. `.json()` rejects the extra data ("Extra data"
+ # JSONDecodeError), even though the leading object is well-formed.
+ text = json.dumps(body) + '{"error":{"code":1,"message":"An unknown error occurred","error_subcode":99}}'
+ response = mock.MagicMock()
+ response.status_code = status
+ response.json.side_effect = RequestsJSONDecodeError("Extra data", text, len(json.dumps(body)))
+ response.text = text
+ 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
@@ -444,6 +458,27 @@ class TestIsTransientError:
response.json.side_effect = RequestsJSONDecodeError("Expecting value", "<html>", 0)
assert _is_transient_error(response) is False
+ def test_trailing_garbage_after_body_still_reads_leading_error(self) -> None:
+ # Real-world shape: Meta returns a well-formed error object followed by a second,
+ # unrelated one in the same body. `response.json()` rejects the extra data outright,
+ # which must not make an otherwise-classifiable transient error read as unclassifiable.
+ response = _mock_response_with_trailing_garbage(
+ 400, {"error": {"message": "Service temporarily unavailable", "code": 2, "is_transient": False}}
+ )
+ assert _is_transient_error(response) is True
+
+
+class TestNonIntErrorSubcode:
+ def test_list_valued_subcode_does_not_crash_timeout_check(self) -> None:
+ # error_subcode is not contractually typed; a list value would raise TypeError on
+ # set-membership (`in`) if tested unguarded, aborting classification entirely.
+ body = {"error": {"error_subcode": [1504018], "message": "timeout"}}
+ assert _is_timeout_error(_mock_response(500, body)) is False
+
+ def test_list_valued_subcode_does_not_crash_shrink_check(self) -> None:
+ body = {"error": {"error_subcode": [1504044], "code": 2}}
+ assert _should_shrink_request(_mock_response(400, body)) is False
+
class TestTransientErrorRetry:
INITIAL_URL = "https://graph.facebook.com/v20/act_123/campaigns"
@@ -849,6 +884,47 @@ class TestTimeRangePagination:
"until": "2026-03-07",
}
+ def test_heavy_query_subcode_with_trailing_garbage_retries_then_shrinks_chunk(self, monkeypatch) -> None:
+ # Same production shape as test_heavy_query_subcode_retries_unchanged_then_shrinks_chunk,
+ # but Meta appended a second, unrelated error object after the real one in the body. That
+ # extra data must not stop the request from retrying and shrinking like the clean case —
+ # without the fix this raised an unclassified, non-retrying exception on the first attempt.
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ heavy_body = {
+ "error": {
+ "message": "Service temporarily unavailable",
+ "type": "OAuthException",
+ "is_transient": False,
+ "code": 2,
+ "error_subcode": 1504044,
+ }
+ }
+ responses = [
+ _mock_response_with_trailing_garbage(400, heavy_body) for _ in range(META_TRANSIENT_ERROR_MAX_ATTEMPTS)
+ ] + [_mock_response(200, {"data": [{"ad_id": str(i)}], "paging": {}}) for i in range(1, 6)]
+
+ 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_time_range_pagination(
+ self.URL,
+ self.PARAMS,
+ {"since": "2026-03-01", "until": "2026-03-30"},
+ None,
+ manager,
+ )
+ )
+
+ assert [b[0]["ad_id"] for b in batches] == ["1", "2", "3", "4", "5"]
+ calls = mock_get.return_value.get.call_args_list
+ assert json.loads(calls[META_TRANSIENT_ERROR_MAX_ATTEMPTS].kwargs["params"]["time_range"]) == {
+ "since": "2026-03-01",
+ "until": "2026-03-07",
+ }
+
def test_exhausting_both_ladders_on_initial_chunk_raises_non_retryable(self) -> None:
manager = _build_manager()
timeout_body = {"error": {"error_subcode": 1504018, "message": "timeout"}}