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 Mailgun pagination when the page cursor repeats (#74801)

posthog[bot]5fbf3e7729e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py
index 93834e21d18f..e90d654554dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py
@@ -52,6 +52,10 @@ MAX_RETRY_AFTER_SECONDS = 120
# ~30 minutes as incomplete. Bounding `end` keeps the incremental watermark behind the
# consistency horizon so late-arriving events aren't skipped on the next sync.
EVENTS_CONSISTENCY_LAG_SECONDS = 30 * 60
+# Backstop for a `paging.next` chain that never terminates and never repeats a URL, which the
+# seen-URL guard below can't catch. Sized far above any real page count (the largest paging
+# endpoint fetches 1000 rows a page) so it only trips on a runaway.
+MAX_PAGES_PER_CHAIN = 100_000
class MailgunRetryableError(Exception):
@@ -192,7 +196,11 @@ def _next_page_url(
if items_count == 0:
return None
next_url = (data.get("paging") or {}).get("next")
- return next_url or None
+ if not next_url or next_url == current_url:
+ # Some endpoints (tags is the known one) hand back a stable cursor that points at the
+ # page we just read instead of an empty page, so following it re-serves the same rows.
+ return None
+ return next_url
def _normalize_row(config: MailgunEndpointConfig, domain: Optional[str], item: dict[str, Any]) -> dict[str, Any]:
@@ -323,8 +331,15 @@ def get_rows(
current_domain = None
current_url = _initial_url(base_url, config, None, begin)
+ # Mailgun's `paging.next` cursors aren't guaranteed to advance — the tags endpoint returns a
+ # stable `page=next&tag=<last>` URL that keeps re-serving the terminal page rather than an
+ # empty one. Without this guard the chain re-yields the same rows until the activity is killed,
+ # and every re-yielded row is billed as a synced row even though the merge dedupes them away.
+ seen_urls: set[str] = set()
+
while current_url is not None or pending_domains:
if current_url is None:
+ seen_urls.clear()
current_domain = pending_domains.pop(0)
current_url = _initial_url(base_url, config, current_domain, begin)
if current_url is None:
@@ -332,6 +347,24 @@ def get_rows(
resumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))
continue
+ loop_reason: Optional[str] = None
+ if current_url in seen_urls:
+ loop_reason = "the page URL repeated"
+ elif len(seen_urls) >= MAX_PAGES_PER_CHAIN:
+ loop_reason = f"the chain exceeded {MAX_PAGES_PER_CHAIN} pages"
+
+ if loop_reason is not None:
+ logger.warning(
+ f"Mailgun: stopping pagination for {endpoint} because {loop_reason}; "
+ f"domain={current_domain}, url={current_url}"
+ )
+ current_url = None
+ current_domain = None
+ resumable_source_manager.save_state(MailgunResumeConfig(pending_domains=pending_domains))
+ continue
+
+ seen_urls.add(current_url)
+
try:
data = _fetch_page(current_url, api_key, logger)
except requests.HTTPError as error:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py
index f59f85de6ce2..f3a8402b7bef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py
@@ -94,13 +94,16 @@ MAILGUN_ENDPOINTS: dict[str, MailgunEndpointConfig] = {
name="tags",
path="/v3/{domain}/tags",
domain_scoped=True,
- page_size=100,
+ page_size=1000,
primary_keys=["domain", "tag"],
),
"templates": MailgunEndpointConfig(
name="templates",
path="/v3/{domain}/templates",
domain_scoped=True,
+ # Left at 100 until someone confirms the cap against a live account: the docs only state
+ # 1000 for tags. A rejected `limit` returns 400, which the fan-out reads as an unqueryable
+ # domain and skips, so guessing too high loses the endpoint on every domain with a warning.
page_size=100,
# Template names are unique per domain; list items aren't guaranteed an `id`.
primary_keys=["domain", "name"],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py
index e31f4e1b5f31..2e07572e4666 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py
@@ -245,6 +245,11 @@ class TestPagination:
data = _paging_page([{"id": "a"}], None)
assert _next_page_url(config, "current", data, 1) is None
+ def test_paging_stops_when_next_points_at_current_page(self):
+ config = MAILGUN_ENDPOINTS["tags"]
+ data = _paging_page([{"tag": "a"}], "current")
+ assert _next_page_url(config, "current", data, 1) is None
+
class TestNormalizeRow:
def test_injects_domain_for_domain_scoped_endpoints(self):
@@ -390,6 +395,67 @@ class TestGetRows:
first_events_url = mock_session.return_value.get.call_args_list[1].args[0]
assert first_events_url.startswith(f"{US_BASE}/v3/a.com/events?")
+ @pytest.mark.parametrize(
+ "self_referencing, expected_requests, expected_rows",
+ [(True, 2, 2), (False, 3, 4)],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_repeating_paging_cursor_terminates(self, mock_session, self_referencing, expected_requests, expected_rows):
+ # Mailgun's tags endpoint re-serves its terminal page behind a stable `page=next&tag=<last>`
+ # cursor instead of returning an empty page. Unguarded, the chain re-yields the same rows
+ # until the activity is killed, and every repeat is billed as a synced row. Two shapes: the
+ # cursor pointing at the page it came from, and a two-URL cycle between pages.
+ items = [{"tag": "t1"}, {"tag": "t2"}]
+ page_a = f"{US_BASE}/v3/a.com/tags?limit=1000"
+ page_b = f"{page_a}&page=next&tag=t2"
+ next_of_a = page_a if self_referencing else page_b
+
+ requests_made: list[str] = []
+
+ def fake_get(url, **kwargs):
+ requests_made.append(url)
+ if len(requests_made) > 6:
+ raise AssertionError("pagination did not terminate")
+ if "/v4/domains" in url:
+ return _response({"items": [{"name": "a.com"}]})
+ return _response(_paging_page(items, next_of_a if url == page_a else page_a))
+
+ mock_session.return_value.get.side_effect = fake_get
+
+ batches = list(get_rows("key", "us", "tags", mock.MagicMock(), _make_manager()))
+
+ assert len(requests_made) == expected_requests
+ assert sum(len(batch) for batch in batches) == expected_rows
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.MAX_PAGES_PER_CHAIN", 3
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
+ def test_paging_stops_at_the_page_cap(self, mock_session):
+ # A cursor that mints a fresh URL for every page never repeats, so the seen-URL guard can't
+ # see it and only the page cap ends the chain.
+ pages_fetched = 0
+
+ def fake_get(url, **kwargs):
+ nonlocal pages_fetched
+ if "/v4/domains" in url:
+ return _response({"items": [{"name": "a.com"}]})
+ pages_fetched += 1
+ if pages_fetched > 10:
+ raise AssertionError("pagination did not terminate")
+ return _response(
+ _paging_page([{"tag": f"t{pages_fetched}"}], f"{US_BASE}/v3/a.com/tags?page=next&tag=t{pages_fetched}")
+ )
+
+ mock_session.return_value.get.side_effect = fake_get
+ logger = mock.MagicMock()
+
+ batches = list(get_rows("key", "us", "tags", logger, _make_manager()))
+
+ assert pages_fetched == 3
+ assert sum(len(batch) for batch in batches) == 3
+ assert "exceeded 3 pages" in logger.warning.call_args.args[0]
+
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")
def test_incremental_run_passes_begin_from_watermark(self, mock_session):
domains_page = {"items": [{"name": "a.com"}]}