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): implement mailersend import source (#65655)

Tom Owers3ac643daaf43
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 42eeca4264c3..18e98ae7a534 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -126,6 +126,7 @@ the row lists both.
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
| mailerlite | HTTP | requests | ✅ |
+| mailersend | HTTP | requests | ✅ |
| mailgun | HTTP | requests | ✅ |
| mailjet | HTTP | requests | ✅ |
| matomo | HTTP | requests | ✅ |
@@ -468,7 +469,6 @@ doesn't conflict with concurrent PRs.
- lokalise
- looker
- luma
-- mailersend
- mailosaur
- mailtrap
- mantle
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 26927bc1f0fe..217478941c5a 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -1790,7 +1790,7 @@ class MailerLiteSourceConfig(config.Config):
@config.config
class MailerSendSourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/mailersend/canonical_descriptions.py b/posthog/temporal/data_imports/sources/mailersend/canonical_descriptions.py
new file mode 100644
index 000000000000..e39a8db8e7bb
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailersend/canonical_descriptions.py
@@ -0,0 +1,64 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Sourced from the MailerSend public API docs (https://developers.mailersend.com/api/v1/).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "domains": {
+ "description": "Sending domains configured in your MailerSend account, with their verification and DNS status.",
+ "docs_url": "https://developers.mailersend.com/api/v1/domains.html",
+ "columns": {
+ "id": "Unique identifier for the domain.",
+ "name": "The domain name (e.g. mail.example.com).",
+ "dkim": "Whether DKIM authentication is configured for the domain.",
+ "spf": "Whether SPF authentication is configured for the domain.",
+ "tracking": "Whether open/click tracking is enabled for the domain.",
+ "is_verified": "Whether the domain has passed verification and can send mail.",
+ "is_cname_verified": "Whether the domain's CNAME records are verified.",
+ "is_dns_active": "Whether the domain's DNS records are active.",
+ "created_at": "Timestamp when the domain was added.",
+ "updated_at": "Timestamp when the domain was last updated.",
+ },
+ },
+ "recipients": {
+ "description": "Recipients that have been sent email through your MailerSend account.",
+ "docs_url": "https://developers.mailersend.com/api/v1/recipients.html",
+ "columns": {
+ "id": "Unique identifier for the recipient.",
+ "email": "The recipient's email address.",
+ "created_at": "Timestamp when the recipient was first seen.",
+ "updated_at": "Timestamp when the recipient was last updated.",
+ "deleted_at": "Timestamp when the recipient was deleted, if applicable.",
+ },
+ },
+ "templates": {
+ "description": "Email templates available in your MailerSend account.",
+ "docs_url": "https://developers.mailersend.com/api/v1/templates.html",
+ "columns": {
+ "id": "Unique identifier for the template.",
+ "name": "Human-readable template name.",
+ "type": "Template type (e.g. html or drag-drop).",
+ "image_path": "URL of the template's preview image.",
+ "created_at": "Timestamp when the template was created.",
+ },
+ },
+ "messages": {
+ "description": "Messages submitted to the MailerSend API. Each row is one send request, which may fan out to multiple recipients and activity events.",
+ "docs_url": "https://developers.mailersend.com/api/v1/messages.html",
+ "columns": {
+ "id": "Unique identifier for the message.",
+ "created_at": "Timestamp when the message was submitted.",
+ "updated_at": "Timestamp when the message was last updated.",
+ },
+ },
+ "activity": {
+ "description": "Per-recipient email activity events (sent, delivered, opened, clicked, bounced, etc.) for a sending domain. Retained for 1-30 days depending on plan.",
+ "docs_url": "https://developers.mailersend.com/api/v1/activity.html",
+ "columns": {
+ "id": "Unique identifier for the activity event.",
+ "domain_id": "Identifier of the sending domain this event belongs to (added by PostHog so the row's primary key is unique across domains).",
+ "type": "Event type: sent, delivered, soft_bounced, hard_bounced, opened, clicked, unsubscribed, spam_complaint, etc.",
+ "created_at": "Timestamp when the event occurred.",
+ "updated_at": "Timestamp when the event was last updated.",
+ "email": "Nested object describing the email this event relates to (subject, status, recipient, tags, ...).",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/mailersend/mailersend.py b/posthog/temporal/data_imports/sources/mailersend/mailersend.py
new file mode 100644
index 000000000000..bb94cc69fa58
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailersend/mailersend.py
@@ -0,0 +1,314 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.mailersend.settings import MAILERSEND_ENDPOINTS
+
+# MailerSend serves every account from a single global base URL (no per-account hostname).
+MAILERSEND_BASE_URL = "https://api.mailersend.com/v1"
+REQUEST_TIMEOUT = 60
+
+
+class MailerSendRetryableError(Exception):
+ pass
+
+
+class MailerSendResumeConfig:
+ # Page to resume from within the current endpoint (1-based, MailerSend page-number pagination).
+ next_page: int = 1
+ # The sending domain currently being paged, for the Activity fan-out. A stable domain id (not a
+ # positional index) so domains added/removed between a crash and the retry can't resume us into
+ # the wrong domain. None for the top-level (non-fan-out) endpoints.
+ domain_id: str | None = None
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ }
+
+
+def _to_datetime(value: Any) -> datetime:
+ """Coerce an incremental cursor value into an aware UTC datetime."""
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, int | float):
+ return datetime.fromtimestamp(float(value), tz=UTC)
+ # ISO 8601 string (MailerSend returns e.g. "2021-08-31T13:43:35.000000Z").
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(UTC)
+
+
+def _activity_date_window(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ lookback_days: int,
+) -> tuple[int, 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.
+ """
+ now = datetime.now(UTC)
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ date_from = _to_datetime(db_incremental_field_last_value)
+ else:
+ date_from = now - timedelta(days=lookback_days)
+
+ if date_from >= now:
+ # A future-dated cursor would make date_from >= date_to and 422 the request; clamp it.
+ date_from = now - timedelta(seconds=1)
+
+ return int(date_from.timestamp()), int(now.timestamp())
+
+
+def check_credentials(api_token: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+ """Probe a cheap endpoint to confirm the token is genuine.
+
+ MailerSend tokens are scoped per sending domain with granular permissions, so a valid token may
+ legitimately lack the "Domains" read scope. We accept a 403 at source-create time (schema_name is
+ None) and only reject an outright 401. Per-schema scope gaps surface later via the sync-time
+ non-retryable error handling.
+ """
+ try:
+ response = make_tracked_session().get(
+ f"{MAILERSEND_BASE_URL}/domains",
+ headers=_get_headers(api_token),
+ params={"limit": 10},
+ timeout=10,
+ )
+ except Exception:
+ return False, "Could not reach MailerSend. Please check your connection and try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 403 and schema_name is None:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid or insufficiently-scoped MailerSend API token."
+ return False, f"Unexpected response from MailerSend (status {response.status_code})."
+
+
+@retry(
+ retry=retry_if_exception_type((MailerSendRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ # MailerSend rate-limits per endpoint (Activity is just 10 req/min) and returns a Retry-After
+ # header on 429. We fall back to exponential jitter capped at 60s, which comfortably spans the
+ # per-minute windows without parsing the header.
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict:
+ response = session.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MailerSendRetryableError(f"MailerSend API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"MailerSend API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_domain_ids(
+ session: requests.Session, headers: dict[str, str], page_size: int, logger: FilteringBoundLogger
+) -> Iterator[str]:
+ """Page through /domains and yield each sending domain's id (drives the Activity fan-out)."""
+ page = 1
+ url = f"{MAILERSEND_BASE_URL}/domains"
+ while True:
+ data = _fetch_page(session, url, headers, {"page": page, "limit": page_size}, logger)
+ items = data.get("data", [])
+ for item in items:
+ yield item["id"]
+ if not items or not data.get("links", {}).get("next"):
+ break
+ page += 1
+
+
+def _iter_top_level_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ path: str,
+ page_size: int,
+ resumable_source_manager: ResumableSourceManager[MailerSendResumeConfig],
+) -> Iterator[Any]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume and resume.next_page else 1
+ url = f"{MAILERSEND_BASE_URL}{path}"
+
+ while True:
+ data = _fetch_page(session, url, headers, {"page": page, "limit": page_size}, logger)
+ items = data.get("data", [])
+ if not items:
+ break
+
+ has_next = bool(data.get("links", {}).get("next"))
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last
+ # page rather than skipping it.
+ if has_next:
+ resumable_source_manager.save_state(MailerSendResumeConfig(next_page=page + 1))
+
+ if not has_next:
+ break
+ page += 1
+
+
+def _iter_activity_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ path: str,
+ page_size: int,
+ date_from: int,
+ date_to: int,
+ resumable_source_manager: ResumableSourceManager[MailerSendResumeConfig],
+) -> Iterator[Any]:
+ """Fan out over every sending domain, paging /activity/{domain_id} within the date window.
+
+ Each row is stamped with its domain_id so the [domain_id, id] primary key stays unique across the
+ whole table (activity ids are only guaranteed unique within a domain).
+ """
+ domain_ids = list(_iter_domain_ids(session, headers, page_size, logger))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = domain_ids
+ resume_page = 1
+ if resume is not None and resume.domain_id is not None and resume.domain_id in domain_ids:
+ remaining = domain_ids[domain_ids.index(resume.domain_id) :]
+ resume_page = resume.next_page or 1
+ logger.debug(f"MailerSend: resuming activity from domain_id={resume.domain_id}, page={resume_page}")
+
+ for index, domain_id in enumerate(remaining):
+ page = resume_page if index == 0 else 1
+ resume_page = 1
+ url = f"{MAILERSEND_BASE_URL}{path.format(domain_id=domain_id)}"
+
+ while True:
+ params = {"page": page, "limit": page_size, "date_from": date_from, "date_to": date_to}
+ data = _fetch_page(session, url, headers, params, logger)
+ items = data.get("data", [])
+ if not items:
+ break
+
+ has_next = bool(data.get("links", {}).get("next"))
+ for item in items:
+ batcher.batch({**item, "domain_id": domain_id})
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if has_next:
+ resumable_source_manager.save_state(
+ MailerSendResumeConfig(next_page=page + 1, domain_id=domain_id)
+ )
+
+ if not has_next:
+ break
+ page += 1
+
+ # Deliberately NO cross-domain checkpoint here. A domain smaller than one batcher chunk
+ # (~20 pages) never triggers a mid-domain yield, so its rows are still buffered and unwritten
+ # when its loop ends — advancing the bookmark to the next domain would skip them on a crash.
+ # The only checkpoints are the after-yield saves above, each written only once its full chunk
+ # has been flushed. On resume we restart from the last such checkpoint and re-fetch forward
+ # across the remaining domains; merge upsert dedupes the re-pulled rows, so nothing is lost.
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailerSendResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = MAILERSEND_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # Source-side batching at the same thresholds the pipeline uses keeps the resume checkpoint
+ # aligned with a written chunk, so save_state-after-yield can't skip unpersisted rows.
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ session = make_tracked_session()
+
+ if config.fan_out_over_domains:
+ date_from, date_to = _activity_date_window(
+ should_use_incremental_field, db_incremental_field_last_value, config.default_lookback_days or 30
+ )
+ yield from _iter_activity_rows(
+ session,
+ headers,
+ logger,
+ batcher,
+ config.path,
+ config.page_size,
+ date_from,
+ date_to,
+ resumable_source_manager,
+ )
+ else:
+ yield from _iter_top_level_rows(
+ session, headers, logger, batcher, config.path, config.page_size, resumable_source_manager
+ )
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def mailersend_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MailerSendResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = MAILERSEND_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ 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,
+ # MailerSend's Activity endpoint doesn't document its sort order. "desc" is the safe choice:
+ # the incremental watermark is only committed once the full window has been read, so an
+ # interrupted sync can't checkpoint past unfetched rows and lose them.
+ sort_mode="desc" if config.supports_incremental else "asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/mailersend/settings.py b/posthog/temporal/data_imports/sources/mailersend/settings.py
new file mode 100644
index 000000000000..58958bedbef1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailersend/settings.py
@@ -0,0 +1,64 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class MailerSendEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Partition by a STABLE creation timestamp so partitions never rewrite (never updated_at).
+ partition_key: Optional[str] = "created_at"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Only true where MailerSend exposes a genuine server-side timestamp filter (the Activity
+ # endpoint's date_from/date_to). Everything else is full refresh — the list endpoints have no
+ # updated_since/created_since cursor.
+ supports_incremental: bool = False
+ # 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
+ page_size: int = 100
+ should_sync_default: bool = True
+
+
+_DT = IncrementalFieldType.DateTime
+
+
+def _created_at_incremental_field() -> IncrementalField:
+ return {"label": "created_at", "type": _DT, "field": "created_at", "field_type": _DT}
+
+
+MAILERSEND_ENDPOINTS: dict[str, MailerSendEndpointConfig] = {
+ # Top-level list endpoints. MailerSend exposes no server-side updated_since/created_since cursor
+ # on these, so they're full refresh only (confirmed against the public API docs).
+ "domains": MailerSendEndpointConfig(name="domains", path="/domains"),
+ "recipients": MailerSendEndpointConfig(name="recipients", path="/recipients"),
+ "templates": MailerSendEndpointConfig(name="templates", path="/templates"),
+ "messages": MailerSendEndpointConfig(name="messages", path="/messages"),
+ # Email activity events (sent, delivered, opened, clicked, bounced, ...). The endpoint requires a
+ # domain_id path segment and a date_from/date_to window, so we fan out over every sending domain
+ # and filter server-side on created_at. Incremental with merge upsert: the date window advances to
+ # the last-seen created_at, and merge dedupes any boundary overlap so re-fetches are harmless.
+ "activity": MailerSendEndpointConfig(
+ name="activity",
+ path="/activity/{domain_id}",
+ primary_keys=["domain_id", "id"],
+ partition_key="created_at",
+ incremental_fields=[_created_at_incremental_field()],
+ supports_incremental=True,
+ fan_out_over_domains=True,
+ default_lookback_days=30,
+ page_size=100,
+ ),
+}
+
+ENDPOINTS = tuple(MAILERSEND_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in MAILERSEND_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/mailersend/source.py b/posthog/temporal/data_imports/sources/mailersend/source.py
index 79bb5bbc29d2..0fc03e5834c5 100644
--- a/posthog/temporal/data_imports/sources/mailersend/source.py
+++ b/posthog/temporal/data_imports/sources/mailersend/source.py
@@ -1,20 +1,37 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import MailerSendSourceConfig
+from posthog.temporal.data_imports.sources.mailersend.mailersend import (
+ MailerSendResumeConfig,
+ check_credentials,
+ mailersend_source,
+)
+from posthog.temporal.data_imports.sources.mailersend.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ MAILERSEND_ENDPOINTS,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MailerSendSource(SimpleSource[MailerSendSourceConfig]):
+class MailerSendSource(ResumableSource[MailerSendSourceConfig, MailerSendResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MAILERSEND
@@ -25,7 +42,102 @@ class MailerSendSource(SimpleSource[MailerSendSourceConfig]):
name=SchemaExternalDataSourceType.MAILER_SEND,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="MailerSend",
- iconPath="/static/services/mailersend.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your MailerSend API token to automatically pull your MailerSend data into the PostHog Data warehouse.
+
+You can create an API token in your [MailerSend domain settings](https://app.mailersend.com/api-tokens).
+
+Grant the token read access to the data you want to sync:
+- Email (for **activity** events)
+- Domains
+- Recipients
+- Templates
+
+Note: MailerSend retains email activity for 1-30 days depending on your plan, so the **activity** table only backfills as far as that retention window on its first sync.
+""",
+ iconPath="/static/services/mailersend.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/mailersend",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="mlsn....",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A revoked or insufficiently-scoped token surfaces as an HTTPError when `_fetch_page`
+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem. Match the
+ # stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.mailersend.com": "Your MailerSend API token is invalid or has been revoked. Create a new token in your MailerSend domain settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.mailersend.com": "Your MailerSend API token is missing the read permissions needed to sync this data. Grant the required read scopes in your MailerSend domain settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: MailerSendSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "activity":
+ return "Email activity events. Only backfills as far as your plan's data retention window (1-30 days) on initial sync."
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = MAILERSEND_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ description=_description(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: MailerSendSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return check_credentials(config.api_token, schema_name)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.mailersend.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailerSendResumeConfig]:
+ return ResumableSourceManager[MailerSendResumeConfig](inputs, MailerSendResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MailerSendSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MailerSendResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return mailersend_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ 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,
)
diff --git a/posthog/temporal/data_imports/sources/mailersend/tests/test_mailersend.py b/posthog/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
new file mode 100644
index 000000000000..87af98b6a15a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailersend/tests/test_mailersend.py
@@ -0,0 +1,336 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.mailersend import mailersend
+from posthog.temporal.data_imports.sources.mailersend.mailersend import (
+ MailerSendResumeConfig,
+ _activity_date_window,
+ _to_datetime,
+ check_credentials,
+ get_rows,
+ mailersend_source,
+)
+from posthog.temporal.data_imports.sources.mailersend.settings import MAILERSEND_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: MailerSendResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[MailerSendResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> MailerSendResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: MailerSendResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _fake_session_returning(status_code: int) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+
+class TestToDatetime:
+ @parameterized.expand(
+ [
+ (
+ "aware_datetime",
+ datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ ),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)),
+ ("date_value", date(2026, 3, 4), datetime(2026, 3, 4, 0, 0, 0, tzinfo=UTC)),
+ ("unix_int", 1443651141, datetime(2015, 9, 30, 22, 12, 21, tzinfo=UTC)),
+ ("iso_z_suffix", "2021-08-31T13:43:35.000000Z", datetime(2021, 8, 31, 13, 43, 35, tzinfo=UTC)),
+ ("iso_offset", "2021-08-31T13:43:35+00:00", datetime(2021, 8, 31, 13, 43, 35, tzinfo=UTC)),
+ ]
+ )
+ def test_to_datetime(self, _name: str, value: Any, expected: datetime) -> None:
+ assert _to_datetime(value) == expected
+
+
+class TestActivityDateWindow:
+ @freeze_time("2026-06-23T00:00:00Z")
+ def test_first_sync_uses_lookback_window(self) -> None:
+ date_from, date_to = _activity_date_window(
+ should_use_incremental_field=True, db_incremental_field_last_value=None, lookback_days=30
+ )
+ # 30 days of seconds between the bounds.
+ assert date_to - date_from == 30 * 24 * 60 * 60
+ assert date_to == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
+
+ @freeze_time("2026-06-23T00:00:00Z")
+ def test_full_refresh_uses_lookback_window(self) -> None:
+ # Activity requires a date window even without an incremental cursor, so a full refresh still
+ # falls back to the lookback window rather than omitting the bounds.
+ date_from, date_to = _activity_date_window(
+ should_use_incremental_field=False, db_incremental_field_last_value=None, lookback_days=30
+ )
+ assert date_to - date_from == 30 * 24 * 60 * 60
+
+ @freeze_time("2026-06-23T00:00:00Z")
+ def test_incremental_starts_from_last_value(self) -> None:
+ last = datetime(2026, 6, 20, 12, 0, 0, tzinfo=UTC)
+ date_from, date_to = _activity_date_window(
+ should_use_incremental_field=True, db_incremental_field_last_value=last, lookback_days=30
+ )
+ assert date_from == int(last.timestamp())
+ assert date_to == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())
+
+ @freeze_time("2026-06-23T00:00:00Z")
+ 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.
+ future = datetime(2027, 1, 1, tzinfo=UTC)
+ date_from, date_to = _activity_date_window(
+ should_use_incremental_field=True, db_incremental_field_last_value=future, lookback_days=30
+ )
+ assert date_from < date_to
+
+
+class TestCheckCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "schema_name", "expected_ok"),
+ [
+ (200, None, True),
+ (401, None, False),
+ (403, None, True), # valid token, missing scope — accepted at source-create
+ (403, "activity", False), # scope gap surfaced for a specific schema
+ (500, None, False),
+ ],
+ )
+ def test_status_mapping(
+ self, status_code: int, schema_name: str | None, expected_ok: bool, monkeypatch: Any
+ ) -> None:
+ monkeypatch.setattr(mailersend, "make_tracked_session", lambda: _fake_session_returning(status_code))
+ ok, _error = check_credentials("mlsn.token", schema_name)
+ assert ok is expected_ok
+
+ def test_network_error_is_not_valid(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ monkeypatch.setattr(mailersend, "make_tracked_session", lambda: session)
+ ok, error = check_credentials("mlsn.token")
+ assert ok is False
+ assert error is not None
+
+
+def _collect(
+ endpoint: str, manager: _FakeResumableManager, monkeypatch: Any, pages: dict[tuple[str, int], Any], **kw: Any
+) -> list[dict]:
+ """Run get_rows with `_fetch_page` mocked from a {(url, page): body} map and flatten the tables."""
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], params: dict[str, Any], logger: Any) -> dict:
+ return pages[(url, params["page"])]
+
+ monkeypatch.setattr(mailersend, "make_tracked_session", lambda: MagicMock())
+ monkeypatch.setattr(mailersend, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(
+ api_token="mlsn.token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kw,
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestTopLevelPagination:
+ def test_single_page(self, monkeypatch: Any) -> None:
+ pages = {
+ ("https://api.mailersend.com/v1/domains", 1): {
+ "data": [{"id": "d1", "name": "a.com"}, {"id": "d2", "name": "b.com"}],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect("domains", _FakeResumableManager(), monkeypatch, pages)
+ assert [r["id"] for r in rows] == ["d1", "d2"]
+
+ def test_follows_pagination_until_links_next_is_null(self, monkeypatch: Any) -> None:
+ pages = {
+ ("https://api.mailersend.com/v1/recipients", 1): {
+ "data": [{"id": "r1"}],
+ "links": {"next": "https://api.mailersend.com/v1/recipients?page=2"},
+ },
+ ("https://api.mailersend.com/v1/recipients", 2): {
+ "data": [{"id": "r2"}],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect("recipients", _FakeResumableManager(), monkeypatch, pages)
+ assert [r["id"] for r in rows] == ["r1", "r2"]
+
+ def test_stops_on_empty_page(self, monkeypatch: Any) -> None:
+ pages = {
+ ("https://api.mailersend.com/v1/templates", 1): {"data": [], "links": {"next": None}},
+ }
+ rows = _collect("templates", _FakeResumableManager(), monkeypatch, pages)
+ assert rows == []
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ # A saved state must skip already-synced earlier pages and pick up where it left off.
+ manager = _FakeResumableManager(MailerSendResumeConfig(next_page=2))
+ pages = {
+ ("https://api.mailersend.com/v1/messages", 2): {
+ "data": [{"id": "m2"}],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect("messages", manager, monkeypatch, pages)
+ assert [r["id"] for r in rows] == ["m2"]
+
+
+class TestActivityFanOut:
+ @staticmethod
+ def _domains_page(*ids: str) -> dict:
+ return {"data": [{"id": i} for i in ids], "links": {"next": None}}
+
+ def test_fans_out_over_domains_and_stamps_domain_id(self, monkeypatch: Any) -> None:
+ pages = {
+ ("https://api.mailersend.com/v1/domains", 1): self._domains_page("d1", "d2"),
+ ("https://api.mailersend.com/v1/activity/d1", 1): {
+ "data": [{"id": "a1", "type": "sent"}],
+ "links": {"next": None},
+ },
+ ("https://api.mailersend.com/v1/activity/d2", 1): {
+ "data": [{"id": "a2", "type": "opened"}],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect(
+ "activity",
+ _FakeResumableManager(),
+ monkeypatch,
+ pages,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+ assert rows == [
+ {"id": "a1", "type": "sent", "domain_id": "d1"},
+ {"id": "a2", "type": "opened", "domain_id": "d2"},
+ ]
+
+ def test_sends_required_date_window_params(self, monkeypatch: Any) -> None:
+ captured: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], params: dict[str, Any], logger: Any) -> dict:
+ captured.append({"url": url, **params})
+ if url.endswith("/domains"):
+ return self._domains_page("d1")
+ return {"data": [{"id": "a1"}], "links": {"next": None}}
+
+ monkeypatch.setattr(mailersend, "make_tracked_session", lambda: MagicMock())
+ monkeypatch.setattr(mailersend, "_fetch_page", fake_fetch)
+
+ list(
+ get_rows(
+ api_token="mlsn.token",
+ endpoint="activity",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+ )
+
+ activity_call = next(c for c in captured if "activity" in c["url"])
+ assert activity_call["date_from"] == int(datetime(2026, 6, 1, tzinfo=UTC).timestamp())
+ assert "date_to" in activity_call
+
+ def test_resumes_from_saved_domain(self, monkeypatch: Any) -> None:
+ # State pointing at d2 must skip d1 entirely and resume at d2's saved page.
+ manager = _FakeResumableManager(MailerSendResumeConfig(next_page=1, domain_id="d2"))
+ pages = {
+ ("https://api.mailersend.com/v1/domains", 1): self._domains_page("d1", "d2"),
+ ("https://api.mailersend.com/v1/activity/d2", 1): {
+ "data": [{"id": "a2"}],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect(
+ "activity",
+ manager,
+ monkeypatch,
+ pages,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+ assert [r["id"] for r in rows] == ["a2"]
+
+ def test_no_checkpoint_skips_unflushed_small_domains(self, monkeypatch: Any) -> None:
+ # Domains smaller than one batcher chunk never yield mid-domain, so their rows are still
+ # buffered when the domain's loop ends. A cross-domain bookmark saved there would skip those
+ # un-flushed rows on a crash. With only after-yield checkpoints, nothing is saved at all here.
+ manager = _FakeResumableManager()
+ pages = {
+ ("https://api.mailersend.com/v1/domains", 1): self._domains_page("d1", "d2"),
+ ("https://api.mailersend.com/v1/activity/d1", 1): {"data": [{"id": "a1"}], "links": {"next": None}},
+ ("https://api.mailersend.com/v1/activity/d2", 1): {"data": [{"id": "a2"}], "links": {"next": None}},
+ }
+ rows = _collect(
+ "activity",
+ manager,
+ monkeypatch,
+ pages,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+ assert [r["id"] for r in rows] == ["a1", "a2"]
+ assert manager.saved == []
+
+
+class TestSourceResponseShape:
+ @parameterized.expand(["domains", "recipients", "templates", "messages", "activity"])
+ def test_primary_keys_match_settings(self, endpoint: str) -> None:
+ resource = mailersend_source(
+ api_token="mlsn.token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ assert resource.name == endpoint
+ assert resource.primary_keys == MAILERSEND_ENDPOINTS[endpoint].primary_keys
+
+ def test_activity_primary_key_includes_domain_id(self) -> None:
+ # Activity ids are only unique within a domain, so the table-wide key must include domain_id.
+ assert MAILERSEND_ENDPOINTS["activity"].primary_keys == ["domain_id", "id"]
+
+ @parameterized.expand(
+ [
+ ("activity", "desc"),
+ ("domains", "asc"),
+ ]
+ )
+ def test_sort_mode(self, endpoint: str, expected_sort: str) -> None:
+ resource = mailersend_source(
+ api_token="mlsn.token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ assert resource.sort_mode == expected_sort
+
+ @parameterized.expand(["domains", "recipients", "templates", "messages", "activity"])
+ def test_partitions_on_created_at(self, endpoint: str) -> None:
+ resource = mailersend_source(
+ api_token="mlsn.token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ assert resource.partition_keys == ["created_at"]
+ assert resource.partition_mode == "datetime"
diff --git a/posthog/temporal/data_imports/sources/mailersend/tests/test_mailersend_source.py b/posthog/temporal/data_imports/sources/mailersend/tests/test_mailersend_source.py
new file mode 100644
index 000000000000..6969e8c0c72e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mailersend/tests/test_mailersend_source.py
@@ -0,0 +1,166 @@
+from typing import Any
+
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import MailerSendSourceConfig
+from posthog.temporal.data_imports.sources.mailersend import source as source_module
+from posthog.temporal.data_imports.sources.mailersend.mailersend import MailerSendResumeConfig
+from posthog.temporal.data_imports.sources.mailersend.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.mailersend.source import MailerSendSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config() -> MailerSendSourceConfig:
+ return MailerSendSourceConfig.from_dict({"api_token": "mlsn.token"})
+
+
+class TestMailerSendSourceConfig:
+ def test_source_type(self) -> None:
+ assert MailerSendSource().source_type == ExternalDataSourceType.MAILERSEND
+
+ def test_source_config_metadata(self) -> None:
+ config = MailerSendSource().get_source_config
+ assert config.label == "MailerSend"
+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL
+ # Stays hidden behind the unreleased flag while in alpha.
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_single_secret_api_token_field(self) -> None:
+ fields = MailerSendSource().get_source_config.fields
+ assert [f.name for f in fields] == ["api_token"]
+ api_token = fields[0]
+ assert isinstance(api_token, SourceFieldInputConfig)
+ assert api_token.required is True
+ assert api_token.secret is True
+
+
+class TestGetSchemas:
+ def test_exposes_every_endpoint(self) -> None:
+ names = {s.name for s in MailerSendSource().get_schemas(_config(), team_id=1)}
+ assert names == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("domains", False, False),
+ ("recipients", False, False),
+ ("templates", False, False),
+ ("messages", False, False),
+ ("activity", True, True),
+ ]
+ )
+ def test_incremental_support_per_endpoint(
+ self, endpoint: str, supports_incremental: bool, supports_append: bool
+ ) -> None:
+ schemas = {s.name: s for s in MailerSendSource().get_schemas(_config(), team_id=1)}
+ assert schemas[endpoint].supports_incremental is supports_incremental
+ assert schemas[endpoint].supports_append is supports_append
+
+ def test_only_activity_is_incremental(self) -> None:
+ # Only the Activity endpoint exposes a server-side date filter; the rest are full refresh.
+ schemas = {s.name: s for s in MailerSendSource().get_schemas(_config(), team_id=1)}
+ incremental = {name for name, s in schemas.items() if s.supports_incremental}
+ assert incremental == {"activity"}
+
+ def test_names_filter(self) -> None:
+ schemas = MailerSendSource().get_schemas(_config(), team_id=1, names=["domains"])
+ assert [s.name for s in schemas] == ["domains"]
+
+
+class TestValidateCredentials:
+ def test_delegates_to_check_credentials(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(source_module, "check_credentials", lambda token, schema: (True, None))
+ ok, error = MailerSendSource().validate_credentials(_config(), team_id=1)
+ assert ok is True
+ assert error is None
+
+ def test_passes_schema_name_through(self, monkeypatch: Any) -> None:
+ seen: dict[str, Any] = {}
+
+ def fake_check(token: str, schema: str | None) -> tuple[bool, str | None]:
+ seen["token"] = token
+ seen["schema"] = schema
+ return False, "bad"
+
+ monkeypatch.setattr(source_module, "check_credentials", fake_check)
+ ok, error = MailerSendSource().validate_credentials(_config(), team_id=1, schema_name="activity")
+ assert ok is False
+ assert seen == {"token": "mlsn.token", "schema": "activity"}
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(["401 Client Error: Unauthorized", "403 Client Error: Forbidden"])
+ def test_auth_errors_are_non_retryable(self, status_text: str) -> None:
+ error = f"{status_text} for url: https://api.mailersend.com/v1/domains?page=1"
+ non_retryable = MailerSendSource().get_non_retryable_errors()
+ assert any(key in error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ "500 Server Error: Internal Server Error for url: https://api.mailersend.com/v1/domains",
+ "HTTPSConnectionPool(host='api.mailersend.com', port=443): Read timed out.",
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, error: str) -> None:
+ non_retryable = MailerSendSource().get_non_retryable_errors()
+ assert not any(key in error for key in non_retryable)
+
+
+class TestResumableWiring:
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = MailerSendSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MailerSendResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> Any:
+ captured.update(kwargs)
+ return MagicMock()
+
+ monkeypatch.setattr(source_module, "mailersend_source", fake_source)
+
+ inputs = MagicMock()
+ inputs.schema_name = "activity"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"
+ manager = MagicMock()
+
+ MailerSendSource().source_for_pipeline(_config(), manager, inputs)
+
+ assert captured["api_token"] == "mlsn.token"
+ assert captured["endpoint"] == "activity"
+ assert captured["should_use_incremental_field"] is True
+ assert captured["db_incremental_field_last_value"] == "2026-06-01T00:00:00Z"
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+ monkeypatch.setattr(source_module, "mailersend_source", lambda **kw: captured.update(kw))
+
+ inputs = MagicMock()
+ inputs.schema_name = "domains"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+
+ MailerSendSource().source_for_pipeline(_config(), MagicMock(), inputs)
+ assert captured["db_incremental_field_last_value"] is None
+
+
+class TestCanonicalDescriptions:
+ def test_covers_every_endpoint(self) -> None:
+ descriptions = MailerSendSource().get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ def test_activity_documents_injected_domain_id(self) -> None:
+ # domain_id is added by PostHog, not MailerSend, so it must be documented for the AI agent.
+ activity = MailerSendSource().get_canonical_descriptions()["activity"]
+ assert "domain_id" in activity["columns"]