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): keep entity syncs retryable when meta refuses the smallest page (#110905)

Kyle Swank2ca2acc7938b
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 7ea556db1e55..6e48d61117ff 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
@@ -470,6 +470,14 @@ META_INVALID_CURSOR_ERROR_MESSAGE = "Meta's pagination cursor for this sync beca
# with the key there.
SHRINK_EXHAUSTED_ERROR_MESSAGE = "Meta could not return this data even at the smallest request size"
+# Entity endpoints (campaigns, ads, ad creatives, ...) have no date range to narrow, so the page
+# limit is the only lever. When Meta still refuses the smallest page, the cause is load on Meta's
+# side, and the same request later succeeds. So the entity path retries the smallest page with
+# backoff, then raises this retryable marker. Temporal then resumes from the saved cursor, and the
+# schema stays enabled for the next scheduled sync.
+ENTITY_PAGE_REFUSED_ERROR_MESSAGE = "Meta could not return this page even at the smallest page size (retryable)"
+SMALLEST_PAGE_LIMIT_MAX_RETRIES = 3
+
def _parse_json_leniently(response: Response) -> dict | None:
"""Parse a Meta API response body as JSON, tolerating trailing garbage after it.
@@ -585,6 +593,20 @@ def _raise_shrink_exhausted_error(response: Response) -> typing.NoReturn:
raise Exception(f"{SHRINK_EXHAUSTED_ERROR_MESSAGE} (Meta API response: {response.status_code} - {response.text})")
+def _raise_entity_page_refused_error(response: Response) -> typing.NoReturn:
+ """Raise once the entity path has retried its smallest page and Meta still refuses it.
+
+ The message leaves out ``response.text`` on purpose. Meta's body carries "Please reduce the
+ amount of data you're asking for", which ``MetaAdsSource.get_non_retryable_errors`` matches
+ before the retryable patterns, so including it would disable the schema again.
+ """
+ error = _meta_error_body(response)
+ raise Exception(
+ f"{ENTITY_PAGE_REFUSED_ERROR_MESSAGE} (Meta API response: {response.status_code}, "
+ f"code {error.get('code')}, subcode {error.get('error_subcode')}, fbtrace_id {error.get('fbtrace_id')})"
+ )
+
+
class MetaAdsAuthError(Exception):
"""Meta rejected the credentials or the permissions they carry (see `_is_permanent_auth_error`)."""
@@ -677,6 +699,8 @@ def _iter_simple_pagination(
fails on those accounts. Retrying the same URL at a smaller limit never
re-emits already-yielded rows — the initial request has yielded nothing
yet, and a cursor points at the start of the next (not-yet-yielded) page.
+ If the smallest limit still fails, the page is retried with backoff and
+ then raised as retryable (see ``ENTITY_PAGE_REFUSED_ERROR_MESSAGE``).
"""
access_token = params["access_token"]
current_limit = PAGE_LIMIT_FALLBACK_SIZES[0]
@@ -704,6 +728,7 @@ def _iter_simple_pagination(
response = _issue()
malformed_json_attempts = 0
+ smallest_limit_retries = 0
while True:
if response.status_code != 200:
@@ -716,7 +741,12 @@ def _iter_simple_pagination(
current_limit = smaller
response = _issue()
continue
- _raise_shrink_exhausted_error(response)
+ if smallest_limit_retries < SMALLEST_PAGE_LIMIT_MAX_RETRIES:
+ smallest_limit_retries += 1
+ _backoff_sleep(smallest_limit_retries)
+ response = _issue()
+ continue
+ _raise_entity_page_refused_error(response)
_raise_meta_api_error(response)
try:
@@ -734,6 +764,7 @@ def _iter_simple_pagination(
response = _issue()
continue
malformed_json_attempts = 0
+ smallest_limit_retries = 0
yield response_payload.get("data", [])
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 4302bc996472..dbf8b4fcb01a 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
@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
MetaAdsSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads import (
+ ENTITY_PAGE_REFUSED_ERROR_MESSAGE,
META_ADS_API_VERSION_V25,
META_ADS_API_VERSION_V26,
META_AUTH_ERROR_MESSAGE,
@@ -194,6 +195,7 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], O
# for volume. Only waiting helps, and the sync already retries via Temporal, so this
# shouldn't page us as a bug either.
META_RATE_LIMIT_ERROR_MESSAGE,
+ ENTITY_PAGE_REFUSED_ERROR_MESSAGE,
}
def get_retry_exhausted_errors(self) -> dict[str, str]:
@@ -209,6 +211,10 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], O
"Meta is rate limiting requests for this connection, so this sync run did not finish. "
"The next sync runs on schedule."
),
+ ENTITY_PAGE_REFUSED_ERROR_MESSAGE: (
+ "Meta was too busy to return this table's data, so this sync run did not finish. "
+ "This usually clears on its own and the next sync runs on schedule."
+ ),
}
def get_schemas(
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 fdcf5000daad..34104ca96d70 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
@@ -13,7 +13,10 @@ from requests.exceptions import (
JSONDecodeError as RequestsJSONDecodeError,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import VersionDeprecation
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ VersionDeprecation,
+ error_message_matches,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
IntegrationAccountListingError,
)
@@ -25,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads import meta_ads as meta_ads_module
from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads import (
AD_ACCOUNT_LISTING_TIMEOUT_SECONDS,
+ ENTITY_PAGE_REFUSED_ERROR_MESSAGE,
MALFORMED_JSON_MAX_ATTEMPTS,
MAX_AD_ACCOUNT_PAGES,
META_ADS_API_VERSION_V25,
@@ -36,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.m
META_TRANSIENT_ERROR_MAX_ATTEMPTS,
PAGE_LIMIT_FALLBACK_SIZES,
SHRINK_EXHAUSTED_ERROR_MESSAGE,
+ SMALLEST_PAGE_LIMIT_MAX_RETRIES,
MetaAdsAuthError,
MetaAdsResumeConfig,
_earliest_supported_since,
@@ -329,21 +334,49 @@ class TestSimplePaginationLimitFallback:
== "https://graph.facebook.com/v20/next?after=p1&limit=100"
)
- def test_exhausting_limit_ladder_raises(self) -> None:
+ def test_exhausting_limit_ladder_raises_retryable_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
manager = _build_manager()
- # Every rung in PAGE_LIMIT_FALLBACK_SIZES returns the too-much-data error.
- responses = [_mock_response(500, self.REDUCE_BODY) for _ in PAGE_LIMIT_FALLBACK_SIZES]
+ attempts = len(PAGE_LIMIT_FALLBACK_SIZES) + SMALLEST_PAGE_LIMIT_MAX_RETRIES
+ responses = []
+ for _ in range(attempts):
+ response = _mock_response(500, self.REDUCE_BODY)
+ # The real body carries Meta's "reduce the amount of data" text, which is a
+ # non-retryable pattern, so the raised error must not echo it.
+ response.text = json.dumps(self.REDUCE_BODY)
+ responses.append(response)
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
- # Terminal: the next attempt would re-issue the same request.
- with pytest.raises(Exception, match=SHRINK_EXHAUSTED_ERROR_MESSAGE):
+ with pytest.raises(Exception) as exc_info:
list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))
- # One attempt per rung, then it gives up.
- assert mock_get.return_value.get.call_count == len(PAGE_LIMIT_FALLBACK_SIZES)
+ assert mock_get.return_value.get.call_count == attempts
+ error_message = str(exc_info.value)
+ assert ENTITY_PAGE_REFUSED_ERROR_MESSAGE in error_message
+ source = MetaAdsSource()
+ assert not error_message_matches(error_message, source.get_non_retryable_errors())
+ assert error_message_matches(error_message, source.get_retryable_errors())
+
+ def test_smallest_limit_recovers_after_backoff(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)
+ manager = _build_manager()
+ refusals = len(PAGE_LIMIT_FALLBACK_SIZES) + SMALLEST_PAGE_LIMIT_MAX_RETRIES - 1
+ responses = [
+ *(_mock_response(500, self.REDUCE_BODY) for _ in range(refusals)),
+ _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_args_list[-1].kwargs["params"]["limit"] == PAGE_LIMIT_FALLBACK_SIZES[-1]
def test_non_timeout_error_does_not_retry(self) -> None:
manager = _build_manager()
@@ -1591,6 +1624,11 @@ class TestRetryableErrors:
'"fbtrace_id":"AaBbCcDdEeFf00112233"}})',
"rate limiting",
),
+ (
+ f"{ENTITY_PAGE_REFUSED_ERROR_MESSAGE} (Meta API response: 500, code 1, subcode None, "
+ "fbtrace_id AaBbCcDdEeFf00112233)",
+ "too busy",
+ ),
],
)
def test_retry_exhausted_message_replaces_the_raw_meta_response(