: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
feat(data-warehouse): backend-driven account picker for meta ads (#69863)
Javier Bahamondes348c24a7c0ce
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.pyindex 1bfa703f5594..3c68f94cc9c3 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py@@ -75,6 +75,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.custom.souPreviewResult,)from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client import LinkedinAdsApiError+from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads import (+ MetaAdsRateLimitError,+ MetaAdsTokenRefreshError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter import PostgresCDCAdapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import (PostgresDiscoveredSchema,@@ -11205,6 +11209,7 @@ class TestOAuthAccountsEndpoint(APIBaseTest):"products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.BingAdsClient.list_accounts")_LINKEDIN_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source"+ _META_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.source"def setUp(self):super().setUp()@@ -11249,6 +11254,16 @@ class TestOAuthAccountsEndpoint(APIBaseTest):created_by=self.user,)+ def _meta_ads_integration(self) -> Integration:+ return Integration.objects.create(+ team=self.team,+ kind="meta-ads",+ config={},+ sensitive_config={"access_token": "token"},+ integration_id="meta_ads_test",+ created_by=self.user,+ )+@staticmethoddef _http_error(status_code: int) -> requests.HTTPError:response = requests.Response()@@ -11284,6 +11299,78 @@ class TestOAuthAccountsEndpoint(APIBaseTest):response = self.client.get(self._url("Salesforce", 1))assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ def test_meta_ads_maps_ad_accounts_to_accounts(self):+ integration = self._meta_ads_integration()+ listed = [+ {"account_id": "1234567890", "name": "Acme Ads", "account_status": 1},+ {"account_id": "9876543210", "name": "Old Ads", "account_status": 101},+ ]+ with (+ patch(f"{self._META_ADS_MODULE}.get_integration_by_id"),+ patch(f"{self._META_ADS_MODULE}.list_ad_accounts", return_value=listed),+ ):+ response = self.client.get(self._url("MetaAds", integration.id))++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json()["accounts"] == [+ {+ "value": "1234567890",+ "display_name": "Acme Ads",+ "is_primary": False,+ "badges": ["Active"],+ "group": None,+ "secondary_text": None,+ },+ {+ "value": "9876543210",+ "display_name": "Old Ads",+ "is_primary": False,+ "badges": ["Closed"],+ "group": None,+ "secondary_text": None,+ },+ ]++ def test_meta_ads_token_refresh_error_returns_actionable_400(self):+ # Meta refusing to refresh the stored token is a customer-side state (revoked access), so it+ # must reach the user as an actionable 400 rather than an unhandled 500.+ integration = self._meta_ads_integration()+ error = MetaAdsTokenRefreshError(+ "Failed to refresh token for Meta Ads integration. Please re-authorize the integration."+ )+ with patch(f"{self._META_ADS_MODULE}.get_integration_by_id", side_effect=error):+ response = self.client.get(self._url("MetaAds", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "re-authorize" in str(response.json()).lower()++ def test_meta_ads_rate_limit_returns_actionable_400(self):+ # Meta throttling us is not a bug — it must not page us as a 500. The user just retries.+ integration = self._meta_ads_integration()+ with (+ patch(f"{self._META_ADS_MODULE}.get_integration_by_id"),+ patch(+ f"{self._META_ADS_MODULE}.list_ad_accounts",+ side_effect=MetaAdsRateLimitError("Meta is rate limiting requests for this connection."),+ ),+ ):+ response = self.client.get(self._url("MetaAds", integration.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "rate limiting" in str(response.json()).lower()++ def test_meta_ads_unexpected_error_is_not_swallowed(self):+ # Only the classified branches become a 400 — anything else is a genuine bug and must keep+ # surfacing as a 500 instead of being reported to the user as bad input.+ integration = self._meta_ads_integration()+ with (+ patch(f"{self._META_ADS_MODULE}.get_integration_by_id"),+ patch(f"{self._META_ADS_MODULE}.list_ad_accounts", side_effect=RuntimeError("boom")),+ ):+ response = self.client.get(self._url("MetaAds", integration.id))++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content+def test_gsc_success_maps_sites_to_accounts(self):integration = self._gsc_integration()with (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 3cb9ccb8ccd5..26790c0725a8 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@@ -8,6 +8,7 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom django.db import OperationalError, close_old_connections+import structlogfrom requests import Responsefrom requests.exceptions import JSONDecodeError as RequestsJSONDecodeError@@ -20,11 +21,16 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineSourceResponse,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccountListingError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import RESOURCE_SCHEMASfrom products.warehouse_sources.backend.types import IncrementalFieldType+logger = structlog.get_logger(__name__)+# Meta Ads API only supports data from the last 3 years. Meta's insights endpoints# reject a `time_range` whose start is beyond ~37 months from today with error code# 3018 ("The start date of the time range cannot be beyond 37 months from the current@@ -144,18 +150,28 @@ def _fetch_integration_row(integration_id: int, team_id: int) -> Integration:_backoff_sleep(attempt)-def get_integration(config: MetaAdsSourceConfig, team_id: int) -> Integration:- """Get the Meta Ads integration."""- integration = _fetch_integration_row(config.meta_ads_integration_id, team_id)+class MetaAdsTokenRefreshError(Exception):+ """Meta refused to refresh the integration's access token — only re-authorization fixes it."""+++def get_integration_by_id(integration_id: int, team_id: int) -> Integration:+ """Get a Meta Ads integration by row id, with a freshly refreshed access token."""+ integration = _fetch_integration_row(integration_id, team_id)meta_ads_integration = MetaAdsIntegration(integration)meta_ads_integration.refresh_access_token()if meta_ads_integration.integration.errors == ERROR_TOKEN_REFRESH_FAILED:- raise Exception("Failed to refresh token for Meta Ads integration. Please re-authorize the integration.")+ raise MetaAdsTokenRefreshError(+ "Failed to refresh token for Meta Ads integration. Please re-authorize the integration."+ )return meta_ads_integration.integration+def get_integration(config: MetaAdsSourceConfig, team_id: int) -> Integration:+ return get_integration_by_id(config.meta_ads_integration_id, team_id)++@dataclassclass MetaAdsSchema:name: str@@ -283,10 +299,33 @@ def _is_timeout_error(response: Response) -> bool:META_AUTH_ERROR_CODES = {102, 190}META_PERMISSION_ERROR_CODES = {10, *range(200, 300)}+# Meta throttling codes. The request was rejected for its volume, not for being malformed, so the+# call is fine and the only fix is waiting — never a bug on our side.+# 4 — application request limit reached (our app, across all users).+# 17 — user request limit reached.+# 32 — page request limit reached.+# 613 — custom-level rate limit reached.+# https://developers.facebook.com/docs/graph-api/overview/rate-limiting+META_RATE_LIMIT_ERROR_CODES = {4, 17, 32, 613}+META_AUTH_ERROR_MESSAGE = ("Meta Ads access token is invalid, expired, or lacks the required permissions. Please re-authorize the integration.")+META_RATE_LIMIT_ERROR_MESSAGE = (+ "Meta is rate limiting requests for this connection. Please wait a few minutes and try again."+)+++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."""+ try:+ error = response.json().get("error", {})+ except (ValueError, AttributeError):+ return None+ code = error.get("code")+ return code if isinstance(code, int) else None+def _is_permanent_auth_error(response: Response) -> bool:"""Return True for Meta errors that only re-authorization can fix.@@ -295,16 +334,15 @@ def _is_permanent_auth_error(response: Response) -> bool:permission denials. These are terminal: retrying the sync keeps failinguntil the user reconnects the integration."""- try:- error = response.json().get("error", {})- except (ValueError, AttributeError):- return False- code = error.get("code")- if not isinstance(code, int):- return False+ code = _meta_error_code(response)return code in META_AUTH_ERROR_CODES or code in META_PERMISSION_ERROR_CODES+def _is_rate_limit_error(response: Response) -> bool:+ """Return True for Meta errors that mean "too many requests", which only waiting fixes."""+ return _meta_error_code(response) in META_RATE_LIMIT_ERROR_CODES++def _raise_meta_api_error(response: Response) -> typing.NoReturn:"""Raise a descriptive exception for a non-200 Meta API response.@@ -318,6 +356,79 @@ def _raise_meta_api_error(response: Response) -> typing.NoReturn:raise Exception(f"Meta API request failed: {response.status_code} - {response.text}")+class MetaAdsAuthError(Exception):+ """Meta rejected the credentials or the permissions they carry (see `_is_permanent_auth_error`)."""+++class MetaAdsRateLimitError(Exception):+ """Meta throttled the request (see `_is_rate_limit_error`) — retrying later is the only fix."""+++# No `business{name}`: reading it needs the `business_management` scope, which the Meta OAuth+# consent doesn't request (`ads_read` only), and Meta 400s the whole request when it's asked for.+AD_ACCOUNT_FIELDS = "account_id,name,account_status"+AD_ACCOUNT_PAGE_LIMIT = 100+# This listing runs in the web request path, not a Temporal worker, so a cursor that never resolves+# would pin a worker. Bound it rather than trusting Meta to end the chain.+MAX_AD_ACCOUNT_PAGES = 100+# Per-request timeout for the listing path. Without it a hung Meta connection pins the web worker+# for the life of the request, since these calls run inline in `oauth_accounts`, not in a worker.+AD_ACCOUNT_LISTING_TIMEOUT_SECONDS = 10+++def _raise_for_meta_error(response: Response) -> None:+ """Map a non-200 Meta listing response to the actionable error the picker surfaces. Called for every+ page, including the one fetched just before the page cap, so an auth or rate-limit failure on the+ final fetch isn't swallowed and mislabeled as "too many pages"."""+ if response.status_code != 200:+ if _is_permanent_auth_error(response):+ raise MetaAdsAuthError(META_AUTH_ERROR_MESSAGE)+ if _is_rate_limit_error(response):+ raise MetaAdsRateLimitError(META_RATE_LIMIT_ERROR_MESSAGE)+ _raise_meta_api_error(response)+++def list_ad_accounts(integration: Integration) -> list[dict]:+ """Every ad account the connected Meta user can access."""+ access_token = integration.sensitive_config["access_token"]+ # `redact_values` masks the access token wherever it lands in telemetry — Meta takes it as a query+ # param here and echoes it back inside each `paging.next` URL, so without this the credential would+ # be recorded in the logged/sampled request URLs.+ session = make_tracked_session(redact_values=(access_token,))+ accounts: list[dict] = []+ response = session.get(+ 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,+ )++ for _ in range(MAX_AD_ACCOUNT_PAGES):+ _raise_for_meta_error(response)++ body = response.json()+ page = body.get("data") or []+ accounts.extend(page)++ next_url = (body.get("paging") or {}).get("next")+ # Meta keeps handing out a `next` cursor past the final page, which then returns no data.+ 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,+ )++ # 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.+ _raise_for_meta_error(response)+ # Hitting the cap means Meta kept returning a fresh, non-empty `next` cursor past the bound. Returning+ # `accounts` here would present a truncated (and possibly duplicated) list as the complete set, so the+ # picker would silently hide accounts. Fail closed with an actionable message instead.+ raise IntegrationAccountListingError("Meta returned too many pages while listing ad accounts. Please try again.")++def _iter_simple_pagination(initial_url: str,params: dict,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 f215c62e8a23..37db1182ea90 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@@ -7,10 +7,13 @@ from posthog.schema import (SourceConfig,SourceFieldInputConfig,SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,SourceFieldOauthConfig,SuggestedTable,)+from posthog.models.integration import Integration+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (SourceInputs,SourceResponse,@@ -23,6 +26,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccount,+ IntegrationAccountListingError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (@@ -32,7 +40,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads import (META_AUTH_ERROR_MESSAGE,+ MetaAdsAuthError,+ MetaAdsRateLimitError,MetaAdsResumeConfig,+ MetaAdsTokenRefreshError,+ get_integration_by_id,+ list_ad_accounts,meta_ads_source,)from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.schemas import (@@ -41,9 +54,28 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.s)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Meta's numeric `account_status`, as the Ads Manager labels it. 201/202 (ANY_ACTIVE, ANY_CLOSED)+# are query filters rather than states an account is ever returned in, so they're absent here.+ACCOUNT_STATUS_LABELS = {+ 1: "Active",+ 2: "Disabled",+ 3: "Unsettled",+ 7: "Pending risk review",+ 8: "Pending settlement",+ 9: "In grace period",+ 100: "Pending closure",+ 101: "Closed",+}+++def _status_badges(account: dict) -> tuple[str, ...]:+ status = account.get("account_status")+ label = ACCOUNT_STATUS_LABELS.get(status) if status is not None else None+ return (label,) if label else ()+@SourceRegistry.register-class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig]):+class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig], OAuthMixin):lists_tables_without_credentials = True # static endpoint catalog — safe for public docssupported_versions = ("v25.0",)@@ -145,20 +177,19 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig]):fields=cast(list[FieldType],[- SourceFieldInputConfig(- name="account_id",- label="Account ID",- type=SourceFieldInputConfigType.TEXT,- required=True,- placeholder="",- secret=False,- ),SourceFieldOauthConfig(name="meta_ads_integration_id",label="Meta Ads account",required=True,kind="meta-ads",),+ SourceFieldOauthAccountSelectConfig(+ name="account_id",+ label="Account ID",+ integrationField="meta_ads_integration_id",+ integrationKind="meta-ads",+ required=True,+ ),SourceFieldInputConfig(name="sync_lookback_days",label="Sync history for insights (days) - applies to AdStats, AdsetStats, CampaignStats",@@ -181,3 +212,38 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig]):),],)++ def get_oauth_accounts(+ self, integration_id: int, team_id: int, search: str | None = None+ ) -> list[IntegrationAccount]:+ # A Meta user's ad accounts are few, so `search` is ignored here and the endpoint filters the list.+ try:+ integration = get_integration_by_id(integration_id, team_id)+ except Integration.DoesNotExist as e:+ raise IntegrationAccountListingError(+ "The linked Meta Ads integration could not be found. Please reconnect your Meta Ads integration."+ ) from e+ except MetaAdsTokenRefreshError as e:+ raise IntegrationAccountListingError(str(e)) from e++ try:+ accounts = list_ad_accounts(integration)+ except MetaAdsAuthError as e:+ raise IntegrationAccountListingError(+ f"{META_AUTH_ERROR_MESSAGE} Make sure the connected account can access your ad accounts."+ ) from e+ except MetaAdsRateLimitError as e:+ # Throttling is not a bug: surface it as an actionable 400 the user can retry, rather+ # than a 500 that pages us.+ raise IntegrationAccountListingError(str(e)) from e++ return [+ IntegrationAccount(+ # Bare id, as the Ads Manager shows it; the pipeline's `_clean_account_id` adds the+ # `act_` prefix the Graph API wants.+ value=account["account_id"],+ display_name=account.get("name") or "Unnamed account",+ badges=_status_badges(account),+ )+ for account in accounts+ ]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 c7b4aac0d9e9..795e3ecbb094 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@@ -10,14 +10,20 @@ from django.db import OperationalErrorfrom requests.exceptions import JSONDecodeError as RequestsJSONDecodeError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccountListingError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MetaAdsSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads import meta_ads as meta_ads_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads import (+ AD_ACCOUNT_LISTING_TIMEOUT_SECONDS,MALFORMED_JSON_MAX_ATTEMPTS,+ MAX_AD_ACCOUNT_PAGES,META_ADS_MAX_HISTORY_DAYS,META_AUTH_ERROR_MESSAGE,PAGE_LIMIT_FALLBACK_SIZES,+ MetaAdsAuthError,MetaAdsResumeConfig,_earliest_supported_since,_fetch_integration_row,@@ -28,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.m_override_limit,_strip_access_token,get_integration,+ list_ad_accounts,meta_ads_source,)from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.source import MetaAdsSource@@ -1244,3 +1251,110 @@ class TestFetchIntegrationRowDbResilience:# A deleted integration row is non-retryable — don't mask it as a transient drop.assert get.call_count == 1+++class TestListAdAccounts:+ @staticmethod+ def _integration() -> Any:+ integration = mock.MagicMock()+ integration.sensitive_config = {"access_token": "token"}+ return integration++ def test_follows_paging_next_to_the_end(self, monkeypatch) -> None:+ session = mock.MagicMock()+ session.get.side_effect = [+ _mock_response(+ 200,+ {+ "data": [{"account_id": "1"}],+ "paging": {"next": "https://graph.facebook.com/v25.0/me/adaccounts?access_token=stale&after=abc"},+ },+ ),+ _mock_response(200, {"data": [{"account_id": "2"}]}),+ ]+ monkeypatch.setattr(meta_ads_module, "make_tracked_session", lambda *args, **kwargs: session)++ accounts = list_ad_accounts(self._integration())++ assert [account["account_id"] for account in accounts] == ["1", "2"]+ cursor_url, cursor_kwargs = session.get.call_args_list[1][0][0], session.get.call_args_list[1][1]+ # The echoed-back token is stripped and a fresh one injected at request time.+ assert "access_token" not in cursor_url+ assert cursor_kwargs["params"] == {"access_token": "token"}++ def test_stops_when_a_trailing_cursor_returns_no_data(self, monkeypatch) -> None:+ next_page = {"next": "https://graph.facebook.com/v25.0/me/adaccounts?after=abc"}+ session = mock.MagicMock()+ session.get.side_effect = [+ _mock_response(200, {"data": [{"account_id": "1"}], "paging": next_page}),+ _mock_response(200, {"data": [], "paging": next_page}),+ ]+ monkeypatch.setattr(meta_ads_module, "make_tracked_session", lambda *args, **kwargs: session)++ accounts = list_ad_accounts(self._integration())++ assert [account["account_id"] for account in accounts] == ["1"]+ assert session.get.call_count == 2++ def test_permanent_auth_failure_raises_meta_ads_auth_error(self, monkeypatch) -> None:+ session = mock.MagicMock()+ session.get.return_value = _mock_response(400, {"error": {"code": 190, "message": "Invalid OAuth token"}})+ monkeypatch.setattr(meta_ads_module, "make_tracked_session", lambda *args, **kwargs: session)++ with pytest.raises(MetaAdsAuthError):+ list_ad_accounts(self._integration())++ def test_page_limit_exceeded_fails_closed_instead_of_returning_partial(self, monkeypatch) -> 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.+ session = mock.MagicMock()+ session.get.return_value = _mock_response(+ 200,+ {"data": [{"account_id": "1"}], "paging": {"next": "https://graph.facebook.com/v25.0/next?after=loop"}},+ )+ monkeypatch.setattr(meta_ads_module, "make_tracked_session", lambda *args, **kwargs: session)++ with pytest.raises(IntegrationAccountListingError):+ list_ad_accounts(self._integration())+ # Initial request plus one per bounded page: it exhausts the cap rather than raising early.+ assert session.get.call_count == MAX_AD_ACCOUNT_PAGES + 1++ def test_error_on_final_page_before_cap_surfaces_real_error_not_too_many_pages(self, monkeypatch) -> None:+ # The response fetched on the last loop iteration isn't re-checked by the loop. If it carries an+ # auth failure, it must surface as MetaAdsAuthError, not be masked by the "too many pages" error.+ ok_page = _mock_response(+ 200,+ {"data": [{"account_id": "1"}], "paging": {"next": "https://graph.facebook.com/v25.0/next?after=loop"}},+ )+ auth_error = _mock_response(400, {"error": {"code": 190, "message": "Invalid OAuth token"}})+ session = mock.MagicMock()+ session.get.side_effect = [ok_page] * MAX_AD_ACCOUNT_PAGES + [auth_error]+ monkeypatch.setattr(meta_ads_module, "make_tracked_session", lambda *args, **kwargs: session)++ with pytest.raises(MetaAdsAuthError):+ list_ad_accounts(self._integration())++ def test_masks_token_and_sets_timeout_on_every_request(self, monkeypatch) -> None:+ session = mock.MagicMock()+ session.get.side_effect = [+ _mock_response(+ 200,+ {+ "data": [{"account_id": "1"}],+ "paging": {"next": "https://graph.facebook.com/v25.0/me/adaccounts?access_token=stale&after=abc"},+ },+ ),+ _mock_response(200, {"data": [{"account_id": "2"}]}),+ ]+ factory = mock.MagicMock(return_value=session)+ monkeypatch.setattr(meta_ads_module, "make_tracked_session", factory)++ list_ad_accounts(self._integration())++ # The access token is registered for redaction so it can't be recorded in logged request URLs.+ factory.assert_called_once_with(redact_values=("token",))+ # Neither the initial request nor the pagination follow-up may run without a timeout, or a hung+ # Meta connection would pin the web worker (this runs inline in the request path).+ assert session.get.call_count == 2+ for call in session.get.call_args_list:+ assert call.kwargs["timeout"] == AD_ACCOUNT_LISTING_TIMEOUT_SECONDS