Skip to content

: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.

feat(meta_ads): treat 'reduce the amount of data' 500 as non-retryable (#56471)

Tom Owers98169325c1e9
diff --git a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
index 1432014dad77..0aa2b9740e4f 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/meta_ads.py
@@ -39,7 +39,10 @@ class MetaAdsResumeConfig:
happened mid-chunk — on resume we fetch that URL directly, skipping the
initial chunk request. When the chunk was complete at save time,
``chunk_next_url`` is None and we issue a fresh initial request for
- ``chunk_since``. Saved URLs have ``access_token`` stripped.
+ ``chunk_since``. ``chunk_limit`` is set when an in-flight timeout caused
+ the per-page limit to be reduced; the smaller limit then persists across
+ resumes so we don't re-trip the same timeout. Saved URLs have
+ ``access_token`` stripped.
"""
next_url: str | None = None
@@ -47,6 +50,7 @@ class MetaAdsResumeConfig:
chunk_since: str | None = None
chunk_size_days: int | None = None
chunk_next_url: str | None = None
+ chunk_limit: int | None = None
def _strip_access_token(url: str) -> str:
@@ -150,6 +154,41 @@ META_TIMEOUT_ERROR_SUBCODES = {1504018, 1504038}
# Start with 30-day chunks, fall back to smaller chunks on timeout
TIME_RANGE_CHUNK_SIZES = [30, 7, 1]
+# Per-page row limits for adaptive pagination. When the Graph API times out
+# mid-chunk (i.e. on a paging.next cursor request, after we've already yielded
+# rows from the chunk), shrinking the chunk's date range would force us to
+# re-issue earlier pages and re-emit rows we've already produced. Instead we
+# shrink the per-page ``limit`` and retry the same cursor URL — Meta accepts
+# ``limit`` as a query param on cursor URLs.
+PAGE_LIMIT_FALLBACK_SIZES = [500, 100, 50]
+
+
+def _override_limit(url: str, limit: int) -> str:
+ """Return ``url`` with its ``limit`` query parameter overridden.
+
+ Meta's ``paging.next`` URLs encode the limit that produced the cursor; if
+ we want a smaller batch on the retry, we have to rewrite the URL.
+ """
+ parts = urlsplit(url)
+ pairs = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if k != "limit"]
+ pairs.append(("limit", str(limit)))
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(pairs), parts.fragment))
+
+
+def _next_smaller_limit(current: int) -> int | None:
+ """Return the next smaller value in ``PAGE_LIMIT_FALLBACK_SIZES``.
+
+ Returns ``None`` if ``current`` is already at or below the smallest rung —
+ in that case the caller should treat the timeout as terminal.
+ """
+ if current in PAGE_LIMIT_FALLBACK_SIZES:
+ idx = PAGE_LIMIT_FALLBACK_SIZES.index(current)
+ if idx >= len(PAGE_LIMIT_FALLBACK_SIZES) - 1:
+ return None
+ return PAGE_LIMIT_FALLBACK_SIZES[idx + 1]
+ smaller = [s for s in PAGE_LIMIT_FALLBACK_SIZES if s < current]
+ return max(smaller) if smaller else 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."""
@@ -214,15 +253,27 @@ def _iter_time_range_pagination(
"""Iterate an insights-style request by chunked date ranges.
The outer loop walks adaptive date chunks (30/7/1 days). The inner loop
- follows ``paging.next`` within each chunk. Resume state captures both
- levels: ``chunk_since`` + ``chunk_size_days`` for the outer loop, and
- ``chunk_next_url`` when the crash happened mid-chunk.
+ follows ``paging.next`` within each chunk. There are two adaptive-fallback
+ dimensions:
+
+ - **Chunk size** (``TIME_RANGE_CHUNK_SIZES``): shrunk only when the
+ *initial* chunk request times out, before any rows are yielded.
+ - **Page limit** (``PAGE_LIMIT_FALLBACK_SIZES``): shrunk when a *cursor*
+ request inside the chunk times out, after we've already yielded earlier
+ pages from this chunk. We must not re-shrink the chunk here — that would
+ force re-yielding rows we already produced. Instead we override the
+ ``limit`` query param on the same cursor URL and retry.
+
+ Resume state captures both levels: ``chunk_since`` + ``chunk_size_days``
+ for the outer loop, ``chunk_next_url`` when the crash happened mid-chunk,
+ and ``chunk_limit`` so a reduced limit persists across resumes.
"""
access_token = params["access_token"]
start_date = dt.datetime.strptime(time_range["since"], "%Y-%m-%d")
end_date = dt.datetime.strptime(time_range["until"], "%Y-%m-%d")
chunk_size_days = TIME_RANGE_CHUNK_SIZES[0]
+ current_limit = PAGE_LIMIT_FALLBACK_SIZES[0]
current_start = start_date
pending_next_url: str | None = None
@@ -230,6 +281,8 @@ def _iter_time_range_pagination(
current_start = dt.datetime.strptime(resume_config.chunk_since, "%Y-%m-%d")
chunk_size_days = resume_config.chunk_size_days or TIME_RANGE_CHUNK_SIZES[0]
pending_next_url = resume_config.chunk_next_url
+ if resume_config.chunk_limit:
+ current_limit = resume_config.chunk_limit
end_date_iso = end_date.strftime("%Y-%m-%d")
@@ -243,22 +296,31 @@ def _iter_time_range_pagination(
chunk_since=since.strftime("%Y-%m-%d"),
chunk_size_days=size_days,
chunk_next_url=sanitised,
+ # Persist only when we've shrunk below the default — keeps
+ # the saved state minimal for healthy syncs.
+ chunk_limit=current_limit if current_limit != PAGE_LIMIT_FALLBACK_SIZES[0] else None,
)
)
while current_start <= end_date:
current_end = min(current_start + dt.timedelta(days=chunk_size_days - 1), end_date)
+ # The most recent cursor URL we tried (without a limit override applied),
+ # used to retry-with-smaller-limit if a mid-chunk request times out.
+ last_paging_url: str | None = None
if pending_next_url:
- # Mid-chunk resume: re-attach a fresh access_token at request time.
- response = _fetch_paging_url(pending_next_url, access_token)
+ # Mid-chunk resume: re-attach a fresh access_token at request time
+ # and apply the (possibly previously-shrunk) limit.
+ last_paging_url = pending_next_url
+ response = _fetch_paging_url(_override_limit(pending_next_url, current_limit), access_token)
pending_next_url = None
else:
chunk_time_range = {
"since": current_start.strftime("%Y-%m-%d"),
"until": current_end.strftime("%Y-%m-%d"),
}
- chunk_params = {**params, "time_range": json.dumps(chunk_time_range)}
+
+ chunk_params = {**params, "limit": current_limit, "time_range": json.dumps(chunk_time_range)}
response = make_tracked_session().get(url, params=chunk_params)
if response.status_code != 200:
@@ -272,6 +334,16 @@ def _iter_time_range_pagination(
while True:
if response.status_code != 200:
+ # 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:
+ smaller = _next_smaller_limit(current_limit)
+ if smaller is not None:
+ current_limit = smaller
+ retry_url = _override_limit(last_paging_url, current_limit)
+ response = _fetch_paging_url(retry_url, access_token)
+ continue
raise Exception(f"Meta API request failed: {response.status_code} - {response.text}")
response_payload = response.json()
@@ -286,7 +358,8 @@ def _iter_time_range_pagination(
# would send two `access_token` query params.
stripped_next_url = _strip_access_token(next_url)
_save(current_start, chunk_size_days, stripped_next_url)
- response = _fetch_paging_url(stripped_next_url, access_token)
+ last_paging_url = stripped_next_url
+ response = _fetch_paging_url(_override_limit(stripped_next_url, current_limit), access_token)
current_start = current_end + dt.timedelta(days=1)
# Always save the chunk-boundary state, even when we've advanced past
@@ -375,7 +448,7 @@ def meta_ads_source(
)
params = {
"fields": ",".join(schema.field_names),
- "limit": 500,
+ "limit": PAGE_LIMIT_FALLBACK_SIZES[0],
**schema.extra_params,
}
diff --git a/posthog/temporal/data_imports/sources/meta_ads/source.py b/posthog/temporal/data_imports/sources/meta_ads/source.py
index 80a4ba4d0ee3..760932c64f7c 100644
--- a/posthog/temporal/data_imports/sources/meta_ads/source.py
+++ b/posthog/temporal/data_imports/sources/meta_ads/source.py
@@ -36,6 +36,10 @@ class MetaAdsSource(ResumableSource[MetaAdsSourceConfig, MetaAdsResumeConfig]):
"Failed to refresh token for Meta Ads integration. Please re-authorize the integration.": None,
"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.
+ "Please reduce the amount of data you're asking for": None,
}
def get_schemas(
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.py
index b3670f39fe4d..328f5183a047 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
@@ -6,11 +6,15 @@ from unittest import mock
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from posthog.temporal.data_imports.sources.meta_ads.meta_ads import (
+ PAGE_LIMIT_FALLBACK_SIZES,
MetaAdsResumeConfig,
_iter_simple_pagination,
_iter_time_range_pagination,
+ _next_smaller_limit,
+ _override_limit,
_strip_access_token,
)
+from posthog.temporal.data_imports.sources.meta_ads.source import MetaAdsSource
def _mock_response(status: int, body: dict) -> mock.MagicMock:
@@ -233,7 +237,7 @@ class TestTimeRangePagination:
# Second request uses the stripped URL plus access_token via params (no duplicate token).
assert (
mock_get.return_value.get.call_args_list[1].args[0]
- == "https://graph.facebook.com/v20/act_1/insights?after=abc"
+ == "https://graph.facebook.com/v20/act_1/insights?after=abc&limit=500"
)
assert mock_get.return_value.get.call_args_list[1].kwargs["params"] == {"access_token": "tok"}
@@ -342,7 +346,7 @@ class TestTimeRangePagination:
# Two requests: the resumed mid-chunk URL, then nothing more to fetch within this chunk.
# (There is a final "past end_date" save_state, but no additional HTTP call is made.)
assert mock_get.return_value.get.call_count == 1
- assert mock_get.return_value.get.call_args_list[0].args[0] == saved_next
+ assert mock_get.return_value.get.call_args_list[0].args[0] == saved_next + "&limit=500"
# access_token is injected fresh — never served from the saved URL.
assert mock_get.return_value.get.call_args_list[0].kwargs["params"] == {"access_token": "tok"}
@@ -431,3 +435,237 @@ class TestTimeRangePagination:
# The first successful request was for a 7-day chunk.
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"}
+
+
+class TestOverrideLimit:
+ @pytest.mark.parametrize(
+ "url,limit,expected",
+ [
+ (
+ "https://graph.facebook.com/v20/x?after=abc",
+ 100,
+ "https://graph.facebook.com/v20/x?after=abc&limit=100",
+ ),
+ (
+ # Existing limit is replaced (not duplicated).
+ "https://graph.facebook.com/v20/x?after=abc&limit=500",
+ 50,
+ "https://graph.facebook.com/v20/x?after=abc&limit=50",
+ ),
+ (
+ "https://graph.facebook.com/v20/x?limit=500&after=abc",
+ 100,
+ "https://graph.facebook.com/v20/x?after=abc&limit=100",
+ ),
+ (
+ "https://graph.facebook.com/v20/x",
+ 100,
+ "https://graph.facebook.com/v20/x?limit=100",
+ ),
+ ],
+ )
+ def test_overrides(self, url: str, limit: int, expected: str) -> None:
+ assert _override_limit(url, limit) == expected
+
+
+class TestNextSmallerLimit:
+ @pytest.mark.parametrize(
+ "current,expected",
+ [
+ (500, 100),
+ (100, 50),
+ # Smallest rung — no further fallback available.
+ (50, None),
+ # Non-standard limit between rungs picks the largest rung below it.
+ (250, 100),
+ # Non-standard limit below the smallest rung — exhausted.
+ (10, None),
+ # Non-standard limit above the largest rung steps down to the largest rung.
+ (1000, 500),
+ ],
+ )
+ def test_step(self, current: int, expected: int | None) -> None:
+ assert _next_smaller_limit(current) == expected
+
+
+class TestMidChunkLimitFallback:
+ URL = "https://graph.facebook.com/v20/act_1/insights"
+ PARAMS: dict[str, Any] = {"fields": "ad_id", "limit": 500, "level": "ad", "access_token": "tok"}
+
+ def test_mid_chunk_timeout_retries_with_smaller_limit_and_persists(self) -> None:
+ manager = _build_manager()
+ timeout_body = {"error": {"error_subcode": 1504018, "message": "timeout"}}
+ responses = [
+ # Initial chunk request returns page 1 + a cursor.
+ _mock_response(
+ 200,
+ {
+ "data": [{"ad_id": "1"}],
+ "paging": {"next": "https://graph.facebook.com/v20/act_1/insights?after=p1"},
+ },
+ ),
+ # Cursor request times out at the default limit.
+ _mock_response(500, timeout_body),
+ # Retry with smaller limit succeeds.
+ _mock_response(200, {"data": [{"ad_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_time_range_pagination(
+ self.URL,
+ self.PARAMS,
+ {"since": "2026-04-21", "until": "2026-04-21"},
+ None,
+ manager,
+ )
+ )
+
+ assert batches == [[{"ad_id": "1"}], [{"ad_id": "2"}]]
+
+ # Initial request used the default 500 limit.
+ first_params = mock_get.return_value.get.call_args_list[0].kwargs["params"]
+ assert first_params["limit"] == 500
+ # Second request (the timeout one) used limit=500 on the cursor URL.
+ assert (
+ mock_get.return_value.get.call_args_list[1].args[0]
+ == "https://graph.facebook.com/v20/act_1/insights?after=p1&limit=500"
+ )
+ # Retry uses the SAME cursor with limit reduced to the next rung (100).
+ assert (
+ mock_get.return_value.get.call_args_list[2].args[0]
+ == "https://graph.facebook.com/v20/act_1/insights?after=p1&limit=100"
+ )
+
+ # The mid-chunk save (before the cursor request) recorded chunk_limit=None
+ # because the limit hadn't been shrunk yet at save time.
+ mid_chunk: MetaAdsResumeConfig = manager.save_state.call_args_list[0].args[0]
+ assert mid_chunk.chunk_next_url == "https://graph.facebook.com/v20/act_1/insights?after=p1"
+ assert mid_chunk.chunk_limit is None
+
+ # After retry succeeds and the chunk completes, the chunk-boundary save
+ # records the reduced limit (100) so future resumes inherit it.
+ final: MetaAdsResumeConfig = manager.save_state.call_args_list[-1].args[0]
+ assert final.chunk_limit == 100
+ assert final.chunk_next_url is None
+
+ def test_resume_honors_chunk_limit_for_mid_chunk_url(self) -> None:
+ saved_cursor = "https://graph.facebook.com/v20/act_1/insights?after=resume"
+ state = MetaAdsResumeConfig(
+ end_date="2026-04-21",
+ chunk_since="2026-04-21",
+ chunk_size_days=1,
+ chunk_next_url=saved_cursor,
+ chunk_limit=50,
+ )
+ manager = _build_manager(can_resume=True, state=state)
+ responses = [_mock_response(200, {"data": [{"ad_id": "x"}], "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
+ list(
+ _iter_time_range_pagination(
+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, state, manager
+ )
+ )
+
+ # The resumed cursor was reissued with the persisted limit (50), not the default 500.
+ assert mock_get.return_value.get.call_args_list[0].args[0] == saved_cursor + "&limit=50"
+
+ def test_resume_honors_chunk_limit_for_initial_chunk_request(self) -> None:
+ # When resume state has chunk_limit but no chunk_next_url, the fresh
+ # initial chunk request must also use the reduced limit.
+ state = MetaAdsResumeConfig(
+ end_date="2026-04-21",
+ chunk_since="2026-04-21",
+ chunk_size_days=1,
+ chunk_next_url=None,
+ chunk_limit=100,
+ )
+ manager = _build_manager(can_resume=True, state=state)
+ responses = [_mock_response(200, {"data": [{"ad_id": "y"}], "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
+ list(
+ _iter_time_range_pagination(
+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, state, manager
+ )
+ )
+
+ sent_params = mock_get.return_value.get.call_args_list[0].kwargs["params"]
+ assert sent_params["limit"] == 100
+
+ def test_exhausting_limit_ladder_raises(self) -> None:
+ manager = _build_manager()
+ timeout_body = {"error": {"error_subcode": 1504018, "message": "timeout"}}
+ responses = [
+ # Initial chunk: page 1 + cursor.
+ _mock_response(
+ 200,
+ {
+ "data": [{"ad_id": "1"}],
+ "paging": {"next": "https://graph.facebook.com/v20/act_1/insights?after=p1"},
+ },
+ ),
+ # All limits in PAGE_LIMIT_FALLBACK_SIZES time out.
+ *[_mock_response(500, timeout_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
+ gen = _iter_time_range_pagination(
+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager
+ )
+ # 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"):
+ list(gen)
+
+ def test_non_timeout_mid_chunk_error_does_not_retry(self) -> None:
+ manager = _build_manager()
+ responses = [
+ _mock_response(
+ 200,
+ {
+ "data": [{"ad_id": "1"}],
+ "paging": {"next": "https://graph.facebook.com/v20/act_1/insights?after=p1"},
+ },
+ ),
+ _mock_response(401, {"error": {"message": "Invalid OAuth access token", "code": 190}}),
+ ]
+
+ 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
+ gen = _iter_time_range_pagination(
+ self.URL, self.PARAMS, {"since": "2026-04-21", "until": "2026-04-21"}, None, manager
+ )
+ assert next(gen) == [{"ad_id": "1"}]
+ with pytest.raises(Exception, match="Meta API request failed: 401"):
+ list(gen)
+
+ # Exactly two requests: initial + the failed cursor. No retry happened.
+ assert mock_get.return_value.get.call_count == 2
+
+
+class TestNonRetryableErrors:
+ @pytest.mark.parametrize(
+ "error_message",
+ [
+ # Token refresh failure raised by get_integration.
+ "Failed to refresh token for Meta Ads integration. Please re-authorize the integration.",
+ # 400 from Meta when the ad account no longer belongs to the authorised user.
+ 'Meta API request failed: 400 - {"error":{"message":"(#200) Ad account owner has NOT granted ads_management or ads_read permission.","type":"OAuthException","code":200}}',
+ # 400 when a specific endpoint cannot be accessed with the granted permissions.
+ 'Meta API request failed: 400 - {"error":{"message":"(#100) This endpoint cannot be loaded due to missing permissions."}}',
+ # 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"}}',
+ ],
+ )
+ def test_errors_match_pattern(self, error_message: str) -> None:
+ patterns = MetaAdsSource().get_non_retryable_errors()
+ assert any(pattern in error_message for pattern in patterns), (
+ f"Meta Ads error '{error_message}' does not match any non-retryable pattern"
+ )