: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 campaign monitor campaign report tables (#68235)
estefania9d76f790c055
diff --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 ee0000bc2526..0e4dcc655a58 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@@ -1,5 +1,6 @@+import functoolsimport dataclasses-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom typing import Anyfrom urllib.parse import urlencode@@ -35,6 +36,9 @@ class CampaignMonitorResumeConfig:# index) so reordered/added/removed lists between a crash and the retry can't resume us into# the wrong list and write rows under the wrong primary key. None for non-fan-out endpoints.list_id: str | None = None+ # The fan-out campaign currently being processed (campaign report endpoints). Same stable-ID+ # bookmark rationale as `list_id`. None for endpoints that don't fan out over campaigns.+ campaign_id: str | None = None# Next page to fetch (1-based). Always 1 for non-paginated array endpoints.page: int = 1@@ -94,6 +98,16 @@ def _list_ids_for_client(return [item["ListID"] for item in data if isinstance(item, dict) and "ListID" in item]+def _campaign_ids_for_client(+ session: requests.Session, api_key: str, client_id: str, logger: FilteringBoundLogger+) -> list[str]:+ # Only sent campaigns have reports, which is exactly what this endpoint returns.+ data = _fetch_json(session, api_key, _build_url(f"clients/{client_id}/campaigns.json"), logger)+ if not isinstance(data, list):+ return []+ return [item["CampaignID"] for item in data if isinstance(item, dict) and "CampaignID" in item]++def _page_params(config: CampaignMonitorEndpointConfig, page: int) -> dict[str, Any]:params: dict[str, Any] = {"page": page, "pagesize": DEFAULT_PAGE_SIZE}if config.uses_date_filter:@@ -112,7 +126,7 @@ def _iter_paginated(logger: FilteringBoundLogger,extra_row_fields: dict[str, Any],resumable_source_manager: ResumableSourceManager[CampaignMonitorResumeConfig],- resume_list_id: str | None,+ make_resume: Callable[[int], CampaignMonitorResumeConfig],start_page: int,) -> Iterator[list[dict[str, Any]]]:page = start_page@@ -127,57 +141,107 @@ def _iter_paginated(# Save AFTER yielding (and only when more pages remain) so a crash re-yields the last# page rather than skipping it — the pipeline's merge dedupes on the primary key.if not is_last_page:- resumable_source_manager.save_state(CampaignMonitorResumeConfig(list_id=resume_list_id, page=page + 1))+ resumable_source_manager.save_state(make_resume(page + 1))if is_last_page:breakpage += 1-def get_rows(+def _iter_fan_out(+ session: requests.Session,api_key: str,- client_id: str,- endpoint: str,+ config: CampaignMonitorEndpointConfig,+ parent_ids: list[str],+ path_param: str,+ row_id_field: str,+ make_resume: Callable[[str | None, int], CampaignMonitorResumeConfig],+ resume_parent_id: str | None,+ resume_page: int,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[CampaignMonitorResumeConfig],) -> Iterator[list[dict[str, Any]]]:- config = CAMPAIGN_MONITOR_ENDPOINTS[endpoint]- session = make_tracked_session(redact_values=(api_key,))-- resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None-- if config.fan_out_over_lists:- list_ids = _list_ids_for_client(session, api_key, client_id, logger)-- # Resolve the saved list-ID bookmark to a position. If the list no longer exists (deleted- # between runs), fall back to restarting from the first list — merge dedupes the re-pulled- # rows on the primary key.- start_index = 0- start_page = 1- if resume and resume.list_id is not None and resume.list_id in list_ids:- start_index = list_ids.index(resume.list_id)- start_page = resume.page-- for parent_index in range(start_index, len(list_ids)):- list_id = list_ids[parent_index]- # Only the list we resumed into keeps its saved page; later lists start at page 1.+ # Resolve the saved parent-ID bookmark to a position. If the parent no longer exists (deleted+ # between runs), fall back to restarting from the first parent — merge dedupes the re-pulled+ # rows on the primary key.+ start_index = 0+ start_page = 1+ if resume_parent_id is not None and resume_parent_id in parent_ids:+ start_index = parent_ids.index(resume_parent_id)+ start_page = resume_page++ for parent_index in range(start_index, len(parent_ids)):+ parent_id = parent_ids[parent_index]+ path = config.path.format(**{path_param: parent_id})+ extra_row_fields = {row_id_field: parent_id}++ if config.paginated:+ # Only the parent we resumed into keeps its saved page; later parents start at page 1.page = start_page if parent_index == start_index else 1yield from _iter_paginated(session,api_key,config,- config.path.format(list_id=list_id),+ path,logger,- {"ListID": list_id},+ extra_row_fields,resumable_source_manager,- list_id,+ functools.partial(make_resume, parent_id),page,)- # Advance the bookmark to the next list so a crash between lists resumes correctly.- if parent_index + 1 < len(list_ids):- resumable_source_manager.save_state(- CampaignMonitorResumeConfig(list_id=list_ids[parent_index + 1], page=1)- )+ else:+ # Single-object endpoints (e.g. campaign summary) return one JSON object per parent.+ data = _fetch_json(session, api_key, _build_url(path), logger)+ if isinstance(data, dict) and data:+ yield [{**data, **extra_row_fields}]++ # Advance the bookmark to the next parent so a crash between parents resumes correctly.+ if parent_index + 1 < len(parent_ids):+ resumable_source_manager.save_state(make_resume(parent_ids[parent_index + 1], 1))+++def get_rows(+ api_key: str,+ client_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CampaignMonitorResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = CAMPAIGN_MONITOR_ENDPOINTS[endpoint]+ session = make_tracked_session(redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.fan_out_over_lists:+ yield from _iter_fan_out(+ session,+ api_key,+ config,+ _list_ids_for_client(session, api_key, client_id, logger),+ "list_id",+ "ListID",+ lambda parent_id, page: CampaignMonitorResumeConfig(list_id=parent_id, page=page),+ resume.list_id if resume else None,+ resume.page if resume else 1,+ logger,+ resumable_source_manager,+ )+ return++ if config.fan_out_over_campaigns:+ yield from _iter_fan_out(+ session,+ api_key,+ config,+ _campaign_ids_for_client(session, api_key, client_id, logger),+ "campaign_id",+ "CampaignID",+ lambda parent_id, page: CampaignMonitorResumeConfig(campaign_id=parent_id, page=page),+ resume.campaign_id if resume else None,+ resume.page if resume else 1,+ logger,+ resumable_source_manager,+ )returnpath = config.path.format(client_id=client_id)@@ -185,7 +249,15 @@ def get_rows(if config.paginated:start_page = resume.page if resume else 1yield from _iter_paginated(- session, api_key, config, path, logger, {}, resumable_source_manager, None, start_page+ session,+ api_key,+ config,+ path,+ logger,+ {},+ resumable_source_manager,+ lambda next_page: CampaignMonitorResumeConfig(page=next_page),+ start_page,)returndiff --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 0abff83864e5..e43b84f93491 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@@ -139,4 +139,93 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"CustomFields": "Custom field values stored against the subscriber.",},},+ "campaign_summary": {+ "description": "Aggregate performance summary for a sent campaign — one row per campaign with recipient, open, click, unsubscribe, bounce, and spam complaint totals.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-summary-2",+ "columns": {+ "CampaignID": "Unique identifier for the campaign the summary belongs to.",+ "Name": "Internal name of the campaign.",+ "Recipients": "Total number of recipients the campaign was sent to.",+ "TotalOpened": "Total number of opens recorded, including repeat opens by the same recipient.",+ "UniqueOpened": "Number of unique recipients who opened the campaign.",+ "Clicks": "Total number of link clicks recorded for the campaign.",+ "Unsubscribed": "Number of recipients who unsubscribed from the campaign.",+ "Bounced": "Number of recipients whose email bounced.",+ "SpamComplaints": "Number of recipients who marked the campaign as spam.",+ "Forwards": "Number of times the campaign was forwarded using the forward-to-a-friend feature.",+ "Likes": "Number of Facebook likes recorded for the campaign.",+ "Mentions": "Number of Twitter mentions recorded for the campaign.",+ "WebVersionURL": "Public web (browser) version URL of the campaign.",+ "WebVersionTextURL": "Public web version URL of the plain-text campaign.",+ "WorldviewURL": "URL of the campaign's public Worldview page.",+ },+ },+ "campaign_opens": {+ "description": "Individual open events for a sent campaign — one row per recorded open, including repeat opens by the same recipient.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-opens",+ "columns": {+ "CampaignID": "Unique identifier for the campaign the open belongs to.",+ "EmailAddress": "Email address of the recipient who opened the campaign.",+ "ListID": "Identifier of the list the recipient belongs to.",+ "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.",+ },+ },+ "campaign_clicks": {+ "description": "Individual link click events for a sent campaign — one row per recorded click.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-clicks",+ "columns": {+ "CampaignID": "Unique identifier for the campaign the click belongs to.",+ "EmailAddress": "Email address of the recipient who clicked.",+ "ListID": "Identifier of the list the recipient belongs to.",+ "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.",+ },+ },+ "campaign_unsubscribes": {+ "description": "Recipients who unsubscribed as a result of a sent campaign — one row per recipient per campaign.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-unsubscribes",+ "columns": {+ "CampaignID": "Unique identifier for the campaign the unsubscribe belongs to.",+ "EmailAddress": "Email address of the recipient who unsubscribed.",+ "ListID": "Identifier of the list the recipient unsubscribed from.",+ "Date": "Date and time the unsubscribe was recorded.",+ "IPAddress": "IP address the unsubscribe was recorded from.",+ },+ },+ "campaign_bounces": {+ "description": "Recipients whose email bounced for a sent campaign — one row per recipient per campaign.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-bounces",+ "columns": {+ "CampaignID": "Unique identifier for the campaign the bounce belongs to.",+ "EmailAddress": "Email address of the recipient whose email bounced.",+ "ListID": "Identifier of the list the recipient belongs to.",+ "BounceType": "Type of bounce (Hard or Soft).",+ "Date": "Date and time the bounce was recorded.",+ "Reason": "Reason reported for the bounce.",+ },+ },+ "campaign_spam_complaints": {+ "description": "Recipients who marked a sent campaign as spam — one row per recipient per campaign.",+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-spam-complaints",+ "columns": {+ "CampaignID": "Unique identifier for the campaign the complaint belongs to.",+ "EmailAddress": "Email address of the recipient who marked the campaign as spam.",+ "ListID": "Identifier of the list the recipient belongs to.",+ "Date": "Date and time the spam complaint was recorded.",+ },+ },}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 ba1c84e3404e..d0e08e18d77a 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@@ -8,7 +8,8 @@ from products.warehouse_sources.backend.types import IncrementalFieldclass CampaignMonitorEndpointConfig:name: str# Path relative to the API base URL. May contain `{client_id}` (filled from the- # source config) or `{list_id}` (filled per-parent when fanning out over lists).+ # source config), `{list_id}` (filled per-parent when fanning out over lists), or+ # `{campaign_id}` (filled per-parent when fanning out over sent campaigns).path: strprimary_keys: list[str]# Whether the endpoint returns a paged envelope (`{"Results": [...], "NumberOfPages": N, ...}`)@@ -17,6 +18,9 @@ class CampaignMonitorEndpointConfig:# Whether this endpoint must be fetched once per subscriber list (fan-out over the# client's lists). Each emitted row is annotated with its `ListID`.fan_out_over_lists: bool = False+ # 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# 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@@ -114,6 +118,63 @@ CAMPAIGN_MONITOR_ENDPOINTS: dict[str, CampaignMonitorEndpointConfig] = {partition_key="Date",order_field="date",),+ # Campaign report endpoints — one request (or paginated walk) per sent campaign. The+ # summary endpoint returns a single JSON object per campaign; the detail endpoints use the+ # standard paged envelope. Their optional `date` filter is omitted so an unfiltered request+ # returns full history.+ "campaign_summary": CampaignMonitorEndpointConfig(+ name="campaign_summary",+ path="campaigns/{campaign_id}/summary.json",+ primary_keys=["CampaignID"],+ fan_out_over_campaigns=True,+ ),+ "campaign_opens": CampaignMonitorEndpointConfig(+ name="campaign_opens",+ # A recipient can open a campaign multiple times, so the open timestamp is part of the key.+ path="campaigns/{campaign_id}/opens.json",+ primary_keys=["CampaignID", "EmailAddress", "Date"],+ paginated=True,+ fan_out_over_campaigns=True,+ partition_key="Date",+ order_field="date",+ ),+ "campaign_clicks": CampaignMonitorEndpointConfig(+ name="campaign_clicks",+ # A recipient can click several links (and the same link several times) per campaign.+ path="campaigns/{campaign_id}/clicks.json",+ primary_keys=["CampaignID", "EmailAddress", "URL", "Date"],+ paginated=True,+ fan_out_over_campaigns=True,+ partition_key="Date",+ order_field="date",+ ),+ "campaign_unsubscribes": CampaignMonitorEndpointConfig(+ name="campaign_unsubscribes",+ path="campaigns/{campaign_id}/unsubscribes.json",+ primary_keys=["CampaignID", "EmailAddress"],+ paginated=True,+ fan_out_over_campaigns=True,+ partition_key="Date",+ order_field="date",+ ),+ "campaign_bounces": CampaignMonitorEndpointConfig(+ name="campaign_bounces",+ path="campaigns/{campaign_id}/bounces.json",+ primary_keys=["CampaignID", "EmailAddress"],+ paginated=True,+ fan_out_over_campaigns=True,+ partition_key="Date",+ order_field="date",+ ),+ "campaign_spam_complaints": CampaignMonitorEndpointConfig(+ name="campaign_spam_complaints",+ path="campaigns/{campaign_id}/spam.json",+ primary_keys=["CampaignID", "EmailAddress"],+ paginated=True,+ fan_out_over_campaigns=True,+ partition_key="Date",+ order_field="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 5c9c378d6894..dc3ff1cc328d 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@@ -214,6 +214,54 @@ class TestGetRowsFanOut:assert "page=1" in session.urls[1]+class TestGetRowsCampaignFanOut:+ def test_fan_out_over_campaigns_injects_campaign_id(self) -> None:+ manager = _manager()+ responses = [+ _make_response([{"CampaignID": "c1"}, {"CampaignID": "c2"}]), # campaigns.json+ _make_response({"Results": [{"EmailAddress": "[email protected]"}], "NumberOfPages": 1, "PageNumber": 1}), # c1+ _make_response({"Results": [{"EmailAddress": "[email protected]"}], "NumberOfPages": 1, "PageNumber": 1}), # c2+ ]+ session, batches = _drive("campaign_opens", responses, manager)++ assert batches == [+ [{"EmailAddress": "[email protected]", "CampaignID": "c1"}],+ [{"EmailAddress": "[email protected]", "CampaignID": "c2"}],+ ]+ assert session.urls[0].endswith("clients/client-abc/campaigns.json")+ assert "campaigns/c1/opens.json" in session.urls[1]+ assert "campaigns/c2/opens.json" in session.urls[2]++ def test_campaign_summary_yields_object_per_campaign_and_advances_bookmark(self) -> None:+ manager = _manager()+ responses = [+ _make_response([{"CampaignID": "c1"}, {"CampaignID": "c2"}]),+ _make_response({"Name": "Newsletter", "Recipients": 100, "UniqueOpened": 40}), # c1 summary+ _make_response({"Name": "Promo", "Recipients": 50, "UniqueOpened": 10}), # c2 summary+ ]+ session, batches = _drive("campaign_summary", responses, manager)++ assert batches == [+ [{"Name": "Newsletter", "Recipients": 100, "UniqueOpened": 40, "CampaignID": "c1"}],+ [{"Name": "Promo", "Recipients": 50, "UniqueOpened": 10, "CampaignID": "c2"}],+ ]+ assert "campaigns/c1/summary.json" in session.urls[1]+ assert "campaigns/c2/summary.json" in session.urls[2]+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [CampaignMonitorResumeConfig(campaign_id="c2", page=1)]++ def test_fan_out_resumes_into_correct_campaign(self) -> None:+ manager = _manager(can_resume=True, state=CampaignMonitorResumeConfig(campaign_id="c2", page=1))+ responses = [+ _make_response([{"CampaignID": "c1"}, {"CampaignID": "c2"}]),+ _make_response({"Results": [{"EmailAddress": "[email protected]"}], "NumberOfPages": 1, "PageNumber": 1}), # c2 only+ ]+ session, batches = _drive("campaign_opens", responses, manager)++ assert batches == [[{"EmailAddress": "[email protected]", "CampaignID": "c2"}]]+ assert "campaigns/c2/opens.json" in session.urls[1]++class TestCampaignMonitorSourceResponse:@pytest.mark.parametrize("endpoint", list(CAMPAIGN_MONITOR_ENDPOINTS.keys()))def test_source_response_primary_keys_match_settings(self, endpoint: str) -> None:@@ -236,6 +284,8 @@ class TestCampaignMonitorSourceResponse:("campaigns", "SentDate"),("suppression_list", "Date"),("active_subscribers", "Date"),+ ("campaign_opens", "Date"),+ ("campaign_summary", None),("clients", None),("lists", None),],