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(appfigures): stop gracefully at the reviews page-depth cap (#72489)

Tom Owers0d4bd46b5161
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
index ee7f1a3060cf..f11e28e67c8c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
@@ -28,6 +28,15 @@ class AppfiguresRetryableError(Exception):
pass
+class AppfiguresPageLimitError(Exception):
+ """Appfigures caps offset pagination at page*count <= 10000 on list endpoints (e.g. reviews).
+ Past the cap it returns 400 with a stable "must be less than or equal to 10000" message. `_fetch`
+ raises this so the caller stops paginating and keeps the rows gathered so far, rather than letting
+ a benign end-of-traversable-data response fail the whole sync via `raise_for_status`."""
+
+ pass
+
+
@dataclasses.dataclass
class AppfiguresResumeConfig:
# "paged" endpoints (reviews): the next page number to fetch (1-based).
@@ -61,6 +70,16 @@ def _to_date_str(value: Any) -> str | None:
return text
+def _is_page_limit_response(response: requests.Response) -> bool:
+ """Detect the page*count>10000 offset-pagination cap. Appfigures surfaces the message via the
+ HTTP reason phrase (picked up by `raise_for_status`), but check the body too in case it's there
+ instead."""
+ if response.status_code != 400:
+ return False
+ text = f"{response.reason or ''} {response.text or ''}"
+ return "must be less than or equal to 10000" in text.lower()
+
+
@retry(
retry=retry_if_exception_type((AppfiguresRetryableError, requests.ReadTimeout, requests.ConnectionError)),
stop=stop_after_attempt(5),
@@ -80,6 +99,9 @@ def _fetch(
if response.status_code == 429 or response.status_code >= 500:
raise AppfiguresRetryableError(f"Appfigures API error (retryable): status={response.status_code}, url={url}")
+ if _is_page_limit_response(response):
+ raise AppfiguresPageLimitError()
+
if not response.ok:
logger.error(f"Appfigures API error: status={response.status_code}, body={response.text}, url={url}")
response.raise_for_status()
@@ -136,7 +158,12 @@ def _iter_paged(
url = f"{APPFIGURES_BASE_URL}{config.path}"
while True:
- data = _fetch(session, url, params, logger)
+ try:
+ data = _fetch(session, url, params, logger)
+ except AppfiguresPageLimitError:
+ logger.info(f"Appfigures: reached page-depth cap, stopping at rows gathered so far: url={url}")
+ break
+
rows = data.get(config.data_key, []) if config.data_key else []
total_pages = data.get("pages", 1) or 1
this_page = data.get("this_page", page) or page
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
index 25d5d63a0100..01eaef2f862e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures
AppfiguresResumeConfig,
_flatten_report,
_headers,
+ _is_page_limit_response,
_to_date_str,
appfigures_source,
check_credentials,
@@ -18,6 +19,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures"
+_PAGE_LIMIT_REASON = (
+ "page * count must be less than or equal to 10000. Please request fewer products or a smaller date range."
+)
+
+
+def _response(status_code: int, reason: str = "", text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.reason = reason
+ response.text = text
+ response.ok = status_code < 400
+ return response
+
def _manager(resume: AppfiguresResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
@@ -86,6 +100,24 @@ class TestIterObject:
assert {row["id"] for row in batches[0]} == {42, 7}
+class TestIsPageLimitResponse:
+ @pytest.mark.parametrize(
+ "status_code,reason,text,expected",
+ [
+ (400, _PAGE_LIMIT_REASON, "", True),
+ (400, "Bad Request", _PAGE_LIMIT_REASON, True),
+ # A different 400 (e.g. a malformed param) must stay fatal, not be swallowed as the cap.
+ (400, "Bad Request", "", False),
+ # Same wording on another status isn't the page-depth cap.
+ (403, _PAGE_LIMIT_REASON, "", False),
+ (200, _PAGE_LIMIT_REASON, "", False),
+ ],
+ )
+ def test_detects_page_limit(self, status_code: int, reason: str, text: str, expected: bool):
+ response = _response(status_code, reason=reason, text=text)
+ assert _is_page_limit_response(response) is expected
+
+
class TestIterPaged:
def test_walks_all_pages_using_pages_and_this_page(self):
pages = [
@@ -146,6 +178,30 @@ class TestIterPaged:
)
assert fetch.call_args_list[0].args[2]["page"] == 3
+ def test_page_limit_stops_and_keeps_rows_gathered_so_far(self):
+ # A backlog deep enough that offset pagination would cross Appfigures' page*count<=10000
+ # cap. Page 1 succeeds; page 2 hits the cap. get_rows must yield page 1's rows and NOT raise
+ # (the reported bug turned this benign boundary into a fatal HTTPError).
+ page1 = _response(200)
+ page1.json.return_value = {"total": 50000, "pages": 100, "this_page": 1, "reviews": [{"id": "a"}]}
+ page_limit = _response(400, reason=_PAGE_LIMIT_REASON)
+
+ session = mock.MagicMock()
+ session.get.side_effect = [page1, page_limit]
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="reviews",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ )
+
+ assert [row["id"] for batch in batches for row in batch] == ["a"]
+ assert session.get.call_count == 2
+
class TestIterReport:
@freeze_time("2024-02-15")