: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add mailersend suppression and daily analytics tables (#114903)
Tom Owers287175ba5671
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 3565542efc65..d5d397e4f405 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -5351,10 +5351,10 @@ Today (5): `activity`, `domains`, `messages`, `recipients`, `templates`Diffed against: <https://developers.mailersend.com/llms.txt>-- [ ] `GET /v1/analytics/date` — opens, clicks, bounces and deliveries bucketed by date — the vendor's headline metric endpoint (high)-- [ ] `GET /v1/suppressions/hard-bounces` — hard bounce suppression list; no suppression data is synced today (high)-- [ ] `GET /v1/suppressions/spam-complaints` — spam complaint suppression list, a core deliverability metric (high)-- [ ] `GET /v1/suppressions/unsubscribes` — unsubscribe suppression list needed to reconcile deliverable recipients (high)+- [x] `GET /v1/analytics/date` — opens, clicks, bounces and deliveries bucketed by date — the vendor's headline metric endpoint (high)+- [x] `GET /v1/suppressions/hard-bounces` — hard bounce suppression list; no suppression data is synced today (high)+- [x] `GET /v1/suppressions/spam-complaints` — spam complaint suppression list, a core deliverability metric (high)+- [x] `GET /v1/suppressions/unsubscribes` — unsubscribe suppression list needed to reconcile deliverable recipients (high)- [ ] `GET /v1/analytics/country` — geographic breakdown dimension for opens and clicks (medium)- [ ] `GET /v1/analytics/ua-name and /v1/analytics/ua-type` — client and device breakdown dimensions for engagement (medium)- [ ] `GET /v1/suppressions/blocklist` — account blocklist entries suppressing sends (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/canonical_descriptions.pyindex 969470c2a3ee..fe75055a8a21 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/canonical_descriptions.py@@ -63,4 +63,55 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"email": "Nested object describing the email this event relates to (subject, status, recipient, tags, ...).",},},+ "hard_bounces": {+ "description": "Recipients on the account's hard bounce suppression list. MailerSend skips sending to them.",+ "docs_url": "https://developers.mailersend.com/api/v1/email/recipients#hard-bounces",+ "columns": {+ "id": "Unique identifier for the suppression entry.",+ "created_at": "Timestamp when the recipient was added to the list.",+ "recipient": "Nested object for the suppressed recipient (id, email, timestamps, and its domain).",+ "reason": "Reason for the hard bounce.",+ },+ },+ "spam_complaints": {+ "description": "Recipients on the account's spam complaint suppression list. MailerSend skips sending to them.",+ "docs_url": "https://developers.mailersend.com/api/v1/email/recipients#spam-complaints",+ "columns": {+ "id": "Unique identifier for the suppression entry.",+ "created_at": "Timestamp when the recipient was added to the list.",+ "recipient": "Nested object for the suppressed recipient (id, email, timestamps, and its domain).",+ },+ },+ "unsubscribes": {+ "description": "Recipients on the account's unsubscribe suppression list. MailerSend skips sending to them.",+ "docs_url": "https://developers.mailersend.com/api/v1/email/recipients#unsubscribes",+ "columns": {+ "id": "Unique identifier for the suppression entry.",+ "created_at": "Timestamp when the recipient was added to the list.",+ "recipient": "Nested object for the suppressed recipient (id, email, timestamps, and its domain).",+ "reason": "Unsubscribe reason code (e.g. NEVER_SIGNED).",+ "readable_reason": "Human-readable unsubscribe reason.",+ },+ },+ "analytics_by_date": {+ "description": "Account-wide email event counts per day. Every day in the synced range has a row, with 0 for days without events. Retained for 6 months.",+ "docs_url": "https://developers.mailersend.com/api/v1/email/analytics#activity-data-by-date",+ "columns": {+ "date": "Start of the day (UTC) the counts cover.",+ "queued": "Number of emails queued.",+ "sent": "Number of emails sent.",+ "delivered": "Number of emails delivered.",+ "soft_bounced": "Number of soft bounces.",+ "hard_bounced": "Number of hard bounces.",+ "deferred": "Number of deferred deliveries.",+ "opened": "Number of opens.",+ "clicked": "Number of clicks.",+ "unsubscribed": "Number of unsubscribes.",+ "spam_complaints": "Number of spam complaints.",+ "survey_opened": "Number of survey opens.",+ "survey_submitted": "Number of survey submissions.",+ "opened_unique": "Number of unique opens.",+ "clicked_unique": "Number of unique clicks.",+ },+ },}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.pyindex d6a43ab569b1..d709a24d9d2c 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@@ -21,7 +21,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (JSONResponsePaginator,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow@@ -44,6 +47,28 @@ MAILERSEND_MAX_PAGE = 1000# Fallback lookback for a date-filtered endpoint that declares no retention tiers.MAILERSEND_DEFAULT_ACTIVITY_DAYS = 30+# MailerSend stores analytics for up to 6 months.+MAILERSEND_ANALYTICS_RETENTION_DAYS = 180++# Every counter /analytics/date can return. The response only carries the events asked for, so+# request all of them to keep the table's columns stable.+MAILERSEND_ANALYTICS_EVENTS = (+ "queued",+ "sent",+ "delivered",+ "soft_bounced",+ "hard_bounced",+ "deferred",+ "opened",+ "clicked",+ "unsubscribed",+ "spam_complaints",+ "survey_opened",+ "survey_submitted",+ "opened_unique",+ "clicked_unique",+)+# 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.@@ -102,18 +127,18 @@ def _to_datetime(value: Any) -> datetime:return datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(UTC)-def _activity_date_window(+def _date_window(should_use_incremental_field: bool,db_incremental_field_last_value: Any,lookback_days: int,) -> SyncWindow[int]:- """Build the required date_from/date_to window for the Activity endpoint as Unix timestamps.+ """Build the required date_from/date_to window for a date-filtered endpoint as Unix timestamps.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.+ reaches back further than the account's retention. `lookback_days` is the retention 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 cursor value;+ merge upsert dedupes the inclusive boundary row."""now = datetime.now(UTC)earliest = now - timedelta(days=lookback_days)@@ -252,7 +277,7 @@ def _activity_pages("""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)+ window = _date_window(should_use_incremental_field, db_incremental_field_last_value, lookback_days)rows_yielded = Falsetry:for page in _activity_resource(@@ -272,6 +297,38 @@ def _activity_pages()+def _analytics_row(row: dict[str, Any]) -> dict[str, Any]:+ # `date` arrives as a Unix timestamp string marking the start of the day bucket.+ row["date"] = datetime.fromtimestamp(int(row["date"]), tz=UTC)+ return row+++def _analytics_resource_config(+ endpoint: str,+ config: MailerSendEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> EndpointResource:+ window = _date_window(+ should_use_incremental_field, db_incremental_field_last_value, MAILERSEND_ANALYTICS_RETENTION_DAYS+ )+ return {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": {+ "date_from": window.start,+ "date_to": window.end,+ "group_by": "days",+ "event[]": list(MAILERSEND_ANALYTICS_EVENTS),+ },+ "data_selector": "data.stats",+ "paginator": "single_page",+ },+ "data_map": _analytics_row,+ }++def mailersend_source(api_token: str,endpoint: str,@@ -310,19 +367,24 @@ def mailersend_source(db_incremental_field_last_value=db_incremental_field_last_value,)else:+ endpoint_resource: EndpointResource+ if config.analytics_by_date:+ endpoint_resource = _analytics_resource_config(+ endpoint, config, should_use_incremental_field, db_incremental_field_last_value+ )+ else:+ endpoint_resource = {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": {"limit": config.page_size},+ "data_selector": "data",+ },+ }simple_config: RESTAPIConfig = {"client": _client_config(api_token),"resource_defaults": {},- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": {"limit": config.page_size},- "data_selector": "data",- },- }- ],+ "resources": [endpoint_resource],}resource = rest_api_resource(simple_config,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.pyindex b8fe9b10f6cb..fbda512cffb8 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@@ -16,9 +16,13 @@ class MailerSendEndpointConfig:# 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+ supports_append: 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+ # /analytics/date returns one non-paginated object holding a `stats` array of per-day counters+ # for a required date_from/date_to window, rather than a paged list.+ analytics_by_date: bool = False# 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@@ -35,6 +39,10 @@ def _created_at_incremental_field() -> IncrementalField:return {"label": "created_at", "type": _DT, "field": "created_at", "field_type": _DT}+def _date_incremental_field() -> IncrementalField:+ return {"label": "date", "type": _DT, "field": "date", "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).@@ -42,6 +50,22 @@ MAILERSEND_ENDPOINTS: dict[str, MailerSendEndpointConfig] = {"recipients": MailerSendEndpointConfig(name="recipients", path="/recipients"),"templates": MailerSendEndpointConfig(name="templates", path="/templates"),"messages": MailerSendEndpointConfig(name="messages", path="/messages"),+ # Account-wide suppression lists (no domain_id filter). Same page-based listing as above.+ "hard_bounces": MailerSendEndpointConfig(name="hard_bounces", path="/suppressions/hard-bounces"),+ "spam_complaints": MailerSendEndpointConfig(name="spam_complaints", path="/suppressions/spam-complaints"),+ "unsubscribes": MailerSendEndpointConfig(name="unsubscribes", path="/suppressions/unsubscribes"),+ # Account-wide email counters bucketed per day. Filtered server-side by date_from/date_to, so+ # incremental re-reads from the last synced day; merge on `date` refreshes that partial day.+ # Append is off because it would add a second row for the same day on every sync.+ "analytics_by_date": MailerSendEndpointConfig(+ name="analytics_by_date",+ path="/analytics/date",+ primary_keys=["date"],+ partition_key="date",+ incremental_fields=[_date_incremental_field()],+ supports_incremental=True,+ analytics_by_date=True,+ ),# 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@@ -53,6 +77,7 @@ MAILERSEND_ENDPOINTS: dict[str, MailerSendEndpointConfig] = {partition_key="created_at",incremental_fields=[_created_at_incremental_field()],supports_incremental=True,+ supports_append=True,fan_out_over_domains=True,window_tiers_days=(30, 7, 1),page_size=100,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/source.pyindex f7674be05c48..d431941276f4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/source.py@@ -55,6 +55,8 @@ Grant the token read access to the data you want to sync:- Domains- Recipients- Templates+- Suppressions (for **hard_bounces**, **spam_complaints** and **unsubscribes**)+- Analytics (for **analytics_by_date**)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.""",@@ -96,6 +98,8 @@ Note: MailerSend retains email activity for 1-30 days depending on your plan, sodef _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."+ if endpoint == "analytics_by_date":+ return "Daily email counts (sent, delivered, opened, clicked, bounced, and more). MailerSend keeps analytics for 6 months, so the first sync backfills up to 6 months."return Nonedef _build_schema(endpoint: str) -> SourceSchema:@@ -103,7 +107,7 @@ Note: MailerSend retains email activity for 1-30 days depending on your plan, soreturn SourceSchema(name=endpoint,supports_incremental=endpoint_config.supports_incremental,- supports_append=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_append,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),should_sync_default=endpoint_config.should_sync_default,description=_description(endpoint),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.pyindex 3ca535d0dc92..fee231d84b6d 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@@ -14,8 +14,9 @@ from requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailersend import mailersendfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailersend.mailersend import (+ MAILERSEND_ANALYTICS_EVENTS,MailerSendResumeConfig,- _activity_date_window,+ _date_window,_to_datetime,check_credentials,mailersend_source,@@ -107,7 +108,7 @@ class TestActivityDateWindow: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)- window = _activity_date_window(+ window = _date_window(should_use_incremental_field=True, db_incremental_field_last_value=future, lookback_days=30)assert window.start < window.end@@ -282,6 +283,64 @@ class TestActivityFanOut:assert [self._window_days(a) for a in attempts] == [30, 7, 1]+class TestAnalyticsByDate:+ @parameterized.expand(+ [+ ("full_refresh_backfills_retention", False, None, datetime(2025, 12, 25, tzinfo=UTC)),+ (+ "incremental_rereads_last_synced_day",+ True,+ datetime(2026, 6, 20, tzinfo=UTC),+ datetime(2026, 6, 20, tzinfo=UTC),+ ),+ ]+ )+ @time_machine.travel("2026-06-23T00:00:00Z", tick=False)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_request_window_and_row_shape(+ self,+ _name: str,+ should_use_incremental_field: bool,+ last_value: datetime | None,+ expected_date_from: datetime,+ MockSession: MagicMock,+ ) -> None:+ session = MockSession.return_value+ snaps = _wire(+ session,+ [+ _response(+ {+ "data": {+ "date_from": "1782172800",+ "date_to": "1782259199",+ "group_by": "days",+ "stats": [{"date": "1782172800", "sent": 4, "opened": 2}],+ }+ }+ )+ ],+ )++ rows = _rows(+ _source(+ "analytics_by_date",+ _make_manager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ )+ )++ assert rows == [{"date": datetime(2026, 6, 23, tzinfo=UTC), "sent": 4, "opened": 2}]+ assert len(snaps) == 1+ request = snaps[0]+ assert request["url"] == f"{BASE}/analytics/date"+ assert request["date_from"] == int(expected_date_from.timestamp())+ assert request["date_to"] == int(datetime(2026, 6, 23, tzinfo=UTC).timestamp())+ assert request["group_by"] == "days"+ assert request["event[]"] == list(MAILERSEND_ANALYTICS_EVENTS)++class TestLegacyResumeStateCompat:def test_legacy_state_shape_still_deserializes(self) -> None:# Resume state saved by the pre-migration source (next_page/domain_id only) must still parse.@@ -292,7 +351,19 @@ class TestLegacyResumeStateCompat:class TestSourceResponseShape:- @parameterized.expand(["domains", "recipients", "templates", "messages", "activity"])+ @parameterized.expand(+ [+ "domains",+ "recipients",+ "templates",+ "messages",+ "activity",+ "hard_bounces",+ "spam_complaints",+ "unsubscribes",+ "analytics_by_date",+ ]+ )def test_primary_keys_match_settings(self, endpoint: str) -> None:resource = _source(endpoint, _make_manager())assert resource.name == endpoint@@ -306,8 +377,20 @@ class TestSourceResponseShape:def test_sort_mode(self, endpoint: str, expected_sort: str) -> None:assert _source(endpoint, _make_manager()).sort_mode == expected_sort- @parameterized.expand(["domains", "recipients", "templates", "messages", "activity"])- def test_partitions_on_created_at(self, endpoint: str) -> None:+ @parameterized.expand(+ [+ ("domains", "created_at"),+ ("recipients", "created_at"),+ ("templates", "created_at"),+ ("messages", "created_at"),+ ("activity", "created_at"),+ ("hard_bounces", "created_at"),+ ("spam_complaints", "created_at"),+ ("unsubscribes", "created_at"),+ ("analytics_by_date", "date"),+ ]+ )+ def test_partitions_on_a_stable_timestamp(self, endpoint: str, expected_key: str) -> None:resource = _source(endpoint, _make_manager())- assert resource.partition_keys == ["created_at"]+ assert resource.partition_keys == [expected_key]assert resource.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend_source.pyindex ebc7e7ad9167..dfc41ce8d2d2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailersend/tests/test_mailersend_source.py@@ -23,6 +23,11 @@ class TestGetSchemas:("templates", False, False),("messages", False, False),("activity", True, True),+ ("hard_bounces", False, False),+ ("spam_complaints", False, False),+ ("unsubscribes", False, False),+ # Append would add a duplicate row for the re-read last day on every sync.+ ("analytics_by_date", True, False),])def test_incremental_support_per_endpoint(