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(campaign_monitor): sync the list and campaign lookup tables (#102224)

Tom Owers4bcafa5457b1
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 55a1b39f8765..c31b4e1fb9ae 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,7 +1197,7 @@ Note: apidocs.callrail.com serves the entire v3 reference as one ~890 KB HTML pa
## CampaignMonitor — gaps
-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`
+Today (30): `active_subscribers`, `bounced_subscribers`, `campaign_bounces`, `campaign_clicks`, `campaign_email_client_usage`, `campaign_lists`, `campaign_opens`, `campaign_recipients`, `campaign_segments`, `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`, `list_custom_fields`, `list_stats`, `lists`, `scheduled_campaigns`, `segments`, `suppression_list`, `templates`, `unsubscribed_subscribers`
Diffed against: <https://www.campaignmonitor.com/api/v3-3/campaigns/>
@@ -1205,16 +1205,16 @@ Diffed against: <https://www.campaignmonitor.com/api/v3-3/campaigns/>
- [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)
-- [ ] `List stats (/lists/{id}/stats)` — per-list growth, unsubscribe, and bounce totals over time (medium)
+- [x] `List custom fields (/lists/{id}/customfields)` — lookup resolving the custom field keys carried on every subscriber row (high)
+- [x] `Campaign lists and segments (/campaigns/{id}/listsandsegments)` — lookup joining campaigns we sync to the lists and segments they targeted (high). The one body carries two independent collections, so it feeds two join tables — `campaign_lists` and `campaign_segments` — rather than one row of nested arrays.
+- [x] `Campaign email client usage (/campaigns/{id}/emailclientusage)` — breakdown dimension on opens (client/device), a standard email reporting cut (medium)
+- [x] `List stats (/lists/{id}/stats)` — per-list growth, unsubscribe, and bounce totals (medium). Audited as totals "over time"; the endpoint serves no history, only a snapshot of the counters at request time (totals plus today/yesterday/week/month/year buckets), so each sync replaces the previous snapshot.
- [ ] `Transactional statistics and Message timeline (/transactional/statistics, /transactional/messages)` — message-level transactional sends and their engagement — a whole product currently invisible (medium)
- [ ] `Unconfirmed and deleted subscribers (/lists/{id}/unconfirmed, /lists/{id}/deleted)` — completes the subscriber state coverage alongside active/bounced/unsubscribed that we already sync (medium)
- [ ] `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, and the Journeys (automation) product and campaign_recipients are now synced. The transactional product remains absent.
+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. None of the four lookup endpoints above accepts a `date` filter, so all five tables ship full refresh like the rest of the source. The transactional product remains absent.
## Campayn — adequate
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.py
index ced2738e72bf..2d7f8cf5a47c 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
@@ -208,6 +208,24 @@ def _child_resource(
"paginator": _paginator(),
"data_selector": "Results",
}
+ elif config.data_selector:
+ # One collection out of a multi-collection body. Stays tolerant of a missing key: a
+ # campaign that targeted no segments is a zero-row page, not a shape change.
+ endpoint = {
+ "path": config.path,
+ "params": params,
+ "paginator": SinglePagePaginator(),
+ "data_selector": config.data_selector,
+ }
+ elif config.returns_array:
+ # Bare-array endpoints: a non-list 200 body means the response shape changed — fail loud
+ # instead of syncing a stray object as a row.
+ endpoint = {
+ "path": config.path,
+ "params": params,
+ "paginator": SinglePagePaginator(),
+ "data_selector_required": True,
+ }
else:
# Single-object endpoints (e.g. campaign summary) return one JSON object per parent,
# which the framework wraps as a single row.
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.py
index cafbde1f7092..e96339c3a5d0 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,6 +139,49 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"CustomFields": "Custom field values stored against the subscriber.",
},
},
+ "list_custom_fields": {
+ "description": "Custom fields defined on a subscriber list — the lookup resolving the custom field keys carried on every subscriber row.",
+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/lists/#list-custom-fields",
+ "columns": {
+ "ListID": "Identifier of the list the custom field is defined on.",
+ "FieldName": "Human-readable name of the custom field.",
+ "Key": "Personalization key of the custom field, in square brackets (for example [website]).",
+ "DataType": "Data type of the custom field (Text, Number, MultiSelectOne, MultiSelectMany, Date, Country, or USState).",
+ "FieldOptions": "Available options for a multi-valued custom field. Empty for other data types.",
+ "VisibleInPreferenceCenter": "Whether subscribers can see and edit the field in the preference center.",
+ },
+ },
+ "list_stats": {
+ "description": "Subscriber counters for a list — active, unsubscribed, deleted, and bounced totals plus today, yesterday, this week, this month, and this year breakdowns. A snapshot taken at sync time, not a history.",
+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/lists/#list-stats",
+ "columns": {
+ "ListID": "Identifier of the list the counters belong to.",
+ "TotalActiveSubscribers": "Total number of active subscribers on the list.",
+ "NewActiveSubscribersToday": "Active subscribers added today, measured from midnight in the client's time zone.",
+ "NewActiveSubscribersYesterday": "Active subscribers added during the 24 hours of the previous day.",
+ "NewActiveSubscribersThisWeek": "Active subscribers added since midnight on the most recent Sunday.",
+ "NewActiveSubscribersThisMonth": "Active subscribers added since midnight on the first of the month.",
+ "NewActiveSubscribersThisYear": "Active subscribers added since midnight on 1 January.",
+ "TotalUnsubscribes": "Total number of subscribers who have unsubscribed from the list.",
+ "UnsubscribesToday": "Unsubscribes recorded today.",
+ "UnsubscribesYesterday": "Unsubscribes recorded during the 24 hours of the previous day.",
+ "UnsubscribesThisWeek": "Unsubscribes recorded since midnight on the most recent Sunday.",
+ "UnsubscribesThisMonth": "Unsubscribes recorded since midnight on the first of the month.",
+ "UnsubscribesThisYear": "Unsubscribes recorded since midnight on 1 January.",
+ "TotalDeleted": "Total number of subscribers deleted from the list.",
+ "DeletedToday": "Subscribers deleted today.",
+ "DeletedYesterday": "Subscribers deleted during the 24 hours of the previous day.",
+ "DeletedThisWeek": "Subscribers deleted since midnight on the most recent Sunday.",
+ "DeletedThisMonth": "Subscribers deleted since midnight on the first of the month.",
+ "DeletedThisYear": "Subscribers deleted since midnight on 1 January.",
+ "TotalBounces": "Total number of bounces recorded for the list.",
+ "BouncesToday": "Bounces recorded today.",
+ "BouncesYesterday": "Bounces recorded during the 24 hours of the previous day.",
+ "BouncesThisWeek": "Bounces recorded since midnight on the most recent Sunday.",
+ "BouncesThisMonth": "Bounces recorded since midnight on the first of the month.",
+ "BouncesThisYear": "Bounces recorded since midnight on 1 January.",
+ },
+ },
"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",
@@ -237,6 +280,36 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"ListID": "Identifier of the list the recipient was included from.",
},
},
+ "campaign_lists": {
+ "description": "Lists a campaign was sent to — one row per campaign and list, the join table between campaigns and lists.",
+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-lists-segments",
+ "columns": {
+ "CampaignID": "Unique identifier for the campaign that was sent.",
+ "ListID": "Identifier of the list the campaign was sent to.",
+ "Name": "Name of the list.",
+ },
+ },
+ "campaign_segments": {
+ "description": "Segments a campaign was sent to — one row per campaign and segment, the join table between campaigns and segments.",
+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-lists-segments",
+ "columns": {
+ "CampaignID": "Unique identifier for the campaign that was sent.",
+ "SegmentID": "Identifier of the segment the campaign was sent to.",
+ "ListID": "Identifier of the list the segment belongs to.",
+ "Title": "Title of the segment.",
+ },
+ },
+ "campaign_email_client_usage": {
+ "description": "Email clients subscribers used to open a campaign — one row per campaign, client family, and client version.",
+ "docs_url": "https://www.campaignmonitor.com/api/v3-3/campaigns/#campaign-email-client-usage",
+ "columns": {
+ "CampaignID": "Unique identifier for the campaign that was opened.",
+ "Client": "Email client family, for example Apple Mail or Microsoft Outlook.",
+ "Version": "Version or device of the email client, for example iPhone or Outlook 2010.",
+ "Percentage": "Share of opens attributed to this client and version, as a percentage.",
+ "Subscribers": "Number of subscribers who opened the campaign in this client and version.",
+ },
+ },
"journeys": {
"description": "An automated journey (marketing automation) belonging to the client.",
"docs_url": "https://www.campaignmonitor.com/api/v3-3/journeys/#getting-journeys",
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.py
index 8c7ae6d72474..3b9d390c844e 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
@@ -34,6 +34,13 @@ class CampaignMonitorEndpointConfig:
# 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
+ # Key holding the row array in a non-paginated response body. Set where one endpoint returns
+ # several collections and each becomes its own table (the campaign lists-and-segments body).
+ data_selector: Optional[str] = None
+ # Non-paginated endpoint returning a bare JSON array rather than a single object. Anything
+ # else on a 200 is a shape change, so the sync fails loud instead of syncing a stray object
+ # as a row.
+ returns_array: bool = False
# Stable datetime field used for datetime partitioning. Must not change over time
# (so never `*Updated`/`*Modified` style fields).
partition_key: Optional[str] = None
@@ -138,6 +145,24 @@ CAMPAIGN_MONITOR_ENDPOINTS: dict[str, CampaignMonitorEndpointConfig] = {
partition_key="Date",
order_field="date",
),
+ # List-scoped lookups — one request per subscriber list, no pagination.
+ "list_custom_fields": CampaignMonitorEndpointConfig(
+ name="list_custom_fields",
+ # Resolves the `[key]` custom fields carried on every subscriber row. Keys are unique
+ # within a list, not across the client's lists.
+ path="lists/{list_id}/customfields.json",
+ primary_keys=["ListID", "Key"],
+ fan_out_over_lists=True,
+ returns_array=True,
+ ),
+ "list_stats": CampaignMonitorEndpointConfig(
+ name="list_stats",
+ # A point-in-time snapshot of the list's subscriber, unsubscribe, deletion and bounce
+ # counters — the API exposes no history, so each sync replaces the previous snapshot.
+ path="lists/{list_id}/stats.json",
+ primary_keys=["ListID"],
+ fan_out_over_lists=True,
+ ),
# 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
@@ -208,6 +233,31 @@ CAMPAIGN_MONITOR_ENDPOINTS: dict[str, CampaignMonitorEndpointConfig] = {
# take — its rows have no date.
order_field="email",
),
+ "campaign_lists": CampaignMonitorEndpointConfig(
+ name="campaign_lists",
+ # `listsandsegments.json` returns one body holding two independent collections, so it
+ # feeds two join tables rather than one row of nested arrays.
+ path="campaigns/{campaign_id}/listsandsegments.json",
+ primary_keys=["CampaignID", "ListID"],
+ fan_out_over_campaigns=True,
+ data_selector="Lists",
+ ),
+ "campaign_segments": CampaignMonitorEndpointConfig(
+ name="campaign_segments",
+ path="campaigns/{campaign_id}/listsandsegments.json",
+ primary_keys=["CampaignID", "SegmentID"],
+ fan_out_over_campaigns=True,
+ data_selector="Segments",
+ ),
+ "campaign_email_client_usage": CampaignMonitorEndpointConfig(
+ name="campaign_email_client_usage",
+ # One row per email client family and version that opened the campaign. A client appears
+ # once per version, so both are part of the key.
+ path="campaigns/{campaign_id}/emailclientusage.json",
+ primary_keys=["CampaignID", "Client", "Version"],
+ fan_out_over_campaigns=True,
+ returns_array=True,
+ ),
# 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(
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.py
index 961d76ae3a22..763c99ce7960 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
@@ -341,6 +341,57 @@ class TestListFanOut:
assert snapshots[1][0].endswith("lists/l1/active.json")
assert snapshots[1][1]["page"] == 1
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_custom_fields_yield_a_row_per_field_with_its_list_id(self, MockSession) -> None:
+ # Custom field keys are unique within a list, not across them, so the list id has to land
+ # as a plain column — it is half the primary key.
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"ListID": "l1"}, {"ListID": "l2"}]),
+ _response([{"FieldName": "website", "Key": "[website]", "DataType": "Text", "FieldOptions": []}]),
+ _response([{"FieldName": "age", "Key": "[age]", "DataType": "Number", "FieldOptions": []}]),
+ ],
+ )
+
+ rows = _rows(_source("list_custom_fields"))
+
+ assert [(row["Key"], row["ListID"]) for row in rows] == [("[website]", "l1"), ("[age]", "l2")]
+ assert snapshots[1][0].endswith("lists/l1/customfields.json")
+ assert snapshots[2][0].endswith("lists/l2/customfields.json")
+ assert "page" not in snapshots[1][1]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_custom_fields_non_list_body_raises_loudly(self, MockSession) -> None:
+ # The endpoint returns a bare array; a 200 object means the response shape changed.
+ session = MockSession.return_value
+ _wire(session, [_response([{"ListID": "l1"}]), _response({"Code": 250, "Message": "Fail"})])
+
+ with pytest.raises(ValueError, match="list response body"):
+ _rows(_source("list_custom_fields"))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stats_yield_one_snapshot_row_per_list(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"ListID": "l1"}, {"ListID": "l2"}]),
+ _response({"TotalActiveSubscribers": 10, "TotalUnsubscribes": 1}),
+ _response({"TotalActiveSubscribers": 20, "TotalUnsubscribes": 2}),
+ ],
+ )
+
+ rows = _rows(_source("list_stats"))
+
+ assert rows == [
+ {"TotalActiveSubscribers": 10, "TotalUnsubscribes": 1, "ListID": "l1"},
+ {"TotalActiveSubscribers": 20, "TotalUnsubscribes": 2, "ListID": "l2"},
+ ]
+ assert snapshots[1][0].endswith("lists/l1/stats.json")
+ assert snapshots[2][0].endswith("lists/l2/stats.json")
+
class TestCampaignFanOut:
@mock.patch(CLIENT_SESSION_PATCH)
@@ -444,6 +495,64 @@ class TestCampaignFanOut:
assert params["orderdirection"] == "asc"
assert "date" not in params
+ @staticmethod
+ def _lists_and_segments() -> Response:
+ return _response(
+ {
+ "Lists": [{"ListID": "l1", "Name": "My List"}],
+ "Segments": [{"ListID": "l1", "SegmentID": "s1", "Title": "My Segment"}],
+ }
+ )
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_row",
+ [
+ ("campaign_lists", {"ListID": "l1", "Name": "My List", "CampaignID": "c1"}),
+ ("campaign_segments", {"ListID": "l1", "SegmentID": "s1", "Title": "My Segment", "CampaignID": "c1"}),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_lists_and_segments_body_feeds_two_tables(self, MockSession, endpoint: str, expected_row: dict) -> None:
+ # One endpoint, two collections: each table must pick only its own array out of the body.
+ session = MockSession.return_value
+ snapshots = _wire(session, [_envelope([{"CampaignID": "c1"}]), self._lists_and_segments()])
+
+ assert _rows(_source(endpoint)) == [expected_row]
+ assert snapshots[1][0].endswith("campaigns/c1/listsandsegments.json")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_lists_and_segments_tolerates_a_missing_collection(self, MockSession) -> None:
+ # A campaign sent to no segments is a zero-row page, not a response-shape failure.
+ session = MockSession.return_value
+ _wire(session, [_envelope([{"CampaignID": "c1"}]), _response({"Lists": [{"ListID": "l1", "Name": "My List"}]})])
+
+ assert _rows(_source("campaign_segments")) == []
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_email_client_usage_yields_a_row_per_client_version(self, MockSession) -> None:
+ # A client family appears once per version, so both are part of the primary key.
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _envelope([{"CampaignID": "c1"}]),
+ _response(
+ [
+ {"Client": "Apple Mail", "Version": "Apple Mail 6", "Percentage": 13.02, "Subscribers": 4633},
+ {"Client": "Apple Mail", "Version": "Apple Mail 7", "Percentage": 4.94, "Subscribers": 1632},
+ ]
+ ),
+ ],
+ )
+
+ rows = _rows(_source("campaign_email_client_usage"))
+
+ assert [(row["Client"], row["Version"], row["CampaignID"]) for row in rows] == [
+ ("Apple Mail", "Apple Mail 6", "c1"),
+ ("Apple Mail", "Apple Mail 7", "c1"),
+ ]
+ assert snapshots[1][0].endswith("campaigns/c1/emailclientusage.json")
+
class TestJourneyFanOut:
@staticmethod