: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(warehouse_sources): sync Campaign Monitor journeys and recipients (#101619)
Tom Owers6f09c1a0129e
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 9ebd37d3fe86..c1073f90cc6e 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@@ -1197,14 +1197,14 @@ Note: apidocs.callrail.com serves the entire v3 reference as one ~890 KB HTML pa## CampaignMonitor — gaps-Today (17): `active_subscribers`, `bounced_subscribers`, `campaign_bounces`, `campaign_clicks`, `campaign_opens`, `campaign_spam_complaints`, `campaign_summary`, `campaign_unsubscribes`, `campaigns`, `clients`, `draft_campaigns`, `lists`, `scheduled_campaigns`, `segments`, `suppression_list`, `templates`, `unsubscribed_subscribers`+Today (25): `active_subscribers`, `bounced_subscribers`, `campaign_bounces`, `campaign_clicks`, `campaign_opens`, `campaign_recipients`, `campaign_spam_complaints`, `campaign_summary`, `campaign_unsubscribes`, `campaigns`, `clients`, `draft_campaigns`, `journey_email_bounces`, `journey_email_clicks`, `journey_email_opens`, `journey_email_recipients`, `journey_email_summary`, `journey_email_unsubscribes`, `journeys`, `lists`, `scheduled_campaigns`, `segments`, `suppression_list`, `templates`, `unsubscribed_subscribers`Diffed against: <https://www.campaignmonitor.com/api/v3-3/campaigns/>-- [ ] `Campaign recipients (/campaigns/{id}/recipients)` — who a campaign was sent to; without it the opens/clicks/bounces tables have no denominator (high)-- [ ] `Getting journeys (/clients/{id}/journeys)` — the automation product is entirely unsynced; journeys is the lookup every journey metric hangs off (high)-- [ ] `Journey email recipients / opens / clicks / bounces / unsubscribes (/journeys/email/{id}/...)` — per-email engagement events for automations, mirroring the campaign\_\* tables we already expose (high)-- [ ] `Getting journey summary (/journeys/email/{id}/summary)` — vendor-computed automation performance, the journey equivalent of campaign_summary (high)+- [x] `Campaign recipients (/campaigns/{id}/recipients)` — who a campaign was sent to; without it the opens/clicks/bounces tables have no denominator (high)+- [x] `Getting journeys (/clients/{id}/journeys)` — the automation product is entirely unsynced; journeys is the lookup every journey metric hangs off (high)+- [x] `Journey email recipients / opens / clicks / bounces / unsubscribes (/journeys/email/{id}/...)` — per-email engagement events for automations, mirroring the campaign\_\* tables we already expose (high)+- [x] `Getting journey summary (/journeys/{id})` — vendor-computed automation performance, the journey equivalent of campaign_summary (high). Audited as `/journeys/email/{id}/summary`, which does not exist; the summary is journey-scoped. Synced as `journey_email_summary`, one row per journey email from the summary's nested `Emails` array — which is also the only place the API exposes a journey email id, so every `journeys/email/{id}/...` table fans out through it.- [ ] `List custom fields (/lists/{id}/customfields)` — lookup resolving the custom field keys carried on every subscriber row (high)- [ ] `Campaign lists and segments (/campaigns/{id}/listsandsegments)` — lookup joining campaigns we sync to the lists and segments they targeted (high)- [ ] `Campaign email client usage (/campaigns/{id}/emailclientusage)` — breakdown dimension on opens (client/device), a standard email reporting cut (medium)@@ -1214,7 +1214,7 @@ Diffed against: <https://www.campaignmonitor.com/api/v3-3/campaigns/>- [ ] `Getting a subscriber's history (/subscribers/history)` — per-subscriber event history across campaigns, for lifecycle analysis (medium)- [ ] `Getting tags (/clients/{id}/tags)` — lookup resolving the tags applied to campaigns and clients (low)-Note: Diffed against the v3.3 reference section index (account, campaigns, clients, journeys, lists, segments, subscribers, transactional), each page fetched and its operation headings parsed. Campaign engagement coverage is strong, but the entire Journeys (automation) product and the transactional product are absent, and campaign_recipients — the denominator for every open/click rate — is missing.+Note: Diffed against the v3.3 reference section index (account, campaigns, clients, journeys, lists, segments, subscribers, transactional), each page fetched and its operation headings parsed. Campaign engagement coverage is strong, and the Journeys (automation) product and campaign_recipients are now synced. The transactional product remains absent.## Campayn — adequatediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/campaign_monitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/campaign_monitor.pyindex bd135010aa61..ced2738e72bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/campaign_monitor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/campaign_monitor.py@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (ClientConfig,Endpoint,+ 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_probe@@ -32,6 +33,12 @@ DEFAULT_PAGE_SIZE = 1000 # Campaign Monitor's documented maximum page size.# Subscriber-state endpoints require a `date`; this fetches the full history (the filter is# inclusive from the given date onward). Used until server-side incremental is verified live.FULL_REFRESH_SINCE_DATE = "1900-01-01"+# The journey report endpoints document their `date` as `YYYY-MM-DD HH:MM`, and default it to the+# last 30 days when it is omitted — so it always has to be sent.+JOURNEY_FULL_REFRESH_SINCE_DATE = "1900-01-01 00:00"+# Intermediate resource fanning the journey summary out into one row per journey email. Not a+# synced table: it exists so the journey report endpoints have an `EmailID` to resolve.+JOURNEY_EMAILS_RESOURCE = "journey_emails"@dataclasses.dataclass@@ -66,6 +73,10 @@ def _paginator() -> PageNumberPaginator:def _page_params(config: CampaignMonitorEndpointConfig) -> dict[str, Any]:# The `page` param itself is injected by the paginator.params: dict[str, Any] = {"pagesize": DEFAULT_PAGE_SIZE}+ if config.journey_report:+ params["date"] = JOURNEY_FULL_REFRESH_SINCE_DATE+ params["orderdirection"] = "asc"+ return paramsif config.uses_date_filter:params["date"] = FULL_REFRESH_SINCE_DATEif config.order_field:@@ -132,93 +143,146 @@ def _top_level_resource()-def _inject_parent_id(prefixed_key: str, target_key: str) -> Callable[[dict[str, Any]], dict[str, Any] | list[Any]]:+def _inject_parent_ids(renames: dict[str, str]) -> Callable[[dict[str, Any]], dict[str, Any] | list[Any]]:def _map(row: dict[str, Any]) -> dict[str, Any] | list[Any]:- value = row.pop(prefixed_key, None)+ values = {target: row.pop(prefixed, None) for prefixed, target in renames.items()}if not row:# An empty body (e.g. a summary object with no fields) is not a row — drop it rather- # than emitting a record that carries only the injected parent id.+ # than emitting a record that carries only the injected parent ids.return []- if value is not None:- row[target_key] = value+ for target, value in values.items():+ if value is not None:+ row[target] = valuereturn rowreturn _map-def _fan_out_resource(- api_key: str,- client_id: str,- config: CampaignMonitorEndpointConfig,- team_id: int,- job_id: str,- manager: ResumableSourceManager[CampaignMonitorResumeConfig],-) -> Resource:- """Fan a list-/campaign-scoped endpoint out over every parent via a dependent resource: the- framework fetches the client's lists (or sent campaigns), pages each parent's child endpoint,- and injects the parent id into every row."""- parent_endpoint: Endpoint- if config.fan_out_over_lists:- parent_name = "lists"- parent_path = f"clients/{client_id}/lists.json"- resolve_param, parent_id_field = "list_id", "ListID"- # The subscriber-lists endpoint returns a bare JSON array.- parent_endpoint = {- "path": parent_path,+def _journeys_resource(client_id: str) -> EndpointResource:+ # The client journeys endpoint returns a bare JSON array.+ return {+ "name": "journeys",+ "endpoint": {+ "path": f"clients/{client_id}/journeys.json","paginator": SinglePagePaginator(),"data_selector_required": True,- }- else:- # Only sent campaigns have reports, which is exactly what campaigns.json returns —- # in the standard paged envelope (`{"Results": [...], "NumberOfPages": N, ...}`), not a- # bare array like the draft/scheduled campaign endpoints.- parent_name = "campaigns"- parent_path = f"clients/{client_id}/campaigns.json"- resolve_param, parent_id_field = "campaign_id", "CampaignID"- parent_endpoint = {- "path": parent_path,- "params": {"pagesize": DEFAULT_PAGE_SIZE},- "paginator": _paginator(),- "data_selector": "Results",- }+ },+ }+- child_params: dict[str, Any] = {- resolve_param: {"type": "resolve", "resource": parent_name, "field": parent_id_field},+def _journey_emails_resource(name: str) -> EndpointResource:+ """One row per journey email, read out of the journey summary's nested `Emails` array. Serves+ both as the `journey_email_summary` table and as the parent the journey report endpoints+ resolve their `EmailID` from — the journeys list itself carries no email ids."""+ return {+ "name": name,+ "endpoint": {+ "path": "journeys/{journey_id}.json",+ "params": {"journey_id": {"type": "resolve", "resource": "journeys", "field": "JourneyID"}},+ "paginator": SinglePagePaginator(),+ # A journey with no emails yields a zero-row page rather than failing the sync.+ "data_selector": "Emails",+ },+ "include_from_parent": ["JourneyID"],+ "data_map": _inject_parent_ids({"_journeys_JourneyID": "JourneyID"}),+ }+++def _child_resource(+ config: CampaignMonitorEndpointConfig,+ parent_name: str,+ resolve_param: str,+ resolve_field: str,+ parent_columns: list[str],+) -> EndpointResource:+ params: dict[str, Any] = {+ resolve_param: {"type": "resolve", "resource": parent_name, "field": resolve_field},}- child_endpoint: Endpoint++ endpoint: Endpointif config.paginated:- child_params.update(_page_params(config))- child_endpoint = {+ params.update(_page_params(config))+ endpoint = {"path": config.path,- "params": child_params,+ "params": params,"paginator": _paginator(),"data_selector": "Results",}else:# Single-object endpoints (e.g. campaign summary) return one JSON object per parent,# which the framework wraps as a single row.- child_endpoint = {+ endpoint = {"path": config.path,- "params": child_params,+ "params": params,"paginator": SinglePagePaginator(),}- rest_config: RESTAPIConfig = {- "client": _client_config(api_key),- "resources": [+ return {+ "name": config.name,+ "endpoint": endpoint,+ "include_from_parent": parent_columns,+ # include_from_parent lands each parent column as `_<parent>_<column>`; rename them to the+ # plain columns the composite primary keys expect.+ "data_map": _inject_parent_ids({f"_{parent_name}_{column}": column for column in parent_columns}),+ }+++def _fan_out_resource(+ api_key: str,+ client_id: str,+ config: CampaignMonitorEndpointConfig,+ team_id: int,+ job_id: str,+ manager: ResumableSourceManager[CampaignMonitorResumeConfig],+) -> Resource:+ """Fan a scoped endpoint out over every parent via dependent resources: the framework walks the+ parents, pages each parent's child endpoint, and injects the parent ids into every row. The+ journey report endpoints hang off a two-level chain, because a journey email id is exposed+ nowhere but inside the journey summary."""+ resources: list[str | EndpointResource]+ if config.fan_out_over_journeys:+ # The journey-emails resource IS this endpoint: the summary's `Emails` array is the table.+ resources = [_journeys_resource(client_id), _journey_emails_resource(config.name)]+ elif config.journey_report:+ resources = [+ _journeys_resource(client_id),+ _journey_emails_resource(JOURNEY_EMAILS_RESOURCE),+ _child_resource(config, JOURNEY_EMAILS_RESOURCE, "email_id", "EmailID", ["EmailID", "JourneyID"]),+ ]+ elif config.fan_out_over_lists:+ resources = [{- "name": parent_name,- "endpoint": parent_endpoint,+ "name": "lists",+ "endpoint": {+ # The subscriber-lists endpoint returns a bare JSON array.+ "path": f"clients/{client_id}/lists.json",+ "paginator": SinglePagePaginator(),+ "data_selector_required": True,+ },},+ _child_resource(config, "lists", "list_id", "ListID", ["ListID"]),+ ]+ else:+ resources = [{- "name": config.name,- "endpoint": child_endpoint,- "include_from_parent": [parent_id_field],- # include_from_parent lands the parent id as `_lists_ListID`/`_campaigns_CampaignID`;- # rename it to the plain column the composite primary keys expect.- "data_map": _inject_parent_id(f"_{parent_name}_{parent_id_field}", parent_id_field),+ "name": "campaigns",+ "endpoint": {+ # Only sent campaigns have reports, which is exactly what campaigns.json+ # returns — in the standard paged envelope (`{"Results": [...],+ # "NumberOfPages": N, ...}`), not a bare array like the draft/scheduled+ # campaign endpoints.+ "path": f"clients/{client_id}/campaigns.json",+ "params": {"pagesize": DEFAULT_PAGE_SIZE},+ "paginator": _paginator(),+ "data_selector": "Results",+ },},- ],+ _child_resource(config, "campaigns", "campaign_id", "CampaignID", ["CampaignID"]),+ ]++ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key),+ "resources": resources,}initial_paginator_state: Optional[dict[str, Any]] = None@@ -227,7 +291,8 @@ def _fan_out_resource(# Only framework-shaped fan-out state is resumable. A pre-migration bookmark# (list_id/campaign_id + page) can't be translated into the completed/current path map, so# such a sync restarts fresh — safe, because the merge dedupes re-pulled rows on the- # primary key.+ # primary key. Nothing is ever saved for the two-level journey chain: the framework+ # declines to share one resume hook across several dependent levels.if resume is not None and resume.fanout_state is not None:initial_paginator_state = resume.fanout_state@@ -235,7 +300,7 @@ def _fan_out_resource(if state:manager.save_state(CampaignMonitorResumeConfig(fanout_state=state))- resources = rest_api_resources(+ built = rest_api_resources(rest_config,team_id,job_id,@@ -243,7 +308,7 @@ def _fan_out_resource(resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)- return next(r for r in resources if r.name == config.name)+ return next(r for r in built if r.name == config.name)def campaign_monitor_source(@@ -256,7 +321,7 @@ def campaign_monitor_source() -> SourceResponse:config = CAMPAIGN_MONITOR_ENDPOINTS[endpoint]- if config.fan_out_over_lists or config.fan_out_over_campaigns:+ if config.is_fanned_out:resource = _fan_out_resource(api_key, client_id, config, team_id, job_id, resumable_source_manager)else:resource = _top_level_resource(api_key, client_id, config, team_id, job_id, resumable_source_manager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/canonical_descriptions.pyindex e43b84f93491..cafbde1f7092 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/canonical_descriptions.py@@ -228,4 +228,106 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"Date": "Date and time the spam complaint was recorded.",},},+ "campaign_recipients": {+ "description": "Subscribers a campaign was sent to — one row per recipient per list, the denominator for every open, click, and bounce rate.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-recipients",+ "columns": {+ "CampaignID": "Unique identifier for the campaign the recipient was sent.",+ "EmailAddress": "Email address the campaign was sent to.",+ "ListID": "Identifier of the list the recipient was included from.",+ },+ },+ "journeys": {+ "description": "An automated journey (marketing automation) belonging to the client.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#getting-journeys",+ "columns": {+ "JourneyID": "Unique identifier for the journey.",+ "ListID": "Identifier of the subscriber list the journey is attached to.",+ "Name": "Name of the journey.",+ "Status": "Current status of the journey (for example Active, Paused, or Not started).",+ },+ },+ "journey_email_summary": {+ "description": "Aggregate performance summary for each email in a journey — one row per journey email with vendor-computed send and engagement totals. Also the lookup resolving the EmailID carried on every journey_email_* table.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#getting-journey-summary",+ "columns": {+ "JourneyID": "Unique identifier for the journey the email belongs to.",+ "EmailID": "Unique identifier for the journey email.",+ "Name": "Name of the journey email.",+ "Sent": "Number of times the journey email was sent.",+ "Opened": "Total number of opens recorded, including repeat opens by the same recipient.",+ "UniqueOpened": "Number of unique recipients who opened the journey email.",+ "Clicked": "Number of link clicks recorded for the journey email.",+ "Bounced": "Number of sends that bounced.",+ "Unsubscribed": "Number of recipients who unsubscribed from the journey email.",+ },+ },+ "journey_email_recipients": {+ "description": "Subscribers a journey email was sent to — one row per send, the denominator for that email's engagement rates.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#journey-email-recipients",+ "columns": {+ "JourneyID": "Unique identifier for the journey the email belongs to.",+ "EmailID": "Unique identifier for the journey email that was sent.",+ "EmailAddress": "Email address the journey email was sent to.",+ "SentDate": "Date and time the journey email was sent to the recipient.",+ },+ },+ "journey_email_opens": {+ "description": "Individual open events for a journey email — one row per recorded open, including repeat opens by the same recipient.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#journey-email-opens",+ "columns": {+ "JourneyID": "Unique identifier for the journey the email belongs to.",+ "EmailID": "Unique identifier for the journey email that was opened.",+ "EmailAddress": "Email address of the recipient who opened the journey email.",+ "Date": "Date and time the open was recorded.",+ "IPAddress": "IP address the open was recorded from.",+ "Latitude": "Approximate latitude geocoded from the IP address, when available.",+ "Longitude": "Approximate longitude geocoded from the IP address, when available.",+ "City": "City geocoded from the IP address, when available.",+ "Region": "Region geocoded from the IP address, when available.",+ "CountryCode": "Country code geocoded from the IP address, when available.",+ "CountryName": "Country name geocoded from the IP address, when available.",+ },+ },+ "journey_email_clicks": {+ "description": "Individual link click events for a journey email — one row per recorded click.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#journey-email-clicks",+ "columns": {+ "JourneyID": "Unique identifier for the journey the email belongs to.",+ "EmailID": "Unique identifier for the journey email that was clicked.",+ "EmailAddress": "Email address of the recipient who clicked.",+ "URL": "The link URL that was clicked.",+ "Date": "Date and time the click was recorded.",+ "IPAddress": "IP address the click was recorded from.",+ "Latitude": "Approximate latitude geocoded from the IP address, when available.",+ "Longitude": "Approximate longitude geocoded from the IP address, when available.",+ "City": "City geocoded from the IP address, when available.",+ "Region": "Region geocoded from the IP address, when available.",+ "CountryCode": "Country code geocoded from the IP address, when available.",+ "CountryName": "Country name geocoded from the IP address, when available.",+ },+ },+ "journey_email_bounces": {+ "description": "Sends of a journey email that bounced — one row per recorded bounce.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#journey-email-bounces",+ "columns": {+ "JourneyID": "Unique identifier for the journey the email belongs to.",+ "EmailID": "Unique identifier for the journey email that bounced.",+ "EmailAddress": "Email address of the recipient whose email bounced.",+ "BounceType": "Type of bounce (Hard or Soft).",+ "Date": "Date and time the bounce was recorded.",+ "Reason": "Reason reported for the bounce.",+ },+ },+ "journey_email_unsubscribes": {+ "description": "Recipients who unsubscribed from a journey email — one row per recorded unsubscribe.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#journey-email-unsubscribes",+ "columns": {+ "JourneyID": "Unique identifier for the journey the email belongs to.",+ "EmailID": "Unique identifier for the journey email that was unsubscribed from.",+ "EmailAddress": "Email address of the recipient who unsubscribed.",+ "Date": "Date and time the unsubscribe was recorded.",+ "IPAddress": "IP address the unsubscribe was recorded from.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/settings.pyindex 01c92aac9ab3..8c7ae6d72474 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/settings.py@@ -4,7 +4,7 @@ from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField-@dataclass+@dataclass(frozen=True)class CampaignMonitorEndpointConfig:name: str# Path relative to the API base URL. May contain `{client_id}` (filled from the@@ -21,6 +21,16 @@ class CampaignMonitorEndpointConfig:# Whether this endpoint must be fetched once per sent campaign (fan-out over the# client's campaigns). Each emitted row is annotated with its `CampaignID`.fan_out_over_campaigns: bool = False+ # Whether this endpoint must be fetched once per journey (fan-out over the client's+ # journeys). Each emitted row is annotated with its `JourneyID`.+ fan_out_over_journeys: bool = False+ # Whether this is a journey report endpoint: fetched once per journey email, reached through a+ # two-level fan-out (journeys -> journey summary, the only place an `EmailID` is exposed).+ # Each emitted row is annotated with its `JourneyID` and `EmailID`. These endpoints speak a+ # slightly different param dialect to the campaign reports: `date` carries a time component,+ # and they accept `orderdirection` but no `orderfield` (they always order by their own date+ # column). Their `date` defaults to the last 30 days, so it must always be sent explicitly.+ journey_report: bool = False# Subscriber-state endpoints accept a `date` query param that filters records to those# added/changed at-or-after that date. We pass a very early date to fetch full history.uses_date_filter: bool = False@@ -31,6 +41,12 @@ class CampaignMonitorEndpointConfig:order_field: Optional[str] = Noneincremental_fields: list[IncrementalField] = field(default_factory=list)+ @property+ def is_fanned_out(self) -> bool:+ return (+ self.fan_out_over_lists or self.fan_out_over_campaigns or self.fan_out_over_journeys or self.journey_report+ )+# Campaign Monitor (CreateSend) API v3.3 endpoints.#@@ -38,11 +54,13 @@ class CampaignMonitorEndpointConfig:# account-level `clients` endpoint is included for reference/joins.## Incremental note: the subscriber-state endpoints (`active`/`unsubscribed`/`bounced`) and the-# campaign report endpoints expose a server-side `date` filter that is the canonical incremental-# mechanism for this API. It is documented but could not be verified against a live account here-# (no credentials), so every endpoint currently ships as full refresh. Enabling incremental is a+# campaign and journey report endpoints expose a server-side `date` filter that is the canonical+# incremental mechanism for this API. It is documented but could not be verified against a live+# account here (no credentials), so every endpoint currently ships as full refresh. Enabling incremental is a# matter of populating `incremental_fields`, flipping `supports_incremental`, and mapping the-# user's cursor value into the `date` param in `campaign_monitor.py` once verified live.+# user's cursor value into the `date` param in `campaign_monitor.py` once verified live. That is+# worth prioritizing: the API serves no journey reporting data older than a year, so a full+# refresh drops rows once they age out of that window, where a merge would keep them.CAMPAIGN_MONITOR_ENDPOINTS: dict[str, CampaignMonitorEndpointConfig] = {"clients": CampaignMonitorEndpointConfig(name="clients",@@ -177,6 +195,77 @@ CAMPAIGN_MONITOR_ENDPOINTS: dict[str, CampaignMonitorEndpointConfig] = {partition_key="Date",order_field="date",),+ "campaign_recipients": CampaignMonitorEndpointConfig(+ name="campaign_recipients",+ # The denominator for every campaign engagement rate. Rows carry only an email address and+ # the list it came from, so there is no timestamp to partition on. A campaign can target+ # several lists, so the list is part of the key.+ path="campaigns/{campaign_id}/recipients.json",+ primary_keys=["CampaignID", "ListID", "EmailAddress"],+ paginated=True,+ fan_out_over_campaigns=True,+ # This endpoint's `orderfield` enum is `email|list`, not the `date` the report endpoints+ # take — its rows have no date.+ order_field="email",+ ),+ # Journeys (automations). The journeys list carries no email ids, so every per-email report+ # below hangs off the journey summary, which is the only endpoint that exposes them.+ "journeys": CampaignMonitorEndpointConfig(+ name="journeys",+ path="clients/{client_id}/journeys.json",+ primary_keys=["JourneyID"],+ ),+ "journey_email_summary": CampaignMonitorEndpointConfig(+ name="journey_email_summary",+ # The journey summary object nests its vendor-computed counters under `Emails`; one row per+ # journey email, which is also the lookup resolving the `EmailID` on every table below.+ path="journeys/{journey_id}.json",+ primary_keys=["JourneyID", "EmailID"],+ fan_out_over_journeys=True,+ ),+ # Journey report endpoints. Unlike a campaign, a journey can send the same email to a+ # subscriber more than once (re-entry), so the event timestamp is part of every key.+ "journey_email_recipients": CampaignMonitorEndpointConfig(+ name="journey_email_recipients",+ path="journeys/email/{email_id}/recipients.json",+ primary_keys=["JourneyID", "EmailID", "EmailAddress", "SentDate"],+ paginated=True,+ journey_report=True,+ partition_key="SentDate",+ ),+ "journey_email_opens": CampaignMonitorEndpointConfig(+ name="journey_email_opens",+ path="journeys/email/{email_id}/opens.json",+ primary_keys=["JourneyID", "EmailID", "EmailAddress", "Date"],+ paginated=True,+ journey_report=True,+ partition_key="Date",+ ),+ "journey_email_clicks": CampaignMonitorEndpointConfig(+ name="journey_email_clicks",+ # A recipient can click several links (and the same link several times) per journey email.+ path="journeys/email/{email_id}/clicks.json",+ primary_keys=["JourneyID", "EmailID", "EmailAddress", "URL", "Date"],+ paginated=True,+ journey_report=True,+ partition_key="Date",+ ),+ "journey_email_bounces": CampaignMonitorEndpointConfig(+ name="journey_email_bounces",+ path="journeys/email/{email_id}/bounces.json",+ primary_keys=["JourneyID", "EmailID", "EmailAddress", "Date"],+ paginated=True,+ journey_report=True,+ partition_key="Date",+ ),+ "journey_email_unsubscribes": CampaignMonitorEndpointConfig(+ name="journey_email_unsubscribes",+ path="journeys/email/{email_id}/unsubscribes.json",+ primary_keys=["JourneyID", "EmailID", "EmailAddress", "Date"],+ paginated=True,+ journey_report=True,+ partition_key="Date",+ ),}ENDPOINTS = tuple(CAMPAIGN_MONITOR_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/tests/test_campaign_monitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/tests/test_campaign_monitor.pyindex f6af4fe5215f..961d76ae3a22 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/tests/test_campaign_monitor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campaign_monitor/tests/test_campaign_monitor.py@@ -10,6 +10,7 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.campaign_monitor.campaign_monitor import (FULL_REFRESH_SINCE_DATE,+ JOURNEY_FULL_REFRESH_SINCE_DATE,CampaignMonitorResumeConfig,campaign_monitor_source,validate_credentials,@@ -421,6 +422,181 @@ class TestCampaignFanOut:assert rows == [{"EmailAddress": "[email protected]", "CampaignID": "c2"}]assert snapshots[1][0].endswith("campaigns/c2/opens.json")+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_campaign_recipients_order_by_email_and_carry_their_list(self, MockSession) -> None:+ # Recipient rows have no timestamp, so this endpoint orders by email rather than by the+ # `date` the other campaign reports use — passing `orderfield=date` here is rejected.+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _envelope([{"CampaignID": "c1"}]),+ _envelope([{"EmailAddress": "[email protected]", "ListID": "l1"}]),+ ],+ )++ rows = _rows(_source("campaign_recipients"))++ assert rows == [{"EmailAddress": "[email protected]", "ListID": "l1", "CampaignID": "c1"}]+ assert snapshots[1][0].endswith("campaigns/c1/recipients.json")+ _url, params = snapshots[1]+ assert params["orderfield"] == "email"+ assert params["orderdirection"] == "asc"+ assert "date" not in params+++class TestJourneyFanOut:+ @staticmethod+ def _summary(journey_id: str, email_ids: list[str]) -> Response:+ return _response(+ {+ "JourneyID": journey_id,+ "Name": "Welcome",+ "TriggerType": "On Subscription",+ "Status": "Active",+ "Emails": [{"EmailID": email_id, "Name": "Email one", "Sent": 1} for email_id in email_ids],+ }+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_summary_yields_one_row_per_journey_email(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"JourneyID": "j1"}, {"JourneyID": "j2"}]), # journeys.json (bare array)+ self._summary("j1", ["e1", "e2"]),+ self._summary("j2", ["e3"]),+ ],+ )++ rows = _rows(_source("journey_email_summary"))++ # the nested `Emails` array is the grain, with the parent journey id as a plain column+ assert [(row["JourneyID"], row["EmailID"]) for row in rows] == [("j1", "e1"), ("j1", "e2"), ("j2", "e3")]+ assert snapshots[0][0].endswith("clients/client-abc/journeys.json")+ assert snapshots[1][0].endswith("journeys/j1.json")+ assert snapshots[2][0].endswith("journeys/j2.json")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_journey_without_emails_yields_nothing(self, MockSession) -> None:+ # A journey that has never been built has no emails — that is a zero-row page, not a+ # response-shape failure.+ session = MockSession.return_value+ _wire(session, [_response([{"JourneyID": "j1"}]), self._summary("j1", [])])++ assert _rows(_source("journey_email_summary")) == []++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_report_resolves_email_ids_through_the_journey_summary(self, MockSession) -> None:+ # The journeys list exposes no email ids, so a report endpoint has to walk two levels:+ # journeys -> journey summary -> the report for each of its emails.+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"JourneyID": "j1"}, {"JourneyID": "j2"}]),+ self._summary("j1", ["e1"]),+ _envelope([{"EmailAddress": "[email protected]", "Date": "2026-01-02 03:04:00"}]),+ self._summary("j2", ["e2"]),+ _envelope([{"EmailAddress": "[email protected]", "Date": "2026-01-03 03:04:00"}]),+ ],+ )++ rows = _rows(_source("journey_email_opens"))++ # both parent ids must land as plain columns — they are part of the primary key+ assert [(row["EmailAddress"], row["JourneyID"], row["EmailID"]) for row in rows] == [+ ("[email protected]", "j1", "e1"),+ ("[email protected]", "j2", "e2"),+ ]+ urls = [url for url, _params in snapshots]+ assert urls[1].endswith("journeys/j1.json")+ assert urls[2].endswith("journeys/email/e1/opens.json")+ assert urls[4].endswith("journeys/email/e2/opens.json")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_report_requests_full_history_without_an_order_field(self, MockSession) -> None:+ # Journey reports default `date` to the last 30 days, so it always has to be sent, in the+ # documented `YYYY-MM-DD HH:MM` form. They accept `orderdirection` but no `orderfield`.+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"JourneyID": "j1"}]),+ self._summary("j1", ["e1"]),+ _envelope([{"EmailAddress": "[email protected]"}]),+ ],+ )++ _rows(_source("journey_email_clicks"))++ _url, params = snapshots[2]+ assert params["date"] == JOURNEY_FULL_REFRESH_SINCE_DATE+ assert params["orderdirection"] == "asc"+ assert "orderfield" not in params+ assert params["pagesize"] == 1000++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_report_paginates_within_a_journey_email(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"JourneyID": "j1"}]),+ self._summary("j1", ["e1"]),+ _envelope([{"EmailAddress": "[email protected]"}], number_of_pages=2, page_number=1),+ _envelope([{"EmailAddress": "[email protected]"}], number_of_pages=2, page_number=2),+ ],+ )++ rows = _rows(_source("journey_email_bounces"))++ assert [row["EmailAddress"] for row in rows] == ["[email protected]", "[email protected]"]+ assert snapshots[3][0].endswith("journeys/email/e1/bounces.json")+ assert snapshots[3][1]["page"] == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_report_saves_no_resume_state(self, MockSession) -> None:+ # The framework refuses to share one resume hook across a two-level chain, because state+ # written from both levels would be ambiguous. A restart re-walks the chain instead, and+ # the merge dedupes the re-pulled rows.+ session = MockSession.return_value+ _wire(+ session,+ [+ _response([{"JourneyID": "j1"}]),+ self._summary("j1", ["e1"]),+ _envelope([{"EmailAddress": "[email protected]"}]),+ ],+ )++ manager = _make_manager()+ _rows(_source("journey_email_unsubscribes", manager))++ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_summary_checkpoints_completed_journeys(self, MockSession) -> None:+ # The summary is a single-level fan-out, so it does checkpoint: a crash resumes on j2.+ session = MockSession.return_value+ _wire(+ session,+ [+ _response([{"JourneyID": "j1"}, {"JourneyID": "j2"}]),+ self._summary("j1", ["e1"]),+ self._summary("j2", ["e2"]),+ ],+ )++ manager = _make_manager()+ _rows(_source("journey_email_summary", manager))++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert any(+ state.fanout_state is not None and "journeys/j1.json" in state.fanout_state["completed"] for state in saved+ )+class TestResumeConfigCompatibility:def test_old_saved_state_still_parses(self) -> None: