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 28 tables to the Mailchimp source (#73854)

Tom Owersd43010ca41a8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/canonical_descriptions.py
index 75c98a72c12d..7328d328cbdc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/canonical_descriptions.py
@@ -88,4 +88,478 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"stats": "Engagement statistics for the contact (average open and click rates).",
},
},
+ "automations": {
+ "description": "An automation (classic automated journey) in Mailchimp, including its trigger and send settings.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/automation/",
+ "columns": {
+ "id": "A string that identifies the Automation.",
+ "create_time": "The date and time the Automation was created in ISO 8601 format.",
+ "start_time": "The date and time the Automation was started in ISO 8601 format.",
+ "status": "The current status of the Automation (save, paused, sending).",
+ "emails_sent": "The total number of emails sent for the Automation.",
+ "recipients": "Audience settings for the Automation, including the target list and segment.",
+ "settings": "The settings for the Automation workflow, including title, from name, and reply-to address.",
+ "tracking": "The tracking options for the Automation.",
+ "trigger_settings": "The trigger that starts the Automation workflow.",
+ "report_summary": "A summary of opens and clicks for campaigns sent by the Automation.",
+ },
+ },
+ "automation_emails": {
+ "description": "An individual email within an automation workflow, including its delay, content, and performance summary.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/automation-email/",
+ "columns": {
+ "id": "A string that uniquely identifies the Automation email.",
+ "workflow_id": "A string that uniquely identifies the Automation workflow this email belongs to.",
+ "web_id": "The ID used in the Mailchimp web application URLs for the Automation email.",
+ "position": "The position of the Automation email in the workflow.",
+ "delay": "The delay settings that control when the Automation email sends.",
+ "create_time": "The date and time the Automation email was created in ISO 8601 format.",
+ "start_time": "The date and time the Automation email was started in ISO 8601 format.",
+ "send_time": "The date and time the Automation email was sent in ISO 8601 format.",
+ "archive_url": "The link to the archived (web) version of the Automation email.",
+ "status": "The current status of the Automation email.",
+ "emails_sent": "The total number of emails sent for this Automation email.",
+ "content_type": "How the email's content is put together (template, drag_and_drop, html, url).",
+ "recipients": "Audience settings for the Automation email.",
+ "settings": "Settings for the email, including subject line, from name, and from email address.",
+ "tracking": "The tracking options for the Automation email.",
+ "trigger_settings": "The trigger that causes this Automation email to send.",
+ "report_summary": "For sent emails, a summary of opens and clicks.",
+ },
+ },
+ "templates": {
+ "description": "An email template available to the account, either built by the user or provided by Mailchimp.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/templates/",
+ "columns": {
+ "id": "The individual id for the template.",
+ "type": "The type of template (user, base, or gallery).",
+ "name": "The name of the template.",
+ "drag_and_drop": "Whether the template uses the drag and drop editor.",
+ "responsive": "Whether the template contains media queries to make it responsive.",
+ "category": "If available, the category the template is listed in.",
+ "date_created": "The date and time the template was created in ISO 8601 format.",
+ "date_edited": "The date and time the template was last edited in ISO 8601 format.",
+ "created_by": "The login name of the template's creator.",
+ "edited_by": "The login name of the user who last edited the template.",
+ "active": "Whether the template is still active. Deleted user templates are marked inactive rather than removed.",
+ "folder_id": "The id of the folder the template is currently in.",
+ "thumbnail": "If available, the URL for a thumbnail of the template.",
+ "share_url": "The URL used for template sharing.",
+ "content_type": "How the template's content is put together.",
+ },
+ },
+ "landing_pages": {
+ "description": "A landing page built in Mailchimp, including its publish state and connected audience.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/landing-pages/",
+ "columns": {
+ "id": "A string that uniquely identifies this landing page.",
+ "name": "The name of this landing page.",
+ "title": "The title of this landing page seen in the browser's title bar.",
+ "description": "The description of this landing page.",
+ "template_id": "The template id of this landing page.",
+ "status": "The status of this landing page (published, unpublished, draft).",
+ "list_id": "The audience id associated with this landing page.",
+ "store_id": "The id of the store associated with this landing page.",
+ "web_id": "The ID used in the Mailchimp web application URLs for the landing page.",
+ "created_by_source": "Whether the landing page was created on mobile or web.",
+ "url": "The URL of the published landing page.",
+ "created_at": "The time this landing page was created.",
+ "published_at": "The time this landing page was published.",
+ "unpublished_at": "The time this landing page was unpublished.",
+ "updated_at": "The time this landing page was last updated.",
+ "tracking": "The tracking settings applied to this landing page.",
+ },
+ },
+ "sms_campaigns": {
+ "description": "An SMS or WhatsApp campaign, including its schedule, channel, and recipient count.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/sms-campaigns/",
+ "columns": {
+ "id": "A string that uniquely identifies this campaign.",
+ "web_id": "The ID used in the Mailchimp web application URLs for the campaign.",
+ "name": "The name of the campaign.",
+ "status": "The current status of the campaign.",
+ "channel": "The channel for this campaign (sms or whatsapp).",
+ "list_id": "The numeric ID of the audience associated with this campaign.",
+ "recipient_count": "The number of recipients for this campaign.",
+ "create_time": "The date and time the campaign was created in ISO 8601 format.",
+ "send_time": "The date and time the campaign is scheduled to send.",
+ "updated_at": "The date and time the campaign was last updated.",
+ "expire_time": "The date and time the campaign will stop sending in ISO 8601 format.",
+ "is_send_now": "Whether the campaign is configured to send immediately.",
+ "folder_id": "The ID of the folder this campaign is in.",
+ "segments": "The segment IDs used to target recipients for this campaign.",
+ "excluded_segments": "The segment IDs excluded from receiving this campaign.",
+ },
+ },
+ "conversations": {
+ "description": "A conversation thread between the account and a contact, started from a campaign reply.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/conversations/",
+ "columns": {
+ "id": "A string that uniquely identifies this conversation.",
+ "message_count": "The total number of messages in this conversation.",
+ "campaign_id": "The unique identifier of the campaign for this conversation.",
+ "list_id": "The unique identifier of the audience for this conversation.",
+ "unread_messages": "The number of unread messages in this conversation.",
+ "from_label": "A label representing the sender of the most recent message.",
+ "from_email": "The email address of the sender of the most recent message.",
+ "subject": "The subject of the message.",
+ "last_message": "The most recent message in the conversation.",
+ },
+ },
+ "campaign_folders": {
+ "description": "A folder used to organize campaigns in the Mailchimp account.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/campaign-folders/",
+ "columns": {
+ "id": "A string that uniquely identifies this campaign folder.",
+ "name": "The name of the folder.",
+ "count": "The number of campaigns in the folder.",
+ },
+ },
+ "campaign_content": {
+ "description": "The rendered HTML and plain-text content of a campaign, one row per campaign.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/campaign-content/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign this content belongs to.",
+ "plain_text": "The plain-text portion of the campaign.",
+ "html": "The raw HTML for the campaign.",
+ "archive_html": "The Archive HTML for the campaign.",
+ "variate_contents": "Content options for multivariate campaigns, one entry per variation.",
+ },
+ },
+ "campaign_feedback": {
+ "description": "A team feedback comment left on a campaign while it was being drafted.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/campaign-feedback/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign the feedback was left on.",
+ "feedback_id": "The individual id for the feedback item.",
+ "parent_id": "If a reply, the id of the parent feedback item.",
+ "block_id": "The block id for the editable block that the feedback addresses.",
+ "message": "The content of the feedback.",
+ "is_complete": "The status of the feedback item.",
+ "created_by": "The login name of the user who created the feedback.",
+ "created_at": "The date and time the feedback item was created in ISO 8601 format.",
+ "updated_at": "The date and time the feedback was last updated in ISO 8601 format.",
+ "source": "The source of the feedback (api, email, sms, web).",
+ },
+ },
+ "verified_domains": {
+ "description": "A sending domain registered on the account, with its verification and authentication state.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/verified-domains/",
+ "columns": {
+ "domain": "The name of this domain.",
+ "verified": "Whether the domain has been verified for sending.",
+ "authenticated": "Whether domain authentication is enabled for this domain.",
+ "verification_email": "The email address receiving the two-factor challenge for this domain.",
+ "verification_sent": "The date and time the two-factor challenge was sent to the verification email.",
+ "status": "The domain's current status.",
+ "is_free_email_provider": "Whether the domain is a public or free email provider.",
+ },
+ },
+ "list_segments": {
+ "description": "A segment or tag defined on an audience, including its conditions and current member count.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/list-segments/",
+ "columns": {
+ "id": "The unique id for the segment.",
+ "list_id": "The unique identifier for the audience the segment belongs to.",
+ "name": "The name of the segment.",
+ "member_count": "The number of active subscribers currently included in the segment.",
+ "type": "The type of segment. Static segments are now known as tags.",
+ "created_at": "The date and time the segment was created in ISO 8601 format.",
+ "updated_at": "The date and time the segment was last updated in ISO 8601 format.",
+ "options": "The conditions of the segment. Tags and fuzzy segments have no conditions.",
+ },
+ },
+ "list_segment_members": {
+ "description": "A contact's membership of an audience segment, with the contact's status and engagement.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/list-segment-members/",
+ "columns": {
+ "id": "The MD5 hash of the member's lowercase email address, used as the identifier.",
+ "list_id": "The unique identifier for the audience the segment belongs to.",
+ "segment_id": "The unique identifier for the segment the member belongs to.",
+ "email_address": "Email address for the subscriber.",
+ "full_name": "The contact's full name.",
+ "unique_email_id": "An identifier for the address across all of Mailchimp.",
+ "email_type": "The type of email the contact prefers (html or text).",
+ "status": "The subscriber's current status.",
+ "merge_fields": "Audience merge fields and values for the contact.",
+ "interests": "The contact's interest subscriptions, keyed by interest id.",
+ "stats": "Open and click rates for this subscriber.",
+ "timestamp_signup": "The date and time the subscriber signed up for the audience in ISO 8601 format.",
+ "timestamp_opt": "The date and time the subscriber confirmed their opt-in status in ISO 8601 format.",
+ "member_rating": "Star rating for this member, between 1 and 5.",
+ "last_changed": "The date and time the member's info was last changed in ISO 8601 format.",
+ "language": "The contact's language preference.",
+ "vip": "Whether the contact is marked as a VIP.",
+ "location": "Subscriber location information.",
+ },
+ },
+ "list_merge_fields": {
+ "description": "A merge field (audience field) defined on an audience, describing how contact data is stored.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/list-merges/",
+ "columns": {
+ "merge_id": "An unchanging id for the merge field.",
+ "list_id": "The unique identifier for the audience the merge field belongs to.",
+ "tag": "The merge tag used in campaigns to reference this field.",
+ "name": "The name of the merge field (audience field).",
+ "type": "The type for the merge field (text, number, address, phone, date, and so on).",
+ "required": "Whether the merge field is required.",
+ "default_value": "The default value for the merge field when null.",
+ "public": "Whether the merge field is displayed on the signup form.",
+ "display_order": "The order that the merge field displays on the audience signup form.",
+ "options": "Extra options for some merge field types.",
+ "help_text": "Extra text to help the subscriber fill out the form.",
+ },
+ },
+ "list_interest_categories": {
+ "description": "An interest category (group title) on an audience, used to group signup form preferences.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/interest-categories/",
+ "columns": {
+ "id": "The id for the interest category.",
+ "list_id": "The unique audience id for the category.",
+ "title": "The text description of this category, shown on signup forms.",
+ "display_order": "The order the categories are displayed in. Lower numbers display first.",
+ "type": "How this category's interests appear on signup forms (checkboxes, dropdown, radio, hidden).",
+ },
+ },
+ "list_growth_history": {
+ "description": "A monthly summary of how an audience grew, one row per audience per month.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/list-growth-history/",
+ "columns": {
+ "list_id": "The audience id for the growth activity report.",
+ "month": "The month that the growth history is describing.",
+ "subscribed": "Total subscribed members on the audience at the end of the month.",
+ "unsubscribed": "Newly unsubscribed members on the audience for the month.",
+ "reconfirm": "Newly reconfirmed members on the audience for the month.",
+ "cleaned": "Newly cleaned (hard-bounced) members on the audience for the month.",
+ "pending": "Pending members on the audience for the month.",
+ "deleted": "Newly deleted members on the audience for the month.",
+ "transactional": "Subscribers that have been sent transactional emails via Mandrill.",
+ },
+ },
+ "list_activity": {
+ "description": "A daily summary of sends, opens, clicks, and subscription changes for an audience.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/list-activity/",
+ "columns": {
+ "list_id": "The unique identifier for the audience the activity is summarized for.",
+ "day": "The date for the activity summary.",
+ "emails_sent": "The total number of emails sent on the date for the activity summary.",
+ "unique_opens": "The number of unique opens.",
+ "recipient_clicks": "The number of clicks.",
+ "hard_bounce": "The number of hard bounces.",
+ "soft_bounce": "The number of soft bounces.",
+ "subs": "The number of subscribes.",
+ "unsubs": "The number of unsubscribes.",
+ "other_adds": "The number of subscribers added outside of the double opt-in process.",
+ "other_removes": "The number of subscribers removed outside of unsubscribing or reporting spam.",
+ },
+ },
+ "report_email_activity": {
+ "description": "Per-recipient open and click activity for a sent campaign, one row per campaign recipient.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/email-activity-reports/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign.",
+ "list_id": "The unique id for the audience the campaign was sent to.",
+ "list_is_active": "The status of the audience used, namely if it's deleted or disabled.",
+ "email_id": "The MD5 hash of the recipient's lowercase email address.",
+ "email_address": "Email address for the subscriber.",
+ "activity": "An array of interactions with the email. Limited to 1,000 open and 1,000 click activities.",
+ },
+ },
+ "report_open_details": {
+ "description": "Members who opened a sent campaign, with open counts and open timestamps.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/open-reports/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign.",
+ "list_id": "The unique id for the audience the campaign was sent to.",
+ "list_is_active": "The status of the audience used, namely if it's deleted or disabled.",
+ "contact_status": "The status of the member at the time of the report.",
+ "email_id": "The MD5 hash of the recipient's lowercase email address.",
+ "email_address": "Email address for the subscriber.",
+ "merge_fields": "Audience merge fields and values for the contact.",
+ "vip": "Whether the contact is marked as a VIP.",
+ "opens_count": "The total number of times this campaign was opened by the member.",
+ "proxy_excluded_opens_count": "Opens excluding those from email clients that use proxies.",
+ "opens": "An array of timestamps for each time the member opened the campaign.",
+ },
+ },
+ "report_click_details": {
+ "description": "Per-link click performance for a sent campaign, one row per tracked URL.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/click-reports/",
+ "columns": {
+ "id": "The unique id for the link.",
+ "campaign_id": "The unique id for the campaign the link belongs to.",
+ "url": "The URL for the link in the campaign.",
+ "total_clicks": "The number of total clicks for the link.",
+ "click_percentage": "The percentage of total clicks the link generated for the campaign.",
+ "unique_clicks": "Number of unique clicks for the link.",
+ "unique_click_percentage": "The percentage of unique clicks the link generated for the campaign.",
+ "last_click": "The date and time of the last recorded click for the link in ISO 8601 format.",
+ "ab_split": "A breakdown of clicks by group for an A/B split campaign.",
+ },
+ },
+ "report_sent_to": {
+ "description": "Every recipient a campaign was sent to, with delivery status and open counts.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/sent-to-reports/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign.",
+ "list_id": "The unique id for the audience the campaign was sent to.",
+ "list_is_active": "The status of the audience used, namely if it's deleted or disabled.",
+ "email_id": "The MD5 hash of the recipient's lowercase email address.",
+ "email_address": "Email address for the subscriber.",
+ "merge_fields": "Audience merge fields and values for the contact.",
+ "vip": "Whether the contact is marked as a VIP.",
+ "status": "The delivery status of the email for this subscriber (sent, hard, soft).",
+ "open_count": "The number of times the campaign was opened by this member.",
+ "last_open": "The date and time of the last open for this member in ISO 8601 format.",
+ "absplit_group": "For A/B split campaigns, the group the member was part of.",
+ "gmt_offset": "For campaigns sent with Timewarp, the time zone group the member is part of.",
+ },
+ },
+ "report_unsubscribed": {
+ "description": "Members who unsubscribed after receiving a campaign, with the time and stated reason.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/unsubscribes/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign.",
+ "list_id": "The unique id for the audience the campaign was sent to.",
+ "list_is_active": "The status of the audience used, namely if it's deleted or disabled.",
+ "email_id": "The MD5 hash of the recipient's lowercase email address.",
+ "email_address": "Email address for the subscriber.",
+ "merge_fields": "Audience merge fields and values for the contact.",
+ "vip": "Whether the contact is marked as a VIP.",
+ "timestamp": "The date and time the member opted out in ISO 8601 format.",
+ "reason": "If available, the reason listed by the member for unsubscribing.",
+ },
+ },
+ "report_abuse_reports": {
+ "description": "Abuse (spam) complaints filed against a sent campaign, one row per complaint.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/abuse-reports/",
+ "columns": {
+ "id": "The id for the abuse report.",
+ "campaign_id": "The campaign id for the abuse report.",
+ "list_id": "The unique id of the audience for the abuse report.",
+ "list_is_active": "The status of the audience used, namely if it's deleted or disabled.",
+ "email_id": "The MD5 hash of the reporter's lowercase email address.",
+ "email_address": "Email address for the subscriber.",
+ "merge_fields": "Audience merge fields and values for the contact.",
+ "vip": "Whether the contact is marked as a VIP.",
+ "date": "Date for the abuse report.",
+ },
+ },
+ "report_domain_performance": {
+ "description": "Campaign performance broken down by recipient email domain, such as gmail.com.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/domain-performance-reports/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign the breakdown belongs to.",
+ "domain": "The name of the domain (gmail.com, hotmail.com, yahoo.com).",
+ "emails_sent": "The number of emails sent to that specific domain.",
+ "bounces": "The number of bounces at the domain.",
+ "opens": "The number of opens for the domain.",
+ "clicks": "The number of clicks for the domain.",
+ "unsubs": "The total number of unsubscribes for the domain.",
+ "delivered": "The number of successful deliveries for the domain.",
+ "emails_pct": "The percentage of total emails that went to this domain.",
+ "bounces_pct": "The percentage of total bounces from this domain.",
+ "opens_pct": "The percentage of total opens from this domain.",
+ "clicks_pct": "The percentage of total clicks from this domain.",
+ "unsubs_pct": "The percentage of total unsubscribes from this domain.",
+ },
+ },
+ "report_locations": {
+ "description": "Campaign opens broken down by the geographic location of the recipient.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/location-reports/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign the breakdown belongs to.",
+ "country_code": "The ISO 3166 2 digit country code.",
+ "region": "An internal code for the region. Blank means the rest of the country.",
+ "region_name": "The name of the region. For blank regions this is 'Rest of Country'.",
+ "opens": "The number of unique campaign opens for the region.",
+ "proxy_excluded_opens": "Unique opens for the region excluding email clients that use proxies.",
+ },
+ },
+ "report_ecommerce_product_activity": {
+ "description": "Revenue and purchase activity attributed to a campaign, broken down by product.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/ecommerce-product-activity-reports/",
+ "columns": {
+ "campaign_id": "The unique id for the campaign the activity is attributed to.",
+ "title": "The title of the product.",
+ "sku": "The stock keeping unit (SKU) of the product.",
+ "image_url": "The image URL for the product.",
+ "total_revenue": "The total revenue attributed to the product for this campaign.",
+ "total_purchased": "The total number of units purchased for this campaign.",
+ "currency_code": "The three-letter ISO 4217 code for the currency of the revenue figures.",
+ "recommendation_total": "Total revenue from product recommendations in the campaign.",
+ "recommendation_purchased": "Total units purchased from product recommendations in the campaign.",
+ },
+ },
+ "ecommerce_stores": {
+ "description": "An ecommerce store connected to the Mailchimp account.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/ecommerce-stores/",
+ "columns": {
+ "id": "The unique identifier for the store.",
+ "list_id": "The unique identifier for the audience associated with the store.",
+ "name": "The name of the store.",
+ "platform": "The ecommerce platform of the store.",
+ "domain": "The store domain.",
+ "is_syncing": "Whether automations are disabled because the store is currently syncing.",
+ "email_address": "The email address for the store.",
+ "currency_code": "The three-letter ISO 4217 code for the currency that the store accepts.",
+ "money_format": "The currency format for the store.",
+ "primary_locale": "The primary locale for the store.",
+ "timezone": "The timezone for the store.",
+ "phone": "The store phone number.",
+ "address": "The store address.",
+ "connected_site": "The connected site associated with the store.",
+ "list_is_active": "The status of the audience connected to the store.",
+ "created_at": "The date and time the store was created in ISO 8601 format.",
+ "updated_at": "The date and time the store was last updated in ISO 8601 format.",
+ },
+ },
+ "ecommerce_orders": {
+ "description": "An ecommerce order synced from a connected store, including totals and campaign attribution.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/ecommerce-orders/",
+ "columns": {
+ "id": "A unique identifier for the order, unique within its store.",
+ "store_id": "The unique identifier for the store the order belongs to.",
+ "customer": "Information about the customer who placed the order.",
+ "campaign_id": "The campaign the order is attributed to, if any.",
+ "cart_id": "The cart id that the order was placed for.",
+ "landing_site": "The URL for the page where the buyer landed when entering the shop.",
+ "financial_status": "The payment status of the order.",
+ "fulfillment_status": "The fulfillment status for the order.",
+ "currency_code": "The three-letter ISO 4217 code for the currency that the store accepts.",
+ "order_total": "The order total associated with the order.",
+ "order_url": "The URL for the order.",
+ "discount_total": "The total amount of the discounts applied to the price of the order.",
+ "tax_total": "The tax total associated with the order.",
+ "shipping_total": "The shipping total for the order.",
+ "tracking_code": "The Mailchimp tracking code for the order.",
+ "processed_at_foreign": "The date and time the order was processed in ISO 8601 format.",
+ "cancelled_at_foreign": "The date and time the order was cancelled in ISO 8601 format.",
+ "updated_at_foreign": "The date and time the order was updated in ISO 8601 format.",
+ "shipping_address": "The shipping address for the order.",
+ "billing_address": "The billing address for the order.",
+ "promos": "The promo codes applied on the order.",
+ "lines": "An array of the order's line items.",
+ "outreach": "The outreach associated with this order, such as an email campaign or ad.",
+ },
+ },
+ "ecommerce_products": {
+ "description": "A product in a connected ecommerce store, including its variants and images.",
+ "docs_url": "https://mailchimp.com/developer/marketing/api/ecommerce-products/",
+ "columns": {
+ "id": "A unique identifier for the product, unique within its store.",
+ "store_id": "The unique identifier for the store the product belongs to.",
+ "title": "The title of the product.",
+ "handle": "The handle of the product.",
+ "url": "The URL for the product.",
+ "description": "The description of the product.",
+ "type": "The type of product.",
+ "vendor": "The vendor for the product.",
+ "image_url": "The image URL for the product.",
+ "currency_code": "The three-letter ISO 4217 code for the product's currency.",
+ "variants": "Up to 50 of the product's variants.",
+ "images": "An array of the product's images.",
+ "published_at_foreign": "The date and time the product was published in ISO 8601 format.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py
index e59cfa4056be..c086240b6c63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/mailchimp.py
@@ -3,7 +3,7 @@ from collections.abc import Iterator
from datetime import date, datetime
from typing import Any, Optional
-from requests import Request, Response
+from requests import Request, Response, Session
from requests.exceptions import RequestException
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -15,7 +15,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
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.mailchimp.settings import MAILCHIMP_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailchimp.settings import (
+ MAILCHIMP_ENDPOINTS,
+ MAX_PAGE_SIZE,
+ MailchimpEndpointConfig,
+ MailchimpPagination,
+ MailchimpParentConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 120
@dataclasses.dataclass
@@ -27,6 +35,9 @@ class MailchimpResumeConfig:
- ``lists``/``campaigns``/``reports`` go through the shared ``rest_api_resource``
path using ``MailchimpPaginator`` (offset/count); their checkpoint is just
``offset`` and ``list_id`` is ``None``.
+ - Fan-out endpoints (report/list/campaign sub-resources) checkpoint the ordered
+ chain of parent ids alongside the offset, so a resume picks the same parent
+ back up rather than restarting the whole fan-out.
On resume we re-request the saved page; duplicates are deduped by the
primary key.
@@ -34,6 +45,7 @@ class MailchimpResumeConfig:
offset: int
list_id: Optional[str] = None
+ parent_ids: Optional[list[str]] = None
def extract_data_center(api_key: str) -> str:
@@ -106,6 +118,27 @@ class MailchimpPaginator(BasePaginator):
self._has_next_page = True
+def _incremental_query_params(
+ config: MailchimpEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> dict[str, str]:
+ """Map the user's chosen cursor field onto Mailchimp's server-side `since_*` filter.
+
+ Endpoints that expose no such filter return an empty dict and fall back to full refresh.
+ """
+ if not should_use_incremental_field or not db_incremental_field_last_value:
+ return {}
+
+ field = incremental_field or config.default_incremental_field
+ param = config.incremental_params.get(field) if field else None
+ if param is None:
+ return {}
+
+ return {param: _format_incremental_value(db_incremental_field_last_value)}
+
+
def get_resource(
name: str,
should_use_incremental_field: bool,
@@ -117,21 +150,11 @@ def get_resource(
params: dict[str, Any] = {
"count": config.page_size,
+ **_incremental_query_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ ),
}
- # Add incremental filter for supported endpoints
- if should_use_incremental_field and db_incremental_field_last_value:
- formatted_value = _format_incremental_value(db_incremental_field_last_value)
- field = incremental_field or config.default_incremental_field
-
- if name == "campaigns":
- if field == "create_time":
- params["since_create_time"] = formatted_value
- elif field == "send_time":
- params["since_send_time"] = formatted_value
- elif name == "reports" and field == "send_time":
- params["since_send_time"] = formatted_value
-
return {
"name": config.name,
"table_name": config.name,
@@ -158,13 +181,9 @@ def validate_credentials(api_key: str) -> tuple[bool, str | None]:
return False, str(e)
url = f"https://{dc}.api.mailchimp.com/3.0/ping"
- headers = {
- "Authorization": f"apikey {api_key}",
- "Accept": "application/json",
- }
try:
- response = make_tracked_session().get(url, headers=headers, timeout=10)
+ response = _mailchimp_session(api_key).get(url, timeout=10)
if response.status_code == 200:
return True, None
@@ -195,12 +214,7 @@ def _fetch_all_lists(api_key: str, dc: str) -> list[dict[str, Any]]:
# One session for the whole pagination loop so urllib3's connection
# pool keeps the TLS connection warm across pages.
- session = make_tracked_session(
- headers={
- "Authorization": f"apikey {api_key}",
- "Accept": "application/json",
- }
- )
+ session = _mailchimp_session(api_key)
while True:
response = session.get(
@@ -235,12 +249,7 @@ def _fetch_contacts_for_list(
page_size = 1000
# One session for the whole pagination loop — see `_fetch_all_lists`.
- session = make_tracked_session(
- headers={
- "Authorization": f"apikey {api_key}",
- "Accept": "application/json",
- }
- )
+ session = _mailchimp_session(api_key)
while True:
params: dict[str, str | int] = {
@@ -321,6 +330,215 @@ def _get_contacts_iterator(
)
+def _mailchimp_session(api_key: str) -> Session:
+ # capture=False keeps requests metered and logged but excludes their bodies from HTTP sample
+ # capture: Mailchimp responses carry subscriber PII (email addresses, activity), campaign
+ # content, feedback, and ecommerce orders that the name-based scrubbers can't reliably redact.
+ return make_tracked_session(
+ headers={
+ "Authorization": f"apikey {api_key}",
+ "Accept": "application/json",
+ },
+ redact_values=(api_key,),
+ capture=False,
+ )
+
+
+def _iter_pages(
+ session: Session,
+ base_url: str,
+ path: str,
+ data_selector: str,
+ pagination: MailchimpPagination,
+ page_size: int,
+ extra_params: dict[str, str],
+ start_offset: int = 0,
+) -> Iterator[tuple[int, list[dict[str, Any]]]]:
+ """Yield ``(offset, records)`` for one Mailchimp collection endpoint.
+
+ Only `count`/`offset` endpoints loop; the others return their whole collection in a
+ single request, so sending pagination params they don't declare is avoided.
+ """
+ offset = start_offset
+
+ while True:
+ params: dict[str, Any] = dict(extra_params)
+ if pagination in ("offset", "count_only"):
+ params["count"] = page_size
+ if pagination == "offset":
+ params["offset"] = offset
+
+ response = session.get(f"{base_url}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+
+ data = response.json()
+ records = data.get(data_selector) or []
+
+ yield offset, records
+
+ if pagination != "offset" or not records:
+ return
+
+ total_items = data.get("total_items", 0)
+ offset += page_size
+
+ if offset >= total_items:
+ return
+
+
+def _resolve_parent_id_maps(
+ session: Session,
+ base_url: str,
+ parents: tuple[MailchimpParentConfig, ...],
+) -> list[dict[str, str]]:
+ """Walk the fan-out chain and return one id map per leaf parent combination.
+
+ Each map is keyed by ``inject_as``, so it both formats the child path and supplies the
+ parent columns written onto every child row.
+ """
+ id_maps: list[dict[str, str]] = [{}]
+
+ for parent in parents:
+ next_maps: list[dict[str, str]] = []
+ for id_map in id_maps:
+ for _, records in _iter_pages(
+ session,
+ base_url,
+ parent.path.format(**id_map),
+ parent.data_selector,
+ "offset",
+ MAX_PAGE_SIZE,
+ {},
+ ):
+ for record in records:
+ parent_id = record.get(parent.id_field)
+ if parent_id is None:
+ continue
+ next_maps.append({**id_map, parent.inject_as: str(parent_id)})
+ id_maps = next_maps
+
+ return id_maps
+
+
+def _fetch_endpoint_rows(
+ session: Session,
+ base_url: str,
+ config: MailchimpEndpointConfig,
+ path: str,
+ id_map: dict[str, str],
+ extra_params: dict[str, str],
+ start_offset: int,
+ resumable_source_manager: ResumableSourceManager[MailchimpResumeConfig],
+ parent_ids: Optional[list[str]],
+) -> Iterator[dict[str, Any]]:
+ if config.single_object:
+ response = session.get(f"{base_url}{path}", params=dict(extra_params), timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ record = response.json()
+ if isinstance(record, dict):
+ yield {**record, **id_map}
+ return
+
+ for offset, records in _iter_pages(
+ session,
+ base_url,
+ path,
+ config.data_selector,
+ config.pagination,
+ config.page_size,
+ extra_params,
+ start_offset,
+ ):
+ if not records:
+ continue
+
+ if config.pagination == "offset":
+ # Checkpoint the page we are about to yield, matching the contacts path: a resume
+ # re-fetches it and the primary key dedupes the overlap.
+ resumable_source_manager.save_state(MailchimpResumeConfig(offset=offset, parent_ids=parent_ids))
+
+ for record in records:
+ yield {**record, **id_map}
+
+
+def _get_endpoint_iterator(
+ api_key: str,
+ config: MailchimpEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[MailchimpResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[dict[str, Any]]:
+ """Fetch an endpoint that the shared `rest_api_resource` path can't express.
+
+ That means anything fanning out over a parent resource, and the handful of collections
+ Mailchimp serves without `count`/`offset` pagination.
+ """
+ dc = extract_data_center(api_key)
+ base_url = f"https://{dc}.api.mailchimp.com/3.0"
+ session = _mailchimp_session(api_key)
+
+ extra_params = _incremental_query_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ if not config.parents:
+ start_offset = 0
+ if config.pagination == "offset" and resumable_source_manager.can_resume():
+ loaded = resumable_source_manager.load_state()
+ if loaded is not None and loaded.parent_ids is None:
+ start_offset = loaded.offset
+
+ yield from _fetch_endpoint_rows(
+ session,
+ base_url,
+ config,
+ config.path,
+ {},
+ extra_params,
+ start_offset,
+ resumable_source_manager,
+ parent_ids=None,
+ )
+ return
+
+ id_maps = _resolve_parent_id_maps(session, base_url, config.parents)
+ parent_keys = [parent.inject_as for parent in config.parents]
+
+ # Only honour the saved checkpoint if its parent chain still exists; otherwise fall back
+ # to a fresh run rather than silently syncing nothing.
+ resume_config: MailchimpResumeConfig | None = None
+ if resumable_source_manager.can_resume():
+ loaded = resumable_source_manager.load_state()
+ if loaded is not None and loaded.parent_ids is not None:
+ known_chains = {tuple(id_map[key] for key in parent_keys) for id_map in id_maps}
+ if tuple(loaded.parent_ids) in known_chains:
+ resume_config = loaded
+
+ for id_map in id_maps:
+ parent_ids = [id_map[key] for key in parent_keys]
+
+ if resume_config is not None:
+ if parent_ids != list(resume_config.parent_ids or []):
+ continue
+ start_offset = resume_config.offset
+ resume_config = None
+ else:
+ start_offset = 0
+
+ yield from _fetch_endpoint_rows(
+ session,
+ base_url,
+ config,
+ config.path.format(**id_map),
+ id_map,
+ extra_params,
+ start_offset,
+ resumable_source_manager,
+ parent_ids=parent_ids,
+ )
+
+
def mailchimp_source(
api_key: str,
endpoint: str,
@@ -344,12 +562,35 @@ def mailchimp_source(
should_use_incremental_field,
db_incremental_field_last_value,
),
- primary_keys=["list_id", "id"],
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+ # Fan-out endpoints and the collections Mailchimp serves without offset pagination can't be
+ # expressed as a single `rest_api_resource`, so they go through the generic iterator.
+ if endpoint_config.parents or endpoint_config.pagination != "offset":
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _get_endpoint_iterator(
+ api_key,
+ endpoint_config,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ incremental_field,
+ ),
+ primary_keys=endpoint_config.primary_keys,
partition_count=1,
partition_size=1,
partition_mode="datetime" if endpoint_config.partition_key else None,
partition_format="week" if endpoint_config.partition_key else None,
partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ chunk_size=endpoint_config.chunk_size,
+ chunk_size_bytes=endpoint_config.chunk_size_bytes,
)
dc = extract_data_center(api_key)
@@ -367,6 +608,10 @@ def mailchimp_source(
"Accept": "application/json",
},
"paginator": MailchimpPaginator(page_size=endpoint_config.page_size),
+ # capture=False for the same reason as `_mailchimp_session`: account-level endpoints
+ # (conversations, ecommerce orders, and the rest) return subscriber PII and free-form
+ # content the name-based scrubbers can't reliably redact, so keep it out of samples.
+ "session": make_tracked_session(redact_values=(api_key,), capture=False),
},
"resource_defaults": {
"write_disposition": "replace",
@@ -412,7 +657,7 @@ def mailchimp_source(
return SourceResponse(
name=endpoint,
items=lambda: resource,
- primary_keys=["id"],
+ primary_keys=endpoint_config.primary_keys,
partition_count=1,
partition_size=1,
partition_mode="datetime" if endpoint_config.partition_key else None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/settings.py
index d40e612ae161..1704f3ff46e2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/settings.py
@@ -1,8 +1,32 @@
-from dataclasses import dataclass
-from typing import Optional
+from dataclasses import dataclass, field
+from typing import Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# How a collection endpoint pages:
+# - "offset": Mailchimp's standard `count`/`offset` pagination, looped until `total_items`.
+# - "count_only": the endpoint accepts `count` but no `offset`, so it is a single capped request.
+# - "none": the endpoint takes no pagination params and returns the whole collection at once.
+MailchimpPagination = Literal["offset", "count_only", "none"]
+
+MAX_PAGE_SIZE = 1000 # Mailchimp caps `count` at 1000 across the API
+
+
+@dataclass
+class MailchimpParentConfig:
+ """One hop of a fan-out chain.
+
+ ``path`` may itself contain ``{placeholder}`` names resolved by earlier hops, so chains
+ deeper than one level (audience -> segment -> member) compose without bespoke code.
+ ``inject_as`` is both the placeholder name in the child path and the column written onto
+ every child row, which is what makes the parent id available for the primary key.
+ """
+
+ path: str
+ data_selector: str
+ id_field: str = "id"
+ inject_as: str = "id"
+
@dataclass
class MailchimpEndpointConfig:
@@ -12,7 +36,25 @@ class MailchimpEndpointConfig:
incremental_fields: list[IncrementalField]
default_incremental_field: Optional[str] = None
partition_key: Optional[str] = None
- page_size: int = 1000 # Mailchimp max is 1000
+ page_size: int = MAX_PAGE_SIZE
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ parents: tuple[MailchimpParentConfig, ...] = ()
+ pagination: MailchimpPagination = "offset"
+ single_object: bool = False
+ """Endpoint returns one object rather than a collection, so it yields a single row per parent."""
+ incremental_params: dict[str, str] = field(default_factory=dict)
+ """Maps an incremental field name to the Mailchimp query param that filters on it server-side."""
+ chunk_size: Optional[int] = None
+ chunk_size_bytes: Optional[int] = None
+
+
+_LISTS_PARENT = MailchimpParentConfig(path="/lists", data_selector="lists", inject_as="list_id")
+_CAMPAIGNS_PARENT = MailchimpParentConfig(path="/campaigns", data_selector="campaigns", inject_as="campaign_id")
+# Reports only exist for campaigns that have actually been sent, so fanning report sub-resources
+# out over /reports avoids a 404 per unsent draft.
+_REPORTS_PARENT = MailchimpParentConfig(path="/reports", data_selector="reports", inject_as="campaign_id")
+_AUTOMATIONS_PARENT = MailchimpParentConfig(path="/automations", data_selector="automations", inject_as="workflow_id")
+_STORES_PARENT = MailchimpParentConfig(path="/ecommerce/stores", data_selector="stores", inject_as="store_id")
MAILCHIMP_ENDPOINTS: dict[str, MailchimpEndpointConfig] = {
@@ -29,6 +71,7 @@ MAILCHIMP_ENDPOINTS: dict[str, MailchimpEndpointConfig] = {
data_selector="campaigns",
incremental_fields=[],
partition_key="create_time",
+ incremental_params={"create_time": "since_create_time", "send_time": "since_send_time"},
),
"reports": MailchimpEndpointConfig(
name="reports",
@@ -36,6 +79,7 @@ MAILCHIMP_ENDPOINTS: dict[str, MailchimpEndpointConfig] = {
data_selector="reports",
incremental_fields=[],
partition_key="send_time",
+ incremental_params={"send_time": "since_send_time"},
),
"contacts": MailchimpEndpointConfig(
name="contacts",
@@ -43,6 +87,7 @@ MAILCHIMP_ENDPOINTS: dict[str, MailchimpEndpointConfig] = {
data_selector="members",
partition_key=None, # No stable timestamp field available
default_incremental_field="last_changed",
+ primary_keys=["list_id", "id"],
incremental_fields=[
{
"label": "last_changed",
@@ -52,6 +97,285 @@ MAILCHIMP_ENDPOINTS: dict[str, MailchimpEndpointConfig] = {
},
],
),
+ # --- Account-level collections ---
+ "automations": MailchimpEndpointConfig(
+ name="automations",
+ path="/automations",
+ data_selector="automations",
+ partition_key="create_time",
+ default_incremental_field="create_time",
+ incremental_params={"create_time": "since_create_time", "start_time": "since_start_time"},
+ incremental_fields=[
+ {
+ "label": "create_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "create_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "start_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "start_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "templates": MailchimpEndpointConfig(
+ name="templates",
+ path="/templates",
+ data_selector="templates",
+ partition_key="date_created",
+ default_incremental_field="date_created",
+ incremental_params={"date_created": "since_date_created"},
+ incremental_fields=[
+ {
+ "label": "date_created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date_created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "sms_campaigns": MailchimpEndpointConfig(
+ name="sms_campaigns",
+ path="/sms-campaigns",
+ data_selector="sms_campaigns",
+ incremental_fields=[],
+ partition_key="create_time",
+ ),
+ "conversations": MailchimpEndpointConfig(
+ name="conversations",
+ path="/conversations",
+ data_selector="conversations",
+ incremental_fields=[],
+ ),
+ "campaign_folders": MailchimpEndpointConfig(
+ name="campaign_folders",
+ path="/campaign-folders",
+ data_selector="folders",
+ incremental_fields=[],
+ ),
+ "ecommerce_stores": MailchimpEndpointConfig(
+ name="ecommerce_stores",
+ path="/ecommerce/stores",
+ data_selector="stores",
+ incremental_fields=[],
+ partition_key="created_at",
+ ),
+ "ecommerce_orders": MailchimpEndpointConfig(
+ name="ecommerce_orders",
+ path="/ecommerce/orders",
+ data_selector="orders",
+ incremental_fields=[],
+ # Order ids come from the connected store, so they are only unique within a store.
+ primary_keys=["store_id", "id"],
+ partition_key="processed_at_foreign",
+ ),
+ "landing_pages": MailchimpEndpointConfig(
+ name="landing_pages",
+ path="/landing-pages",
+ data_selector="landing_pages",
+ incremental_fields=[],
+ pagination="count_only", # the endpoint accepts `count` but has no `offset`
+ partition_key="created_at",
+ ),
+ "verified_domains": MailchimpEndpointConfig(
+ name="verified_domains",
+ path="/verified-domains",
+ data_selector="domains",
+ incremental_fields=[],
+ pagination="none",
+ primary_keys=["domain"],
+ ),
+ # --- Audience (list) fan-out ---
+ "list_segments": MailchimpEndpointConfig(
+ name="list_segments",
+ path="/lists/{list_id}/segments",
+ data_selector="segments",
+ parents=(_LISTS_PARENT,),
+ primary_keys=["list_id", "id"],
+ partition_key="created_at",
+ default_incremental_field="updated_at",
+ incremental_params={"created_at": "since_created_at", "updated_at": "since_updated_at"},
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "list_segment_members": MailchimpEndpointConfig(
+ name="list_segment_members",
+ path="/lists/{list_id}/segments/{segment_id}/members",
+ data_selector="members",
+ parents=(
+ _LISTS_PARENT,
+ MailchimpParentConfig(path="/lists/{list_id}/segments", data_selector="segments", inject_as="segment_id"),
+ ),
+ incremental_fields=[],
+ primary_keys=["list_id", "segment_id", "id"],
+ ),
+ "list_merge_fields": MailchimpEndpointConfig(
+ name="list_merge_fields",
+ path="/lists/{list_id}/merge-fields",
+ data_selector="merge_fields",
+ parents=(_LISTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["list_id", "merge_id"],
+ ),
+ "list_interest_categories": MailchimpEndpointConfig(
+ name="list_interest_categories",
+ path="/lists/{list_id}/interest-categories",
+ data_selector="categories",
+ parents=(_LISTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["list_id", "id"],
+ ),
+ "list_growth_history": MailchimpEndpointConfig(
+ name="list_growth_history",
+ path="/lists/{list_id}/growth-history",
+ data_selector="history",
+ parents=(_LISTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["list_id", "month"],
+ ),
+ "list_activity": MailchimpEndpointConfig(
+ name="list_activity",
+ path="/lists/{list_id}/activity",
+ data_selector="activity",
+ parents=(_LISTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["list_id", "day"],
+ ),
+ # --- Campaign fan-out ---
+ "campaign_content": MailchimpEndpointConfig(
+ name="campaign_content",
+ path="/campaigns/{campaign_id}/content",
+ data_selector="", # single object response
+ parents=(_CAMPAIGNS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id"],
+ pagination="none",
+ single_object=True,
+ # Rendered HTML makes these rows far larger than a typical API row, so batch fewer of them.
+ chunk_size=200,
+ chunk_size_bytes=50 * 1024 * 1024,
+ ),
+ "campaign_feedback": MailchimpEndpointConfig(
+ name="campaign_feedback",
+ path="/campaigns/{campaign_id}/feedback",
+ data_selector="feedback",
+ parents=(_CAMPAIGNS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "feedback_id"],
+ pagination="none",
+ partition_key="created_at",
+ ),
+ # --- Report fan-out (per-recipient engagement) ---
+ "report_email_activity": MailchimpEndpointConfig(
+ name="report_email_activity",
+ path="/reports/{campaign_id}/email-activity",
+ data_selector="emails",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "email_id"],
+ ),
+ "report_open_details": MailchimpEndpointConfig(
+ name="report_open_details",
+ path="/reports/{campaign_id}/open-details",
+ data_selector="members",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "email_id"],
+ ),
+ "report_click_details": MailchimpEndpointConfig(
+ name="report_click_details",
+ path="/reports/{campaign_id}/click-details",
+ data_selector="urls_clicked",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "id"],
+ ),
+ "report_sent_to": MailchimpEndpointConfig(
+ name="report_sent_to",
+ path="/reports/{campaign_id}/sent-to",
+ data_selector="sent_to",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "email_id"],
+ ),
+ "report_unsubscribed": MailchimpEndpointConfig(
+ name="report_unsubscribed",
+ path="/reports/{campaign_id}/unsubscribed",
+ data_selector="unsubscribes",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "email_id"],
+ partition_key="timestamp",
+ ),
+ "report_abuse_reports": MailchimpEndpointConfig(
+ name="report_abuse_reports",
+ path="/reports/{campaign_id}/abuse-reports",
+ data_selector="abuse_reports",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "id"],
+ pagination="none",
+ partition_key="date",
+ ),
+ "report_domain_performance": MailchimpEndpointConfig(
+ name="report_domain_performance",
+ path="/reports/{campaign_id}/domain-performance",
+ data_selector="domains",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "domain"],
+ pagination="none",
+ ),
+ "report_locations": MailchimpEndpointConfig(
+ name="report_locations",
+ path="/reports/{campaign_id}/locations",
+ data_selector="locations",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "country_code", "region"],
+ ),
+ "report_ecommerce_product_activity": MailchimpEndpointConfig(
+ name="report_ecommerce_product_activity",
+ path="/reports/{campaign_id}/ecommerce-product-activity",
+ data_selector="products",
+ parents=(_REPORTS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["campaign_id", "title", "sku"],
+ ),
+ # --- Automation fan-out ---
+ "automation_emails": MailchimpEndpointConfig(
+ name="automation_emails",
+ path="/automations/{workflow_id}/emails",
+ data_selector="emails",
+ parents=(_AUTOMATIONS_PARENT,),
+ incremental_fields=[],
+ primary_keys=["workflow_id", "id"],
+ pagination="none",
+ partition_key="create_time",
+ ),
+ # --- Ecommerce store fan-out ---
+ "ecommerce_products": MailchimpEndpointConfig(
+ name="ecommerce_products",
+ path="/ecommerce/stores/{store_id}/products",
+ data_selector="products",
+ parents=(_STORES_PARENT,),
+ incremental_fields=[],
+ primary_keys=["store_id", "id"],
+ ),
}
ENDPOINTS = tuple(MAILCHIMP_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.py
index 7631124dd6bb..de8531c76807 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/tests/test_mailchimp.py
@@ -1,3 +1,4 @@
+import re
import json
from collections.abc import Iterable
from datetime import date, datetime
@@ -16,10 +17,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailchimp.
_fetch_contacts_for_list,
_format_incremental_value,
_get_contacts_iterator,
+ _get_endpoint_iterator,
+ _incremental_query_params,
extract_data_center,
mailchimp_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailchimp.settings import MAILCHIMP_ENDPOINTS
class TestExtractDataCenter:
@@ -412,8 +416,10 @@ class TestRestEndpointResumeBehavior:
sent_params.append(dict(request.params))
return next(response_iter)
+ # The REST path builds its own capture-disabled session in mailchimp_source and passes it
+ # into the config, so patch it at that origin rather than inside rest_client.
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailchimp.mailchimp.make_tracked_session"
) as MockSession:
mock_session = MockSession.return_value
mock_session.headers = {}
@@ -503,3 +509,342 @@ class TestRestEndpointResumeBehavior:
reconstituted = MailchimpResumeConfig(**json.loads(as_json))
assert reconstituted == cfg
assert reconstituted.list_id is None
+
+
+def _routed_session(routes: dict[str, list[dict[str, Any]]]) -> tuple[Any, list[tuple[str, dict[str, Any]]]]:
+ """Session double serving canned JSON bodies keyed by API path, recording every call.
+
+ A path may map to several bodies; the nth request to it gets the nth body, and the last
+ body repeats once they run out.
+ """
+ calls: list[tuple[str, dict[str, Any]]] = []
+ seen: dict[str, int] = {}
+
+ def get(url: str, params: dict[str, Any] | None = None, timeout: int | None = None) -> MagicMock:
+ path = url.split("/3.0", 1)[1]
+ calls.append((path, dict(params or {})))
+
+ bodies = routes[path]
+ index = min(seen.get(path, 0), len(bodies) - 1)
+ seen[path] = seen.get(path, 0) + 1
+
+ response = MagicMock()
+ response.json.return_value = bodies[index]
+ response.raise_for_status.return_value = None
+ return response
+
+ session = MagicMock()
+ session.get.side_effect = get
+ return session, calls
+
+
+def _patch_session(monkeypatch, session: Any) -> None:
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailchimp.mailchimp._mailchimp_session",
+ lambda *a, **k: session,
+ )
+
+
+class TestEndpointConfigInvariants:
+ @pytest.mark.parametrize("name", sorted(MAILCHIMP_ENDPOINTS))
+ def test_fan_out_path_placeholders_match_declared_parents(self, name: str) -> None:
+ # A placeholder with no matching parent raises KeyError at str.format() time — mid-sync,
+ # on that endpoint only. `contacts` is exempt: it formats its path in its own iterator.
+ config = MAILCHIMP_ENDPOINTS[name]
+ if name == "contacts":
+ return
+
+ placeholders = set(re.findall(r"\{(\w+)\}", config.path))
+ assert placeholders == {parent.inject_as for parent in config.parents}
+
+ @pytest.mark.parametrize("name", sorted(MAILCHIMP_ENDPOINTS))
+ def test_fan_out_primary_keys_include_every_parent_id(self, name: str) -> None:
+ # Child rows are pooled from every parent, so a key without the parent id is not unique
+ # table-wide and every later merge multi-matches the duplicates.
+ config = MAILCHIMP_ENDPOINTS[name]
+ for parent in config.parents:
+ assert parent.inject_as in config.primary_keys
+
+
+class TestIncrementalQueryParams:
+ @pytest.mark.parametrize(
+ ("endpoint", "field", "expected"),
+ [
+ # Guards the params the pre-existing endpoints have always sent.
+ ("campaigns", "create_time", {"since_create_time": "2024-01-02T03:04:05+00:00"}),
+ ("campaigns", "send_time", {"since_send_time": "2024-01-02T03:04:05+00:00"}),
+ ("reports", "send_time", {"since_send_time": "2024-01-02T03:04:05+00:00"}),
+ ("reports", "create_time", {}),
+ ("lists", None, {}),
+ ("automations", "create_time", {"since_create_time": "2024-01-02T03:04:05+00:00"}),
+ ("automations", "start_time", {"since_start_time": "2024-01-02T03:04:05+00:00"}),
+ ("templates", "date_created", {"since_date_created": "2024-01-02T03:04:05+00:00"}),
+ ("list_segments", "updated_at", {"since_updated_at": "2024-01-02T03:04:05+00:00"}),
+ ("list_segments", "created_at", {"since_created_at": "2024-01-02T03:04:05+00:00"}),
+ # No server-side filter available, so the endpoint stays on full refresh.
+ ("ecommerce_orders", "processed_at_foreign", {}),
+ ],
+ )
+ def test_field_maps_to_vendor_filter(self, endpoint: str, field: str | None, expected: dict[str, str]) -> None:
+ assert (
+ _incremental_query_params(
+ MAILCHIMP_ENDPOINTS[endpoint],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5),
+ incremental_field=field,
+ )
+ == expected
+ )
+
+ def test_no_filter_sent_when_incremental_is_off(self) -> None:
+ assert (
+ _incremental_query_params(
+ MAILCHIMP_ENDPOINTS["automations"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5),
+ incremental_field="create_time",
+ )
+ == {}
+ )
+
+
+class TestGenericEndpointIterator:
+ @pytest.mark.parametrize(
+ ("endpoint", "routes", "expected_paths", "expected_params"),
+ [
+ (
+ # count/offset endpoint: both params sent.
+ "list_activity",
+ {
+ "/lists": [{"lists": [{"id": "l1"}], "total_items": 1}],
+ "/lists/l1/activity": [{"activity": [{"day": "2024-01-01"}], "total_items": 1}],
+ },
+ ["/lists", "/lists/l1/activity"],
+ {"count": 1000, "offset": 0},
+ ),
+ (
+ # `count` is accepted but `offset` is not — sending it risks a 400.
+ "landing_pages",
+ {"/landing-pages": [{"landing_pages": [{"id": "p1"}], "total_items": 1}]},
+ ["/landing-pages"],
+ {"count": 1000},
+ ),
+ (
+ # No pagination params at all on this endpoint.
+ "verified_domains",
+ {"/verified-domains": [{"domains": [{"domain": "example.com"}], "total_items": 1}]},
+ ["/verified-domains"],
+ {},
+ ),
+ ],
+ )
+ def test_only_supported_pagination_params_are_sent(
+ self,
+ monkeypatch,
+ endpoint: str,
+ routes: dict[str, list[dict[str, Any]]],
+ expected_paths: list[str],
+ expected_params: dict[str, Any],
+ ) -> None:
+ session, calls = _routed_session(routes)
+ _patch_session(monkeypatch, session)
+
+ rows = list(_get_endpoint_iterator("key-us6", MAILCHIMP_ENDPOINTS[endpoint], _fake_manager()))
+
+ assert [path for path, _ in calls] == expected_paths
+ assert calls[-1][1] == expected_params
+ assert len(rows) == 1
+
+ def test_fan_out_injects_parent_id_onto_rows_the_api_omits(self, monkeypatch) -> None:
+ # /reports/{id}/locations rows carry no campaign_id, so without injection the
+ # primary key would collapse every campaign's regions onto each other.
+ session, calls = _routed_session(
+ {
+ "/reports": [{"reports": [{"id": "c1"}, {"id": "c2"}], "total_items": 2}],
+ "/reports/c1/locations": [{"locations": [{"country_code": "US", "region": "CA"}], "total_items": 1}],
+ "/reports/c2/locations": [{"locations": [{"country_code": "GB", "region": ""}], "total_items": 1}],
+ }
+ )
+ _patch_session(monkeypatch, session)
+
+ rows = list(_get_endpoint_iterator("key-us6", MAILCHIMP_ENDPOINTS["report_locations"], _fake_manager()))
+
+ assert rows == [
+ {"campaign_id": "c1", "country_code": "US", "region": "CA"},
+ {"campaign_id": "c2", "country_code": "GB", "region": ""},
+ ]
+ assert [path for path, _ in calls] == ["/reports", "/reports/c1/locations", "/reports/c2/locations"]
+
+ def test_two_level_fan_out_resolves_both_parents(self, monkeypatch) -> None:
+ session, calls = _routed_session(
+ {
+ "/lists": [{"lists": [{"id": "l1"}], "total_items": 1}],
+ "/lists/l1/segments": [{"segments": [{"id": 7}, {"id": 8}], "total_items": 2}],
+ "/lists/l1/segments/7/members": [{"members": [{"id": "m1"}], "total_items": 1}],
+ "/lists/l1/segments/8/members": [{"members": [{"id": "m2"}], "total_items": 1}],
+ }
+ )
+ _patch_session(monkeypatch, session)
+
+ rows = list(_get_endpoint_iterator("key-us6", MAILCHIMP_ENDPOINTS["list_segment_members"], _fake_manager()))
+
+ assert rows == [
+ {"id": "m1", "list_id": "l1", "segment_id": "7"},
+ {"id": "m2", "list_id": "l1", "segment_id": "8"},
+ ]
+ assert calls[-1][0] == "/lists/l1/segments/8/members"
+
+ def test_single_object_endpoint_yields_one_row_per_parent(self, monkeypatch) -> None:
+ session, _ = _routed_session(
+ {
+ "/campaigns": [{"campaigns": [{"id": "c1"}], "total_items": 1}],
+ "/campaigns/c1/content": [{"html": "<p>hi</p>", "plain_text": "hi"}],
+ }
+ )
+ _patch_session(monkeypatch, session)
+
+ rows = list(_get_endpoint_iterator("key-us6", MAILCHIMP_ENDPOINTS["campaign_content"], _fake_manager()))
+
+ assert rows == [{"campaign_id": "c1", "html": "<p>hi</p>", "plain_text": "hi"}]
+
+ def test_multi_page_child_checkpoints_each_page_against_its_parent(self, monkeypatch) -> None:
+ session, calls = _routed_session(
+ {
+ "/reports": [{"reports": [{"id": "c1"}], "total_items": 1}],
+ "/reports/c1/sent-to": [
+ {"sent_to": [{"email_id": "e1"}], "total_items": 1500},
+ {"sent_to": [{"email_id": "e2"}], "total_items": 1500},
+ ],
+ }
+ )
+ manager = _fake_manager()
+ _patch_session(monkeypatch, session)
+
+ rows = list(_get_endpoint_iterator("key-us6", MAILCHIMP_ENDPOINTS["report_sent_to"], manager))
+
+ assert [row["email_id"] for row in rows] == ["e1", "e2"]
+ assert [params.get("offset") for path, params in calls if path.endswith("/sent-to")] == [0, 1000]
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ MailchimpResumeConfig(offset=0, parent_ids=["c1"]),
+ MailchimpResumeConfig(offset=1000, parent_ids=["c1"]),
+ ]
+
+ def test_resume_skips_completed_parents_and_seeds_the_saved_offset(self, monkeypatch) -> None:
+ session, calls = _routed_session(
+ {
+ "/reports": [{"reports": [{"id": "c1"}, {"id": "c2"}], "total_items": 2}],
+ "/reports/c2/sent-to": [{"sent_to": [{"email_id": "e9"}], "total_items": 1001}],
+ }
+ )
+ _patch_session(monkeypatch, session)
+
+ rows = list(
+ _get_endpoint_iterator(
+ "key-us6",
+ MAILCHIMP_ENDPOINTS["report_sent_to"],
+ _fake_manager(can_resume=True, load_state=MailchimpResumeConfig(offset=1000, parent_ids=["c2"])),
+ )
+ )
+
+ assert [row["email_id"] for row in rows] == ["e9"]
+ assert [path for path, _ in calls] == ["/reports", "/reports/c2/sent-to"]
+ assert calls[-1][1]["offset"] == 1000
+
+ def test_checkpoint_for_a_vanished_parent_falls_back_to_a_fresh_run(self, monkeypatch) -> None:
+ # Honouring a checkpoint whose campaign no longer exists would skip every parent and
+ # sync nothing at all.
+ session, calls = _routed_session(
+ {
+ "/reports": [{"reports": [{"id": "c1"}], "total_items": 1}],
+ "/reports/c1/sent-to": [{"sent_to": [{"email_id": "e1"}], "total_items": 1}],
+ }
+ )
+ _patch_session(monkeypatch, session)
+
+ rows = list(
+ _get_endpoint_iterator(
+ "key-us6",
+ MAILCHIMP_ENDPOINTS["report_sent_to"],
+ _fake_manager(can_resume=True, load_state=MailchimpResumeConfig(offset=2000, parent_ids=["deleted"])),
+ )
+ )
+
+ assert [row["email_id"] for row in rows] == ["e1"]
+ assert calls[-1][1]["offset"] == 0
+
+ def test_incremental_filter_is_forwarded_to_the_child_request(self, monkeypatch) -> None:
+ session, calls = _routed_session(
+ {
+ "/lists": [{"lists": [{"id": "l1"}], "total_items": 1}],
+ "/lists/l1/segments": [{"segments": [{"id": 1}], "total_items": 1}],
+ }
+ )
+ _patch_session(monkeypatch, session)
+
+ list(
+ _get_endpoint_iterator(
+ "key-us6",
+ MAILCHIMP_ENDPOINTS["list_segments"],
+ _fake_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 5, 6, 7, 8, 9),
+ incremental_field="updated_at",
+ )
+ )
+
+ # The parent listing must stay unfiltered, or new segments on old audiences go missing.
+ assert calls[0] == ("/lists", {"count": 1000, "offset": 0})
+ assert calls[1][1]["since_updated_at"] == "2024-05-06T07:08:09+00:00"
+
+
+class TestSourceResponseForNewEndpoints:
+ def test_fan_out_endpoint_is_routed_away_from_the_rest_path(self, monkeypatch) -> None:
+ # Routing a fan-out endpoint through rest_api_resource would request the literal
+ # unformatted `/reports/{campaign_id}/locations` and 404.
+ session, calls = _routed_session(
+ {
+ "/reports": [{"reports": [{"id": "c1"}], "total_items": 1}],
+ "/reports/c1/locations": [{"locations": [{"country_code": "US", "region": ""}], "total_items": 1}],
+ }
+ )
+ _patch_session(monkeypatch, session)
+
+ response = mailchimp_source(
+ api_key="key-us6",
+ endpoint="report_locations",
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_fake_manager(),
+ )
+ rows = list(cast(Iterable[Any], response.items()))
+
+ assert response.primary_keys == ["campaign_id", "country_code", "region"]
+ assert rows == [{"campaign_id": "c1", "country_code": "US", "region": ""}]
+ assert [path for path, _ in calls] == ["/reports", "/reports/c1/locations"]
+
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_primary_keys", "expected_partition_keys"),
+ [
+ ("lists", ["id"], ["date_created"]),
+ ("contacts", ["list_id", "id"], None),
+ ("ecommerce_orders", ["store_id", "id"], ["processed_at_foreign"]),
+ ("verified_domains", ["domain"], None),
+ ("report_unsubscribed", ["campaign_id", "email_id"], ["timestamp"]),
+ ],
+ )
+ def test_primary_and_partition_keys_come_from_the_endpoint_config(
+ self,
+ endpoint: str,
+ expected_primary_keys: list[str],
+ expected_partition_keys: list[str] | None,
+ ) -> None:
+ response = mailchimp_source(
+ api_key="key-us6",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_fake_manager(),
+ )
+
+ assert response.primary_keys == expected_primary_keys
+ assert response.partition_keys == expected_partition_keys