: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(data-warehouse): stop shippo syncs failing at the pagination depth cap (#103686)
Tom Owers26856624c1e6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/shippo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/shippo.pyindex 2b684625e28c..984aa900bc0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/shippo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/shippo.py@@ -2,7 +2,7 @@ import dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optional-from urllib.parse import urlencode, urlsplit+from urllib.parse import parse_qs, urlencode, urlsplitimport requestsfrom structlog.types import FilteringBoundLogger@@ -117,16 +117,51 @@ def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLoggereturn data+def _page_number(url: str) -> Optional[int]:+ raw = parse_qs(urlsplit(url).query).get("page", [None])[0]+ if raw is None:+ return None+ try:+ return int(raw)+ except ValueError:+ return None+++def _is_pagination_cap(error: requests.HTTPError, url: str) -> bool:+ """Was this 404 Shippo refusing a page number past its pagination depth limit?++ Shippo keeps advertising a `next` link past the deepest page its list endpoints will+ serve, and answers that page with 404 instead of an empty result set. Only a paged URL+ can hit that limit, so a 404 on the unpaged first page is still a real failure.+ """+ response = getattr(error, "response", None)+ if response is None or response.status_code != 404:+ return False+ page = _page_number(url)+ return page is not None and page > 1++def _paginate(session: requests.Session,first_url: str,window_start: str | None,+ endpoint: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[ShippoResumeConfig],) -> Iterator[list[dict[str, Any]]]:url: str | None = first_urlwhile url:- data = _fetch_page(session, _validate_pagination_url(url), logger)+ validated_url = _validate_pagination_url(url)+ try:+ data = _fetch_page(session, validated_url, logger)+ except requests.HTTPError as error:+ if not _is_pagination_cap(error, validated_url):+ raise+ logger.warning(+ f"Shippo did not return page {_page_number(validated_url)} of {endpoint}. "+ "Shippo limits how deep you can page through a list endpoint, so this table may be missing some records."+ )+ returnitems: list[dict[str, Any]] = data["results"]if items:yield items@@ -183,7 +218,7 @@ def get_rows("object_created_lte": _format_datetime(window_end),},)- yield from _paginate(session, first_url, start_iso, logger, resumable_source_manager)+ yield from _paginate(session, first_url, start_iso, endpoint, logger, resumable_source_manager)window_start = window_endresumable_source_manager.save_state(@@ -195,7 +230,7 @@ def get_rows(logger.debug(f"Shippo: resuming {endpoint} from {first_url}")else:first_url = _build_url(config.path, {"results": PAGE_SIZE})- yield from _paginate(session, first_url, None, logger, resumable_source_manager)+ yield from _paginate(session, first_url, None, endpoint, logger, resumable_source_manager)def shippo_source(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.pyindex c2a00d53aa09..f826b3931853 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shippo/tests/test_shippo.py@@ -46,12 +46,18 @@ def _query_params(url: str) -> dict[str, str]:return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}+def _http_error(status: int) -> requests.HTTPError:+ response = MagicMock()+ response.status_code = status+ return requests.HTTPError(f"{status} Client Error", response=response)++class TestGetRows:@staticmethoddef _collect(manager: _FakeResumableManager,monkeypatch: Any,- pages: dict[str, dict],+ pages: dict[str, Any],endpoint: str = "shipments",should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,@@ -62,6 +68,8 @@ class TestGetRows:requested.append(url)for prefix, response in pages.items():if url.startswith(prefix):+ if isinstance(response, Exception):+ raise responsereturn responseraise AssertionError(f"Unexpected URL fetched: {url}")@@ -182,6 +190,42 @@ class TestGetRows:assert rows == [{"object_id": "s"}]assert "object_created_gt" not in requested[0]+ def test_pagination_cap_404_ends_the_table_without_failing(self, monkeypatch: Any) -> None:+ # Shippo advertises a `next` link past its deepest addressable page and 404s that page.+ # Following it must finish the table, not fail the whole sync.+ manager = _FakeResumableManager()+ capped_page = f"{SHIPPO_BASE_URL}/addresses/?page=1001&results={PAGE_SIZE}"+ pages: dict[str, Any] = {+ capped_page: _http_error(404),+ f"{SHIPPO_BASE_URL}/addresses/?results={PAGE_SIZE}": {+ "next": capped_page,+ "results": [{"object_id": "a"}],+ },+ }+ rows, requested = self._collect(manager, monkeypatch, pages, endpoint="addresses")++ assert rows == [{"object_id": "a"}]+ assert requested[-1] == capped_page++ def test_resuming_onto_a_capped_page_ends_cleanly(self, monkeypatch: Any) -> None:+ # The capped URL is persisted as resume state before it is ever fetched, so a resumed+ # run starts on it and must still terminate instead of retrying the 404 forever.+ capped_page = f"{SHIPPO_BASE_URL}/addresses/?page=1001&results={PAGE_SIZE}"+ manager = _FakeResumableManager(ShippoResumeConfig(next_url=capped_page, window_start=None))+ rows, requested = self._collect(manager, monkeypatch, {capped_page: _http_error(404)}, endpoint="addresses")++ assert rows == []+ assert requested == [capped_page]++ @parameterized.expand([("unpaged_first_page", ""), ("explicit_first_page", "page=1&")])+ def test_404_outside_the_pagination_cap_still_fails(self, _name: str, page_param: str) -> None:+ # A 404 that is not a deep-page refusal means the endpoint itself is gone; swallowing it+ # would silently sync an empty table.+ url = f"{SHIPPO_BASE_URL}/addresses/?{page_param}results={PAGE_SIZE}"+ manager = _FakeResumableManager(ShippoResumeConfig(next_url=url) if page_param else None)+ with pytest.MonkeyPatch.context() as monkeypatch, pytest.raises(requests.HTTPError):+ self._collect(manager, monkeypatch, {url: _http_error(404)}, endpoint="addresses")+def test_first_page_url_uses_endpoint_path(self, monkeypatch: Any) -> None:# The customs endpoints live under a nested path; a bare name-derived URL would 404.manager = _FakeResumableManager()