: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): shrink insights requests on Meta's unknown-error subcode (#74286)
Jordan Mryyan5b3728c06f17
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 7973e1d6fb2a..6ecea7e36b98 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@@ -228,6 +228,15 @@ def get_schemas() -> dict[str, MetaAdsSchema]:# https://developers.facebook.com/docs/marketing-api/insights/error-codesMETA_TIMEOUT_ERROR_SUBCODES = {1504018, 1504038}+# Subcode 1504044 ("Unknown Error Occurred") is documented alongside the timeouts+# above, with the same remedy: ask for less data. It arrives as `code: 2` with+# `message: "Service temporarily unavailable"`, so without this set it reads as a+# momentary blip and only ever gets retried unchanged. Kept separate from the+# timeouts because it really can be one, and is worth a few unchanged retries+# before we start shrinking.+# https://developers.facebook.com/docs/marketing-api/insights/error-codes+META_HEAVY_QUERY_ERROR_SUBCODES = {1504044}+# Chunk sizes for adaptive time-range pagination (in days)# Start with 30-day chunks, fall back to smaller chunks on timeoutTIME_RANGE_CHUNK_SIZES = [30, 7, 1]@@ -278,7 +287,13 @@ def _next_smaller_limit(current: int) -> int | None:def _is_timeout_error(response: Response) -> bool:- """Check if the response is a Meta API timeout error that can be resolved with smaller date ranges."""+ """Check if the response is a Meta API timeout error that can be resolved with smaller date ranges.++ Deliberately narrower than ``_should_shrink_request``: these subcodes are+ unambiguous, so ``_get_with_transient_retry`` hands them straight to the+ shrink ladders instead of spending retries on a request Meta has already+ told us is too big.+ """try:error = response.json().get("error", {})@@ -293,6 +308,19 @@ def _is_timeout_error(response: Response) -> bool:return False+def _should_shrink_request(response: Response) -> bool:+ """Return True for failures a smaller date range or page size can resolve.++ Covers the unambiguous timeouts plus the heavy-query subcodes, which reach+ here only after ``_get_with_transient_retry`` has spent its unchanged+ retries on them without the error clearing. A failure that survives those is+ not the momentary blip Meta's error body claims.+ """+ if _is_timeout_error(response):+ return True+ return _meta_error_body(response).get("error_subcode") in META_HEAVY_QUERY_ERROR_SUBCODES++# 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@@ -391,14 +419,23 @@ META_RATE_LIMIT_ERROR_MESSAGE = ("Meta is rate limiting requests for this connection. Please wait a few minutes and try again.")+# Matched by `MetaAdsSource.get_non_retryable_errors`, so it has to stay in sync+# with the key there.+SHRINK_EXHAUSTED_ERROR_MESSAGE = "Meta could not return this data even at the smallest request size"-def _meta_error_code(response: Response) -> int | None:- """The numeric ``error.code`` of a Meta error body, or None if it carries no parseable one."""++def _meta_error_body(response: Response) -> dict:+ """The ``error`` object of a Meta error response, or an empty dict if it carries none."""try:error = response.json().get("error", {})except (ValueError, AttributeError):- return None- code = error.get("code")+ return {}+ return error if isinstance(error, dict) else {}+++def _meta_error_code(response: Response) -> int | None:+ """The numeric ``error.code`` of a Meta error body, or None if it carries no parseable one."""+ code = _meta_error_body(response).get("code")return code if isinstance(code, int) else None@@ -426,18 +463,31 @@ def _raise_meta_api_error(response: Response) -> typing.NoReturn:fast instead of burning retries. A momentary backend blip (see``_is_transient_error``) that has already exhausted its in-process retries istagged 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.+ failure out of error tracking once Temporal retries the activity, excluding+ anything the shrink ladders can still act on, which ends at+ ``_raise_shrink_exhausted_error`` instead. 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):+ if _is_transient_error(response) and not _should_shrink_request(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}")+def _raise_shrink_exhausted_error(response: Response) -> typing.NoReturn:+ """Raise once both shrink ladders have bottomed out and Meta still refuses.++ Terminal on purpose: the date range is down to a single day and the page+ size to its smallest rung, so the next Temporal retry would re-issue exactly+ the request that just failed. ``MetaAdsSource.get_non_retryable_errors``+ matches on the message, so the job stops and tells the user what to change+ rather than retrying against the schedule forever.+ """+ raise Exception(f"{SHRINK_EXHAUSTED_ERROR_MESSAGE} (Meta API response: {response.status_code} - {response.text})")++class MetaAdsAuthError(Exception):"""Meta rejected the credentials or the permissions they carry (see `_is_permanent_auth_error`)."""@@ -563,12 +613,13 @@ def _iter_simple_pagination(# Too-much-data: shrink the page limit and retry the same request.# Re-issuing the same URL/cursor at a smaller limit is safe — no# already-yielded rows are re-emitted.- if _is_timeout_error(response):+ if _should_shrink_request(response):smaller = _next_smaller_limit(current_limit)if smaller is not None:current_limit = smallerresponse = _issue()continue+ _raise_shrink_exhausted_error(response)_raise_meta_api_error(response)try:@@ -687,11 +738,20 @@ def _iter_time_range_pagination(if response.status_code != 200:# Fallback only happens on the initial chunk request (before any data is yielded).- if _is_timeout_error(response) and chunk_size_days in TIME_RANGE_CHUNK_SIZES:- current_index = TIME_RANGE_CHUNK_SIZES.index(chunk_size_days)- if current_index < len(TIME_RANGE_CHUNK_SIZES) - 1:- chunk_size_days = TIME_RANGE_CHUNK_SIZES[current_index + 1]+ if _should_shrink_request(response):+ if chunk_size_days in TIME_RANGE_CHUNK_SIZES:+ current_index = TIME_RANGE_CHUNK_SIZES.index(chunk_size_days)+ if current_index < len(TIME_RANGE_CHUNK_SIZES) - 1:+ chunk_size_days = TIME_RANGE_CHUNK_SIZES[current_index + 1]+ continue+ # The date range is already a single day, so the page size+ # is the only dimension left. Re-issuing the same chunk at a+ # smaller limit is safe: nothing has been yielded yet.+ smaller_limit = _next_smaller_limit(current_limit)+ if smaller_limit is not None:+ current_limit = smaller_limitcontinue+ _raise_shrink_exhausted_error(response)_raise_meta_api_error(response)malformed_json_attempts = 0@@ -700,13 +760,14 @@ def _iter_time_range_pagination(# Mid-chunk timeout: retry the same cursor URL with a smaller# ``limit``. Re-issuing earlier pages (i.e. shrinking the# chunk) is not safe here — we've already yielded them.- if _is_timeout_error(response) and last_paging_url is not None:+ if _should_shrink_request(response) and last_paging_url is not None:smaller = _next_smaller_limit(current_limit)if smaller is not None:current_limit = smallerretry_url = _override_limit(last_paging_url, current_limit)response = _fetch_paging_url(retry_url, access_token)continue+ _raise_shrink_exhausted_error(response)_raise_meta_api_error(response)try: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.pyindex b3687a25e84e..a0020cac4885 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@@ -39,6 +39,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads import (META_AUTH_ERROR_MESSAGE,+ SHRINK_EXHAUSTED_ERROR_MESSAGE,MetaAdsAuthError,MetaAdsRateLimitError,MetaAdsResumeConfig,@@ -129,6 +130,14 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], O# both paths shrink the per-page limit 500 → 100 → 50); if it still escapes after those# fallbacks are exhausted, retrying the whole job won't help."Please reduce the amount of data you're asking for": None,+ # Raised by `meta_ads._raise_shrink_exhausted_error` once both ladders+ # have bottomed out. The next attempt would re-issue the identical+ # single-day, smallest-page request that just failed, so the only thing+ # left is for the user to narrow the sync window.+ SHRINK_EXHAUSTED_ERROR_MESSAGE: (+ "Meta couldn't return this data even at the smallest request size. Lower the sync "+ "history for insights in your Meta Ads source settings, then run the sync again."+ ),}def get_retryable_errors(self) -> set[str]: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 9c559e600bcb..e757903a8895 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@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mMETA_AUTH_ERROR_MESSAGE,META_TRANSIENT_ERROR_MAX_ATTEMPTS,PAGE_LIMIT_FALLBACK_SIZES,+ SHRINK_EXHAUSTED_ERROR_MESSAGE,MetaAdsAuthError,MetaAdsResumeConfig,_earliest_supported_since,@@ -309,7 +310,8 @@ class TestSimplePaginationLimitFallback:"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- with pytest.raises(Exception, match="Meta API request failed: 500"):+ # Terminal: the next attempt would re-issue the same request.+ with pytest.raises(Exception, match=SHRINK_EXHAUSTED_ERROR_MESSAGE):list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))# One attempt per rung, then it gives up.@@ -783,6 +785,70 @@ class TestTimeRangePagination:tr = json.loads(mock_get.return_value.get.call_args_list[1].kwargs["params"]["time_range"])assert tr == {"since": "2026-03-01", "until": "2026-03-07"}+ def test_heavy_query_subcode_retries_unchanged_then_shrinks_chunk(self, monkeypatch) -> None:+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)+ manager = _build_manager()+ # Production shape: labeled code 2, so it retries unchanged before shrinking.+ heavy_body = {+ "error": {+ "message": "Service temporarily unavailable",+ "type": "OAuthException",+ "is_transient": False,+ "code": 2,+ "error_subcode": 1504044,+ }+ }+ responses = [_mock_response(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+ for call in calls[:META_TRANSIENT_ERROR_MAX_ATTEMPTS]:+ assert json.loads(call.kwargs["params"]["time_range"]) == {"since": "2026-03-01", "until": "2026-03-30"}+ 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"}}+ # Three chunk rungs, then two page-limit rungs once the chunk hits one day.+ responses = [_mock_response(500, timeout_body) for _ in range(5)]++ 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+ with pytest.raises(Exception, match=SHRINK_EXHAUSTED_ERROR_MESSAGE):+ list(+ _iter_time_range_pagination(+ self.URL,+ self.PARAMS,+ {"since": "2026-03-01", "until": "2026-03-30"},+ None,+ manager,+ )+ )++ limits = [call.kwargs["params"]["limit"] for call in mock_get.return_value.get.call_args_list]+ assert limits == [500, 500, 500, 100, 50]+class TestOverrideLimit:@pytest.mark.parametrize(@@ -975,7 +1041,7 @@ class TestMidChunkLimitFallback:)# Drain the first batch (which succeeds), then expect the failure.assert next(gen) == [{"ad_id": "1"}]- with pytest.raises(Exception, match="Meta API request failed: 500"):+ with pytest.raises(Exception, match=SHRINK_EXHAUSTED_ERROR_MESSAGE):list(gen)def test_non_timeout_mid_chunk_error_does_not_retry(self) -> None:@@ -1184,6 +1250,10 @@ class TestNonRetryableErrors:# 500 when Meta's backend refuses to service the query even after adaptive# chunking has shrunk the window to its smallest size.'Meta API request failed: 500 - {"error":{"code":1,"message":"Please reduce the amount of data you\'re asking for, then retry your request"}}',+ # Both shrink ladders bottomed out, so the next attempt would re-issue+ # the identical single-day, smallest-page request that just failed.+ f"{SHRINK_EXHAUSTED_ERROR_MESSAGE} (Meta API response: 400 - "+ '{"error":{"message":"Service temporarily unavailable","code":2,"error_subcode":1504044}})',# code 190 / subcode 459 — account checkpoint, the user must log in to Facebook.f"{META_AUTH_ERROR_MESSAGE} (Meta API response: 400 - "'{"error":{"message":"You cannot access the app till you log in to www.facebook.com and follow the '