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 a batch node lookup aborted by Meta's own timeout (#120805)

Tom Owers7344cc8278a3
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 425594542580..6b70ffdb1cf5 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
@@ -719,6 +719,32 @@ def _is_refused_batch_subresponse(error: typing.Any) -> bool:
return isinstance(subcode, int) and subcode in META_REFUSED_CREATIVE_ERROR_SUBCODES
+# Meta's batch endpoint can abort one subrequest on its own, independently of the rest of the
+# batch and of the overall call returning 200 — observed as code 960, "Request aborted. This could
+# happen if a dependent request failed or the entire request timed out." Our subrequests have no
+# JSONPath dependencies between them, so the cause is the batch nearing a timeout rather than the
+# lookup itself being invalid. `_get_with_transient_retry` never sees this: it only inspects the
+# outer HTTP response, and that response is a plain 200.
+META_BATCH_SUBREQUEST_ABORTED_ERROR_CODE = 960
+
+
+def _is_transient_batch_subresponse_error(sub_response: typing.Any, error: typing.Any) -> bool:
+ """Return True for a batch subresponse worth retrying the whole batch for (see above).
+
+ Meta also leaves a subresponse ``None`` for a subrequest it hadn't gotten back to before the
+ batch call itself ran out of time, which carries no error object to inspect — the same
+ batch-timeout condition as code 960, just without a body to classify.
+ """
+ if sub_response is None:
+ return True
+ if not isinstance(error, dict):
+ return False
+ return error.get("is_transient") is True or error.get("code") in (
+ *META_TRANSIENT_ERROR_CODES,
+ META_BATCH_SUBREQUEST_ABORTED_ERROR_CODE,
+ )
+
+
def _fetch_refusable_fields(
node_lookup_url: str, ids: list[str], fields: tuple[str, ...], access_token: str
) -> dict[str, dict]:
@@ -745,6 +771,7 @@ def _fetch_refusable_fields(
return make_tracked_session().post(node_lookup_url, data=data)
malformed_json_attempts = 0
+ transient_subresponse_attempts = 0
while True:
response = _get_with_transient_retry(_issue)
if response.status_code != 200:
@@ -756,14 +783,35 @@ def _fetch_refusable_fields(
if malformed_json_attempts >= MALFORMED_JSON_MAX_ATTEMPTS:
raise
continue
+
+ parsed_sub_responses: list[tuple[dict | None, typing.Any, dict | None]] = []
+ for sub_response in sub_responses:
+ if sub_response is None:
+ parsed_sub_responses.append((None, None, None))
+ continue
+ try:
+ body = json.loads(sub_response.get("body") or "{}")
+ except (ValueError, TypeError):
+ body = None
+ error = body.get("error") if isinstance(body, dict) else None
+ parsed_sub_responses.append((sub_response, body, error))
+
+ has_transient_error = any(
+ _is_transient_batch_subresponse_error(sub_response, error)
+ for sub_response, _body, error in parsed_sub_responses
+ )
+ if has_transient_error and transient_subresponse_attempts < META_TRANSIENT_ERROR_MAX_ATTEMPTS - 1:
+ transient_subresponse_attempts += 1
+ _backoff_sleep(transient_subresponse_attempts)
+ continue
break
- for node_id, sub_response in zip(chunk, sub_responses):
- try:
- body = json.loads(sub_response.get("body") or "{}")
- except (ValueError, TypeError):
- body = None
- error = body.get("error") if isinstance(body, dict) else None
+ for node_id, (sub_response, body, error) in zip(chunk, parsed_sub_responses):
+ if sub_response is None:
+ raise Exception(
+ f"Meta API request failed: node lookup error - subrequest for node {node_id} "
+ "never completed before the batch call timed out"
+ )
if sub_response.get("code") == 200 and isinstance(body, dict):
nodes[node_id] = body
elif _is_refused_batch_subresponse(error):
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 a8b374a8a428..309f58feaef7 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
@@ -364,6 +364,16 @@ class TestSimplePaginationRefusedFields:
response.text = ""
return response
+ @staticmethod
+ def _null_batch_response() -> mock.MagicMock:
+ # Meta leaves a subresponse `null` for a subrequest it hadn't gotten back to before the
+ # whole batch call ran out of time.
+ response = mock.MagicMock()
+ response.status_code = 200
+ response.json.return_value = [None]
+ response.text = ""
+ return response
+
@pytest.mark.parametrize("subcode", [2446211, 1443048])
def test_refused_row_syncs_without_refusable_fields(self, subcode: int) -> None:
manager = _build_manager()
@@ -432,6 +442,113 @@ class TestSimplePaginationRefusedFields:
)
)
+ def test_batch_subresponse_transient_error_retries_whole_batch(self, monkeypatch) -> None:
+ # Meta can abort a single batch subrequest on its own, even though the overall batch call
+ # returns 200 — code 960, "Request aborted. This could happen if a dependent request failed
+ # or the entire request timed out." Our subrequests have no dependency on one another, so
+ # this is the batch nearing a timeout rather than the lookup itself being invalid.
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ aborted_body = {"error": {"message": "Request aborted.", "code": 960, "fbtrace_id": "abc123"}}
+ get_responses = [
+ _mock_response(400, self.REFUSED_BODY),
+ _mock_response(200, {"data": [{"id": "1", "name": "a"}], "paging": {}}),
+ ]
+ batch_responses = [
+ self._batch_response([(500, aborted_body)]),
+ self._batch_response([(200, {"id": "1", "creative": {"id": "c1"}})]),
+ ]
+
+ 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 = get_responses
+ mock_get.return_value.post.side_effect = batch_responses
+ batches = list(
+ _iter_simple_pagination(
+ self.INITIAL_URL, self.PARAMS, None, manager, ("creative",), self.NODE_LOOKUP_URL
+ )
+ )
+
+ assert batches == [[{"id": "1", "name": "a", "creative": {"id": "c1"}}]]
+ assert mock_get.return_value.post.call_count == 2
+
+ def test_persistent_batch_subresponse_transient_error_raises_after_bounded_attempts(self, monkeypatch) -> None:
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ aborted_body = {"error": {"message": "Request aborted.", "code": 960, "fbtrace_id": "abc123"}}
+ get_responses = [
+ _mock_response(400, self.REFUSED_BODY),
+ _mock_response(200, {"data": [{"id": "1", "name": "a"}], "paging": {}}),
+ ]
+ batch_responses = [
+ self._batch_response([(500, aborted_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 = get_responses
+ mock_get.return_value.post.side_effect = batch_responses
+ # Still surfaces the raw failure, so it stays retryable at the Temporal layer.
+ with pytest.raises(Exception, match="node lookup error"):
+ list(
+ _iter_simple_pagination(
+ self.INITIAL_URL, self.PARAMS, None, manager, ("creative",), self.NODE_LOOKUP_URL
+ )
+ )
+
+ assert mock_get.return_value.post.call_count == META_TRANSIENT_ERROR_MAX_ATTEMPTS
+
+ def test_batch_null_subresponse_retries_then_succeeds(self, monkeypatch) -> None:
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ get_responses = [
+ _mock_response(400, self.REFUSED_BODY),
+ _mock_response(200, {"data": [{"id": "1", "name": "a"}], "paging": {}}),
+ ]
+ batch_responses = [
+ self._null_batch_response(),
+ self._batch_response([(200, {"id": "1", "creative": {"id": "c1"}})]),
+ ]
+
+ 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 = get_responses
+ mock_get.return_value.post.side_effect = batch_responses
+ batches = list(
+ _iter_simple_pagination(
+ self.INITIAL_URL, self.PARAMS, None, manager, ("creative",), self.NODE_LOOKUP_URL
+ )
+ )
+
+ assert batches == [[{"id": "1", "name": "a", "creative": {"id": "c1"}}]]
+ assert mock_get.return_value.post.call_count == 2
+
+ def test_persistent_batch_null_subresponse_raises_after_bounded_attempts(self, monkeypatch) -> None:
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ get_responses = [
+ _mock_response(400, self.REFUSED_BODY),
+ _mock_response(200, {"data": [{"id": "1", "name": "a"}], "paging": {}}),
+ ]
+ batch_responses = [self._null_batch_response() 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 = get_responses
+ mock_get.return_value.post.side_effect = batch_responses
+ with pytest.raises(Exception, match="node lookup error"):
+ list(
+ _iter_simple_pagination(
+ self.INITIAL_URL, self.PARAMS, None, manager, ("creative",), self.NODE_LOOKUP_URL
+ )
+ )
+
+ assert mock_get.return_value.post.call_count == META_TRANSIENT_ERROR_MAX_ATTEMPTS
+
def test_restore_lookup_chunks_at_batch_limit(self) -> None:
# Meta's batch endpoint accepts at most META_BATCH_MAX_SUBREQUESTS (50) subrequests per
# call, so restoring fields for more ids than that must split across multiple POSTs.