: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): keep loop returns date windows inside the api cap (#104158)
Tom Owers7f389f67d55d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.pyindex 8d34c833ab7b..b1737051110b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py@@ -75,8 +75,8 @@ def start_date_error(start_date: str, now: Optional[datetime] = None) -> Optiona"""Why a configured start date is unusable, or None if it's fine.Rejects a date we can't parse, and one reaching back further than `MAX_BACKFILL_DAYS`: the- returns endpoint walks history one 120-day window per state pass, so an unbounded lookback- would turn a single sync into thousands of empty-window requests.+ returns endpoint walks history one window per state pass, so an unbounded lookback would turn+ a single sync into thousands of empty-window requests."""try:parsed = parse_datetime(start_date)@@ -162,10 +162,10 @@ class LoopReturnsResumeConfig:class LoopReturnsPaginator(BasePaginator):- """Walks `state` passes, then 120-day windows within each pass, then cursor pages in a window.+ """Walks `state` passes, then date windows within each pass, then cursor pages in a window.- Loop caps a list request at a 120-day range and its `state` filter takes a single value, so a- full history needs several requests along both axes. Pages are ordered oldest window first;+ Loop caps a list request's date range and its `state` filter takes a single value, so a full+ history needs several requests along both axes. Pages are ordered oldest window first;within a window Loop documents no ordering, which is why the source declares `sort_mode="desc"`for incremental syncs and lets the watermark land only once a run completes."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.pyindex 6edc944701b7..f9d6fd215a61 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py@@ -3,9 +3,14 @@ from dataclasses import dataclassfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_fieldfrom products.warehouse_sources.backend.types import IncrementalField-# Loop rejects a list request whose `from`/`to` range is wider than 120 days, so backfills walk-# the history in windows of at most this size.-MAX_WINDOW_DAYS = 120+# Loop documents a 120-day maximum for a list request's `from`/`to` range.+API_MAX_RANGE_DAYS = 120++# How wide a window actually asks for. A range whose bounds sit exactly the documented maximum+# apart is rejected with a 422, and Loop doesn't say where its off-by-one is, so a window keeps a+# margin under the cap. A quarter matches the range in Loop's own example request and costs a+# couple of extra requests per backfill.+MAX_WINDOW_DAYS = 90# `pageSize` accepts up to 750. Return rows carry nested line items, exchanges and labels, so we# stay well under the cap to keep a single page's payload modest.@@ -15,8 +20,8 @@ DEFAULT_PAGE_SIZE = 250# Loop only returns the previous 24 hours, so a default is required for a usable backfill.DEFAULT_BACKFILL_DAYS = 730-# The furthest back a configured start date may reach. A backfill walks history one 120-day window-# per state pass, so an unbounded start date turns a single sync into thousands of empty-window+# The furthest back a configured start date may reach. A backfill walks history one window per+# state pass, so an unbounded start date turns a single sync into thousands of empty-window# requests that tie up a worker. Cap the lookback at validation time instead.MAX_BACKFILL_DAYS = 5 * 365diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.pyindex 9fb6363ce1b4..7d5de15e822a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py@@ -25,10 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returvalidate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.settings import (+ API_MAX_RANGE_DAYS,DEFAULT_BACKFILL_DAYS,LOOP_RETURNS_ENDPOINTS,MAX_BACKFILL_DAYS,- MAX_WINDOW_DAYS,RETURN_STATES,)@@ -98,21 +98,22 @@ class TestLoopReturnsPaginator:assert request.params == {"from": "2024-01-01T00:00:00.000Z",- "to": "2024-04-30T00:00:00.000Z",+ "to": "2024-03-31T00:00:00.000Z","filter": "created_at","state": "open","paginate": "true","pageSize": 250,}- def test_windows_never_exceed_the_api_range_cap(self) -> None:- # Loop rejects a range wider than 120 days, so every window has to stay inside it.+ def test_windows_stay_inside_the_api_range_cap(self) -> None:+ # A window spanning Loop's full documented 120-day range comes back 422, which fails the+ # whole sync, so every window has to ask for a strictly narrower range.sent = _walk(_paginator(days=250), [{"returns": [], "nextPageUrl": None}] * 3)for params in sent:start = datetime.fromisoformat(params["from"].replace("Z", "+00:00"))end = datetime.fromisoformat(params["to"].replace("Z", "+00:00"))- assert end - start <= timedelta(days=MAX_WINDOW_DAYS)+ assert end - start < timedelta(days=API_MAX_RANGE_DAYS)def test_windows_walk_the_whole_range_then_restart_for_the_next_state(self) -> None:# Loop's `state` filter takes one value and defaults to open/closed/expired, so cancelled@@ -121,9 +122,9 @@ class TestLoopReturnsPaginator:first_pass = [(params["from"], params["to"]) for params in sent[:3]]assert first_pass == [- ("2024-01-01T00:00:00.000Z", "2024-04-30T00:00:00.000Z"),- ("2024-04-30T00:00:00.000Z", "2024-08-28T00:00:00.000Z"),- ("2024-08-28T00:00:00.000Z", "2024-09-07T00:00:00.000Z"),+ ("2024-01-01T00:00:00.000Z", "2024-03-31T00:00:00.000Z"),+ ("2024-03-31T00:00:00.000Z", "2024-06-29T00:00:00.000Z"),+ ("2024-06-29T00:00:00.000Z", "2024-09-07T00:00:00.000Z"),]assert [params["state"] for params in sent] == [state for state in RETURN_STATES for _ in range(3)]assert sent[3]["from"] == "2024-01-01T00:00:00.000Z"@@ -173,7 +174,7 @@ class TestLoopReturnsPaginator:],)saved = paginator.get_resume_state()- assert saved == {"window_start": "2024-04-30T00:00:00.000Z", "state_index": 0, "cursor": "xyz"}+ assert saved == {"window_start": "2024-03-31T00:00:00.000Z", "state_index": 0, "cursor": "xyz"}resumed = _paginator(days=250)resumed.set_resume_state(cast(dict[str, Any], saved))@@ -181,7 +182,7 @@ class TestLoopReturnsPaginator:resumed.init_request(request)assert request.params is not None- assert request.params["from"] == "2024-04-30T00:00:00.000Z"+ assert request.params["from"] == "2024-03-31T00:00:00.000Z"assert request.params["cursor"] == "xyz"assert request.params["state"] == "open"@@ -226,11 +227,12 @@ class TestLoopReturnsPaginator:assert request.params["to"] == request.params["from"]def test_endpoint_without_pagination_or_states_only_windows(self) -> None:- sent = _walk(_paginator("advanced_shipping_notices", days=200), [[], []])+ sent = _walk(_paginator("advanced_shipping_notices", days=200), [[], [], []])assert [(params["from"], params["to"]) for params in sent] == [- ("2024-01-01T00:00:00.000Z", "2024-04-30T00:00:00.000Z"),- ("2024-04-30T00:00:00.000Z", "2024-07-19T00:00:00.000Z"),+ ("2024-01-01T00:00:00.000Z", "2024-03-31T00:00:00.000Z"),+ ("2024-03-31T00:00:00.000Z", "2024-06-29T00:00:00.000Z"),+ ("2024-06-29T00:00:00.000Z", "2024-07-19T00:00:00.000Z"),]assert all("state" not in params and "cursor" not in params for params in sent)# The ASN report doesn't accept the `filter` param, so it must not be sent.