: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(warehouse-sources): stop retrying an invalidated meta ads pagination cursor (#103420)
Tom Owerscb5e26442526
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 923ac648e01b..bf05ffa79bea 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@@ -450,6 +450,14 @@ META_UNSUPPORTED_GET_REQUEST_MESSAGE = "unsupported get request"# https://developers.facebook.com/docs/graph-api/overview/rate-limitingMETA_RATE_LIMIT_ERROR_CODES = {4, 17, 32, 613}+# Meta error code 2642: the `paging.next` cursor used to follow a page was rejected as invalid.+# Terminal for this job — `_iter_time_range_pagination`/`_iter_simple_pagination` save that same+# cursor to resumable state before fetching it, so a Temporal retry of this job would resume with+# the identical cursor and fail the same way every time. A later sync run gets a fresh job id (and+# so a fresh resumable-state key, see `ResumableSourceManager`), which starts pagination from+# scratch with a new cursor.+META_INVALID_CURSOR_ERROR_CODE = 2642+META_AUTH_ERROR_MESSAGE = ("Meta Ads access token is invalid, expired, or lacks the required permissions. Please re-authorize the integration.")@@ -458,6 +466,8 @@ META_RATE_LIMIT_ERROR_MESSAGE = ("Meta is rate limiting requests for this connection. Please wait a few minutes and try again.")+META_INVALID_CURSOR_ERROR_MESSAGE = "Meta's pagination cursor for this sync became invalid. Please run the sync 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"@@ -497,6 +507,12 @@ def _is_rate_limit_error(response: Response) -> bool:return _meta_error_code(response) in META_RATE_LIMIT_ERROR_CODES+def _is_invalid_cursor_error(response: Response) -> bool:+ """Return True for Meta's "Invalid cursors values" error (code 2642), which retrying this+ job can't recover from — see `META_INVALID_CURSOR_ERROR_CODE`."""+ return _meta_error_code(response) == META_INVALID_CURSOR_ERROR_CODE++def _raise_meta_api_error(response: Response) -> typing.NoReturn:"""Raise a descriptive exception for a non-200 Meta API response.@@ -517,6 +533,10 @@ def _raise_meta_api_error(response: Response) -> typing.NoReturn:raise Exception(f"{META_RATE_LIMIT_ERROR_MESSAGE} (Meta API response: {response.status_code} - {response.text})")+ if _is_invalid_cursor_error(response):+ raise Exception(+ f"{META_INVALID_CURSOR_ERROR_MESSAGE} (Meta API response: {response.status_code} - {response.text})"+ )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}")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 70f9f3320ba6..33ddf777a68d 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@@ -43,6 +43,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mMETA_ADS_API_VERSION_V25,META_ADS_API_VERSION_V26,META_AUTH_ERROR_MESSAGE,+ META_INVALID_CURSOR_ERROR_MESSAGE,META_RATE_LIMIT_ERROR_MESSAGE,SHRINK_EXHAUSTED_ERROR_MESSAGE,MetaAdsAuthError,@@ -174,6 +175,12 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], O"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."),+ # Graph API code 2642: the pagination cursor was rejected as invalid. The resumable+ # source manager would resume this exact job with the same saved cursor and fail the+ # same way every time, so retrying is pointless — only a fresh sync run (a new job,+ # with a fresh cursor) can recover. `meta_ads._raise_meta_api_error` raises this+ # message for that code.+ META_INVALID_CURSOR_ERROR_MESSAGE: META_INVALID_CURSOR_ERROR_MESSAGE,}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 de60d2199437..7e84c1f5c3ec 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@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mMETA_ADS_API_VERSION_V26,META_ADS_MAX_HISTORY_DAYS,META_AUTH_ERROR_MESSAGE,+ META_INVALID_CURSOR_ERROR_MESSAGE,META_TRANSIENT_ERROR_MAX_ATTEMPTS,PAGE_LIMIT_FALLBACK_SIZES,SHRINK_EXHAUSTED_ERROR_MESSAGE,@@ -38,6 +39,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mMetaAdsResumeConfig,_earliest_supported_since,_fetch_integration_row,+ _is_invalid_cursor_error,_is_permanent_auth_error,_is_transient_error,_iter_simple_pagination,@@ -1368,6 +1370,10 @@ class TestNonRetryableErrors:'{"error":{"message":"Error validating access token: The session has been invalidated because the '"user changed their password or Facebook has changed the session for security "'reasons.","type":"OAuthException","code":190,"error_subcode":460}})',+ # code 2642 — a paging cursor was rejected as invalid mid-sync. Retrying this job+ # would resume with the same saved cursor and fail identically every time.+ f"{META_INVALID_CURSOR_ERROR_MESSAGE} (Meta API response: 400 - "+ '{"error":{"message":"(#2642) Invalid cursors values","type":"OAuthException","code":2642}})',],)def test_errors_match_pattern(self, error_message: str) -> None:@@ -1423,6 +1429,27 @@ class TestNonRetryableErrors:def test_is_permanent_auth_error(self, body: dict, expected: bool) -> None:assert _is_permanent_auth_error(_mock_response(400, body)) is expected+ @pytest.mark.parametrize(+ "body,expected",+ [+ ({"error": {"code": 2642, "message": "(#2642) Invalid cursors values", "type": "OAuthException"}}, True),+ # A different code must not be swept into the same reclassification.+ ({"error": {"code": 1, "message": "An unknown error has occurred."}}, False),+ ({"error": {}}, False),+ ({}, False),+ ],+ )+ def test_is_invalid_cursor_error(self, body: dict, expected: bool) -> None:+ assert _is_invalid_cursor_error(_mock_response(400, body)) is expected++ def test_invalid_cursor_error_raises_non_retryable_message(self) -> None:+ # Confirms `_raise_meta_api_error` itself classifies a live 2642 response into the+ # message `get_non_retryable_errors` matches on — the parametrized test above only+ # checks the dict against a hand-written string, not the wiring that produces it.+ body = {"error": {"code": 2642, "message": "(#2642) Invalid cursors values", "type": "OAuthException"}}+ with pytest.raises(Exception, match=META_INVALID_CURSOR_ERROR_MESSAGE):+ _raise_meta_api_error(_mock_response(400, body))+class TestRetryableErrors:@pytest.mark.parametrize(