: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): show a retry message when meta fails while listing ad accounts (#122698)
Tom Owersaae888bd9b7e
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 bc8fb7da1648..9e00d63e95d6 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@@ -9,7 +9,7 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom django.db import OperationalError, close_old_connectionsimport structlog-from requests import Response+from requests import Response, Sessionfrom requests.exceptions import (ChunkedEncodingError,ConnectionError as RequestsConnectionError,@@ -497,6 +497,10 @@ META_RATE_LIMIT_ERROR_MESSAGE = ("Meta is rate limiting requests for this connection. Please wait a few minutes and try again.")+META_AD_ACCOUNT_LISTING_UNAVAILABLE_MESSAGE = (+ "Meta Ads didn't respond while listing your ad accounts. Wait a minute, then 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@@ -678,9 +682,22 @@ def _raise_for_meta_error(response: Response) -> None:raise MetaAdsAuthError(META_AUTH_ERROR_MESSAGE)if _is_rate_limit_error(response):raise MetaAdsRateLimitError(META_RATE_LIMIT_ERROR_MESSAGE)+ if _is_transient_error(response):+ raise IntegrationAccountListingError(META_AD_ACCOUNT_LISTING_UNAVAILABLE_MESSAGE)_raise_meta_api_error(response)+def _get_ad_account_page(session: Session, url: str, access_token: str, params: dict[str, typing.Any]) -> Response:+ # The tracked session has already retried a blip by the time one of these escapes, and this+ # listing runs in the web request path, so turn it into a message the picker can show.+ try:+ return session.get(+ url, params={**params, "access_token": access_token}, timeout=AD_ACCOUNT_LISTING_TIMEOUT_SECONDS+ )+ except NETWORK_TRANSIENT_ERRORS as e:+ raise IntegrationAccountListingError(META_AD_ACCOUNT_LISTING_UNAVAILABLE_MESSAGE) from e++def list_ad_accounts(integration: Integration) -> list[dict]:"""Every ad account the connected Meta user can access."""access_token = integration.sensitive_config["access_token"]@@ -689,10 +706,11 @@ def list_ad_accounts(integration: Integration) -> list[dict]:# be recorded in the logged/sampled request URLs.session = make_tracked_session(redact_values=(access_token,))accounts: list[dict] = []- response = session.get(+ response = _get_ad_account_page(+ session,f"https://graph.facebook.com/{MetaAdsIntegration.api_version}/me/adaccounts",- params={"fields": AD_ACCOUNT_FIELDS, "limit": AD_ACCOUNT_PAGE_LIMIT, "access_token": access_token},- timeout=AD_ACCOUNT_LISTING_TIMEOUT_SECONDS,+ access_token,+ {"fields": AD_ACCOUNT_FIELDS, "limit": AD_ACCOUNT_PAGE_LIMIT},)for _ in range(MAX_AD_ACCOUNT_PAGES):@@ -707,11 +725,7 @@ def list_ad_accounts(integration: Integration) -> list[dict]:if not next_url or not page:return accounts- response = session.get(- _strip_access_token(next_url),- params={"access_token": access_token},- timeout=AD_ACCOUNT_LISTING_TIMEOUT_SECONDS,- )+ response = _get_ad_account_page(session, _strip_access_token(next_url), access_token, {})# The response fetched on the final loop iteration is never re-checked by the loop, so surface a real# auth/rate-limit failure there rather than masking it with the "too many pages" error below.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 5bdd0a036bc3..2803f294d775 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@@ -38,6 +38,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.mENTITY_PAGE_REFUSED_ERROR_MESSAGE,MALFORMED_JSON_MAX_ATTEMPTS,MAX_AD_ACCOUNT_PAGES,+ META_AD_ACCOUNT_LISTING_UNAVAILABLE_MESSAGE,META_ADS_API_VERSION_V25,META_ADS_API_VERSION_V26,META_ADS_MAX_HISTORY_DAYS,@@ -2132,6 +2133,20 @@ class TestListAdAccounts:with pytest.raises(MetaAdsAuthError):list_ad_accounts(self._integration())+ @pytest.mark.parametrize(+ "answer",+ [+ ScriptedResponse(status=500, json={"error": {"message": "Service temporarily unavailable", "code": 2}}),+ ScriptedResponse(status=503, body=b""),+ ConnectionResetError(104, "Connection reset by peer"),+ ],+ ids=["meta_transient_code", "empty_5xx", "connection_reset"],+ )+ def test_transient_failure_surfaces_retry_message_to_the_picker(self, answer: Any) -> None:+ with scripted_network(always(answer)):+ with pytest.raises(IntegrationAccountListingError, match=META_AD_ACCOUNT_LISTING_UNAVAILABLE_MESSAGE):+ list_ad_accounts(self._integration())+def test_page_limit_exceeded_fails_closed_instead_of_returning_partial(self) -> None:# Meta keeps handing back a fresh, non-empty `next` cursor past the cap. Returning the# accumulated (truncated) accounts would present them to the picker as the complete set.