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): add elasticemail list contacts, stats and verification tables (#115314)

Tom Owers12747d3dac4b
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 4424b884a6f0..6f07aed45b01 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -518,8 +518,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/easypost/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/easypromos.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/elasticemail.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/elevenlabs.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/elevenlabs/settings.py
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.md
index 76a993c36e72..fa40ea9b039b 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
@@ -2834,12 +2834,12 @@ Today (7): `campaigns`, `contacts`, `events`, `lists`, `segments`, `suppressions
Diffed against: <https://api.elasticemail.com/public/v4/swagger>
-- [ ] `/statistics/campaigns (Load Campaigns Stats)` — per-campaign delivery/engagement aggregates (sent, opened, clicked, bounced, unsubscribed) — the headline metric for the campaigns we already sync (high)
-- [ ] `/lists/{listname}/contacts (Load Contacts in List)` — list membership join table linking the contacts and lists we already sync (high)
-- [ ] `/statistics (Load Statistics)` — account-level delivery stats over a date range, the top-level deliverability rollup (high)
+- [x] `/statistics/campaigns (Load Campaigns Stats)` — per-campaign delivery/engagement aggregates (sent, opened, clicked, bounced, unsubscribed) — the headline metric for the campaigns we already sync (high)
+- [x] `/lists/{listname}/contacts (Load Contacts in List)` — list membership join table linking the contacts and lists we already sync (high)
+- [x] `/statistics (Load Statistics)` — account-level delivery stats over a date range, the top-level deliverability rollup (high)
- [ ] `/statistics/channels + /statistics/channels/{name}` — per-channel send stats for attributing volume across sending channels (medium)
- [ ] `/subaccounts` — lookup resolving the sub-account that owns campaigns, events and statistics rows (medium)
-- [ ] `/verifications (Get Emails Verification Results)` — email verification outcomes per address, useful for list hygiene analysis (medium)
+- [x] `/verifications (Get Emails Verification Results)` — email verification outcomes per address, useful for list hygiene analysis (medium)
- [ ] `/events/channels/{name} (Load Channel Events)` — channel-scoped event stream for splitting engagement events by sending channel (low)
- [ ] `/suppressions/bounces, /suppressions/complaints, /suppressions/unsubscribes` — typed suppression sub-lists; only worth adding if the generic /suppressions payload does not carry the suppression type (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/canonical_descriptions.py
index 143ee133b752..be02f68a63ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/canonical_descriptions.py
@@ -88,4 +88,75 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"DateUpdated": "Date the suppression was last changed.",
},
},
+ "list_contacts": {
+ "description": "List membership: one row per contact in each contact list.",
+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Lists",
+ "columns": {
+ "ListName": "Name of the list the contact belongs to.",
+ "Email": "Contact's email address.",
+ "Status": "Subscription status (e.g. Active, Bounced, Unsubscribed, Transactional).",
+ "FirstName": "Contact's first name.",
+ "LastName": "Contact's last name.",
+ "CustomFields": "Key-value map of custom contact fields defined in the account.",
+ "DateAdded": "Date the contact was created, in YYYY-MM-DDThh:mm:ss format.",
+ "DateUpdated": "Date the contact was last changed.",
+ },
+ },
+ "campaign_statistics": {
+ "description": "Delivery and engagement totals for each campaign.",
+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Statistics",
+ "columns": {
+ "ChannelName": "Name of the campaign the totals belong to.",
+ "Recipients": "Number of recipients.",
+ "EmailTotal": "Number of emails.",
+ "SmsTotal": "Number of SMS messages.",
+ "Delivered": "Number of delivered messages.",
+ "Bounced": "Number of bounced messages.",
+ "InProgress": "Number of messages still in progress.",
+ "Opened": "Number of opened messages.",
+ "Clicked": "Number of clicked messages.",
+ "Unsubscribed": "Number of unsubscribed messages.",
+ "Complaints": "Number of complaint messages.",
+ "Inbound": "Number of inbound messages.",
+ "ManualCancel": "Number of manually cancelled messages.",
+ "NotDelivered": "Number of messages flagged with 'Not Delivered'.",
+ },
+ },
+ "statistics": {
+ "description": "Account-level delivery and engagement totals, one row per UTC day.",
+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Statistics",
+ "columns": {
+ "Date": "UTC day the totals cover, in YYYY-MM-DD format.",
+ "Recipients": "Number of recipients.",
+ "EmailTotal": "Number of emails.",
+ "SmsTotal": "Number of SMS messages.",
+ "Delivered": "Number of delivered messages.",
+ "Bounced": "Number of bounced messages.",
+ "InProgress": "Number of messages still in progress.",
+ "Opened": "Number of opened messages.",
+ "Clicked": "Number of clicked messages.",
+ "Unsubscribed": "Number of unsubscribed messages.",
+ "Complaints": "Number of complaint messages.",
+ "Inbound": "Number of inbound messages.",
+ "ManualCancel": "Number of manually cancelled messages.",
+ "NotDelivered": "Number of messages flagged with 'Not Delivered'.",
+ },
+ },
+ "verifications": {
+ "description": "Results of single email address verifications.",
+ "docs_url": "https://elasticemail.com/developers/api-documentation/rest-api#tag/Verifications",
+ "columns": {
+ "Email": "Full email address that was verified.",
+ "Account": "Local part of the email address.",
+ "Domain": "Domain of the email address.",
+ "SuggestedSpelling": "Suggested spelling if a possible mistake was found.",
+ "Disposable": "Whether the address uses a temporary domain.",
+ "Role": "Whether the address is a role address (e.g. info@, noreply@).",
+ "Reason": "All detected issues.",
+ "DateAdded": "Date the verification was added.",
+ "Result": "Verification result (None, Valid, Unknown, Risky, Invalid).",
+ "PredictedScore": "Predicted deliverability score.",
+ "PredictedStatus": "Predicted status (None, Valid, LowRisk, HighRisk, Invalid).",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/elasticemail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/elasticemail.py
index a571ee5dbd18..c78020b36218 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/elasticemail.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/elasticemail.py
@@ -1,24 +1,33 @@
import dataclasses
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
-from urllib.parse import urlencode
+from urllib.parse import quote, urlencode
import requests
+from requests import Request, Response
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 (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
OffsetPaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ ResponseAction,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.elasticemail.settings import (
ELASTICEMAIL_ENDPOINTS,
PAGE_SIZE,
+ STATISTICS_LOOKBACK_DAYS,
ElasticEmailEndpointConfig,
)
@@ -43,11 +52,44 @@ VALIDATION_PATH = "/statistics"
_AUTH_BODY_TOKENS = ("apikey", "api key", "access token", "unauthorized", "expired")
[email protected](frozen=True)
class ElasticEmailResumeConfig:
# Next offset to request. Elastic Email paginates with limit/offset, so the offset alone is enough
# to resume mid-endpoint; the incremental `from` window is re-derived from the stored cursor each run.
offset: int = 0
+ fanout_state: Optional[dict[str, Any]] = None
+ next_day: Optional[str] = None
+
+
+class DailyWindowPaginator(BasePaginator):
+ """Requests one UTC day per page, from `start` through `end` inclusive, via `from`/`to`."""
+
+ def __init__(self, start: date, end: date) -> None:
+ super().__init__()
+ self._day = start
+ self._end = end
+
+ def _apply(self, request: Request) -> None:
+ day = self._day.isoformat()
+ request.params = {**(request.params or {}), "from": f"{day}T00:00:00", "to": f"{day}T23:59:59"}
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ for row in data or []:
+ row["Date"] = self._day.isoformat()
+ self._day += timedelta(days=1)
+ self._has_next_page = self._day <= self._end
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"day": self._day.isoformat()}
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ self._day = date.fromisoformat(state["day"])
def _get_headers(api_key: str) -> dict[str, str]:
@@ -78,6 +120,29 @@ def _clamp_future_value_to_now(value: Any) -> Any:
return value
+def _to_date(value: Any) -> date:
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ return date.fromisoformat(str(value)[:10])
+
+
+def _statistics_start_day(
+ should_use_incremental_field: bool, db_incremental_field_last_value: Any, today: date
+) -> date:
+ if should_use_incremental_field and db_incremental_field_last_value:
+ # Re-fetch the watermark day itself: it was usually still in progress at the last sync, and
+ # rows merge on Date so the refreshed totals replace the partial ones.
+ return min(_to_date(db_incremental_field_last_value), today)
+ return today - timedelta(days=STATISTICS_LOOKBACK_DAYS)
+
+
+def _add_encoded_list_name(row: dict[str, Any]) -> dict[str, Any]:
+ # The fan-out binds the path with str.format, which applies no escaping.
+ return {**row, "EncodedListName": quote(str(row.get("ListName", "")), safe="")}
+
+
def _build_url(path: str, params: dict[str, Any]) -> str:
# doseq=True expands list values (e.g. scopeType=Personal&scopeType=Global) into repeated params.
return f"{ELASTICEMAIL_BASE_URL}{path}?{urlencode(params, doseq=True)}"
@@ -152,6 +217,26 @@ def validate_credentials(
return not _is_auth_error_body(response.status_code, response.text or "")
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": ELASTICEMAIL_BASE_URL,
+ # Elastic Email carries the key in the X-ElasticEmail-ApiKey header; framework auth redacts it.
+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-ElasticEmail-ApiKey", "location": "header"},
+ "headers": {"Accept": "application/json"},
+ # limit/offset pagination over a bare JSON array; a short page (data < limit) ends it, just
+ # like the old `len(items) < PAGE_SIZE` check. No total is reported in body or header.
+ "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None),
+ }
+
+
+def _load_resume_state(
+ resumable_source_manager: ResumableSourceManager[ElasticEmailResumeConfig],
+) -> Optional[ElasticEmailResumeConfig]:
+ if not resumable_source_manager.can_resume():
+ return None
+ return resumable_source_manager.load_state()
+
+
def elasticemail_source(
api_key: str,
endpoint: str,
@@ -162,17 +247,58 @@ def elasticemail_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = ELASTICEMAIL_ENDPOINTS[endpoint]
+ resume = _load_resume_state(resumable_source_manager)
+
+ if config.fanout is not None:
+ fanout_resource = build_dependent_resource(
+ endpoint_configs=ELASTICEMAIL_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(api_key),
+ parent_data_map=_add_encoded_list_name,
+ parent_endpoint_extra={"data_selector_required": True, "response_actions": _auth_response_actions()},
+ child_endpoint_extra={
+ "data_selector_required": True,
+ "response_actions": [{"status_code": 404, "action": "ignore"}, *_auth_response_actions()],
+ },
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=lambda state: _save_fanout_state(resumable_source_manager, state),
+ initial_paginator_state=resume.fanout_state if resume else None,
+ )
+ return _source_response(endpoint, config, fanout_resource)
+
+ if config.daily_window:
+ today = datetime.now(UTC).date()
+ start = _statistics_start_day(should_use_incremental_field, db_incremental_field_last_value, today)
+ statistics_config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": dict(config.extra_params),
+ "paginator": DailyWindowPaginator(start=start, end=today),
+ "response_actions": _auth_response_actions(),
+ },
+ }
+ ],
+ }
+ statistics_resource = rest_api_resource(
+ statistics_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=lambda state: _save_next_day(resumable_source_manager, state),
+ initial_paginator_state={"day": resume.next_day} if resume and resume.next_day else None,
+ )
+ return _source_response(endpoint, config, statistics_resource)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": ELASTICEMAIL_BASE_URL,
- # Elastic Email carries the key in the X-ElasticEmail-ApiKey header; framework auth redacts it.
- "auth": {"type": "api_key", "api_key": api_key, "name": "X-ElasticEmail-ApiKey", "location": "header"},
- "headers": {"Accept": "application/json"},
- # limit/offset pagination over a bare JSON array; a short page (data < limit) ends it, just
- # like the old `len(items) < PAGE_SIZE` check. No total is reported in body or header.
- "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None),
- },
+ "client": _client_config(api_key),
"resources": [
{
"name": endpoint,
@@ -189,12 +315,6 @@ def elasticemail_source(
],
}
- initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume = resumable_source_manager.load_state()
- if resume is not None:
- initial_paginator_state = {"offset": resume.offset}
-
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# OffsetPaginator only reports state while more pages remain, so the final short page saves
# nothing — a crash re-fetches from the last persisted offset rather than skipping rows.
@@ -207,9 +327,26 @@ def elasticemail_source(
job_id,
db_incremental_field_last_value if should_use_incremental_field else None,
resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
+ initial_paginator_state={"offset": resume.offset} if resume is not None else None,
)
+ return _source_response(endpoint, config, resource)
+
+
+def _save_fanout_state(
+ resumable_source_manager: ResumableSourceManager[ElasticEmailResumeConfig], state: Optional[dict[str, Any]]
+) -> None:
+ if state:
+ resumable_source_manager.save_state(ElasticEmailResumeConfig(fanout_state=state))
+
+
+def _save_next_day(
+ resumable_source_manager: ResumableSourceManager[ElasticEmailResumeConfig], state: Optional[dict[str, Any]]
+) -> None:
+ if state and state.get("day"):
+ resumable_source_manager.save_state(ElasticEmailResumeConfig(next_day=str(state["day"])))
+
+def _source_response(endpoint: str, config: ElasticEmailEndpointConfig, resource: Any) -> SourceResponse:
return SourceResponse(
name=endpoint,
items=lambda: resource,
@@ -219,7 +356,7 @@ def elasticemail_source(
partition_mode="datetime" if config.partition_key else None,
partition_format="week" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
- # Events are fetched oldest-first (orderBy=DateAscending); the other endpoints are full refresh
- # where order does not affect correctness.
+ # Events are fetched oldest-first (orderBy=DateAscending) and statistics day by day ascending;
+ # the other endpoints are full refresh where order does not affect correctness.
sort_mode="asc",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/settings.py
index fed2e6009e57..04d407ba155a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/settings.py
@@ -1,14 +1,21 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Elastic Email v4 caps each request at 1000 items and most list endpoints accept limit/offset.
# Use the max page size so we make as few round-trips as possible.
PAGE_SIZE = 1000
+# `/statistics` returns one rollup for a `from`/`to` range, so we request one day at a time. A full
+# refresh (or the first incremental sync) backfills this many days, one request per day.
+STATISTICS_LOOKBACK_DAYS = 365
-@dataclass
+
+@dataclass(frozen=True)
class ElasticEmailEndpointConfig:
name: str
path: str
@@ -26,6 +33,12 @@ class ElasticEmailEndpointConfig:
# events force ascending order so the watermark advances correctly).
extra_params: dict[str, list[str] | str] = field(default_factory=dict)
should_sync_default: bool = True
+ fanout: Optional[DependentEndpointConfig] = None
+ # `/statistics` is a single aggregate per date range; it's fetched one UTC day per request and each
+ # row is stamped with that day.
+ daily_window: bool = False
+ page_size: int = PAGE_SIZE
+ default_incremental_field: Optional[str] = None
def _datetime_incremental_field(name: str) -> IncrementalField:
@@ -86,6 +99,47 @@ ELASTICEMAIL_ENDPOINTS: dict[str, ElasticEmailEndpointConfig] = {
path="/suppressions",
primary_keys=["Email"],
),
+ "list_contacts": ElasticEmailEndpointConfig(
+ name="list_contacts",
+ path="/lists/{listname}/contacts",
+ # A contact can belong to many lists, so the membership row is keyed by list + email.
+ primary_keys=["ListName", "Email"],
+ partition_key="DateAdded",
+ fanout=DependentEndpointConfig(
+ parent_name="lists",
+ resolve_param="listname",
+ # List names can contain spaces and slashes; the parent data map adds a percent-encoded copy.
+ resolve_field="EncodedListName",
+ include_from_parent=["ListName"],
+ parent_field_renames={"ListName": "ListName"},
+ ),
+ ),
+ "campaign_statistics": ElasticEmailEndpointConfig(
+ name="campaign_statistics",
+ path="/statistics/campaigns",
+ primary_keys=["ChannelName"],
+ ),
+ "statistics": ElasticEmailEndpointConfig(
+ name="statistics",
+ path="/statistics",
+ primary_keys=["Date"],
+ daily_window=True,
+ incremental_fields=[
+ {
+ "label": "Date",
+ "type": IncrementalFieldType.Date,
+ "field": "Date",
+ "field_type": IncrementalFieldType.Date,
+ }
+ ],
+ default_incremental_field="Date",
+ ),
+ "verifications": ElasticEmailEndpointConfig(
+ name="verifications",
+ path="/verifications",
+ primary_keys=["Email"],
+ partition_key="DateAdded",
+ ),
}
ENDPOINTS = tuple(ELASTICEMAIL_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/source.py
index 63eb43e4fe28..801b9f18c89b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/source.py
@@ -98,9 +98,10 @@ Grant the key read access to the data you want to sync (Contacts, Campaigns, Tem
has_incremental_field = bool(INCREMENTAL_FIELDS.get(endpoint))
return SourceSchema(
name=endpoint,
- # Events are immutable, so they sync append-only via the server-side `from` filter. No
- # other list endpoint exposes a server-side timestamp filter, so they are full refresh only.
- supports_incremental=False,
+ # Events are immutable, so they sync append-only via the server-side `from` filter. Daily
+ # statistics merge on Date via the `from`/`to` range. No other list endpoint exposes a
+ # server-side timestamp filter, so they are full refresh only.
+ supports_incremental=has_incremental_field and not endpoint_config.append_only,
supports_append=has_incremental_field and endpoint_config.append_only,
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
should_sync_default=endpoint_config.should_sync_default,
@@ -123,6 +124,9 @@ Grant the key read access to the data you want to sync (Contacts, Campaigns, Tem
# that endpoint's path so we surface a per-endpoint permission problem early.
if schema_name is not None and schema_name in ELASTICEMAIL_ENDPOINTS:
endpoint_config = ELASTICEMAIL_ENDPOINTS[schema_name]
+ # A fan-out child's path has a placeholder, so probe the parent listing it reads first.
+ if endpoint_config.fanout is not None:
+ endpoint_config = ELASTICEMAIL_ENDPOINTS[endpoint_config.fanout.parent_name]
valid = validate_elasticemail_credentials(
config.api_key, endpoint_config.path, endpoint_config.extra_params
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py
index 18c35f8b5ff4..92b45a844ae5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail.py
@@ -163,6 +163,102 @@ class TestPagination:
assert [r["Email"] for r in rows] == ["[email protected]"]
+class TestListContactsFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_per_list_with_encoded_names(self, MockSession: Any) -> None:
+ session = MockSession.return_value
+ session.headers = {}
+ requests_seen: list[tuple[str, dict[str, Any]]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ requests_seen.append((request.url, dict(request.params or {})))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [
+ _make_response(200, json_body=[{"ListName": "News / EU"}, {"ListName": "Gone"}, {"ListName": "VIP"}]),
+ _make_response(200, json_body=[{"Email": "[email protected]"}, {"Email": "[email protected]"}]),
+ _make_response(404, text='{"Error":"List not found"}'),
+ _make_response(200, json_body=[{"Email": "[email protected]"}]),
+ ]
+
+ rows = _rows(_source("list_contacts", _make_manager()))
+
+ assert [(r["ListName"], r["Email"]) for r in rows] == [
+ ("News / EU", "[email protected]"),
+ ("News / EU", "[email protected]"),
+ ("VIP", "[email protected]"),
+ ]
+ assert [url for url, _ in requests_seen] == [
+ "https://api.elasticemail.com/v4/lists",
+ "https://api.elasticemail.com/v4/lists/News%20%2F%20EU/contacts",
+ "https://api.elasticemail.com/v4/lists/Gone/contacts",
+ "https://api.elasticemail.com/v4/lists/VIP/contacts",
+ ]
+ assert all(params["limit"] == elasticemail.PAGE_SIZE for _, params in requests_seen)
+
+
+class TestDailyStatistics:
+ @parameterized.expand(
+ [
+ (
+ "incremental_refetches_watermark_day",
+ True,
+ date(2026, 6, 13),
+ None,
+ ["2026-06-13", "2026-06-14", "2026-06-15"],
+ ),
+ (
+ "resume_skips_finished_days",
+ True,
+ date(2026, 6, 10),
+ ElasticEmailResumeConfig(next_day="2026-06-14"),
+ ["2026-06-14", "2026-06-15"],
+ ),
+ ("future_watermark_clamps_to_today", True, date(2026, 7, 1), None, ["2026-06-15"]),
+ ]
+ )
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_one_day_per_request(
+ self,
+ _name: str,
+ incremental: bool,
+ watermark: date,
+ resume: ElasticEmailResumeConfig | None,
+ expected_days: list[str],
+ MockSession: Any,
+ ) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_make_response(200, json_body={"Delivered": i}) for i in range(len(expected_days))])
+
+ rows = _rows(
+ _source(
+ "statistics",
+ _make_manager(resume),
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=watermark,
+ )
+ )
+
+ assert [(r["Date"], r["Delivered"]) for r in rows] == [(day, i) for i, day in enumerate(expected_days)]
+ assert [(p["from"], p["to"]) for p in params] == [(f"{d}T00:00:00", f"{d}T23:59:59") for d in expected_days]
+ assert all("limit" not in p and "offset" not in p for p in params)
+
+ @time_machine.travel("2026-06-15T12:00:00Z", tick=False)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_backfills_lookback_window(self, MockSession: Any) -> None:
+ session = MockSession.return_value
+ days = elasticemail.STATISTICS_LOOKBACK_DAYS + 1
+ params = _wire(session, [_make_response(200, json_body={"Delivered": 0}) for _ in range(days)])
+
+ rows = _rows(_source("statistics", _make_manager()))
+
+ assert len(rows) == days
+ assert params[0]["from"] == "2025-06-15T00:00:00"
+ assert params[-1]["from"] == "2026-06-15T00:00:00"
+
+
def _wire_repeating(session: mock.MagicMock, response: requests.Response) -> None:
"""Return the same response for every send — a retryable status is re-issued until attempts run out."""
session.headers = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail_source.py
index 0da59c6c8ece..5aa1ef620f91 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticemail/tests/test_elasticemail_source.py
@@ -1,7 +1,7 @@
from types import SimpleNamespace
from typing import Any
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -14,7 +14,19 @@ class TestGetSchemas:
schemas = ElasticemailSource().get_schemas(MagicMock(), team_id=1, names=["contacts", "events"])
assert {s.name for s in schemas} == {"contacts", "events"}
- @parameterized.expand([("contacts",), ("lists",), ("segments",), ("campaigns",), ("templates",), ("suppressions",)])
+ @parameterized.expand(
+ [
+ ("contacts",),
+ ("lists",),
+ ("segments",),
+ ("campaigns",),
+ ("templates",),
+ ("suppressions",),
+ ("list_contacts",),
+ ("campaign_statistics",),
+ ("verifications",),
+ ]
+ )
def test_non_event_endpoints_are_full_refresh(self, endpoint: str) -> None:
schemas = {s.name: s for s in ElasticemailSource().get_schemas(MagicMock(), team_id=1)}
schema = schemas[endpoint]
@@ -22,6 +34,12 @@ class TestGetSchemas:
assert schema.supports_append is False
assert schema.incremental_fields == []
+ @parameterized.expand([("statistics", True, False), ("events", False, True)])
+ def test_time_filtered_endpoints(self, endpoint: str, incremental: bool, append: bool) -> None:
+ schema = {s.name: s for s in ElasticemailSource().get_schemas(MagicMock(), team_id=1)}[endpoint]
+ assert schema.supports_incremental is incremental
+ assert schema.supports_append is append
+
class TestValidateCredentials:
def test_failure(self, monkeypatch: Any) -> None:
@@ -30,7 +48,15 @@ class TestValidateCredentials:
assert valid is False
assert error == "Invalid Elastic Email API key"
- def test_per_schema_probe_uses_endpoint_path(self, monkeypatch: Any) -> None:
+ @parameterized.expand(
+ [
+ ("templates", "/templates", {"scopeType": ["Personal", "Global"]}),
+ ("list_contacts", "/lists", {}),
+ ]
+ )
+ def test_per_schema_probe_uses_endpoint_path(
+ self, schema_name: str, expected_path: str, expected_params: dict[str, Any]
+ ) -> None:
captured: dict[str, Any] = {}
def fake_validate(api_key: str, path: str = "/statistics", extra_params: Any = None) -> bool:
@@ -38,10 +64,14 @@ class TestValidateCredentials:
captured["extra_params"] = extra_params
return True
- monkeypatch.setattr(source_module, "validate_elasticemail_credentials", fake_validate)
- ElasticemailSource().validate_credentials(SimpleNamespace(api_key="key"), team_id=1, schema_name="templates") # type: ignore[arg-type]
- assert captured["path"] == "/templates"
- assert captured["extra_params"] == {"scopeType": ["Personal", "Global"]}
+ with patch.object(source_module, "validate_elasticemail_credentials", fake_validate):
+ ElasticemailSource().validate_credentials(
+ SimpleNamespace(api_key="key"), # type: ignore[arg-type]
+ team_id=1,
+ schema_name=schema_name,
+ )
+ assert captured["path"] == expected_path
+ assert captured["extra_params"] == expected_params
class TestNonRetryableErrors: