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(data-warehouse): add Loop Returns source (#77102)

Tom Owersdcd08d362e80
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index d4d456054dd9..0f58c4aa1c4b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -379,6 +379,7 @@ the row lists both.
| llama_cloud | HTTP | requests | ✅ |
| lob | HTTP | requests | ✅ |
| logz_io | HTTP | requests | ✅ |
+| loop_returns | HTTP | requests + `rest_source.RESTClient` | ✅ |
| loops | HTTP | requests + `rest_source.RESTClient` | ✅ |
| luma | HTTP | requests | ✅ |
| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1092,7 +1093,6 @@ doesn't conflict with concurrent PRs.
- logrocket
- lokalise
- looker
-- loop_returns
- m3ter
- mailtrap
- mantle
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/loopreturns.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/loopreturns.py
index 8ff188b7c6ba..cc87c02dbafd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/loopreturns.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/loopreturns.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class LoopReturnsSourceConfig(config.Config):
- pass
+ api_key: str
+ start_date: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/canonical_descriptions.py
new file mode 100644
index 000000000000..b9c33499a6fc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/canonical_descriptions.py
@@ -0,0 +1,125 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "returns": {
+ "description": "Returns created in your Loop shop, with their line items, exchanges, refund breakdown and shipping label.",
+ "docs_url": "https://docs.loopreturns.com/api-reference/latest/return-data/detailed-returns-list",
+ "columns": {
+ "id": "Unique identifier for the return.",
+ "state": "Current state of the return: open, closed, cancelled, expired or review.",
+ "created_at": "When the return was created.",
+ "updated_at": "When the return was last updated.",
+ "edited_at": "When the return was last edited.",
+ "total": "Total value of the return.",
+ "outcome": "What the customer chose: exchange, upsell, refund, credit, or a combination.",
+ "order_id": "Identifier of the order the return was created from.",
+ "order_name": "Name of the order the return was created from.",
+ "order_number": "Number of the order the return was created from.",
+ "provider_order_id": "Order identifier in the commerce platform Loop is connected to.",
+ "provider_order_number": "Order number in the commerce platform Loop is connected to.",
+ "customer": "Email address of the customer who made the return.",
+ "origin_country": "Country the return is shipped from.",
+ "origin_country_code": "ISO 3166-1 alpha-2 code of the country the return is shipped from.",
+ "multi_currency": "Whether the return involves more than one currency.",
+ "currency": "ISO 4217 currency code the return amounts are given in.",
+ "return_product_total": "Value of the returned products before discounts and tax.",
+ "return_discount_total": "Discounts applied to the returned products.",
+ "return_tax_total": "Tax on the returned products.",
+ "return_total": "Total value of the returned products.",
+ "refund_shipping_total": "Shipping amount included in the refund.",
+ "refund_shipping_tax_total": "Tax on the refunded shipping amount.",
+ "return_credit_total": "Store credit issued for the return.",
+ "exchange_product_total": "Value of the exchange products before discounts and tax.",
+ "exchange_discount_total": "Discounts applied to the exchange products.",
+ "exchange_tax_total": "Tax on the exchange products.",
+ "exchange_total": "Total value of the exchange products.",
+ "exchange_credit_total": "Store credit applied to the exchange.",
+ "gift_card": "Value of the gift card issued for the return.",
+ "gift_card_order_name": "Name of the order the gift card was issued against.",
+ "gift_card_order_id": "Identifier of the order the gift card was issued against.",
+ "gift_card_presentment": "Gift card value and currency as presented to the customer.",
+ "handling_fee": "Handling fee charged for the return.",
+ "refund": "Amount refunded to the customer's original payment method.",
+ "upsell": "Amount the customer paid on top when upgrading their exchange.",
+ "line_items": "Items being returned, each with its reason, refund breakdown, condition and disposition.",
+ "presentment": "Return totals in the currency shown to the customer.",
+ "exchanges": "Items the customer chose in exchange for the returned items.",
+ "carrier": "Carrier used for the return shipment.",
+ "tracking_number": "Tracking number of the return shipment.",
+ "label_status": "Status of the return shipping label.",
+ "label_url": "Link to the return shipping label.",
+ "label_rate": "Cost of the return shipping label.",
+ "status_page_url": "Link to the customer-facing status page for the return.",
+ "label_updated_at": "When the return shipping label was last updated.",
+ "destination_id": "Identifier of the destination the return is shipped to.",
+ "return_method": "How the return is being sent back, including the address and its state.",
+ "package_reference": "Reference of the package the return was shipped in.",
+ "type": "Type of return: standard or warranty.",
+ "labels": "All shipping labels created for the return.",
+ },
+ },
+ "advanced_shipping_notices": {
+ "description": "Advanced shipping notice report: one row per returned item, with its shipment, restock and destination details.",
+ "docs_url": "https://docs.loopreturns.com/api-reference/latest/return-data/advanced-shipping-notice",
+ "columns": {
+ "id": "Identifier of the advanced shipping notice row.",
+ "return_line_item_id": "Identifier of the returned line item this row reports on.",
+ "order_id": "Identifier of the order the item was bought on.",
+ "order_name": "Name of the order the item was bought on.",
+ "order_number": "Number of the order the item was bought on.",
+ "provider_order_number": "Order number in the commerce platform Loop is connected to.",
+ "state": "State of the return: open, closed, expired, cancelled or review.",
+ "customer_email": "Email address of the customer who made the return.",
+ "title": "Title of the returned product.",
+ "purchase_price": "Price the item was bought for.",
+ "sku": "SKU of the returned product.",
+ "barcode": "Barcode of the returned product.",
+ "carrier": "Carrier handling the return shipment.",
+ "service": "Carrier service used for the return shipment.",
+ "label_status": "Status of the return shipping label.",
+ "tracking_number": "Tracking number of the return shipment.",
+ "integration_tracking_url": "Tracking link supplied by the connected integration.",
+ "restock_status": "Whether the item has been restocked.",
+ "currency": "ISO 4217 currency code the amounts are given in.",
+ "label_updated_at": "When the return shipping label was last updated.",
+ "label_url": "Link to the return shipping label.",
+ "label_rate": "Cost of the return shipping label.",
+ "closed_at": "When the return was closed.",
+ "updated_at": "When the return was last updated.",
+ "created_at": "When the return was created.",
+ "return_reason": "Reason the customer gave for returning the item.",
+ "actioned_by": "Who actioned the return.",
+ "return_method": "How the item was sent back.",
+ "return_method_rma_code": "RMA code of the return method.",
+ "return_method_state": "State of the return method, such as in transit or delivered.",
+ "date_delivered": "When the return shipment was delivered.",
+ "outcome": "What the customer chose: refund, exchange, credit, upsell, or a combination.",
+ "scannable_id": "Scannable identifier used at drop-off.",
+ "package_reference": "Reference of the package the item was shipped in.",
+ "shipping_box_barcode": "Barcode of the shipping box the item arrived in.",
+ "provider_created_at": "When the original order was created in the commerce platform.",
+ "destination_id": "Identifier of the destination the item is shipped to.",
+ "destination_name": "Name of the destination the item is shipped to.",
+ "destination_address1": "First address line of the destination.",
+ "destination_address2": "Second address line of the destination.",
+ "destination_city": "City of the destination.",
+ "destination_state": "State or region of the destination.",
+ "destination_zip": "Postal code of the destination.",
+ "consolidation_tracking": "Tracking number of the consolidated shipment, when the item was consolidated.",
+ },
+ },
+ "destinations": {
+ "description": "Places returns can be shipped to, such as warehouses and stores.",
+ "docs_url": "https://docs.loopreturns.com/api-reference/latest/destinations/get-all-destinations",
+ "columns": {
+ "id": "Unique identifier for the destination.",
+ "type": "Type of destination.",
+ "name": "Name of the destination.",
+ "enabled": "Whether returns can currently be routed to the destination.",
+ "provider_location_id": "Matching location identifier in the commerce platform Loop is connected to.",
+ "address": "Postal address of the destination.",
+ },
+ },
+}
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.py
new file mode 100644
index 000000000000..7aae6be5f7b2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py
@@ -0,0 +1,446 @@
+import logging
+import dataclasses
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlsplit
+
+from requests import Request, Response
+from requests.exceptions import RequestException
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.settings import (
+ DEFAULT_BACKFILL_DAYS,
+ DEFAULT_PAGE_SIZE,
+ FILTER_FIELDS,
+ LOOP_RETURNS_ENDPOINTS,
+ MAX_BACKFILL_DAYS,
+ MAX_WINDOW_DAYS,
+ LoopReturnsEndpointConfig,
+)
+
+logger = logging.getLogger(__name__)
+
+API_HOST = "https://api.loopreturns.com"
+AUTH_HEADER = "X-Authorization"
+PROBE_TIMEOUT_SECONDS = 30
+INVALID_START_DATE_ERROR = "Start date must be a date or datetime, for example 2024-01-01"
+START_DATE_TOO_OLD_ERROR = (
+ f"Start date can't be more than {MAX_BACKFILL_DAYS // 365} years ago. Pick a more recent date."
+)
+
+
+def base_url(api_version: str) -> str:
+ return f"{API_HOST}/api/{api_version}"
+
+
+def _format_datetime(value: datetime) -> str:
+ """Loop's documented format is `2022-01-01T00:00:00.000Z`; millisecond precision keeps window
+ boundaries exact so a watermark-derived start doesn't truncate backwards."""
+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def parse_datetime(value: Any) -> datetime:
+ if isinstance(value, datetime):
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+ raise ValueError(f"Cannot parse a datetime from {value!r}")
+
+
+def start_date_error(start_date: str, now: Optional[datetime] = None) -> Optional[str]:
+ """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.
+ """
+ try:
+ parsed = parse_datetime(start_date)
+ except ValueError:
+ return INVALID_START_DATE_ERROR
+
+ floor = (now or datetime.now(UTC)) - timedelta(days=MAX_BACKFILL_DAYS)
+ if parsed < floor:
+ return START_DATE_TOO_OLD_ERROR
+
+ return None
+
+
+def resolve_window_start(
+ *,
+ now: datetime,
+ start_date: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> datetime:
+ """Where a sync begins walking Loop's history.
+
+ An incremental run resumes at the stored watermark. Everything else starts at the configured
+ start date, falling back to `DEFAULT_BACKFILL_DAYS` — Loop returns only the previous 24 hours
+ when neither `from` nor `to` is sent, so a fresh sync always needs an explicit start.
+ """
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ return parse_datetime(db_incremental_field_last_value)
+
+ if start_date:
+ return parse_datetime(start_date)
+
+ return now - timedelta(days=DEFAULT_BACKFILL_DAYS)
+
+
+def resolve_filter_field(should_use_incremental_field: bool, incremental_field: Optional[str]) -> str:
+ """Which timestamp `from`/`to` apply to. Honors the cursor field the user picked."""
+ if should_use_incremental_field and incremental_field in FILTER_FIELDS:
+ return incremental_field
+ return FILTER_FIELDS[0]
+
+
+def next_cursor(response: Response) -> Optional[str]:
+ """The `cursor` value of the response's `nextPageUrl`, or `None` on the last page.
+
+ The cursor is re-applied to our own params rather than following `nextPageUrl` verbatim, so the
+ window and state filters stay attached to every page even if Loop's link were to drop them.
+ """
+ try:
+ body = response.json()
+ except ValueError:
+ return None
+
+ if not isinstance(body, dict):
+ return None
+
+ next_page_url = body.get("nextPageUrl")
+ if not next_page_url or not isinstance(next_page_url, str):
+ return None
+
+ cursors = parse_qs(urlsplit(next_page_url).query).get("cursor")
+ if not cursors or not cursors[0]:
+ # Undocumented shape: a next link we can't turn into a cursor. Stop this window rather than
+ # refetch page one forever, and log it so a link format change is visible.
+ logger.warning("Loop Returns nextPageUrl carried no cursor; treating the page as the last one")
+ return None
+
+ return cursors[0]
+
+
+class LoopReturnsResumeConfig:
+ """Checkpoint for a windowed endpoint: which state pass, which window, which page.
+
+ Windows are re-derived from `window_start` with a fixed width, so boundaries stay identical
+ across attempts. State is saved after a batch is yielded, so a crash re-yields the last batch
+ (merge dedupes on the primary key) instead of skipping it.
+ """
+
+ window_start: str
+ state_index: int = 0
+ cursor: Optional[str] = None
+
+
+class LoopReturnsPaginator(BasePaginator):
+ """Walks `state` passes, then 120-day 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;
+ 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.
+ """
+
+ def __init__(
+ self,
+ *,
+ config: LoopReturnsEndpointConfig,
+ window_start: datetime,
+ window_end: datetime,
+ filter_field: Optional[str] = None,
+ page_size: int = DEFAULT_PAGE_SIZE,
+ ) -> None:
+ super().__init__()
+ self._config = config
+ self._overall_start = window_start
+ self._overall_end = window_end
+ self._filter_field = filter_field
+ self._page_size = page_size
+ self._state_index = 0
+ self._current_start = window_start
+ self._cursor: Optional[str] = None
+ self._previous_cursor: Optional[str] = None
+
+ @property
+ def current_window(self) -> tuple[datetime, datetime]:
+ end = min(self._current_start + timedelta(days=MAX_WINDOW_DAYS), max(self._overall_end, self._current_start))
+ return self._current_start, end
+
+ def _apply(self, request: Request) -> None:
+ params = request.params if request.params is not None else {}
+ request.params = params
+
+ if self._config.windowed:
+ start, end = self.current_window
+ params["from"] = _format_datetime(start)
+ params["to"] = _format_datetime(end)
+ if self._config.supports_filter_param and self._filter_field:
+ params["filter"] = self._filter_field
+
+ if self._config.states:
+ params["state"] = self._config.states[self._state_index]
+
+ if self._config.paginate:
+ params["paginate"] = "true"
+ params["pageSize"] = self._page_size
+ if self._cursor is not None:
+ params["cursor"] = self._cursor
+ else:
+ params.pop("cursor", None)
+
+ def _advance_window(self) -> None:
+ _, end = self.current_window
+ if end < self._overall_end:
+ self._current_start = end
+ self._has_next_page = True
+ return
+
+ if self._state_index + 1 < len(self._config.states):
+ self._state_index += 1
+ self._current_start = self._overall_start
+ self._has_next_page = True
+ return
+
+ self._has_next_page = False
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if self._config.paginate:
+ cursor = next_cursor(response)
+ if cursor is not None and cursor != self._previous_cursor:
+ self._previous_cursor = cursor
+ self._cursor = cursor
+ self._has_next_page = True
+ return
+ if cursor is not None:
+ logger.warning("Loop Returns pagination is not advancing; treating the page as the last one")
+
+ self._cursor = None
+ self._previous_cursor = None
+ self._advance_window()
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {
+ "window_start": _format_datetime(self._current_start),
+ "state_index": self._state_index,
+ "cursor": self._cursor,
+ }
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ window_start = state.get("window_start")
+ if window_start is None:
+ return
+
+ self._current_start = parse_datetime(window_start)
+ saved_index = int(state.get("state_index") or 0)
+ self._state_index = min(max(saved_index, 0), max(len(self._config.states) - 1, 0))
+ cursor = state.get("cursor")
+ self._cursor = str(cursor) if cursor is not None else None
+ # Seed the repeat guard so a checkpoint whose cursor the API echoes back stops the window
+ # instead of looping on the same page.
+ self._previous_cursor = self._cursor
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"LoopReturnsPaginator(endpoint={self._config.name})"
+
+
+def get_resource(config: LoopReturnsEndpointConfig, should_use_incremental_field: bool) -> EndpointResource:
+ endpoint: Endpoint = {"path": config.path}
+ if config.data_selector is not None:
+ endpoint["data_selector"] = config.data_selector
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+
+def probe_endpoint(api_key: str, api_version: str, endpoint: str) -> tuple[bool, str | None]:
+ """One cheap request against `endpoint`, reporting whether the key can read it."""
+ config = LOOP_RETURNS_ENDPOINTS[endpoint]
+
+ params: dict[str, Any] = {}
+ if config.windowed:
+ end = datetime.now(UTC)
+ params["from"] = _format_datetime(end - timedelta(hours=1))
+ params["to"] = _format_datetime(end)
+ if config.paginate:
+ params["paginate"] = "true"
+ params["pageSize"] = 1
+
+ session = make_tracked_session(redact_values=(api_key,))
+ try:
+ response = session.get(
+ f"{base_url(api_version)}{config.path}",
+ headers={AUTH_HEADER: api_key},
+ params=params,
+ timeout=PROBE_TIMEOUT_SECONDS,
+ )
+ except RequestException as e:
+ return False, str(e)
+
+ if response.ok:
+ return True, None
+
+ if response.status_code in (401, 403):
+ return (
+ False,
+ f"Loop rejected the API key for {endpoint}. Check that the key exists and has the "
+ f"{config.required_scope} scope.",
+ )
+
+ return False, f"Loop returned HTTP {response.status_code} for {endpoint}: {response.text[:200]}"
+
+
+def validate_credentials(api_key: str, api_version: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name in LOOP_RETURNS_ENDPOINTS:
+ return probe_endpoint(api_key, api_version, schema_name)
+
+ is_valid, error = probe_endpoint(api_key, api_version, "returns")
+ if is_valid:
+ return True, None
+
+ # A key scoped for another table only is still a working key, so don't block setup on the
+ # returns probe alone. Per-table scope gaps surface in the table picker instead.
+ fallback_valid, _ = probe_endpoint(api_key, api_version, "destinations")
+ if fallback_valid:
+ return True, None
+
+ return False, error
+
+
+def endpoint_permissions(api_key: str, api_version: str, endpoints: list[str]) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ if endpoint not in LOOP_RETURNS_ENDPOINTS:
+ permissions[endpoint] = None
+ continue
+
+ is_valid, error = probe_endpoint(api_key, api_version, endpoint)
+ permissions[endpoint] = None if is_valid else error
+ return permissions
+
+
+def loop_returns_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+ resumable_source_manager: ResumableSourceManager[LoopReturnsResumeConfig],
+ start_date: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+ now: Optional[datetime] = None,
+) -> SourceResponse:
+ config = LOOP_RETURNS_ENDPOINTS[endpoint]
+ window_end = now or datetime.now(UTC)
+
+ paginator: BasePaginator
+ if config.windowed:
+ paginator = LoopReturnsPaginator(
+ config=config,
+ window_start=resolve_window_start(
+ now=window_end,
+ start_date=start_date,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ window_end=window_end,
+ filter_field=resolve_filter_field(should_use_incremental_field, incremental_field),
+ )
+ else:
+ paginator = SinglePagePaginator()
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url(api_version),
+ "auth": {
+ "type": "api_key",
+ "api_key": api_key,
+ "name": AUTH_HEADER,
+ "location": "header",
+ },
+ "paginator": paginator,
+ },
+ "resources": [get_resource(config, should_use_incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if config.windowed and resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = dataclasses.asdict(resume_config)
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Called after each batch is yielded; `None` once the paginator is exhausted.
+ if not state or not state.get("window_start"):
+ return
+ resumable_source_manager.save_state(
+ LoopReturnsResumeConfig(
+ window_start=str(state["window_start"]),
+ state_index=int(state.get("state_index") or 0),
+ cursor=state.get("cursor"),
+ )
+ )
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ # Window bounds are computed here, not by the framework's incremental params.
+ None,
+ resume_hook=save_checkpoint if config.windowed else None,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=list(config.primary_keys),
+ # Loop documents no ordering within a window, so a mid-sync watermark write could skip rows
+ # the run never reached. "desc" defers that write to a successful job end
+ # (finalize_desc_sort_incremental_value); the next run re-reads from the old watermark and
+ # merge dedupes. Full-refresh syncs keep no watermark, so their sort mode is moot.
+ sort_mode="desc" if should_use_incremental_field else "asc",
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
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.py
new file mode 100644
index 000000000000..6edc944701b7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/settings.py
@@ -0,0 +1,92 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from 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
+
+# `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.
+DEFAULT_PAGE_SIZE = 250
+
+# How far back a first sync reaches when the user doesn't give a start date. Without `from`/`to`
+# 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
+# requests that tie up a worker. Cap the lookback at validation time instead.
+MAX_BACKFILL_DAYS = 5 * 365
+
+# `state` is a single-valued enum and, when omitted, Loop returns only open, closed and expired
+# returns. Each state is fetched as its own pass so cancelled and in-review returns land too.
+RETURN_STATES = ("open", "closed", "cancelled", "expired", "review")
+
+# The `filter` param picks which timestamp `from`/`to` apply to.
+FILTER_FIELDS = ("created_at", "updated_at")
+
+
+@dataclass(frozen=True)
+class LoopReturnsEndpointConfig:
+ name: str
+ path: str
+ primary_keys: tuple[str, ...]
+ # Key holding the row array; `None` for endpoints that return a bare array.
+ data_selector: str | None = None
+ # Cursor pagination through `paginate`/`pageSize` with a `nextPageUrl` in the body.
+ paginate: bool = False
+ # Endpoint accepts `from`/`to`, so history is walked in windows.
+ windowed: bool = False
+ # States fetched one pass each; empty means the endpoint has no `state` param.
+ states: tuple[str, ...] = ()
+ # Whether the endpoint accepts the `filter` param that selects the windowed timestamp.
+ supports_filter_param: bool = False
+ # Stable creation timestamp to partition on; `None` disables partitioning.
+ partition_key: str | None = None
+ # API key scope the endpoint needs, as named in Loop's dashboard.
+ required_scope: str = "Returns"
+
+
+LOOP_RETURNS_ENDPOINTS: dict[str, LoopReturnsEndpointConfig] = {
+ "returns": LoopReturnsEndpointConfig(
+ name="returns",
+ path="/warehouse/return/list",
+ primary_keys=("id",),
+ data_selector="returns",
+ paginate=True,
+ windowed=True,
+ states=RETURN_STATES,
+ supports_filter_param=True,
+ partition_key="created_at",
+ ),
+ "advanced_shipping_notices": LoopReturnsEndpointConfig(
+ name="advanced_shipping_notices",
+ path="/warehouse/reporting/asn",
+ # One row per returned line item. `id` looks like a per-row identifier, but the docs don't
+ # state that it is unique across the report, so the line item id is part of the key — a key
+ # that is unique per parent only would seed duplicates that every later merge multi-matches.
+ primary_keys=("id", "return_line_item_id"),
+ windowed=True,
+ partition_key="created_at",
+ ),
+ "destinations": LoopReturnsEndpointConfig(
+ name="destinations",
+ path="/destinations",
+ primary_keys=("id",),
+ data_selector="destinations",
+ required_scope="Destinations (Read)",
+ ),
+}
+
+ENDPOINTS = tuple(LOOP_RETURNS_ENDPOINTS)
+
+# `returns` windows on either timestamp via the `filter` param. The ASN report takes `from`/`to`
+# but doesn't document which timestamp they apply to, so only `created_at` is advertised there:
+# whichever timestamp the server filters on, a window starting at the highest `created_at` we have
+# still contains every row created after it.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "returns": [incremental_field("created_at"), incremental_field("updated_at")],
+ "advanced_shipping_notices": [incremental_field("created_at")],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py
index 5bcfd6055b28..0ffc11ce51b2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/source.py
@@ -1,21 +1,53 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.loopreturns import (
LoopReturnsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns import (
+ LoopReturnsResumeConfig,
+ endpoint_permissions,
+ loop_returns_source,
+ start_date_error,
+ validate_credentials as validate_loop_returns_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LoopReturnsSource(SimpleSource[LoopReturnsSourceConfig]):
+class LoopReturnsSource(ResumableSource[LoopReturnsSourceConfig, LoopReturnsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ # Loop versions its API by date (`2026-07`) and documents `v1` as an alias of that release,
+ # kept for backward compatibility. The returns OpenAPI spec and the warehouse endpoint pages
+ # all serve from `/api/v1`, so that is the path this source calls and the version it pins.
+ supported_versions = ("v1",)
+ default_version = "v1"
+ api_docs_url = "https://docs.loopreturns.com/api-reference/versioning"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LOOPRETURNS
@@ -26,7 +58,106 @@ class LoopReturnsSource(SimpleSource[LoopReturnsSourceConfig]):
name=SchemaExternalDataSourceType.LOOP_RETURNS,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="Loop Returns",
+ releaseStatus=ReleaseStatus.ALPHA,
+ docsUrl="https://posthog.com/docs/cdp/sources/loop-returns",
+ caption="""Enter your Loop API key to pull your returns data into the PostHog Data warehouse.
+
+Create a key in Loop under **Settings** > **Developers**. The key needs the `Returns` scope for the returns and advanced shipping notice tables, and `Destinations (Read)` for the destinations table.
+
+Start date is optional and sets how far back the first sync reaches. Without it, syncing starts two years ago.""",
iconPath="/static/services/loop_returns.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2024-01-01",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.loopreturns.com": "Loop rejected your API key. Check that the key is still active and has the scope this table needs, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.loopreturns.com": "Your Loop API key does not have permission to read this table. Add the required scope to the key and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: LoopReturnsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: LoopReturnsSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if config.start_date:
+ error = start_date_error(config.start_date)
+ if error is not None:
+ return False, error
+
+ return validate_loop_returns_credentials(
+ config.api_key, self.resolve_api_version(api_version), schema_name=schema_name
+ )
+
+ def get_endpoint_permissions(
+ self,
+ config: LoopReturnsSourceConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ return endpoint_permissions(config.api_key, self.resolve_api_version(api_version), endpoints)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LoopReturnsResumeConfig]:
+ return ResumableSourceManager[LoopReturnsResumeConfig](inputs, LoopReturnsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LoopReturnsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LoopReturnsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return loop_returns_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ api_version=self.resolve_api_version(inputs.api_version),
+ resumable_source_manager=resumable_source_manager,
+ start_date=config.start_date,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --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.py
new file mode 100644
index 000000000000..13a86e1aea17
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns.py
@@ -0,0 +1,586 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+from requests.exceptions import ConnectionError as RequestsConnectionError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns import (
+ INVALID_START_DATE_ERROR,
+ START_DATE_TOO_OLD_ERROR,
+ LoopReturnsPaginator,
+ LoopReturnsResumeConfig,
+ endpoint_permissions,
+ loop_returns_source,
+ next_cursor,
+ probe_endpoint,
+ resolve_filter_field,
+ resolve_window_start,
+ start_date_error,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.settings import (
+ DEFAULT_BACKFILL_DAYS,
+ LOOP_RETURNS_ENDPOINTS,
+ MAX_BACKFILL_DAYS,
+ MAX_WINDOW_DAYS,
+ RETURN_STATES,
+)
+
+WINDOW_START = datetime(2024, 1, 1, tzinfo=UTC)
+API_KEY = "loop_test_key"
+API_VERSION = "v1"
+
+
+class FakeResumableSourceManager(ResumableSourceManager[LoopReturnsResumeConfig]):
+ def __init__(self, state: Optional[LoopReturnsResumeConfig] = None) -> None:
+ self.state = state
+ self.saved: list[LoopReturnsResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[LoopReturnsResumeConfig]:
+ return self.state
+
+ def save_state(self, data: LoopReturnsResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _http_response(body: Any, status_code: int = 200) -> Response:
+ response = Response()
+ response.status_code = status_code
+ response._content = json.dumps(body).encode()
+ response.headers["Content-Type"] = "application/json"
+ return response
+
+
+def _paginator(endpoint: str = "returns", *, days: int = 250) -> LoopReturnsPaginator:
+ return LoopReturnsPaginator(
+ config=LOOP_RETURNS_ENDPOINTS[endpoint],
+ window_start=WINDOW_START,
+ window_end=WINDOW_START + timedelta(days=days),
+ filter_field="created_at",
+ )
+
+
+def _request() -> Request:
+ return Request(method="GET", url="https://api.loopreturns.com/api/v1/warehouse/return/list")
+
+
+def _walk(paginator: LoopReturnsPaginator, responses: list[Any], max_pages: int = 40) -> list[dict[str, Any]]:
+ """Drive the paginator through `responses` and return the params of each request it built."""
+ request = _request()
+ paginator.init_request(request)
+ sent = [dict(request.params or {})]
+
+ for body in responses:
+ if len(sent) >= max_pages:
+ break
+ paginator.update_state(_http_response(body))
+ paginator.update_request(request)
+ if not paginator.has_next_page:
+ break
+ sent.append(dict(request.params or {}))
+
+ return sent
+
+
+class TestLoopReturnsPaginator:
+ def test_first_request_carries_the_window_state_and_pagination_params(self) -> None:
+ request = _request()
+ _paginator().init_request(request)
+
+ assert request.params == {
+ "from": "2024-01-01T00:00:00.000Z",
+ "to": "2024-04-30T00: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.
+ 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)
+
+ 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
+ # and in-review returns only land if each state gets its own pass over the full range.
+ sent = _walk(_paginator(days=250), [{"returns": [], "nextPageUrl": None}] * 20)
+
+ 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"),
+ ]
+ 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"
+
+ def test_cursor_pages_stay_inside_the_current_window(self) -> None:
+ # A next page that dropped `from`/`to` would walk back through all of history on every page.
+ sent = _walk(
+ _paginator(days=10),
+ [
+ {"returns": [], "nextPageUrl": "https://api.loopreturns.com/api/v1/warehouse/return/list?cursor=abc"},
+ {"returns": [], "nextPageUrl": None},
+ ],
+ )
+
+ assert [params.get("cursor") for params in sent[:2]] == [None, "abc"]
+ assert sent[1]["from"] == sent[0]["from"]
+ assert sent[1]["to"] == sent[0]["to"]
+
+ @pytest.mark.parametrize(
+ ("label", "second_body"),
+ [
+ ("next_link_without_a_cursor", {"returns": [], "nextPageUrl": "https://api.loopreturns.com/next"}),
+ (
+ "repeated_cursor",
+ {"returns": [], "nextPageUrl": "https://api.loopreturns.com/api/v1/warehouse/return/list?cursor=abc"},
+ ),
+ ],
+ )
+ def test_pagination_that_cannot_advance_moves_on_instead_of_looping(self, label: str, second_body: Any) -> None:
+ first_body = {
+ "returns": [],
+ "nextPageUrl": "https://api.loopreturns.com/api/v1/warehouse/return/list?cursor=abc",
+ }
+ sent = _walk(_paginator(days=10), [first_body, second_body, {"returns": [], "nextPageUrl": None}])
+
+ # Page three is the next state's pass over the same window, not a third fetch of the cursor.
+ assert [params["state"] for params in sent[:3]] == ["open", "open", "closed"]
+ assert sent[2].get("cursor") is None
+
+ def test_resume_state_round_trips_the_window_state_and_cursor(self) -> None:
+ paginator = _paginator(days=250)
+ _walk(
+ paginator,
+ [
+ {"returns": [], "nextPageUrl": None},
+ {"returns": [], "nextPageUrl": "https://api.loopreturns.com/api/v1/warehouse/return/list?cursor=xyz"},
+ ],
+ )
+ saved = paginator.get_resume_state()
+ assert saved == {"window_start": "2024-04-30T00:00:00.000Z", "state_index": 0, "cursor": "xyz"}
+
+ resumed = _paginator(days=250)
+ resumed.set_resume_state(cast(dict[str, Any], saved))
+ request = _request()
+ resumed.init_request(request)
+
+ assert request.params is not None
+ assert request.params["from"] == "2024-04-30T00:00:00.000Z"
+ assert request.params["cursor"] == "xyz"
+ assert request.params["state"] == "open"
+
+ def test_resume_state_restores_a_later_state_pass(self) -> None:
+ resumed = _paginator(days=10)
+ resumed.set_resume_state({"window_start": "2024-01-05T00:00:00.000Z", "state_index": 3, "cursor": None})
+ request = _request()
+ resumed.init_request(request)
+
+ assert request.params is not None
+ assert request.params["state"] == RETURN_STATES[3]
+ assert "cursor" not in request.params
+
+ @pytest.mark.parametrize(
+ ("label", "state"),
+ [
+ ("missing_window_start", {}),
+ ("null_window_start", {"window_start": None}),
+ ],
+ )
+ def test_unusable_resume_state_is_ignored(self, label: str, state: dict[str, Any]) -> None:
+ paginator = _paginator(days=10)
+ paginator.set_resume_state(state)
+ request = _request()
+ paginator.init_request(request)
+
+ assert request.params is not None
+ assert request.params["from"] == "2024-01-01T00:00:00.000Z"
+
+ def test_a_watermark_after_the_window_end_never_inverts_the_range(self) -> None:
+ # A watermark at (or past) "now" must not produce `to` before `from`, which Loop rejects.
+ paginator = LoopReturnsPaginator(
+ config=LOOP_RETURNS_ENDPOINTS["returns"],
+ window_start=WINDOW_START,
+ window_end=WINDOW_START - timedelta(days=1),
+ filter_field="created_at",
+ )
+ request = _request()
+ paginator.init_request(request)
+
+ assert request.params is not None
+ 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), [[], []])
+
+ 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"),
+ ]
+ 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.
+ assert all("filter" not in params for params in sent)
+
+
+class TestNextCursor:
+ @pytest.mark.parametrize(
+ ("label", "body", "expected"),
+ [
+ ("cursor_in_next_link", {"nextPageUrl": "https://api.loopreturns.com/x?cursor=c1&pageSize=250"}, "c1"),
+ ("last_page", {"nextPageUrl": None}, None),
+ ("no_next_link", {"returns": []}, None),
+ ("next_link_without_cursor", {"nextPageUrl": "https://api.loopreturns.com/x?pageSize=250"}, None),
+ ("bare_array_body", [{"id": "1"}], None),
+ ],
+ )
+ def test_next_cursor(self, label: str, body: Any, expected: Optional[str]) -> None:
+ assert next_cursor(_http_response(body)) == expected
+
+ def test_non_json_body_has_no_cursor(self) -> None:
+ response = Response()
+ response.status_code = 200
+ response._content = b"<html>error</html>"
+
+ assert next_cursor(response) is None
+
+
+class TestResolveWindowStart:
+ @pytest.mark.parametrize(
+ ("label", "kwargs", "expected"),
+ [
+ (
+ "incremental_run_resumes_at_the_watermark",
+ {"should_use_incremental_field": True, "db_incremental_field_last_value": "2025-03-04T05:06:07Z"},
+ datetime(2025, 3, 4, 5, 6, 7, tzinfo=UTC),
+ ),
+ (
+ "incremental_run_without_a_watermark_uses_the_start_date",
+ {"should_use_incremental_field": True, "start_date": "2023-02-01"},
+ datetime(2023, 2, 1, tzinfo=UTC),
+ ),
+ ("full_refresh_uses_the_start_date", {"start_date": "2023-02-01"}, datetime(2023, 2, 1, tzinfo=UTC)),
+ (
+ "full_refresh_ignores_the_watermark",
+ {"db_incremental_field_last_value": "2025-03-04T05:06:07Z", "start_date": "2023-02-01"},
+ datetime(2023, 2, 1, tzinfo=UTC),
+ ),
+ ("no_start_date_backfills_the_default_window", {}, WINDOW_START - timedelta(days=DEFAULT_BACKFILL_DAYS)),
+ (
+ "blank_start_date_backfills_the_default_window",
+ {"start_date": ""},
+ WINDOW_START - timedelta(days=DEFAULT_BACKFILL_DAYS),
+ ),
+ ],
+ )
+ def test_resolve_window_start(self, label: str, kwargs: dict[str, Any], expected: datetime) -> None:
+ # Loop only returns the previous 24 hours when `from`/`to` are omitted, so a wrong start
+ # here silently reduces a backfill to one day.
+ assert resolve_window_start(now=WINDOW_START, **kwargs) == expected
+
+ def test_a_naive_watermark_is_treated_as_utc(self) -> None:
+ assert resolve_window_start(
+ now=WINDOW_START,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2025, 3, 4, 5, 6, 7),
+ ) == datetime(2025, 3, 4, 5, 6, 7, tzinfo=UTC)
+
+
+class TestStartDateError:
+ @pytest.mark.parametrize(
+ ("label", "start_date", "expected"),
+ [
+ ("unparseable", "not-a-date", INVALID_START_DATE_ERROR),
+ ("impossible_calendar_date", "2024-13-01", INVALID_START_DATE_ERROR),
+ ("reaches_back_past_the_cap", "1000-01-01", START_DATE_TOO_OLD_ERROR),
+ ("within_the_cap", "2023-06-01", None),
+ ],
+ )
+ def test_start_date_error(self, label: str, start_date: str, expected: Optional[str]) -> None:
+ # A start date the paginator can't cheaply walk (unparseable, or older than MAX_BACKFILL_DAYS)
+ # must be caught here, before a backfill fans out into thousands of empty-window requests.
+ now = datetime(2025, 8, 4, tzinfo=UTC)
+ assert start_date_error(start_date, now=now) == expected
+
+ def test_the_cap_floor_is_measured_from_now(self) -> None:
+ now = datetime(2025, 8, 4, tzinfo=UTC)
+ floor = now - timedelta(days=MAX_BACKFILL_DAYS)
+ assert start_date_error(floor.isoformat(), now=now) is None
+ assert start_date_error((floor - timedelta(days=1)).isoformat(), now=now) == START_DATE_TOO_OLD_ERROR
+
+
+class TestResolveFilterField:
+ @pytest.mark.parametrize(
+ ("label", "should_use_incremental_field", "incremental_field", "expected"),
+ [
+ ("honors_the_chosen_cursor", True, "updated_at", "updated_at"),
+ ("honors_created_at", True, "created_at", "created_at"),
+ ("unknown_field_falls_back", True, "closed_at", "created_at"),
+ ("no_field_falls_back", True, None, "created_at"),
+ ("full_refresh_windows_on_created_at", False, "updated_at", "created_at"),
+ ],
+ )
+ def test_resolve_filter_field(
+ self, label: str, should_use_incremental_field: bool, incremental_field: Optional[str], expected: str
+ ) -> None:
+ assert resolve_filter_field(should_use_incremental_field, incremental_field) == expected
+
+
+class TestLoopReturnsSource:
+ def _drive(
+ self,
+ endpoint: str,
+ responses: list[Response],
+ manager: Optional[FakeResumableSourceManager] = None,
+ **kwargs: Any,
+ ) -> tuple[list[dict[str, Any]], list[Any], FakeResumableSourceManager]:
+ manager = manager or FakeResumableSourceManager()
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = loop_returns_source(
+ api_key=API_KEY,
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ api_version=API_VERSION,
+ resumable_source_manager=manager,
+ now=WINDOW_START,
+ **kwargs,
+ )
+ rows = [row for batch in cast(Iterable[Any], source_response.items()) for row in batch]
+
+ return sent_params, rows, manager
+
+ @pytest.mark.parametrize(
+ ("endpoint", "body", "expected_ids"),
+ [
+ ("returns", {"returns": [{"id": "r1"}, {"id": "r2"}], "nextPageUrl": None}, ["r1", "r2"]),
+ ("advanced_shipping_notices", [{"id": 1}, {"id": 2}], [1, 2]),
+ ("destinations", {"destinations": [{"id": 7}]}, [7]),
+ ],
+ )
+ def test_rows_are_extracted_from_each_endpoints_response_shape(
+ self, endpoint: str, body: Any, expected_ids: list[Any]
+ ) -> None:
+ states = len(LOOP_RETURNS_ENDPOINTS[endpoint].states) or 1
+ _, rows, _ = self._drive(
+ endpoint, [_http_response(body) for _ in range(states)], start_date="2023-12-31T00:00:00Z"
+ )
+
+ assert [row["id"] for row in rows] == expected_ids * states
+
+ def test_a_returns_sync_covers_every_state(self) -> None:
+ sent_params, _, _ = self._drive(
+ "returns",
+ [_http_response({"returns": [], "nextPageUrl": None}) for _ in RETURN_STATES],
+ start_date="2023-12-31T00:00:00Z",
+ )
+
+ assert [params["state"] for params in sent_params] == list(RETURN_STATES)
+
+ def test_an_incremental_run_starts_at_the_watermark_and_windows_on_the_chosen_field(self) -> None:
+ sent_params, _, _ = self._drive(
+ "returns",
+ [_http_response({"returns": [], "nextPageUrl": None}) for _ in RETURN_STATES],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2023-12-25T00:00:00Z",
+ incremental_field="updated_at",
+ )
+
+ assert sent_params[0]["from"] == "2023-12-25T00:00:00.000Z"
+ assert sent_params[0]["filter"] == "updated_at"
+
+ def test_state_is_checkpointed_after_each_batch(self) -> None:
+ _, _, manager = self._drive(
+ "returns",
+ [_http_response({"returns": [], "nextPageUrl": None}) for _ in RETURN_STATES],
+ start_date="2023-12-31T00:00:00Z",
+ )
+
+ assert manager.saved == [
+ LoopReturnsResumeConfig(window_start="2023-12-31T00:00:00.000Z", state_index=index, cursor=None)
+ for index in range(1, len(RETURN_STATES))
+ ]
+
+ def test_a_resumed_run_picks_up_at_the_saved_state_pass(self) -> None:
+ manager = FakeResumableSourceManager(
+ LoopReturnsResumeConfig(window_start="2023-12-31T12:00:00.000Z", state_index=3, cursor="c9")
+ )
+ sent_params, _, _ = self._drive(
+ "returns",
+ [_http_response({"returns": [], "nextPageUrl": None}) for _ in range(2)],
+ manager=manager,
+ start_date="2023-12-31T00:00:00Z",
+ )
+
+ assert sent_params[0]["state"] == RETURN_STATES[3]
+ assert sent_params[0]["cursor"] == "c9"
+ assert sent_params[0]["from"] == "2023-12-31T12:00:00.000Z"
+ # The next pass restarts at the configured start date, not the resumed window.
+ assert sent_params[1]["from"] == "2023-12-31T00:00:00.000Z"
+
+ def test_destinations_are_not_resumed_or_windowed(self) -> None:
+ manager = FakeResumableSourceManager(
+ LoopReturnsResumeConfig(window_start="2023-12-31T00:00:00.000Z", state_index=2, cursor="c9")
+ )
+ sent_params, _, _ = self._drive("destinations", [_http_response({"destinations": []})], manager=manager)
+
+ assert sent_params == [{}]
+ assert manager.saved == []
+
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_primary_keys", "expected_partition_keys"),
+ [
+ ("returns", ["id"], ["created_at"]),
+ ("advanced_shipping_notices", ["id", "return_line_item_id"], ["created_at"]),
+ ("destinations", ["id"], None),
+ ],
+ )
+ def test_primary_and_partition_keys(
+ self, endpoint: str, expected_primary_keys: list[str], expected_partition_keys: Optional[list[str]]
+ ) -> None:
+ # An ASN key of just `id` would seed duplicates if `id` repeats per return, and every later
+ # merge would multi-match them.
+ source_response = loop_returns_source(
+ api_key=API_KEY,
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ api_version=API_VERSION,
+ resumable_source_manager=FakeResumableSourceManager(),
+ )
+
+ assert source_response.primary_keys == expected_primary_keys
+ assert source_response.partition_keys == expected_partition_keys
+
+ @pytest.mark.parametrize(
+ ("should_use_incremental_field", "expected_sort_mode"),
+ [(True, "desc"), (False, "asc")],
+ )
+ def test_incremental_syncs_defer_the_watermark_write(
+ self, should_use_incremental_field: bool, expected_sort_mode: str
+ ) -> None:
+ # Loop documents no ordering within a window, so an "asc" claim would checkpoint a
+ # watermark past rows a crashed run never fetched.
+ source_response = loop_returns_source(
+ api_key=API_KEY,
+ endpoint="returns",
+ team_id=1,
+ job_id="job-1",
+ api_version=API_VERSION,
+ resumable_source_manager=FakeResumableSourceManager(),
+ should_use_incremental_field=should_use_incremental_field,
+ )
+
+ assert source_response.sort_mode == expected_sort_mode
+
+
+class TestCredentialValidation:
+ def _session(self, responses: list[Response]) -> MagicMock:
+ session = MagicMock()
+ session.get.side_effect = responses
+ return session
+
+ @pytest.mark.parametrize(
+ ("label", "status_codes", "expected_valid"),
+ [
+ ("returns_readable", [200], True),
+ # A key scoped only for destinations still works, just for fewer tables.
+ ("returns_denied_destinations_readable", [401, 200], True),
+ ("everything_denied", [401, 401], False),
+ ("forbidden", [403, 403], False),
+ ("server_error", [500, 500], False),
+ ],
+ )
+ def test_validate_credentials(self, label: str, status_codes: list[int], expected_valid: bool) -> None:
+ responses = [_http_response({}, status_code=code) for code in status_codes]
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns.make_tracked_session",
+ return_value=self._session(responses),
+ ):
+ is_valid, error = validate_credentials(API_KEY, API_VERSION)
+
+ assert is_valid is expected_valid
+ assert (error is None) is expected_valid
+
+ def test_a_denied_key_names_the_scope_to_add(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns.make_tracked_session",
+ return_value=self._session([_http_response({}, status_code=401) for _ in range(2)]),
+ ):
+ _, error = validate_credentials(API_KEY, API_VERSION)
+
+ assert error is not None
+ assert "Returns" in error
+
+ def test_validating_one_schema_probes_only_that_endpoint(self) -> None:
+ session = self._session([_http_response({"destinations": []})])
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns.make_tracked_session",
+ return_value=session,
+ ):
+ is_valid, error = validate_credentials(API_KEY, API_VERSION, schema_name="destinations")
+
+ assert (is_valid, error) == (True, None)
+ assert session.get.call_args.args[0] == "https://api.loopreturns.com/api/v1/destinations"
+
+ def test_a_network_failure_is_reported_not_raised(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = RequestsConnectionError("no route to host")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns.make_tracked_session",
+ return_value=session,
+ ):
+ is_valid, error = validate_credentials(API_KEY, API_VERSION)
+
+ assert is_valid is False
+ assert error is not None and "no route to host" in error
+
+ def test_probe_sends_the_api_key_in_loops_auth_header(self) -> None:
+ session = self._session([_http_response({"returns": [], "nextPageUrl": None})])
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns.make_tracked_session",
+ return_value=session,
+ ):
+ probe_endpoint(API_KEY, API_VERSION, "returns")
+
+ assert session.get.call_args.kwargs["headers"] == {"X-Authorization": API_KEY}
+
+ def test_endpoint_permissions_reports_each_table_separately(self) -> None:
+ responses = [_http_response({}, status_code=200), _http_response({}, status_code=401)]
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns.make_tracked_session",
+ return_value=self._session(responses),
+ ):
+ permissions = endpoint_permissions(API_KEY, API_VERSION, ["returns", "destinations"])
+
+ assert permissions["returns"] is None
+ assert permissions["destinations"] is not None
+ assert "Destinations (Read)" in cast(str, permissions["destinations"])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns_source.py
new file mode 100644
index 000000000000..af8e63824d9d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/tests/test_loop_returns_source.py
@@ -0,0 +1,169 @@
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.loopreturns import (
+ LoopReturnsSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.loop_returns import (
+ LoopReturnsResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.source import LoopReturnsSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+VALIDATE_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.loop_returns.source."
+ "validate_loop_returns_credentials"
+)
+
+
+class FakeResumableSourceManager(ResumableSourceManager[LoopReturnsResumeConfig]):
+ def __init__(self) -> None:
+ pass
+
+ def can_resume(self) -> bool:
+ return False
+
+ def load_state(self) -> Optional[LoopReturnsResumeConfig]:
+ return None
+
+
+def _source_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "returns",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ return SourceInputs(**{**defaults, **overrides})
+
+
+class TestLoopReturnsSource:
+ def setup_method(self) -> None:
+ self.source = LoopReturnsSource()
+ self.team_id = 1
+ self.config = LoopReturnsSourceConfig(api_key="loop_test_key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.LOOPRETURNS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.label == "Loop Returns"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/loop_returns.png"
+
+ fields = {field.name: field for field in config.fields if isinstance(field, SourceFieldInputConfig)}
+ assert set(fields) == {"api_key", "start_date"}
+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_key"].required is True
+ assert fields["api_key"].secret is True
+ # The start date only bounds a backfill, so requiring it would block setup for no reason.
+ assert fields["start_date"].required is False
+
+ def test_get_schemas(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ # Only the endpoints with a server-side `from`/`to` filter may claim incremental support.
+ assert {name for name, schema in schemas.items() if schema.supports_incremental} == set(INCREMENTAL_FIELDS)
+ assert [field["field"] for field in schemas["returns"].incremental_fields] == ["created_at", "updated_at"]
+ assert [field["field"] for field in schemas["advanced_shipping_notices"].incremental_fields] == ["created_at"]
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["destinations"])
+
+ assert [schema.name for schema in schemas] == ["destinations"]
+
+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))
+ def test_every_endpoint_is_documented(self, endpoint: str) -> None:
+ # `lists_tables_without_credentials` publishes this catalog to the public docs, so an
+ # endpoint added without a canonical entry ships an undocumented table.
+ entry = self.source.get_canonical_descriptions()[endpoint]
+
+ assert entry["description"]
+ assert entry["docs_url"].startswith("https://docs.loopreturns.com/")
+ assert entry["columns"]["id"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.loopreturns.com/api/v1/warehouse/return/list",
+ "403 Client Error: Forbidden for url: https://api.loopreturns.com/api/v1/destinations",
+ ],
+ )
+ def test_auth_failures_are_non_retryable(self, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ def test_other_vendors_auth_failures_are_left_alone(self) -> None:
+ assert not any(
+ key in "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers"
+ for key in self.source.get_non_retryable_errors()
+ )
+
+ @mock.patch(VALIDATE_PATH)
+ def test_validate_credentials_passes_the_schema_through(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+
+ assert self.source.validate_credentials(self.config, self.team_id, schema_name="destinations") == (True, None)
+ mock_validate.assert_called_once_with("loop_test_key", "v1", schema_name="destinations")
+
+ @pytest.mark.parametrize("start_date", ["not-a-date", "2024-13-01", "1000-01-01"])
+ @mock.patch(VALIDATE_PATH)
+ def test_a_bad_start_date_is_rejected_before_calling_loop(
+ self, mock_validate: mock.MagicMock, start_date: str
+ ) -> None:
+ config = LoopReturnsSourceConfig(api_key="loop_test_key", start_date=start_date)
+
+ is_valid, error = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert error is not None and "Start date" in error
+ mock_validate.assert_not_called()
+
+ @mock.patch(VALIDATE_PATH)
+ def test_a_valid_start_date_is_accepted(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ config = LoopReturnsSourceConfig(api_key="loop_test_key", start_date="2024-01-01")
+
+ assert self.source.validate_credentials(config, self.team_id) == (True, None)
+
+ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs())
+
+ assert manager._data_class is LoopReturnsResumeConfig
+
+ def test_source_for_pipeline_builds_the_requested_table(self) -> None:
+ source_response = self.source.source_for_pipeline(
+ self.config, FakeResumableSourceManager(), _source_inputs(schema_name="advanced_shipping_notices")
+ )
+
+ assert source_response.name == "advanced_shipping_notices"
+ assert source_response.primary_keys == ["id", "return_line_item_id"]
+
+ def test_source_for_pipeline_ignores_a_stale_watermark_on_a_full_refresh(self) -> None:
+ source_response = self.source.source_for_pipeline(
+ self.config,
+ FakeResumableSourceManager(),
+ _source_inputs(should_use_incremental_field=False, db_incremental_field_last_value="2025-01-01T00:00:00Z"),
+ )
+
+ assert source_response.sort_mode == "asc"