: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 mailtrap contacts, campaigns and daily stats tables (#114901)
Tom Owersa8e707886505
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex ba7d6ecd6ec4..c88833615e14 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -779,8 +779,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/mailosaur.py1 products/warehouse_sources/backend/temporal/data_imports/sources/mailosaur/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py1 products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py1 products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/settings.pydiff --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 4c3f36c8921d..43c5d59fd7d0 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@@ -5424,9 +5424,9 @@ Today (6): `accounts`, `contact_lists`, `email_logs`, `email_templates`, `sendinDiffed against: <https://github.com/mailtrap/mailtrap-openapi/tree/main/specs>-- [ ] `/api/contacts` — The core marketing audience table; contact_lists is synced but not its members (high)-- [ ] `/api/email_campaigns` — Campaign objects - currently no campaign table at all despite contact_lists being synced (high)-- [ ] `/api/stats/date` — Daily aggregated sending stats, the headline dashboard metric (high)+- [x] `/api/contacts` — The core marketing audience table; contact_lists is synced but not its members (high)+- [x] `/api/email_campaigns` — Campaign objects - currently no campaign table at all despite contact_lists being synced (high)+- [x] `/api/stats/date` — Daily aggregated sending stats, the headline dashboard metric (high)- [ ] `/api/contacts/{contact_identifier}/events` — Per-contact engagement event stream (opens, clicks, unsubscribes) (high)- [ ] `/api/email_campaigns/{email_campaign_id}/stats` — Per-campaign performance metrics; resolves campaign rows into results (high)- [ ] `/api/stats/domains` — Sending stats broken down by sending domain, joining to the sending_domains table (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/canonical_descriptions.pyindex c2deed9b4f47..8796475a261e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/canonical_descriptions.py@@ -90,4 +90,52 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"access_levels": "The token's access levels on the account (1000 owner, 100 admin, 10 viewer).",},},+ "contacts": {+ "description": "A marketing contact (email recipient) with its subscription status, list memberships, and custom fields.",+ "docs_url": "https://docs.mailtrap.io/developers/promotional/contacts/contacts",+ "columns": {+ "id": "The unique UUID of the contact.",+ "email": "The contact's email address.",+ "fields": "Custom contact field values, keyed by field merge tag.",+ "list_ids": "IDs of the contact lists the contact belongs to.",+ "status": "Subscription status: subscribed, or unsubscribed if the email is on the suppression list.",+ "created_at": "Creation time as a Unix timestamp in milliseconds.",+ "updated_at": "Last update time as a Unix timestamp in milliseconds.",+ },+ },+ "email_campaigns": {+ "description": "A marketing email campaign sent to contact lists or segments from a sending domain.",+ "docs_url": "https://docs.mailtrap.io/developers/promotional/email-campaigns",+ "columns": {+ "id": "The unique ID of the email campaign.",+ "domain_id": "The ID of the sending domain used for the campaign.",+ "domain_name": "The sending domain name.",+ "name": "The campaign name.",+ "from_local_part": "Local part of the sender address (before the @).",+ "from_display_name": "Sender display name.",+ "reply_to": "Reply-to settings of the campaign.",+ "current_state": "Lifecycle state (draft, scheduled, started, queued, paused, terminating, under_review, finished, failed, or failed_immediately).",+ "current_state_metadata": "Metadata about the most recent state transition, such as the scheduled time or failure errors.",+ "created_at": "When the campaign was created.",+ "updated_at": "When the campaign was last updated.",+ "last_started_at": "When the campaign was last started, if ever.",+ },+ },+ "sending_stats_by_date": {+ "description": "Daily aggregated email sending stats for the account across all sending domains and streams.",+ "docs_url": "https://docs.mailtrap.io/developers/email-sending/stats",+ "columns": {+ "date": "The calendar day the stats cover.",+ "delivery_count": "Number of delivered emails.",+ "delivery_rate": "Delivery rate, as a fraction between 0 and 1.",+ "bounce_count": "Number of bounced emails.",+ "bounce_rate": "Bounce rate, as a fraction between 0 and 1.",+ "open_count": "Number of email opens.",+ "open_rate": "Open rate, as a fraction between 0 and 1.",+ "click_count": "Number of link clicks.",+ "click_rate": "Click rate, as a fraction between 0 and 1.",+ "spam_count": "Number of spam complaints.",+ "spam_rate": "Spam complaint rate, as a fraction between 0 and 1.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.pyindex 49fb6b031a6d..0e240dcb1f9b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/mailtrap.py@@ -1,5 +1,6 @@import dataclasses-from datetime import date, datetime+from collections.abc import Callable+from datetime import UTC, date, datetimefrom typing import Any, Optionalfrom requests import Request, Response@@ -27,12 +28,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.sMAILTRAP_BASE_URL = "https://mailtrap.io"# Cheap probe to confirm a token is genuine: every token can list the accounts it has access to.DEFAULT_PROBE_PATH = "/api/accounts"+# Lower bound of the stats window: predates the Mailtrap Email Sending product, so a full refresh+# covers an account's whole history in one request.+STATS_START_DATE = "2020-01-01"[email protected](frozen=True)class MailtrapResumeConfig:- # Opaque cursor for the next page: `next_page_cursor` for email_logs, the last suppression's- # UUID for suppressions. A crashed sync resumes from the page after the last one yielded; merge+ # Opaque cursor for the next page: `next_page_cursor` for email_logs, `pagination.next_token`+ # for contacts and email_campaigns, the last suppression's UUID for suppressions. A crashed+ # sync resumes from the page after the last one yielded; merge# dedupes the re-pulled page on the primary key. `None` means start from the first page.cursor: str | None = None@@ -102,6 +107,18 @@ class LastIdPaginator(BasePaginator):self._has_next_page = True+def _flatten(field_name: str) -> Callable[[dict[str, Any]], dict[str, Any]]:+ def _map(row: dict[str, Any]) -> dict[str, Any]:+ nested = row.get(field_name)+ if not isinstance(nested, dict):+ return row+ flat = {k: v for k, v in row.items() if k != field_name}+ flat.update(nested)+ return flat++ return _map++def _build_paginator(config: MailtrapEndpointConfig) -> BasePaginator:if config.cursor_response_key is not None and config.cursor_param is not None:return JSONResponseCursorPaginator(cursor_path=config.cursor_response_key, cursor_param=config.cursor_param)@@ -130,7 +147,10 @@ def mailtrap_source() -> SourceResponse:config = MAILTRAP_ENDPOINTS[endpoint]- params: dict[str, Any] = {}+ params: dict[str, Any] = dict(config.params)+ if config.date_range:+ params["start_date"] = STATS_START_DATE+ params["end_date"] = datetime.now(UTC).date().isoformat()if config.incremental_param is not None:# Server-side lower bound (filters[sent_after] / start_time). The framework injects the# watermark (db_incremental_field_last_value) once and re-sends it on every page, so cursor@@ -164,6 +184,7 @@ def mailtrap_source(# is a transient/malformed payload — retry rather than ingest garbage."data_selector_malformed_retryable": True,},+ **({"data_map": _flatten(config.flatten_field)} if config.flatten_field else {}),}],}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.pyindex 0a0b91c75fe9..49b65ac6ff6a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/settings.py@@ -1,10 +1,10 @@from dataclasses import dataclass, field-from typing import Optional+from typing import Any, Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-@dataclass+@dataclass(frozen=True)class MailtrapEndpointConfig:name: strpath: str@@ -24,6 +24,12 @@ class MailtrapEndpointConfig:incremental_fields: list[IncrementalField] = field(default_factory=list)# Stable datetime field used for partitioning (creation/send time, never an updated_at).partition_key: Optional[str] = None+ # Static query params sent on every request (page sizes).+ params: dict[str, Any] = field(default_factory=dict)+ # Endpoint requires a `start_date`/`end_date` window (stats endpoints).+ date_range: bool = False+ # Nested object whose keys are lifted onto the row root.+ flatten_field: Optional[str] = None# Mailtrap REST API list endpoints (https://mailtrap.io/api, Api-Token header auth). All paths are@@ -36,6 +42,10 @@ class MailtrapEndpointConfig:# pagination, capped at 1000 rows per request.# Both are declared sort_mode="desc" so the incremental watermark only commits once a sync# completes (suppressions ordering is undocumented; email logs are documented newest-first).+# - contacts and email_campaigns paginate via `token` / `pagination.next_token` but expose no+# timestamp filter: full refresh only.+# - sending_stats_by_date requires a date window and returns one row per day in a single response.+# It stays full refresh because past days' open/click counts keep changing after the send date.# The remaining endpoints return unpaginated arrays with no timestamp filter: full refresh only.MAILTRAP_ENDPOINTS: dict[str, MailtrapEndpointConfig] = {"email_logs": MailtrapEndpointConfig(@@ -77,6 +87,31 @@ MAILTRAP_ENDPOINTS: dict[str, MailtrapEndpointConfig] = {"contact_lists": MailtrapEndpointConfig(name="contact_lists", path="/api/contacts/lists"),"sending_domains": MailtrapEndpointConfig(name="sending_domains", path="/api/domains", data_key="data"),"accounts": MailtrapEndpointConfig(name="accounts", path="/api/accounts"),+ "contacts": MailtrapEndpointConfig(+ name="contacts",+ path="/api/contacts",+ data_key="data",+ cursor_param="token",+ cursor_response_key="pagination.next_token",+ params={"per_page": 50},+ ),+ "email_campaigns": MailtrapEndpointConfig(+ name="email_campaigns",+ path="/api/email_campaigns",+ data_key="data",+ cursor_param="token",+ cursor_response_key="pagination.next_token",+ params={"per_page": 100},+ partition_key="created_at",+ ),+ "sending_stats_by_date": MailtrapEndpointConfig(+ name="sending_stats_by_date",+ path="/api/stats/date",+ primary_keys=["date"],+ date_range=True,+ flatten_field="stats",+ partition_key="date",+ ),}ENDPOINTS = tuple(MAILTRAP_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.pyindex d0c3a274a361..b86c44265301 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/source.py@@ -95,7 +95,7 @@ You can create an API token under **Settings → API Tokens** in [Mailtrap](httpapi_version: str | None = None,) -> list[SourceSchema]:# Only email_logs (filters[sent_after]) and suppressions (start_time) expose a server-side- # timestamp bound; the other endpoints are unpaginated full-refresh lists.+ # timestamp bound; the other endpoints are full refresh only.return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)def validate_credentials(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap.pyindex 6c4b17bf49b4..2ca12ead2be9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailtrap/tests/test_mailtrap.py@@ -2,6 +2,7 @@ import jsonfrom typing import Any, Optionalimport pytest+import time_machinefrom unittest import mockimport requests@@ -13,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res)from products.warehouse_sources.backend.temporal.data_imports.sources.mailtrap.mailtrap import (MAILTRAP_BASE_URL,+ STATS_START_DATE,MailtrapResumeConfig,mailtrap_source,validate_credentials,@@ -152,6 +154,49 @@ class TestPagination:# The saved last-row id seeds the first request so already-synced pages are skipped.assert params[0]["last_id"] == "s99"+ @parameterized.expand(+ [+ ("contacts", "018dd5e3-a", 50),+ ("email_campaigns", 2, 100),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_pagination_token_endpoints_follow_next_token(+ self, endpoint: str, next_token: Any, per_page: int, MockSession+ ) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _response({"data": [{"id": "a"}], "pagination": {"next_token": next_token}}),+ _response({"data": [{"id": "b"}], "pagination": {"next_token": None}}),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source(endpoint, manager))++ assert rows == [{"id": "a"}, {"id": "b"}]+ assert "token" not in params[0]+ assert params[1]["token"] == next_token+ assert all(p["per_page"] == per_page for p in params)+ manager.save_state.assert_called_once_with(MailtrapResumeConfig(cursor=str(next_token)))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sending_stats_by_date_sends_required_window_and_flattens_stats(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [_response([{"date": "2026-01-01", "stats": {"delivery_count": 190, "open_rate": 0.9}}])],+ )++ with time_machine.travel("2026-03-15T12:00:00Z", tick=False):+ rows = _rows(_source("sending_stats_by_date", _make_manager()))++ # start_date and end_date are required: omitting either returns a 400.+ assert params == [{"start_date": STATS_START_DATE, "end_date": "2026-03-15"}]+ assert rows == [{"date": "2026-01-01", "delivery_count": 190, "open_rate": 0.9}]+@parameterized.expand([("email_templates", [{"id": 1}]),@@ -224,7 +269,7 @@ class TestSourceResponseShape:assert response.partition_mode == "datetime"else:assert response.sort_mode == "asc"- assert response.partition_mode is None+ assert response.partition_mode == ("datetime" if config.partition_key else None)class TestValidateCredentials: