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.

fix(warehouse-sources): narrow Meta chunk when page limit bottoms out (#80977)

jake sciottoe6244dce8088
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.py
index 36e2313e30fe..5d19e38edfd0 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
@@ -247,9 +247,11 @@ 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.
+# re-issue earlier pages and re-emit rows we've already produced. So we prefer
+# to shrink the per-page ``limit`` and retry the same cursor URL, which Meta
+# accepts as a query param on cursor URLs. Only once this ladder bottoms out
+# does the chunk ladder take over, because a re-emit costs less than a dead sync
+# and every stats table keys on its breakdown columns, so the rows upsert.
PAGE_LIMIT_FALLBACK_SIZES = [500, 100, 50]
# Meta's Graph API intermittently returns HTTP 200 with a truncated/partial JSON
@@ -289,6 +291,22 @@ def _next_smaller_limit(current: int) -> int | None:
return max(smaller) if smaller else None
+def _next_smaller_chunk_size(current: int) -> int | None:
+ """Return the next smaller value in ``TIME_RANGE_CHUNK_SIZES``.
+
+ Returns ``None`` if ``current`` is already at or below the smallest rung. A
+ resumed sync can carry a chunk size that predates the current ladder, so an
+ off-ladder value steps to the largest rung below it rather than giving up.
+ """
+ if current in TIME_RANGE_CHUNK_SIZES:
+ idx = TIME_RANGE_CHUNK_SIZES.index(current)
+ if idx >= len(TIME_RANGE_CHUNK_SIZES) - 1:
+ return None
+ return TIME_RANGE_CHUNK_SIZES[idx + 1]
+ smaller = [s for s in TIME_RANGE_CHUNK_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.
@@ -686,13 +704,14 @@ def _iter_time_range_pagination(
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.
+ - **Chunk size** (``TIME_RANGE_CHUNK_SIZES``): shrunk when the *initial*
+ chunk request times out, before any rows are yielded, and as the last
+ resort for a *cursor* timeout once the page limit bottoms out.
+ - **Page limit** (``PAGE_LIMIT_FALLBACK_SIZES``): the first lever for a
+ *cursor* request that times out after we already yielded earlier pages
+ from this chunk. Overriding the ``limit`` on the same cursor URL leaves
+ those pages alone, so we exhaust this ladder before restarting the chunk
+ at a smaller size and re-yielding them.
Resume state captures both levels: ``chunk_since`` + ``chunk_size_days``
for the outer loop, ``chunk_next_url`` when the crash happened mid-chunk,
@@ -740,6 +759,9 @@ def _iter_time_range_pagination(
# Params of the initial chunk request, kept so a truncated 200 body can be
# re-fetched. Only set on the non-resume path; unused once we're on a cursor.
chunk_params: dict | None = None
+ # Set when the page-limit ladder bottoms out mid-chunk and a smaller chunk
+ # takes over, so the outer loop restarts this chunk instead of advancing.
+ restart_chunk = False
if pending_next_url:
# Mid-chunk resume: re-attach a fresh access_token at request time
@@ -759,11 +781,10 @@ def _iter_time_range_pagination(
if response.status_code != 200:
# Fallback only happens on the initial chunk request (before any data is yielded).
if _should_shrink_request(response):
- if chunk_size_days in TIME_RANGE_CHUNK_SIZES:
- current_index = TIME_RANGE_CHUNK_SIZES.index(chunk_size_days)
- if current_index < len(TIME_RANGE_CHUNK_SIZES) - 1:
- chunk_size_days = TIME_RANGE_CHUNK_SIZES[current_index + 1]
- continue
+ smaller_chunk = _next_smaller_chunk_size(chunk_size_days)
+ if smaller_chunk is not None:
+ chunk_size_days = smaller_chunk
+ continue
# The date range is already a single day, so the page size
# is the only dimension left. Re-issuing the same chunk at a
# smaller limit is safe: nothing has been yielded yet.
@@ -787,6 +808,20 @@ def _iter_time_range_pagination(
retry_url = _override_limit(last_paging_url, current_limit)
response = _fetch_paging_url(retry_url, access_token)
continue
+ # The page limit cannot go lower, so narrow the window instead and
+ # restart this chunk from its first day. Meta prices an insights
+ # request on the window and the breakdown, not on the page size, so
+ # a chunk this heavy keeps timing out at every limit. Re-yielding
+ # the chunk's earlier pages costs a merge that the primary key
+ # already dedupes, which beats failing the whole sync.
+ smaller_chunk = _next_smaller_chunk_size(chunk_size_days)
+ if smaller_chunk is not None:
+ chunk_size_days = smaller_chunk
+ # Drop the saved cursor. It encodes the wider window, so a
+ # resume has to re-enter this chunk at the new size.
+ _save(current_start, chunk_size_days, None)
+ restart_chunk = True
+ break
_raise_shrink_exhausted_error(response)
_raise_meta_api_error(response)
@@ -824,6 +859,9 @@ def _iter_time_range_pagination(
last_paging_url = stripped_next_url
response = _fetch_paging_url(_override_limit(stripped_next_url, current_limit), access_token)
+ if restart_chunk:
+ continue
+
current_start = current_end + dt.timedelta(days=1)
# Always save the chunk-boundary state, even when we've advanced past
# end_date. This clears any stale mid-chunk next_url from the previous
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.py
index ba5f6642a66f..a7b3046ca72d 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
@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.m
_is_transient_error,
_iter_simple_pagination,
_iter_time_range_pagination,
+ _next_smaller_chunk_size,
_next_smaller_limit,
_override_limit,
_raise_meta_api_error,
@@ -920,6 +921,24 @@ class TestNextSmallerLimit:
assert _next_smaller_limit(current) == expected
+class TestNextSmallerChunkSize:
+ @pytest.mark.parametrize(
+ "current,expected",
+ [
+ (30, 7),
+ (7, 1),
+ # Smallest rung, so no further fallback is available.
+ (1, None),
+ # A resumed sync can carry a size between rungs; it picks the largest below it.
+ (14, 7),
+ # A resumed size above the largest rung steps down to that rung.
+ (60, 30),
+ ],
+ )
+ def test_step(self, current: int, expected: int | None) -> None:
+ assert _next_smaller_chunk_size(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"}
@@ -1035,9 +1054,11 @@ class TestMidChunkLimitFallback:
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:
+ def test_exhausting_limit_ladder_falls_back_to_smaller_chunk(self) -> None:
manager = _build_manager()
timeout_body = {"error": {"error_subcode": 1504018, "message": "timeout"}}
+ # 04-01..04-08 is one 30-day attempt clamped to the range end. Once the limit
+ # ladder bottoms out mid-chunk, 7-day chunks cover it: 04-01..04-07, 04-08.
responses = [
# Initial chunk: page 1 + cursor.
_mock_response(
@@ -1049,6 +1070,59 @@ class TestMidChunkLimitFallback:
),
# All limits in PAGE_LIMIT_FALLBACK_SIZES time out.
*[_mock_response(500, timeout_body) for _ in PAGE_LIMIT_FALLBACK_SIZES],
+ _mock_response(200, {"data": [{"ad_id": "2"}], "paging": {}}),
+ _mock_response(200, {"data": [{"ad_id": "3"}], "paging": {}}),
+ ]
+
+ with mock.patch(
+ "products.warehouse_sources.backend.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-01", "until": "2026-04-08"}, None, manager
+ )
+ )
+
+ assert [b[0]["ad_id"] for b in batches] == ["1", "2", "3"]
+
+ # Every rung was tried on the same cursor before the chunk narrowed.
+ cursor_calls = [c.args[0] for c in mock_get.return_value.get.call_args_list[1:4]]
+ assert cursor_calls == [
+ f"https://graph.facebook.com/v20/act_1/insights?after=p1&limit={limit}"
+ for limit in PAGE_LIMIT_FALLBACK_SIZES
+ ]
+
+ # The restarted chunk re-requests the window from its first day, at 7 days,
+ # keeping the smallest limit so the request only ever gets cheaper.
+ restart_params = mock_get.return_value.get.call_args_list[4].kwargs["params"]
+ assert json.loads(restart_params["time_range"]) == {"since": "2026-04-01", "until": "2026-04-07"}
+ assert restart_params["limit"] == PAGE_LIMIT_FALLBACK_SIZES[-1]
+
+ # The restart drops the saved cursor, which still encodes the wider window.
+ restart_save: MetaAdsResumeConfig = next(
+ s.args[0] for s in manager.save_state.call_args_list if s.args[0].chunk_size_days == 7
+ )
+ assert restart_save.chunk_since == "2026-04-01"
+ assert restart_save.chunk_next_url is None
+
+ def test_exhausting_both_ladders_mid_chunk_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"},
+ },
+ ),
+ # Every page limit on the cursor times out, and so does the restarted
+ # chunk at each remaining size (7 days, then 1 day).
+ *[_mock_response(500, timeout_body) for _ in PAGE_LIMIT_FALLBACK_SIZES],
+ _mock_response(500, timeout_body),
+ _mock_response(500, timeout_body),
]
with mock.patch(
@@ -1063,6 +1137,9 @@ class TestMidChunkLimitFallback:
with pytest.raises(Exception, match=SHRINK_EXHAUSTED_ERROR_MESSAGE):
list(gen)
+ # Both ladders terminate rather than looping on the smallest request.
+ assert mock_get.return_value.get.call_count == len(responses)
+
def test_non_timeout_mid_chunk_error_does_not_retry(self) -> None:
manager = _build_manager()
responses = [