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(data-warehouse): stop mailersend syncs failing on rejected requests (#103652)

Tom Owerse23e522f2a51
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py
index f128f2e37940..d6a43ab569b1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/mailersend.py
@@ -1,6 +1,13 @@
import dataclasses
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime, timedelta
+from functools import partial
from typing import Any, Optional
+from urllib.parse import parse_qs, urlsplit
+
+import structlog
+from requests import Response
+from requests.exceptions import HTTPError
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 (
@@ -19,18 +26,31 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.mailersend.settings import MAILERSEND_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailersend.settings import (
+ MAILERSEND_ENDPOINTS,
+ MailerSendEndpointConfig,
+)
+
+logger = structlog.get_logger(__name__)
# MailerSend serves every account from a single global base URL (no per-account hostname).
MAILERSEND_BASE_URL = "https://api.mailersend.com/v1"
+# Every MailerSend list endpoint is page based and accepts page numbers 1 to 1000. The API keeps
+# advertising a `links.next` on page 1000, so following it asks for page 1001 and the request is
+# rejected with a 422. Stop at the cap instead and finish the table.
+MAILERSEND_MAX_PAGE = 1000
+
+# Fallback lookback for a date-filtered endpoint that declares no retention tiers.
+MAILERSEND_DEFAULT_ACTIVITY_DAYS = 30
+
# Parent resource name for the Activity fan-out. include_from_parent=["id"] injects the parent
# domain's id as `_domains_id`; a data_map renames it to `domain_id` so each activity row carries
# the same key it did before the rest_source migration.
_DOMAINS_PARENT = "domains"
[email protected](frozen=True)
class MailerSendResumeConfig:
# Legacy fields kept (with defaults) so resume state saved by the pre-migration source still
# deserializes via `dataclass(**saved)`. New runs checkpoint through `fanout_state` — the
@@ -41,6 +61,35 @@ class MailerSendResumeConfig:
fanout_state: dict[str, Any] | None = None
+def _page_number(url: Optional[str]) -> int:
+ """The page a MailerSend pagination link points at; 1 when the link carries no page param."""
+ if not url:
+ return 1
+ values = parse_qs(urlsplit(url).query).get("page")
+ if not values:
+ return 1
+ try:
+ return int(values[0])
+ except ValueError:
+ return 1
+
+
+class MailerSendPaginator(JSONResponsePaginator):
+ """Follows `links.next` but never past MailerSend's last accepted page."""
+
+ def __init__(self) -> None:
+ super().__init__(next_url_path="links.next")
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if self._has_next_page and _page_number(self._next_url) > MAILERSEND_MAX_PAGE:
+ logger.warning(
+ "mailersend.page_cap_reached",
+ max_page=MAILERSEND_MAX_PAGE,
+ )
+ self._has_next_page = False
+
+
def _to_datetime(value: Any) -> datetime:
"""Coerce an incremental cursor value into an aware UTC datetime."""
if isinstance(value, datetime):
@@ -60,16 +109,18 @@ def _activity_date_window(
) -> SyncWindow[int]:
"""Build the required date_from/date_to window for the Activity endpoint as Unix timestamps.
- MailerSend requires both bounds and rejects date_from >= date_to. On the first sync (or a full
- refresh) we look back `lookback_days`, capped to the activity retention window the plan allows.
- On incremental syncs the window starts at the last-seen created_at; merge upsert dedupes the
- inclusive boundary row.
+ MailerSend requires both bounds, rejects date_from >= date_to, and rejects a window that
+ reaches back further than the account's activity retention. `lookback_days` is the retention
+ tier being tried, so it bounds the first-sync lookback and also clamps an incremental cursor
+ that has fallen behind retention. On incremental syncs the window starts at the last-seen
+ created_at; merge upsert dedupes the inclusive boundary row.
"""
now = datetime.now(UTC)
+ earliest = now - timedelta(days=lookback_days)
if should_use_incremental_field and db_incremental_field_last_value is not None:
- date_from = _to_datetime(db_incremental_field_last_value)
+ date_from = max(_to_datetime(db_incremental_field_last_value), earliest)
else:
- date_from = now - timedelta(days=lookback_days)
+ date_from = earliest
if date_from >= now:
# A future-dated cursor would make date_from >= date_to and 422 the request; clamp it.
@@ -111,7 +162,7 @@ def _client_config(api_token: str) -> ClientConfig:
"headers": {"Accept": "application/json", "Content-Type": "application/json"},
"auth": {"type": "bearer", "token": api_token},
# MailerSend returns the next page as a full URL under `links.next`, null on the last page.
- "paginator": JSONResponsePaginator(next_url_path="links.next"),
+ "paginator": MailerSendPaginator(),
# `links.next` is followed verbatim, so pin every request (and the Bearer token) to
# api.mailersend.com and refuse redirects — a tampered/off-host `links.next` or a 3xx can't
# retarget the credentialed request. `allowed_hosts=[]` means base-host only.
@@ -120,6 +171,107 @@ def _client_config(api_token: str) -> ClientConfig:
}
+def _activity_resource(
+ api_token: str,
+ endpoint: str,
+ config: MailerSendEndpointConfig,
+ team_id: int,
+ job_id: str,
+ window: SyncWindow[int],
+ resume_hook: Callable[[Optional[dict[str, Any]]], None],
+ initial_state: Optional[dict[str, Any]],
+) -> Any:
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_token),
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": _DOMAINS_PARENT,
+ "endpoint": {
+ "path": "/domains",
+ "params": {"limit": config.page_size},
+ "data_selector": "data",
+ },
+ },
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": {
+ "domain_id": {
+ "type": "resolve",
+ "resource": _DOMAINS_PARENT,
+ "field": "id",
+ },
+ "limit": config.page_size,
+ # The window is computed once per run and rides as static query params —
+ # MailerSend filters server-side on created_at within [date_from, date_to].
+ "date_from": window.start,
+ "date_to": window.end,
+ },
+ "data_selector": "data",
+ },
+ "include_from_parent": ["id"],
+ # activity ids are only unique within a domain, so stamp each row with its
+ # domain_id — the [domain_id, id] primary key stays unique table-wide.
+ "data_map": rename_parent_fields(_DOMAINS_PARENT, {"id": "domain_id"}),
+ },
+ ],
+ }
+ resources = {
+ resource.name: resource
+ for resource in rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_state,
+ )
+ }
+ return resources[endpoint]
+
+
+def _activity_pages(
+ api_token: str,
+ endpoint: str,
+ config: MailerSendEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resume_hook: Callable[[Optional[dict[str, Any]]], None],
+ initial_state: Optional[dict[str, Any]],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[Any]]:
+ """Page the Activity endpoint, narrowing the date window when MailerSend rejects it.
+
+ How far back activity can be read is set by the account's plan and no endpoint reports it, so
+ the only way to find it is to ask. Start at the widest retention tier and step down a tier each
+ time a request comes back rejected, so an account on any plan syncs the activity it does keep.
+ Once rows have come back the window was accepted, and a later rejection is a real failure.
+ """
+ tiers = config.window_tiers_days or (MAILERSEND_DEFAULT_ACTIVITY_DAYS,)
+ for index, lookback_days in enumerate(tiers):
+ window = _activity_date_window(should_use_incremental_field, db_incremental_field_last_value, lookback_days)
+ rows_yielded = False
+ try:
+ for page in _activity_resource(
+ api_token, endpoint, config, team_id, job_id, window, resume_hook, initial_state
+ ):
+ rows_yielded = rows_yielded or bool(page)
+ yield page
+ return
+ except HTTPError as error:
+ window_rejected = error.response is not None and error.response.status_code == 422
+ if rows_yielded or not window_rejected or index == len(tiers) - 1:
+ raise
+ logger.warning(
+ "mailersend.activity_window_narrowed",
+ rejected_lookback_days=lookback_days,
+ next_lookback_days=tiers[index + 1],
+ )
+
+
def mailersend_source(
api_token: str,
endpoint: str,
@@ -143,59 +295,20 @@ def mailersend_source(
if state is not None:
resumable_source_manager.save_state(MailerSendResumeConfig(fanout_state=state))
+ items: Callable[[], Any]
if config.fan_out_over_domains:
- window = _activity_date_window(
- should_use_incremental_field, db_incremental_field_last_value, config.default_lookback_days or 30
+ items = partial(
+ _activity_pages,
+ api_token=api_token,
+ endpoint=endpoint,
+ config=config,
+ team_id=team_id,
+ job_id=job_id,
+ resume_hook=save_checkpoint,
+ initial_state=initial_state,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
)
- rest_config: RESTAPIConfig = {
- "client": _client_config(api_token),
- "resource_defaults": {},
- "resources": [
- {
- "name": _DOMAINS_PARENT,
- "endpoint": {
- "path": "/domains",
- "params": {"limit": config.page_size},
- "data_selector": "data",
- },
- },
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": {
- "domain_id": {
- "type": "resolve",
- "resource": _DOMAINS_PARENT,
- "field": "id",
- },
- "limit": config.page_size,
- # The window is computed once per run and rides as static query params —
- # MailerSend filters server-side on created_at within [date_from, date_to].
- "date_from": window.start,
- "date_to": window.end,
- },
- "data_selector": "data",
- },
- "include_from_parent": ["id"],
- # activity ids are only unique within a domain, so stamp each row with its
- # domain_id — the [domain_id, id] primary key stays unique table-wide.
- "data_map": rename_parent_fields(_DOMAINS_PARENT, {"id": "domain_id"}),
- },
- ],
- }
- resources = {
- resource.name: resource
- for resource in rest_api_resources(
- rest_config,
- team_id,
- job_id,
- None,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_state,
- )
- }
- resource = resources[endpoint]
else:
simple_config: RESTAPIConfig = {
"client": _client_config(api_token),
@@ -219,10 +332,11 @@ def mailersend_source(
resume_hook=save_checkpoint,
initial_paginator_state=initial_state,
)
+ items = lambda: resource
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/settings.py
index 58bf9622c879..b8fe9b10f6cb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/settings.py
@@ -4,7 +4,7 @@ from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class MailerSendEndpointConfig:
name: str
path: str
@@ -19,9 +19,11 @@ class MailerSendEndpointConfig:
# The Activity stream lives under /activity/{domain_id}; we fan out one paginated request per
# sending domain and stamp each row with its domain_id.
fan_out_over_domains: bool = False
- # First-sync lookback (days) for date-filtered endpoints. Capped to MailerSend's activity data
- # retention window (1-30 days depending on plan); 30 is the widest a request can ask for.
- default_lookback_days: Optional[int] = None
+ # Activity retention tiers (days), widest first, for the date-filtered Activity endpoint.
+ # MailerSend keeps email activity for 30, 7 or 1 days depending on the account's plan and
+ # rejects a window reaching back further with a 422, but exposes no endpoint for the plan. The
+ # sync asks for the widest window and narrows to the next tier when a request is rejected.
+ window_tiers_days: tuple[int, ...] = ()
page_size: int = 100
should_sync_default: bool = True
@@ -52,7 +54,7 @@ MAILERSEND_ENDPOINTS: dict[str, MailerSendEndpointConfig] = {
incremental_fields=[_created_at_incremental_field()],
supports_incremental=True,
fan_out_over_domains=True,
- default_lookback_days=30,
+ window_tiers_days=(30, 7, 1),
page_size=100,
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
index 6ba43499c334..bfeeb735867b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
@@ -10,6 +10,7 @@ from unittest.mock import MagicMock
from parameterized import parameterized
from requests import Response
+from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.mailersend import mailersend
from products.warehouse_sources.backend.temporal.data_imports.sources.mailersend.mailersend import (
@@ -128,6 +129,16 @@ class TestActivityDateWindow:
assert window.start == int(last.timestamp())
assert window.end == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
+ def test_cursor_older_than_the_tier_is_clamped(self) -> None:
+ # A watermark left behind by a paused sync asks for more history than the plan retains,
+ # which MailerSend rejects; it must be clamped to the tier being tried.
+ stale = datetime(2026, 1, 1, tzinfo=UTC)
+ window = _activity_date_window(
+ should_use_incremental_field=True, db_incremental_field_last_value=stale, lookback_days=7
+ )
+ assert window.end - window.start == 7 * 24 * 60 * 60
+
@time_machine.travel("2026-06-23T00:00:00Z", tick=False)
def test_future_cursor_is_clamped_below_date_to(self) -> None:
# A future-dated cursor would make date_from >= date_to and 422 the request; it must be clamped.
@@ -203,6 +214,38 @@ class TestTopLevelPagination:
fanout_state={"next_url": f"{BASE}/recipients?page=2&limit=100"}
)
+ @parameterized.expand(
+ [
+ ("last_allowed_page_is_followed", 1000, 2, ["r1", "r2"]),
+ ("page_past_the_cap_ends_the_table", 1001, 1, ["r1"]),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_at_the_documented_page_cap(
+ self,
+ _name: str,
+ next_page: int,
+ expected_requests: int,
+ expected_ids: list[str],
+ MockSession: MagicMock,
+ ) -> None:
+ # MailerSend accepts pages 1-1000 and rejects page 1001 with a 422, but still advertises a
+ # next link on page 1000, so the cap has to end the table instead of following that link.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _page([{"id": "r1"}], next_url=f"{BASE}/recipients?page={next_page}&limit=100"),
+ _page([{"id": "r2"}], next_url=None),
+ ],
+ )
+ manager = _make_manager()
+
+ rows = _rows(_source("recipients", manager))
+
+ assert [r["id"] for r in rows] == expected_ids
+ assert session.send.call_count == expected_requests
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_stops_on_empty_page_without_checkpoint(self, MockSession: MagicMock) -> None:
session = MockSession.return_value
@@ -281,6 +324,7 @@ class TestActivityFanOut:
{"id": "a2", "type": "opened", "domain_id": "d2"},
]
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
@mock.patch(CLIENT_SESSION_PATCH)
def test_sends_required_date_window_params(self, MockSession: MagicMock) -> None:
session = MockSession.return_value
@@ -322,6 +366,59 @@ class TestActivityFanOut:
assert [r["id"] for r in rows] == ["a2"]
assert [c["url"] for c in snaps if "/activity/" in c["url"]] == [f"{BASE}/activity/d2"]
+ @staticmethod
+ def _rejected_window() -> Response:
+ # MailerSend rejects a window reaching past the account's activity retention.
+ return _response({"message": "The given data was invalid."}, status_code=422)
+
+ @staticmethod
+ def _window_days(snapshot: dict[str, Any]) -> float:
+ return (snapshot["date_to"] - snapshot["date_from"]) / (24 * 60 * 60)
+
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_narrows_the_window_when_the_account_retains_less(self, MockSession: MagicMock) -> None:
+ # Activity retention is 30, 7 or 1 days depending on the plan and no endpoint reports it,
+ # so a rejected window must step down a tier rather than fail the whole sync.
+ session = MockSession.return_value
+ snaps = _wire(
+ session,
+ [
+ self._domains("d1"),
+ self._rejected_window(),
+ self._domains("d1"),
+ _page([{"id": "a1"}], next_url=None),
+ ],
+ )
+
+ rows = _rows(_source("activity", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["a1"]
+ attempts = [c for c in snaps if "/activity/" in c["url"]]
+ assert [self._window_days(a) for a in attempts] == [30, 7]
+
+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_every_tier_rejected_fails_the_sync(self, MockSession: MagicMock) -> None:
+ session = MockSession.return_value
+ snaps = _wire(
+ session,
+ [
+ self._domains("d1"),
+ self._rejected_window(),
+ self._domains("d1"),
+ self._rejected_window(),
+ self._domains("d1"),
+ self._rejected_window(),
+ ],
+ )
+
+ with pytest.raises(HTTPError):
+ _rows(_source("activity", _make_manager()))
+
+ attempts = [c for c in snaps if "/activity/" in c["url"]]
+ assert [self._window_days(a) for a in attempts] == [30, 7, 1]
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_all_rows_yielded_for_small_domains(self, MockSession: MagicMock) -> None:
# Every domain's rows are yielded even when each domain is smaller than a page.