: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): adapt entity-endpoint pagination to too-large 500s (#63793)
Tom Owers9bb16ace3ed0
diff --git a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.pyindex 409905736a2b..ddaf1c8753ac 100644--- a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py+++ b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py@@ -264,15 +264,53 @@ def _iter_simple_pagination(On resume, the saved ``next_url`` is re-issued with a fresh ``access_token``injected at request time, so the initial request is skipped.++ Like the stats path, this adapts to Meta's "reduce the amount of data" 500s+ by shrinking the per-page ``limit`` (``PAGE_LIMIT_FALLBACK_SIZES``) and+ retrying the same request. Entity endpoints (campaigns/adsets/ads) carry+ heavy fields like ``targeting`` and ``creative``, so a default-sized page+ can be too large for Meta to serve; without this fallback the whole sync+ 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."""access_token = params["access_token"]+ current_limit = PAGE_LIMIT_FALLBACK_SIZES[0]++ # None while on the initial request; set to the active ``paging.next``+ # cursor once we start following pages. Used to retry-at-smaller-limit.+ cursor_url: str | None = Noneif resume_config is not None and resume_config.next_url and resume_config.end_date is None:- response = _fetch_paging_url(resume_config.next_url, access_token)- else:- response = make_tracked_session().get(initial_url, params=params)+ cursor_url = resume_config.next_url++ def _issue() -> Response:+ # Only rewrite the request once the limit has actually been shrunk, so+ # healthy syncs keep their original request shape (saved cursor URLs and+ # the caller's params already encode the default limit).+ if cursor_url is not None:+ url = (+ _override_limit(cursor_url, current_limit)+ if current_limit != PAGE_LIMIT_FALLBACK_SIZES[0]+ else cursor_url+ )+ return _fetch_paging_url(url, access_token)+ if current_limit != PAGE_LIMIT_FALLBACK_SIZES[0]:+ return make_tracked_session().get(initial_url, params={**params, "limit": current_limit})+ return make_tracked_session().get(initial_url, params=params)++ response = _issue()while True:if response.status_code != 200:+ # 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):+ smaller = _next_smaller_limit(current_limit)+ if smaller is not None:+ current_limit = smaller+ response = _issue()+ continue_raise_meta_api_error(response)response_payload = response.json()@@ -286,9 +324,9 @@ def _iter_simple_pagination(# the already-yielded page is not re-emitted (primary keys would dedupe it anyway).# Strip access_token from the URL before using it so we don't end up with a# duplicated `access_token` query param (requests merges `params=...` into the URL).- stripped_next_url = _strip_access_token(next_url)- resumable_source_manager.save_state(MetaAdsResumeConfig(next_url=stripped_next_url))- response = _fetch_paging_url(stripped_next_url, access_token)+ cursor_url = _strip_access_token(next_url)+ resumable_source_manager.save_state(MetaAdsResumeConfig(next_url=cursor_url))+ response = _issue()def _iter_time_range_pagination(diff --git a/posthog/temporal/data_imports/sources/meta_ads/source.py b/posthog/temporal/data_imports/sources/meta_ads/source.pyindex 1fe51b4059b6..ce573bf09a10 100644--- a/posthog/temporal/data_imports/sources/meta_ads/source.py+++ b/posthog/temporal/data_imports/sources/meta_ads/source.py@@ -47,8 +47,9 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig]):"Ad account owner has NOT": None,"cannot be loaded due to missing permissions": None,# Meta returns this 500 when the requested query is too large for their backend to- # service. We already adaptively shrink stats chunks (30 → 7 → 1 day) and detect this- # message in `_is_timeout_error`; if it still escapes, retrying the whole job won't help.+ # service. Both pagination paths adapt to it (stats chunks shrink 30 → 7 → 1 day, and+ # 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,}diff --git a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.pyindex 0e50ec8d12cc..f73a0425a7f6 100644--- a/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py+++ b/posthog/temporal/data_imports/sources/meta_ads/test_meta_ads.py@@ -192,6 +192,88 @@ class TestSimplePagination:assert mock_get.return_value.get.call_args_list[0].kwargs["params"] == {"access_token": "tok"}+class TestSimplePaginationLimitFallback:+ INITIAL_URL = "https://graph.facebook.com/v20/act_123/campaigns"+ # Mirrors production params from `meta_ads_source`: a default page limit is always set.+ PARAMS: dict[str, Any] = {"fields": "id,name", "limit": 500, "access_token": "tok"}+ REDUCE_BODY: dict[str, Any] = {+ "error": {"code": 1, "message": "Please reduce the amount of data you're asking for, then retry your request"}+ }++ def test_initial_too_much_data_retries_with_smaller_limit(self) -> None:+ manager = _build_manager()+ responses = [+ # Initial request at the default limit is rejected as too large.+ _mock_response(500, self.REDUCE_BODY),+ # Retry at the next-smaller limit succeeds.+ _mock_response(200, {"data": [{"id": "1"}], "paging": {}}),+ ]++ with mock.patch("posthog.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"}]]+ # First attempt used the default 500 limit.+ assert mock_get.return_value.get.call_args_list[0].args[0] == self.INITIAL_URL+ assert mock_get.return_value.get.call_args_list[0].kwargs["params"]["limit"] == 500+ # Retry re-issues the same initial URL with the limit reduced to the next rung (100).+ assert mock_get.return_value.get.call_args_list[1].args[0] == self.INITIAL_URL+ assert mock_get.return_value.get.call_args_list[1].kwargs["params"]["limit"] == 100++ def test_cursor_too_much_data_retries_with_smaller_limit(self) -> None:+ manager = _build_manager()+ responses = [+ # Page 1 succeeds and hands back a cursor.+ _mock_response(+ 200,+ {"data": [{"id": "1"}], "paging": {"next": "https://graph.facebook.com/v20/next?after=p1"}},+ ),+ # The cursor request is rejected as too large at the default limit.+ _mock_response(500, self.REDUCE_BODY),+ # Retry of the SAME cursor at a smaller limit succeeds; no more pages.+ _mock_response(200, {"data": [{"id": "2"}], "paging": {}}),+ ]++ with mock.patch("posthog.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"}], [{"id": "2"}]]+ # Cursor first tried without a limit override (still at the default).+ assert mock_get.return_value.get.call_args_list[1].args[0] == "https://graph.facebook.com/v20/next?after=p1"+ # Retry uses the SAME cursor with the limit reduced to 100.+ assert (+ mock_get.return_value.get.call_args_list[2].args[0]+ == "https://graph.facebook.com/v20/next?after=p1&limit=100"+ )++ def test_exhausting_limit_ladder_raises(self) -> 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]++ with mock.patch("posthog.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"):+ 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)++ def test_non_timeout_error_does_not_retry(self) -> None:+ manager = _build_manager()+ # Transient service error (code 2) — not a too-much-data error, so no limit fallback.+ responses = [_mock_response(500, {"error": {"message": "Service temporarily unavailable", "code": 2}})]++ with mock.patch("posthog.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"):+ list(_iter_simple_pagination(self.INITIAL_URL, self.PARAMS, None, manager))++ assert mock_get.return_value.get.call_count == 1++class TestTimeRangePagination:URL = "https://graph.facebook.com/v20/act_1/insights"PARAMS: dict[str, Any] = {"fields": "ad_id", "limit": 500, "level": "ad", "access_token": "tok"}