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): stop paddle pagination looping on its final page (#75813)

Eli Reismane785aff3f228
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 e5391228dfab..4b0ed93c5c1d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -448,7 +448,7 @@ the row lists both.
| outbrain | HTTP | requests | ✅ |
| pabbly_subscriptions_billing | HTTP | requests | ✅ |
| packagist | HTTP | requests | ✅ |
-| paddle | HTTP | requests | ✅ |
+| paddle | HTTP | requests + `rest_source.RESTClient` | ✅ |
| optimizely | HTTP | requests | ✅ |
| pagerduty | HTTP | requests | ✅ |
| pandadoc | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/baserow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/baserow.py
index 52f20951dbc0..0e0f3713fb9d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/baserow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/baserow.py
@@ -177,10 +177,10 @@ class BaserowPaginator(JSONResponsePaginator):
def __init__(self, base_url: str) -> None:
super().__init__(next_url_path="next")
self._allowed_netloc = urlparse(normalize_base_url(base_url)).netloc.lower()
- # Cycle guards: a host that keeps returning a `next` link can otherwise keep a
- # resumable import issuing requests until its week-long activity timeout. Track the
- # link we just followed to catch a repeated URL, and count pages as a coarse backstop.
- self._previous_next_url: Optional[str] = None
+ # Page cap: a host that keeps returning fresh `next` links can otherwise keep a
+ # resumable import issuing requests until its week-long activity timeout. The
+ # repeated-URL case is caught by the base paginator's guard, hardened below to
+ # raise rather than silently stop.
self._pages_followed = 0
def _pin(self, url: str) -> None:
@@ -188,16 +188,18 @@ class BaserowPaginator(JSONResponsePaginator):
if target.scheme != "https" or target.netloc.lower() != self._allowed_netloc:
raise ValueError(f"Baserow pagination URL {url!r} is not on the configured instance")
+ def _handle_non_advancing_page(self, next_url: str) -> None:
+ # A repeated next link from a user-controlled host is treated as hostile, not as
+ # a benign end-of-data quirk, so fail the sync loudly instead of completing it.
+ raise ValueError(f"Baserow pagination is not advancing (repeated next URL {next_url!r})")
+
def _guard_progress(self) -> None:
if self._next_url is None:
return
self._pin(self._next_url)
- if self._next_url == self._previous_next_url:
- raise ValueError(f"Baserow pagination is not advancing (repeated next URL {self._next_url!r})")
self._pages_followed += 1
if self._pages_followed > MAX_PAGES_PER_SYNC:
raise ValueError(f"Baserow sync exceeded the {MAX_PAGES_PER_SYNC}-page limit")
- self._previous_next_url = self._next_url
def update_state(self, response: requests.Response, data: Optional[list[Any]] = None) -> None:
super().update_state(response, data)
@@ -205,12 +207,11 @@ class BaserowPaginator(JSONResponsePaginator):
self._guard_progress()
def set_resume_state(self, state: dict[str, Any]) -> None:
+ # The base class seeds the repeat guard from the resumed link; pin it here too
+ # (a tampered resume URL must not be followed).
super().set_resume_state(state)
if self._next_url is not None:
- # Seed the repeat guard from the resumed link so a host that immediately echoes it
- # back is caught, and pin it here too (a tampered resume URL must not be followed).
self._pin(self._next_url)
- self._previous_next_url = self._next_url
def list_tables(base_url: Optional[str], database_token: str) -> list[dict[str, Any]]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py
index 519098c4dc0c..82872e711655 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/paginators.py
@@ -1,11 +1,15 @@
import re
+import logging
from abc import ABC, abstractmethod
from typing import Any, Literal, Optional
+from urllib.parse import urlsplit
from requests import Request, Response
from .jsonpath_utils import TJsonPath, find_values
+logger = logging.getLogger(__name__)
+
# Where a paginator writes its pagination fields. "query" (default) mutates request.params;
# "json" mutates the POST body — for APIs that carry page/cursor/limit inside the JSON payload.
ParamLocation = Literal["query", "json"]
@@ -64,6 +68,42 @@ class BaseNextUrlPaginator(BasePaginator):
def __init__(self) -> None:
super().__init__()
self._next_url: Optional[str] = None
+ self._previous_next_url: Optional[str] = None
+
+ def _advance_to(self, next_url: Optional[str]) -> None:
+ """Follow ``next_url`` as the next page, or stop when there is none.
+
+ A next URL identical to the one just followed is treated as the last page:
+ some APIs (e.g. Paddle) return a populated next link even on their final
+ page, and following it would refetch the same page forever. Without this
+ guard the sync loops until its Temporal activity timeout, which is a week
+ for resumable sources.
+ """
+ if not next_url:
+ self._has_next_page = False
+ return
+ if next_url == self._previous_next_url:
+ self._handle_non_advancing_page(next_url)
+ return
+ self._previous_next_url = next_url
+ self._next_url = next_url
+ self._has_next_page = True
+
+ def _handle_non_advancing_page(self, next_url: str) -> None:
+ """Called when a response's next link equals the one just followed.
+
+ Default: treat it as the last page and log, so end-of-data quirks complete
+ the sync instead of looping. Subclasses that consider a repeated link
+ hostile (e.g. Baserow's user-controlled hosts) override this to raise.
+ """
+ # Log only scheme/host/path: pagination links are echoed by the remote API and
+ # can carry credentials in their query string for query-param-authenticated sources.
+ redacted_url = urlsplit(next_url)._replace(query="", fragment="").geturl()
+ logger.warning(
+ "Pagination is not advancing (repeated next URL); treating as last page",
+ extra={"paginator": str(self), "next_url": redacted_url},
+ )
+ self._has_next_page = False
def init_request(self, request: Request) -> None:
# Apply a seeded resume URL to the first request so a resumed run starts at the
@@ -89,6 +129,9 @@ class BaseNextUrlPaginator(BasePaginator):
next_url = state.get("next_url")
if next_url is not None:
self._next_url = next_url
+ # Seed the repeat guard so a resumed page whose response echoes the
+ # saved URL stops instead of looping on a poisoned checkpoint.
+ self._previous_next_url = next_url
self._has_next_page = True
@@ -98,13 +141,8 @@ class HeaderLinkPaginator(BaseNextUrlPaginator):
self.links_next_key = links_next_key
def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
- links = response.links
- next_link = links.get(self.links_next_key)
- if next_link:
- self._next_url = next_link.get("url")
- self._has_next_page = True
- else:
- self._has_next_page = False
+ next_link = response.links.get(self.links_next_key)
+ self._advance_to(next_link.get("url") if next_link else None)
def __str__(self) -> str:
return f"HeaderLinkPaginator(links_next_key={self.links_next_key})"
@@ -122,11 +160,7 @@ class JSONResponsePaginator(BaseNextUrlPaginator):
values = find_values(self.next_url_path, response.json())
except Exception:
values = []
- if values and values[0]:
- self._next_url = values[0]
- self._has_next_page = True
- else:
- self._has_next_page = False
+ self._advance_to(values[0] if values else None)
def __str__(self) -> str:
return f"JSONResponsePaginator(next_url_path={self.next_url_path})"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py
index d2f16dc35372..84404f92339d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_paginators.py
@@ -2,9 +2,11 @@ import json
from typing import Any
import pytest
+from unittest import mock
from requests import PreparedRequest, Request, Response, Session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import paginators
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
HeaderLinkPaginator,
JSONLinkPaginator,
@@ -68,6 +70,31 @@ class TestJSONResponsePaginator:
p.update_state(resp)
assert p.has_next_page is False
+ def test_stops_when_next_url_repeats(self) -> None:
+ # Some APIs (e.g. Paddle) populate `next` even on the last page, pointing at
+ # the page just fetched. Following it verbatim loops forever.
+ p = JSONResponsePaginator(next_url_path="next")
+ url = "https://api.example.com/page2?api_key=secret-token"
+ p.update_state(_make_response({"next": url, "data": []}))
+ assert p.has_next_page is True
+ # Patch the logger rather than use caplog: the suite's logging config can
+ # disable this module's logger, which would drop the record before capture.
+ with mock.patch.object(paginators.logger, "warning") as warning:
+ p.update_state(_make_response({"next": url, "data": []}))
+ # The logged URL must not carry the query string, which can hold credentials.
+ assert warning.call_args.kwargs["extra"]["next_url"] == "https://api.example.com/page2"
+ assert "secret-token" not in str(warning.call_args)
+ assert p.has_next_page is False
+
+ def test_header_link_paginator_stops_when_next_url_repeats(self) -> None:
+ p = HeaderLinkPaginator()
+ resp = _make_response()
+ resp.headers["Link"] = '<https://api.example.com/page2>; rel="next"'
+ p.update_state(resp)
+ assert p.has_next_page is True
+ p.update_state(resp)
+ assert p.has_next_page is False
+
def test_json_link_paginator_is_alias(self) -> None:
assert JSONLinkPaginator is JSONResponsePaginator
@@ -247,6 +274,15 @@ class TestPaginatorResume:
resumed.init_request(req)
assert req.url == "https://api.example.com/page2"
+ def test_next_url_paginator_stops_when_resumed_page_echoes_saved_url(self) -> None:
+ # A checkpoint saved on an API's final page points at that same page; when the
+ # resumed fetch echoes the saved URL back as `next`, the sync must complete
+ # rather than loop on the checkpoint.
+ resumed = JSONResponsePaginator(next_url_path="next")
+ resumed.set_resume_state({"next_url": "https://api.example.com/page9"})
+ resumed.update_state(_make_response({"next": "https://api.example.com/page9", "data": []}))
+ assert resumed.has_next_page is False
+
class TestOffsetPaginatorTotalHeader:
def test_stops_when_offset_reaches_header_total(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify.py
index 91fe5b9e2219..5f76314c70a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify.py
@@ -234,10 +234,12 @@ class TestPageCap:
# Hitting the per-parent page cap must fail loudly rather than silently truncate the table.
paginator = NetlifyCappedHeaderLinkPaginator(max_pages=2, context={"table": "builds"})
page = [{"id": "x"}]
- resp = _response(page, next_url=f"{BASE}/sites/s1/builds?page=2")
- paginator.update_state(resp, page) # page 1: under the cap
+ paginator.update_state(
+ _response(page, next_url=f"{BASE}/sites/s1/builds?page=2"), page
+ ) # page 1: under the cap
with pytest.raises(NetlifyPageCapExceededError):
- paginator.update_state(resp, page) # page 2: cap reached with more pages remaining
+ # page 2: cap reached with more pages remaining
+ paginator.update_state(_response(page, next_url=f"{BASE}/sites/s1/builds?page=3"), page)
def test_capped_paginator_stops_cleanly_when_no_more_pages(self) -> None:
paginator = NetlifyCappedHeaderLinkPaginator(max_pages=2, context={"table": "builds"})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py
index a97d5f98d361..c267faa15744 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py
@@ -39,6 +39,29 @@ class PaddlePermissionError(Exception):
pass
+class PaddlePaginator(JSONResponsePaginator):
+ """Follows ``meta.pagination.next``, gated on ``meta.pagination.has_more``.
+
+ Paddle populates ``next`` on every page, including the last one; per their
+ pagination docs, ``has_more`` is the only end-of-results signal. Following
+ ``next`` alone therefore refetches the final page forever.
+ """
+
+ def update_state(self, response: requests.Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ body = response.json()
+ except Exception:
+ body = {}
+ meta = body.get("meta") if isinstance(body, dict) else None
+ pagination = meta.get("pagination") if isinstance(meta, dict) else None
+ if isinstance(pagination, dict) and pagination.get("has_more") is False:
+ self._has_next_page = False
+ return
+ # has_more missing or malformed: fall back to the next link, where the base
+ # class still stops on a repeated URL.
+ super().update_state(response, data)
+
+
def _format_paddle_datetime_query_value(value: Any) -> str:
if isinstance(value, datetime):
parsed = value
@@ -99,7 +122,7 @@ def paddle_source(
"base_url": PADDLE_BASE_URL,
"headers": {"Content-Type": "application/json"},
"auth": {"type": "bearer", "token": api_key},
- "paginator": JSONResponsePaginator(next_url_path="meta.pagination.next"),
+ "paginator": PaddlePaginator(next_url_path="meta.pagination.next"),
},
"resources": [
{
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py
index 5cfcb7a7517f..8f050cff3ac0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py
@@ -27,8 +27,18 @@ PADDLE_SESSION_PATCH = (
)
-def _response(items: list[dict[str, Any]] | None, *, next_url: str | None = None, drop_data: bool = False) -> Response:
- body: dict[str, Any] = {"meta": {"pagination": {"per_page": 200, "next": next_url}}}
+def _response(
+ items: list[dict[str, Any]] | None,
+ *,
+ next_url: str | None = None,
+ has_more: bool | None = None,
+ drop_data: bool = False,
+) -> Response:
+ # Real Paddle bodies always carry has_more; default it from next_url so fixture
+ # pages terminate the way real responses do (via has_more, not a null next).
+ if has_more is None:
+ has_more = next_url is not None
+ body: dict[str, Any] = {"meta": {"pagination": {"per_page": 200, "next": next_url, "has_more": has_more}}}
if not drop_data:
body["data"] = items or []
resp = Response()
@@ -108,6 +118,27 @@ class TestPagination:
assert [r["id"] for r in rows] == ["a", "b"]
assert session.send.call_count == 1
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_terminates_when_last_page_repeats_next_url(self, MockSession) -> None:
+ # Real Paddle populates `next` on every page, including the last, where it
+ # points back at the page just fetched; has_more is the only stop signal.
+ # Following `next` alone refetches the final page forever.
+ session = MockSession.return_value
+ last_url = f"{PADDLE_BASE_URL}/customers?after=c_1"
+ _wire(
+ session,
+ [
+ _response([{"id": "c_1"}], next_url=last_url, has_more=True),
+ _response([{"id": "c_2"}], next_url=last_url, has_more=False),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("customers", manager))
+
+ assert [r["id"] for r in rows] == ["c_1", "c_2"]
+ assert session.send.call_count == 2
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_missing_data_key_yields_no_rows(self, MockSession) -> None:
session = MockSession.return_value
@@ -191,6 +222,23 @@ class TestResume:
assert urls[0] == saved_url
assert params[0] == {}
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_checkpoint_saved_on_last_page_terminates_on_resume(self, MockSession) -> None:
+ # A checkpoint saved while looping on the final page points at that page.
+ # The resumed fetch sees has_more=false, completes, and writes the empty
+ # terminal marker instead of re-saving the same URL.
+ session = MockSession.return_value
+ saved_url = f"{PADDLE_BASE_URL}/customers?after=c_9"
+ _wire(session, [_response([], next_url=saved_url, has_more=False)])
+
+ manager = _make_manager(PaddleResumeConfig(next_url=saved_url))
+ rows = _rows(_source("customers", manager))
+
+ assert rows == []
+ assert session.send.call_count == 1
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [PaddleResumeConfig(next_url="")]
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_empty_saved_url_starts_fresh(self, MockSession) -> None:
session = MockSession.return_value