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 24 tables to the Klaviyo source (#73853)

Tom Owersbaf9f71075ac
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/klaviyo.py
index 83ef5e1a1b94..c6b8d06683cb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/klaviyo.py
@@ -7,3 +7,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class KlaviyoSourceConfig(config.Config):
api_key: str
+ conversion_metric_id: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py
index 2eea5313a84f..d173042242bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py
@@ -27,6 +27,60 @@ _CAMPAIGN_COLUMNS = {
"send_time": "Time at which the campaign was sent.",
}
+_CATALOG_SHARED_COLUMNS = {
+ "external_id": "The ID of the record in the external system the catalog is fed from.",
+ "title": "The title of the record.",
+ "description": "A description of the record.",
+ "price": "The price displayed for the record in feeds and blocks.",
+ "url": "URL pointing to the location of the record on your website.",
+ "image_full_url": "URL pointing to a full image of the record.",
+ "image_thumbnail_url": "URL pointing to an image thumbnail of the record.",
+ "images": "List of URLs pointing to images of the record.",
+ "custom_metadata": "Flat JSON blob of custom metadata about the record.",
+ "published": "Whether the record is published.",
+ "created": "Date and time when the record was created.",
+ "updated": "Date and time when the record was last updated.",
+}
+
+# Both values reports return the same statistics; only the grouping columns differ. Rate statistics
+# come back as fractions between 0 and 1.
+_VALUES_REPORT_STATISTIC_COLUMNS = {
+ "timeframe_key": "The Klaviyo timeframe the statistics were computed over.",
+ "conversion_metric_id": "ID of the metric conversion statistics were attributed to.",
+ "send_channel": "The channel the message was sent through (email, sms, push-notification, or whatsapp).",
+ "average_order_value": "Average value of the orders attributed to the message.",
+ "bounce_rate": "Share of delivered attempts that bounced.",
+ "bounced": "Number of messages that bounced.",
+ "bounced_or_failed": "Number of messages that bounced or failed to send.",
+ "bounced_or_failed_rate": "Share of messages that bounced or failed to send.",
+ "click_rate": "Share of delivered messages that were clicked.",
+ "click_to_open_rate": "Share of opened messages that were clicked.",
+ "clicks": "Total number of clicks.",
+ "clicks_unique": "Number of recipients who clicked at least once.",
+ "conversion_rate": "Share of recipients who completed the conversion metric.",
+ "conversion_uniques": "Number of recipients who completed the conversion metric.",
+ "conversion_value": "Total value of the conversions attributed to the message.",
+ "conversions": "Number of times the conversion metric was completed.",
+ "delivered": "Number of messages delivered.",
+ "delivery_rate": "Share of messages that were delivered.",
+ "failed": "Number of messages that failed to send.",
+ "failed_rate": "Share of messages that failed to send.",
+ "message_segment_count_sum": "Total number of SMS segments the messages were split into.",
+ "open_rate": "Share of delivered messages that were opened.",
+ "opens": "Total number of opens.",
+ "opens_unique": "Number of recipients who opened at least once.",
+ "recipients": "Number of recipients the message was sent to.",
+ "revenue_per_recipient": "Conversion value divided by the number of recipients.",
+ "spam_complaint_rate": "Share of delivered messages marked as spam.",
+ "spam_complaints": "Number of messages marked as spam.",
+ "text_message_credit_usage_amount": "SMS credits consumed by the messages.",
+ "text_message_roi": "Return on investment for the SMS spend.",
+ "text_message_spend": "Amount spent sending the SMS messages.",
+ "unsubscribe_rate": "Share of recipients who unsubscribed.",
+ "unsubscribe_uniques": "Number of recipients who unsubscribed.",
+ "unsubscribes": "Total number of unsubscribes.",
+}
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"email_campaigns": {
"description": "An email marketing campaign in Klaviyo sent to a target audience.",
@@ -132,4 +186,304 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
),
},
},
+ "segments": {
+ "description": "A segment in Klaviyo: a dynamic group of profiles that matches a set of conditions.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_segments",
+ "columns": {
+ "id": "Unique identifier for the segment.",
+ "name": "The segment's name.",
+ "definition": "The condition groups that determine which profiles belong to the segment.",
+ "is_active": "Whether the segment is active and being evaluated.",
+ "is_processing": "Whether Klaviyo is currently recalculating the segment's membership.",
+ "is_starred": "Whether the segment is starred in the Klaviyo UI.",
+ "created": "Time at which the segment was created.",
+ "updated": "Time at which the segment was last updated.",
+ },
+ },
+ "segment_profiles": {
+ "description": (
+ "A flat join table mapping which profiles belong to which Klaviyo segment. Segment membership is "
+ "recalculated by Klaviyo, so profiles that stop matching are only removed on a full refresh."
+ ),
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_segment_profiles",
+ "columns": {
+ "segment_id": "Identifier of the segment.",
+ "profile_id": "Identifier of a profile that is a member of the segment.",
+ "joined_group_at": "The datetime when the profile most recently joined the segment.",
+ },
+ },
+ "flow_actions": {
+ "description": "A step in a Klaviyo flow, such as sending a message, waiting, or branching on a condition.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_flow_flow_actions",
+ "columns": {
+ "id": "Unique identifier for the flow action.",
+ "flow_id": "Identifier of the flow this action belongs to.",
+ "definition": (
+ "The encoded definition of what the action does. Its `type` holds the action type and its "
+ "`data` holds the action's configuration, including the action's status and, for send steps, "
+ "the message."
+ ),
+ "created": "Time at which the action was created.",
+ "updated": "Time at which the action was last updated.",
+ },
+ },
+ "flow_messages": {
+ "description": "A message sent by a Klaviyo flow step, holding the content the step delivers.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_flow_action_messages",
+ "columns": {
+ "id": "Unique identifier for the flow message.",
+ "flow_action_id": "Identifier of the flow action that sends this message.",
+ "flow_id": "Identifier of the flow the sending action belongs to.",
+ "channel": "The channel the message is sent through (email, sms, or push-notification).",
+ "definition": (
+ "The encoded definition of the message, holding its name, subject line, sender details, "
+ "template, and body."
+ ),
+ "created": "Time at which the message was created.",
+ "updated": "Time at which the message was last updated.",
+ },
+ },
+ "campaign_values_reports": {
+ "description": (
+ "Klaviyo's own computed performance statistics for each campaign message over the last 365 days. "
+ "Replaced in full on every sync, so it is a snapshot rather than a history."
+ ),
+ "docs_url": "https://developers.klaviyo.com/en/reference/query_campaign_values",
+ "columns": {
+ "campaign_id": "Identifier of the campaign the statistics belong to.",
+ "campaign_message_id": "Identifier of the campaign message the statistics belong to.",
+ **_VALUES_REPORT_STATISTIC_COLUMNS,
+ },
+ },
+ "flow_values_reports": {
+ "description": (
+ "Klaviyo's own computed performance statistics for each flow message over the last 365 days. "
+ "Replaced in full on every sync, so it is a snapshot rather than a history."
+ ),
+ "docs_url": "https://developers.klaviyo.com/en/reference/query_flow_values",
+ "columns": {
+ "flow_id": "Identifier of the flow the statistics belong to.",
+ "flow_message_id": "Identifier of the flow message the statistics belong to.",
+ **_VALUES_REPORT_STATISTIC_COLUMNS,
+ },
+ },
+ "templates": {
+ "description": "A reusable email template in Klaviyo that campaigns and flow messages render from.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_templates",
+ "columns": {
+ "id": "Unique identifier for the template.",
+ "name": "The template's name.",
+ "editor_type": (
+ "Which editor built the template: SYSTEM_DRAGGABLE (drag and drop), SIMPLE (rich text), "
+ "CODE (custom HTML), or USER_DRAGGABLE (custom HTML in the drag and drop editor)."
+ ),
+ "html": "The rendered HTML of the template.",
+ "text": "The plain text version of the template.",
+ "amp": "The AMP version of the template, when AMP email is enabled.",
+ "definition": "The structured definition of the template body and styles.",
+ "created": "Time at which the template was created.",
+ "updated": "Time at which the template was last updated.",
+ },
+ },
+ "forms": {
+ "description": "A signup form in Klaviyo that collects profiles from your site.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_forms",
+ "columns": {
+ "id": "Unique identifier for the form.",
+ "name": "The form's name.",
+ "status": "Current status of the form (e.g. draft, live).",
+ "ab_test": "Whether the form is running an A/B test.",
+ "created_at": "Time at which the form was created.",
+ "updated_at": "Time at which the form was last updated.",
+ },
+ },
+ "reviews": {
+ "description": "A product review collected by Klaviyo Reviews.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_reviews",
+ "columns": {
+ "id": "Unique identifier for the review.",
+ "email": "Email address of the reviewer.",
+ "author": "Display name of the reviewer.",
+ "title": "The review's title.",
+ "content": "The body of the review.",
+ "rating": "The star rating the reviewer gave, from 1 to 5.",
+ "status": "Moderation status of the review, holding its `value` and any rejection reason.",
+ "review_type": "Whether the review is about a product or the store overall.",
+ "verified": "Whether the review comes from a verified buyer.",
+ "images": "Images the reviewer attached.",
+ "product": "The catalog product the review is about.",
+ "public_reply": "The store's public reply to the review, if any.",
+ "smart_quote": "A short highlighted excerpt Klaviyo picked out of the review.",
+ "created": "Time at which the review was submitted.",
+ "updated": "Time at which the review was last updated.",
+ },
+ },
+ "catalog_items": {
+ "description": "A product in your Klaviyo catalog, used for product feeds, blocks, and attribution.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_catalog_items",
+ "columns": {"id": "Unique identifier for the catalog item.", **_CATALOG_SHARED_COLUMNS},
+ },
+ "catalog_variants": {
+ "description": "A variant of a catalog item, such as a specific size or color.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_catalog_variants",
+ "columns": {
+ "id": "Unique identifier for the catalog variant.",
+ "sku": "The SKU of the variant.",
+ "inventory_policy": "Whether the variant stays visible in feeds and blocks when out of stock.",
+ "inventory_quantity": "The quantity of the variant currently in stock.",
+ **_CATALOG_SHARED_COLUMNS,
+ },
+ },
+ "catalog_categories": {
+ "description": "A category that groups catalog items together.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_catalog_categories",
+ "columns": {
+ "id": "Unique identifier for the catalog category.",
+ "external_id": "The ID of the category in the external system the catalog is fed from.",
+ "name": "The name of the category.",
+ "updated": "Date and time when the category was last updated.",
+ },
+ },
+ "coupons": {
+ "description": "A coupon in Klaviyo that unique codes are issued from.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_coupons",
+ "columns": {
+ "id": "Unique identifier for the coupon.",
+ "external_id": "The ID of the coupon in the ecommerce platform it came from.",
+ "description": "A description of the coupon.",
+ "monitor_configuration": "How Klaviyo monitors the coupon's code pool.",
+ },
+ },
+ "coupon_codes": {
+ "description": "A unique coupon code assigned to a profile.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_coupon_codes",
+ "columns": {
+ "id": "Unique identifier for the coupon code.",
+ "unique_code": "The code assigned to the profile.",
+ "expires_at": "The datetime when the code expires.",
+ "status": "Current status of the code (e.g. unassigned, assigned_to_profile, used).",
+ },
+ },
+ "tags": {
+ "description": "A tag used to organize Klaviyo campaigns, flows, lists, and segments.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_tags",
+ "columns": {
+ "id": "Unique identifier for the tag.",
+ "name": "The tag's name.",
+ },
+ },
+ "tag_groups": {
+ "description": "A group that the tags in your account belong to.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_tag_groups",
+ "columns": {
+ "id": "Unique identifier for the tag group.",
+ "name": "The tag group's name.",
+ "exclusive": "Whether a resource can carry only one tag from this group.",
+ "default": "Whether this is the account's default tag group.",
+ },
+ },
+ "custom_metrics": {
+ "description": "A custom metric in Klaviyo, defined by combining and filtering other metrics.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_custom_metrics",
+ "columns": {
+ "id": "Unique identifier for the custom metric.",
+ "name": "The custom metric's name, unique across the account.",
+ "definition": "The definition that computes the custom metric.",
+ "created": "Time at which the custom metric was created.",
+ "updated": "Time at which the custom metric was last updated.",
+ },
+ },
+ "data_sources": {
+ "description": "A source that feeds custom object data into Klaviyo.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_data_sources",
+ "columns": {
+ "id": "Unique identifier for the data source.",
+ "title": "The data source's title.",
+ "description": "A description of the data source.",
+ "namespace": "The namespace the data source writes into.",
+ "visibility": "The status of the data source.",
+ },
+ },
+ "object_types": {
+ "description": "A custom object type defined in Klaviyo, describing the shape of records you send it.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_object_types",
+ "columns": {
+ "id": "Unique identifier for the object type.",
+ "title": "The object type's title.",
+ "description": "A description of the object type.",
+ "status": "The status of the schema associated with the object type.",
+ "namespace": "The namespace the object type belongs to.",
+ "created_at": "Time at which the object type was created.",
+ "updated_at": "Time at which the object type was last updated.",
+ },
+ },
+ "push_tokens": {
+ "description": "A push notification token registered against a profile's device.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_push_tokens",
+ "columns": {
+ "id": "Unique identifier for the push token.",
+ "token": "The push token itself.",
+ "enablement_status": "Whether the device currently accepts push notifications.",
+ "platform": "The device platform (ios or android).",
+ "vendor": "The push vendor the token belongs to (APNs or FCM).",
+ "background": "The background state of the token.",
+ "recorded_date": "The date the token was recorded.",
+ "metadata": "Device metadata Klaviyo captured with the token.",
+ "created": "Time at which the token was created.",
+ },
+ },
+ "images": {
+ "description": "An image uploaded to your Klaviyo image library.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_images",
+ "columns": {
+ "id": "Unique identifier for the image.",
+ "name": "The image's name.",
+ "image_url": "URL the image is served from.",
+ "format": "The image's file format.",
+ "size": "The image's size in bytes.",
+ "hidden": "Whether the image is hidden in the Klaviyo UI.",
+ "updated_at": "Time at which the image was last updated.",
+ },
+ },
+ "web_feeds": {
+ "description": "A web feed Klaviyo fetches to render dynamic content in messages.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_web_feeds",
+ "columns": {
+ "id": "Unique identifier for the web feed.",
+ "name": "The web feed's name.",
+ "url": "The URL the feed is fetched from.",
+ "request_method": "The HTTP method used to fetch the feed.",
+ "content_type": "The content type of the feed.",
+ "status": "The cache status of the feed.",
+ "created": "Time at which the web feed was created.",
+ "updated": "Time at which the web feed was last updated.",
+ },
+ },
+ "webhooks": {
+ "description": "A webhook Klaviyo posts events to.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_webhooks",
+ "columns": {
+ "id": "Unique identifier for the webhook.",
+ "name": "The webhook's name.",
+ "description": "A description of the webhook.",
+ "endpoint_url": "The URL Klaviyo posts to, truncated for security.",
+ "enabled": "Whether the webhook is enabled.",
+ "created_at": "Time at which the webhook was created.",
+ "updated_at": "Time at which the webhook was last updated.",
+ },
+ },
+ "accounts": {
+ "description": "Your Klaviyo account's settings, including its timezone and preferred currency.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_accounts",
+ "columns": {
+ "id": "Unique identifier for the account, which is its public API key.",
+ "test_account": "Whether the account is marked as a test account.",
+ "contact_information": "The contact details shown in the footer of the account's messages.",
+ "industry": "The kind of business the account is for.",
+ "timezone": "The IANA timezone dates and times are displayed in.",
+ "preferred_currency": "The currency used for the account's currency-based metrics.",
+ "public_api_key": "The public API key used for client-side calls.",
+ "locale": "The account's region and language.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
index 950b70659a4b..257cde31fa44 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
@@ -17,10 +17,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.co
from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.settings import (
KLAVIYO_ENDPOINTS,
KlaviyoEndpointConfig,
+ KlaviyoFanOutConfig,
)
KLAVIYO_BASE_URL = "https://a.klaviyo.com/api"
+# Klaviyo's reporting API requires a conversion metric on every values report. Placed Order is the
+# metric its own reporting defaults to, so it's the fallback when the source doesn't name one.
+DEFAULT_CONVERSION_METRIC_NAME = "Placed Order"
+# Accounts have tens of metrics, so the fallback lookup stays bounded rather than walking forever.
+MAX_CONVERSION_METRIC_PAGES = 20
+
class KlaviyoRetryableError(Exception):
pass
@@ -28,12 +35,14 @@ class KlaviyoRetryableError(Exception):
@dataclasses.dataclass
class KlaviyoResumeConfig:
- # Next page URL to fetch. None means "start the list at its first page" — used when the bookmark
- # advances to a fan-out list whose first page URL isn't known until it's built.
+ # Next page URL to fetch. None means "start the parent at its first page" — used when the
+ # bookmark advances to a fan-out parent whose first page URL isn't known until it's built.
next_url: str | None = None
- # The fan-out list currently being processed. A stable list-ID bookmark (not a positional index)
- # so lists added/removed between a crash and the retry can't resume us into the wrong list. None
- # for the standard (non-fan-out) endpoints.
+ # The fan-out parent currently being processed (a list, segment, or flow action, depending on
+ # the endpoint). A stable ID bookmark (not a positional index) so parents added or removed
+ # between a crash and the retry can't resume us into the wrong one. None for the standard
+ # (non-fan-out) endpoints. Named `list_id` because list membership was the first fan-out and
+ # in-flight resume state persisted under that key must keep deserializing.
list_id: str | None = None
@@ -97,7 +106,7 @@ def _build_filter(
) -> str | None:
"""Build Klaviyo filter string from config."""
filter_field = incremental_field or config.default_incremental_field
- incremental_filter = f"greater-than({filter_field},{formatted_value})" if formatted_value else None
+ incremental_filter = f"{config.incremental_operator}({filter_field},{formatted_value})" if formatted_value else None
if config.base_filter and incremental_filter:
return f"and({config.base_filter},{incremental_filter})"
@@ -204,15 +213,23 @@ def _build_initial_params(
reraise=True,
)
def _fetch_page(
- session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger
+ session: requests.Session,
+ page_url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ json_body: dict[str, Any] | None = None,
) -> dict:
- response = session.get(page_url, headers=headers, timeout=60)
+ # Klaviyo's reporting endpoints take their query in a POST body; every other endpoint is a GET.
+ if json_body is None:
+ response = session.get(page_url, headers=headers, timeout=60)
+ else:
+ response = session.post(page_url, headers=headers, json=json_body, timeout=60)
if response.status_code == 429 or response.status_code >= 500:
raise KlaviyoRetryableError(f"Klaviyo API error (retryable): status={response.status_code}, url={page_url}")
if not response.ok:
- # 404 is expected and handled during the list_profiles fan-out (a list deleted mid-sync).
+ # 404 is expected and handled during a fan-out (a parent deleted mid-sync).
log = logger.warning if response.status_code == 404 else logger.error
log(f"Klaviyo API error: status={response.status_code}, body={response.text}, url={page_url}")
response.raise_for_status()
@@ -220,10 +237,15 @@ def _fetch_page(
return response.json()
-def _iter_list_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:
- """Page through /lists and yield each list's id, following the cursor links."""
- # Klaviyo caps the /lists endpoint at a page size of 10 (larger values 400).
- url = _build_url(f"{KLAVIYO_BASE_URL}/lists", {"page[size]": 10})
+def _iter_resource_ids(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ path: str,
+ page_size: int,
+) -> Iterator[str]:
+ """Page through a Klaviyo collection and yield each row's id, following the cursor links."""
+ url = _build_url(f"{KLAVIYO_BASE_URL}{path}", {"page[size]": page_size})
while True:
data = _fetch_page(session, url, headers, logger)
for item in data.get("data", []):
@@ -235,7 +257,57 @@ def _iter_list_ids(session: requests.Session, headers: dict[str, str], logger: F
url = next_url
-def _get_list_profile_rows(
+def _iter_fan_out_parents(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ fan_out: KlaviyoFanOutConfig,
+) -> Iterator[tuple[dict[str, str], str]]:
+ """Yield (ancestor columns, parent id) for every parent the child endpoint fans out over.
+
+ A one-level fan-out walks the parent collection directly and carries no ancestor columns. A
+ two-level fan-out (flows -> flow actions -> flow messages) walks the grandparent first and
+ formats the parent path with each grandparent id, tagging every parent with that id.
+ """
+ if fan_out.grandparent is None:
+ for parent_id in _iter_resource_ids(session, headers, logger, fan_out.parent_path, fan_out.parent_page_size):
+ yield {}, parent_id
+ return
+
+ grandparent = fan_out.grandparent
+ for grandparent_id in _iter_resource_ids(
+ session, headers, logger, grandparent.parent_path, grandparent.parent_page_size
+ ):
+ path = fan_out.parent_path.format(**{grandparent.parent_id_column: grandparent_id})
+ try:
+ for parent_id in _iter_resource_ids(session, headers, logger, path, fan_out.parent_page_size):
+ yield {grandparent.parent_id_column: grandparent_id}, parent_id
+ except requests.HTTPError as exc:
+ # A grandparent deleted between enumeration and this fetch 404s; its children are gone
+ # with it, so skip rather than failing the whole sync.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Klaviyo: {path} not found while enumerating fan-out parents, skipping")
+ else:
+ raise
+
+
+def _fan_out_row(
+ fan_out: KlaviyoFanOutConfig, ancestors: dict[str, str], parent_id: str, item: dict[str, Any]
+) -> dict[str, Any]:
+ if fan_out.membership_rows:
+ return {
+ fan_out.parent_id_column: parent_id,
+ "profile_id": item["id"],
+ "joined_group_at": item.get("attributes", {}).get("joined_group_at"),
+ }
+
+ row = _flatten_item(item)
+ row[fan_out.parent_id_column] = parent_id
+ row.update(ancestors)
+ return row
+
+
+def _get_fan_out_rows(
session: requests.Session,
headers: dict[str, str],
logger: FilteringBoundLogger,
@@ -244,35 +316,43 @@ def _get_list_profile_rows(
config: KlaviyoEndpointConfig,
params: dict[str, Any],
) -> Iterator[Any]:
- """Fan out over every list, materializing membership as {list_id, profile_id, joined_group_at} rows.
+ """Fan out over every parent, tagging each child row with the parent (and grandparent) it came from.
+
+ For membership endpoints this materializes the otherwise-unqueryable many-to-many as flat
+ {<parent>_id, profile_id, joined_group_at} rows; for the rest it yields the flattened child
+ resource plus its ancestor ids.
- `params` carries any incremental filter on `joined_group_at` (minus the config lookback, so joins
- that landed in already-fetched lists mid-run get re-pulled; merge dedupes on the
- [list_id, profile_id] primary key). Klaviyo updates `joined_group_at` on re-join, so re-joins are
- picked up too — but there is no removal timestamp, so profiles removed from a list only disappear
- on a full refresh.
+ `params` carries any incremental filter (minus the config lookback, so rows that changed in an
+ already-fetched parent mid-run get re-pulled; merge dedupes on the primary key). Klaviyo updates
+ `joined_group_at` on re-join, so re-joins are picked up too — but there is no removal timestamp,
+ so profiles removed from a list or segment only disappear on a full refresh.
Fan-out runs report sort_mode="desc" (see klaviyo_source), so the watermark persists only after
- every list completes. A crash + resume can also finalize an under-advanced watermark (the resumed
- attempt's running max only sees post-resume batches) — safe direction, the next run just
+ every parent completes. A crash + resume can also finalize an under-advanced watermark (the
+ resumed attempt's running max only sees post-resume batches) — safe direction, the next run just
re-fetches a wider window that merge dedupes.
"""
- list_ids = list(_iter_list_ids(session, headers, logger))
-
- # Resolve the saved list-ID bookmark to the slice of lists still to process. If the bookmarked list
- # no longer exists (deleted between runs), start over from the first list — merge dedupes the
- # re-pulled rows on the primary key. `resume_url` is consumed by the first list only.
+ fan_out = config.fan_out
+ assert fan_out is not None
+ parents = list(_iter_fan_out_parents(session, headers, logger, fan_out))
+ parent_ids = [parent_id for _, parent_id in parents]
+
+ # Resolve the saved parent-ID bookmark to the slice of parents still to process. If the
+ # bookmarked parent no longer exists (deleted between runs), start over from the first one —
+ # merge dedupes the re-pulled rows on the primary key. `resume_url` is consumed by the first
+ # parent only.
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- remaining = list_ids
+ remaining = parents
resume_url: str | None = None
- if resume is not None and resume.list_id is not None and resume.list_id in list_ids:
- remaining = list_ids[list_ids.index(resume.list_id) :]
+ if resume is not None and resume.list_id is not None and resume.list_id in parent_ids:
+ remaining = parents[parent_ids.index(resume.list_id) :]
resume_url = resume.next_url
- logger.debug(f"Klaviyo: resuming list_profiles from list_id={resume.list_id}, url={resume_url}")
+ logger.debug(f"Klaviyo: resuming {config.name} from parent={resume.list_id}, url={resume_url}")
- for index, list_id in enumerate(remaining):
- url = resume_url or _build_url(f"{KLAVIYO_BASE_URL}{config.path.format(list_id=list_id)}", params)
- resume_url = None # only the resumed-into list uses the saved URL; the rest start fresh
+ for index, (ancestors, parent_id) in enumerate(remaining):
+ child_path = config.path.format(**{fan_out.parent_id_column: parent_id})
+ url = resume_url or _build_url(f"{KLAVIYO_BASE_URL}{child_path}", params)
+ resume_url = None # only the resumed-into parent uses the saved URL; the rest start fresh
try:
while True:
@@ -281,36 +361,122 @@ def _get_list_profile_rows(
next_url = data.get("links", {}).get("next")
for item in items:
- batcher.batch(
- {
- "list_id": list_id,
- "profile_id": item["id"],
- "joined_group_at": item.get("attributes", {}).get("joined_group_at"),
- }
- )
+ batcher.batch(_fan_out_row(fan_out, ancestors, parent_id, item))
if batcher.should_yield():
yield batcher.get_table()
# Save AFTER yielding (and only when more pages remain) so a crash re-yields the
# last page rather than skipping it — merge dedupes on the primary key.
if next_url:
- resumable_source_manager.save_state(KlaviyoResumeConfig(next_url=next_url, list_id=list_id))
+ resumable_source_manager.save_state(
+ KlaviyoResumeConfig(next_url=next_url, list_id=parent_id)
+ )
if not next_url:
break
url = next_url
except requests.HTTPError as exc:
- # A list deleted between enumeration and this fetch 404s. Skip it rather than failing the
- # whole sync — the membership is genuinely gone. Any other HTTP error is re-raised.
+ # A parent deleted between enumeration and this fetch 404s. Skip it rather than failing
+ # the whole sync — the rows are genuinely gone. Any other HTTP error is re-raised.
if exc.response is not None and exc.response.status_code == 404:
- logger.warning(f"Klaviyo: list {list_id} not found while fetching profiles, skipping")
+ logger.warning(f"Klaviyo: {child_path} not found while fetching {config.name}, skipping")
else:
raise
- # Advance the bookmark to the next list so a crash between lists resumes correctly. Its first
- # page URL is built fresh when the loop reaches it.
+ # Advance the bookmark to the next parent so a crash between parents resumes correctly. Its
+ # first page URL is built fresh when the loop reaches it.
if index + 1 < len(remaining):
- resumable_source_manager.save_state(KlaviyoResumeConfig(next_url=None, list_id=remaining[index + 1]))
+ resumable_source_manager.save_state(KlaviyoResumeConfig(next_url=None, list_id=remaining[index + 1][1]))
+
+
+def _resolve_conversion_metric_id(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> str | None:
+ """Pick the metric that conversion statistics in the values reports are attributed to.
+
+ Klaviyo requires a conversion metric on every values report but has no "account default" to
+ read, so fall back to the Placed Order metric its own reporting defaults to, then to whatever
+ metric the account defines first. A user who wants a different one sets it on the source.
+ """
+ url = f"{KLAVIYO_BASE_URL}/metrics"
+ first_metric_id: str | None = None
+
+ for _ in range(MAX_CONVERSION_METRIC_PAGES):
+ data = _fetch_page(session, url, headers, logger)
+ for item in data.get("data", []):
+ if first_metric_id is None:
+ first_metric_id = item["id"]
+ if item.get("attributes", {}).get("name") == DEFAULT_CONVERSION_METRIC_NAME:
+ return item["id"]
+
+ next_url = data.get("links", {}).get("next")
+ if not next_url:
+ break
+ url = next_url
+
+ return first_metric_id
+
+
+def _get_values_report_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ config: KlaviyoEndpointConfig,
+ conversion_metric_id: str | None,
+) -> Iterator[Any]:
+ """Post a Klaviyo values report and flatten each grouping's statistics into one row.
+
+ The report is an aggregate over a rolling window rather than a resource collection, so there is
+ no cursor to advance — the table is replaced in full on every sync.
+ """
+ report = config.values_report
+ assert report is not None
+
+ metric_id = conversion_metric_id or _resolve_conversion_metric_id(session, headers, logger)
+ if not metric_id:
+ logger.warning(
+ f"Klaviyo: no conversion metric found for {config.name}; set a conversion metric ID on the source"
+ )
+ return
+
+ body = {
+ "data": {
+ "type": report.report_type,
+ "attributes": {
+ "statistics": report.statistics,
+ "timeframe": {"key": report.timeframe_key},
+ "conversion_metric_id": metric_id,
+ "group_by": report.group_by,
+ },
+ }
+ }
+ # Klaviyo rejects a reporting POST that isn't sent as JSON:API.
+ post_headers = {**headers, "Content-Type": "application/vnd.api+json"}
+ url = f"{KLAVIYO_BASE_URL}{config.path}"
+
+ while True:
+ data = _fetch_page(session, url, post_headers, logger, json_body=body)
+ attributes = data.get("data", {}).get("attributes", {})
+
+ for result in attributes.get("results", []):
+ batcher.batch(
+ {
+ **result.get("groupings", {}),
+ **result.get("statistics", {}),
+ "timeframe_key": report.timeframe_key,
+ "conversion_metric_id": metric_id,
+ }
+ )
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ next_url = data.get("links", {}).get("next")
+ if not next_url:
+ break
+ url = next_url
def get_rows(
@@ -322,11 +488,12 @@ def get_rows(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
incremental_field: str | None = None,
+ conversion_metric_id: str | None = None,
) -> Iterator[Any]:
config = KLAVIYO_ENDPOINTS[endpoint]
headers = _get_headers(api_key, api_version)
batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
- # One session reused across every page (and, for fan-out, every list) so urllib3 keeps the
+ # One session reused across every page (and, for fan-out, every parent) so urllib3 keeps the
# connection alive instead of re-handshaking per request.
session = make_tracked_session()
@@ -334,8 +501,14 @@ def get_rows(
config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
)
- if config.fan_out_over_lists:
- yield from _get_list_profile_rows(session, headers, logger, batcher, resumable_source_manager, config, params)
+ if config.values_report is not None:
+ yield from _get_values_report_rows(session, headers, logger, batcher, config, conversion_metric_id)
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+ return
+
+ if config.fan_out is not None:
+ yield from _get_fan_out_rows(session, headers, logger, batcher, resumable_source_manager, config, params)
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
return
@@ -389,6 +562,7 @@ def klaviyo_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
+ conversion_metric_id: str | None = None,
) -> SourceResponse:
endpoint_config = KLAVIYO_ENDPOINTS[endpoint]
@@ -403,12 +577,13 @@ def klaviyo_source(
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
incremental_field=incremental_field,
+ conversion_metric_id=conversion_metric_id,
),
primary_keys=endpoint_config.primary_keys,
# Fan-out runs persist the incremental watermark only at successful job end (desc mode): a
- # partial run's max says nothing about lists it never reached, so per-batch persistence could
- # advance the watermark past rows a crashed run still owes.
- sort_mode="desc" if endpoint_config.fan_out_over_lists else "asc",
+ # partial run's max says nothing about parents it never reached, so per-batch persistence
+ # could advance the watermark past rows a crashed run still owes.
+ sort_mode="desc" if endpoint_config.fan_out is not None else "asc",
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/klaviyo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py
index b80742d00fa7..98e049e5db42 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py
@@ -5,6 +5,39 @@ from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+@dataclass
+class KlaviyoFanOutConfig:
+ """Walk a parent collection and follow a per-parent child endpoint for each of its rows.
+
+ The owning endpoint's `path` is a template formatted with `parent_id_column`, e.g.
+ `/lists/{list_id}/profiles` with `parent_id_column="list_id"`.
+ """
+
+ parent_path: str # collection whose ids the child path is fanned out over, e.g. "/lists"
+ parent_page_size: int # Klaviyo caps page[size] per endpoint; a larger value 400s the fan-out
+ parent_id_column: str # column written onto every child row identifying its parent
+ # Emit flat {parent_id_column, profile_id, joined_group_at} membership rows instead of the
+ # flattened resource. Group-membership endpoints return whole profiles; only the join matters.
+ membership_rows: bool = False
+ # Two-level fan-out: `parent_path` is itself a template formatted with this collection's ids,
+ # and every child row also carries the grandparent's id column.
+ grandparent: Optional["KlaviyoFanOutConfig"] = None
+
+
+@dataclass
+class KlaviyoValuesReportConfig:
+ """A Klaviyo reporting query: POST a statistics request, get one row back per grouping.
+
+ Reporting endpoints are aggregates over a rolling window rather than a resource collection, so
+ they are always full refresh — there is no per-row cursor to advance.
+ """
+
+ report_type: str # JSON:API resource type the request body declares
+ statistics: list[str] # statistics to request; rate statistics come back as fractions [0, 1]
+ timeframe_key: str # Klaviyo's predefined timeframe key, capped at one year by the API
+ group_by: list[str] # grouping attributes, which are also the row's primary key
+
+
@dataclass
class KlaviyoEndpointConfig:
name: str
@@ -26,10 +59,56 @@ class KlaviyoEndpointConfig:
# rows that merge dedupes on the primary key. Composes additively with the per-schema
# incremental_field_lookback_seconds the framework applies before the value reaches the source.
incremental_lookback: Optional[timedelta] = None
- # Fan out over every synced list, following the per-list profiles endpoint to materialize the
- # otherwise-unqueryable many-to-many list<->profile membership as one row per member.
- # When True, `path` is a template with a `{list_id}` placeholder.
- fan_out_over_lists: bool = False
+ # Klaviyo's filter operator for the incremental cursor. Most collections accept `greater-than`;
+ # a few (reviews) only document `greater-or-equal`, which re-pulls the boundary row that merge
+ # then dedupes on the primary key.
+ incremental_operator: str = "greater-than"
+ # Set when the endpoint is a per-parent child collection rather than a top-level one.
+ fan_out: Optional[KlaviyoFanOutConfig] = None
+ # Set when the endpoint is a reporting query posted as a body rather than a paged collection.
+ values_report: Optional[KlaviyoValuesReportConfig] = None
+ # Shown next to the table in the schema picker.
+ description: Optional[str] = None
+
+
+# Every statistic Klaviyo's campaign and flow values reports accept. Both endpoints document the
+# same set, so one list drives both tables.
+VALUES_REPORT_STATISTICS = [
+ "average_order_value",
+ "bounce_rate",
+ "bounced",
+ "bounced_or_failed",
+ "bounced_or_failed_rate",
+ "click_rate",
+ "click_to_open_rate",
+ "clicks",
+ "clicks_unique",
+ "conversion_rate",
+ "conversion_uniques",
+ "conversion_value",
+ "conversions",
+ "delivered",
+ "delivery_rate",
+ "failed",
+ "failed_rate",
+ "message_segment_count_sum",
+ "open_rate",
+ "opens",
+ "opens_unique",
+ "recipients",
+ "revenue_per_recipient",
+ "spam_complaint_rate",
+ "spam_complaints",
+ "text_message_credit_usage_amount",
+ "text_message_roi",
+ "text_message_spend",
+ "unsubscribe_rate",
+ "unsubscribe_uniques",
+ "unsubscribes",
+]
+
+# The widest window Klaviyo's reporting API allows is one year.
+VALUES_REPORT_TIMEFRAME_KEY = "last_365_days"
KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
@@ -79,6 +158,7 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
default_incremental_field="datetime",
partition_key="datetime",
default_lookback_days=365,
+ description="Only syncs the last 365 days on initial sync",
incremental_fields=[
{
"label": "datetime",
@@ -185,7 +265,368 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
],
primary_keys=["list_id", "profile_id"],
should_sync_default=False,
- fan_out_over_lists=True,
+ fan_out=KlaviyoFanOutConfig(
+ # Klaviyo caps the /lists endpoint at a page size of 10 (larger values 400).
+ parent_path="/lists",
+ parent_page_size=10,
+ parent_id_column="list_id",
+ membership_rows=True,
+ ),
+ description=(
+ "Maps which profiles belong to which list as {list_id, profile_id, joined_group_at} rows. "
+ "Incremental syncs pick up new joins and re-joins; profiles removed from a list are only "
+ "reflected on a full refresh. List membership is not the same as subscription: check the "
+ "$consent array in the profiles table's properties column to see which channels (sms, "
+ "email, push) a profile is currently subscribed to"
+ ),
+ ),
+ # Segment membership has the same shape as list membership: Klaviyo only exposes it per segment,
+ # so the many-to-many can't be joined from HogQL without materializing it. Opt-in because a fan
+ # out costs one paginated request per segment.
+ "segment_profiles": KlaviyoEndpointConfig(
+ name="segment_profiles",
+ path="/segments/{segment_id}/profiles",
+ default_incremental_field="joined_group_at",
+ page_size=100,
+ sort="-joined_group_at",
+ extra_params={"fields[profile]": "joined_group_at"},
+ incremental_lookback=timedelta(hours=24),
+ incremental_fields=[
+ {
+ "label": "joined_group_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "joined_group_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ primary_keys=["segment_id", "profile_id"],
+ should_sync_default=False,
+ fan_out=KlaviyoFanOutConfig(
+ # Klaviyo caps the /segments endpoint at a page size of 10.
+ parent_path="/segments",
+ parent_page_size=10,
+ parent_id_column="segment_id",
+ membership_rows=True,
+ ),
+ description=(
+ "Maps which profiles belong to which segment as {segment_id, profile_id, joined_group_at} "
+ "rows. Segments are recomputed by Klaviyo, so profiles that no longer match are only "
+ "removed on a full refresh"
+ ),
+ ),
+ "segments": KlaviyoEndpointConfig(
+ name="segments",
+ path="/segments",
+ default_incremental_field="updated",
+ partition_key="created",
+ page_size=10, # Segments endpoint max is 10
+ sort="updated",
+ incremental_fields=[
+ {
+ "label": "updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Flows only expose their step structure per flow, and messages only per action, so the two
+ # tables below are a one- and two-level fan out respectively.
+ "flow_actions": KlaviyoEndpointConfig(
+ name="flow_actions",
+ path="/flows/{flow_id}/flow-actions",
+ default_incremental_field="updated",
+ partition_key="created",
+ page_size=50, # Flow actions endpoint max is 50
+ sort="-updated",
+ incremental_lookback=timedelta(hours=24),
+ incremental_fields=[
+ {
+ "label": "updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ fan_out=KlaviyoFanOutConfig(
+ parent_path="/flows",
+ parent_page_size=50, # Flows endpoint max is 50
+ parent_id_column="flow_id",
+ ),
+ description="One row per step in a flow, carrying the flow_id it belongs to",
+ ),
+ "flow_messages": KlaviyoEndpointConfig(
+ name="flow_messages",
+ path="/flow-actions/{flow_action_id}/flow-messages",
+ default_incremental_field="updated",
+ partition_key="created",
+ page_size=50, # Flow messages endpoint max is 50
+ sort="-updated",
+ incremental_lookback=timedelta(hours=24),
+ incremental_fields=[
+ {
+ "label": "updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ should_sync_default=False,
+ fan_out=KlaviyoFanOutConfig(
+ parent_path="/flows/{flow_id}/flow-actions",
+ parent_page_size=50,
+ parent_id_column="flow_action_id",
+ grandparent=KlaviyoFanOutConfig(
+ parent_path="/flows",
+ parent_page_size=50,
+ parent_id_column="flow_id",
+ ),
+ ),
+ description=(
+ "One row per message sent by a flow step, carrying the flow_action_id and flow_id it "
+ "belongs to. Opt-in: it walks every action of every flow"
+ ),
+ ),
+ "campaign_values_reports": KlaviyoEndpointConfig(
+ name="campaign_values_reports",
+ path="/campaign-values-reports",
+ incremental_fields=[],
+ primary_keys=["campaign_id", "campaign_message_id", "send_channel"],
+ values_report=KlaviyoValuesReportConfig(
+ report_type="campaign-values-report",
+ statistics=VALUES_REPORT_STATISTICS,
+ timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
+ group_by=["campaign_id", "campaign_message_id", "send_channel"],
+ ),
+ description=(
+ "Klaviyo's own computed performance statistics per campaign message over the last 365 "
+ "days, replaced in full on every sync. Conversion statistics use the conversion metric "
+ "recorded in the conversion_metric_id column"
+ ),
+ ),
+ "flow_values_reports": KlaviyoEndpointConfig(
+ name="flow_values_reports",
+ path="/flow-values-reports",
+ incremental_fields=[],
+ primary_keys=["flow_id", "flow_message_id", "send_channel"],
+ values_report=KlaviyoValuesReportConfig(
+ report_type="flow-values-report",
+ statistics=VALUES_REPORT_STATISTICS,
+ timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
+ group_by=["flow_id", "flow_message_id", "send_channel"],
+ ),
+ description=(
+ "Klaviyo's own computed performance statistics per flow message over the last 365 days, "
+ "replaced in full on every sync. Conversion statistics use the conversion metric recorded "
+ "in the conversion_metric_id column"
+ ),
+ ),
+ "templates": KlaviyoEndpointConfig(
+ name="templates",
+ path="/templates",
+ default_incremental_field="updated",
+ partition_key="created",
+ page_size=10, # Templates endpoint max is 10
+ sort="updated",
+ incremental_fields=[
+ {
+ "label": "updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "forms": KlaviyoEndpointConfig(
+ name="forms",
+ path="/forms",
+ default_incremental_field="updated_at",
+ partition_key="created_at",
+ page_size=100,
+ sort="updated_at",
+ incremental_fields=[
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Klaviyo only documents greater-or-equal / less-or-equal on the review `created` filter, and
+ # exposes no filter on `updated`, so `created` is the only usable cursor here.
+ "reviews": KlaviyoEndpointConfig(
+ name="reviews",
+ path="/reviews",
+ default_incremental_field="created",
+ partition_key="created",
+ page_size=100,
+ sort="created",
+ incremental_operator="greater-or-equal",
+ incremental_fields=[
+ {
+ "label": "created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "images": KlaviyoEndpointConfig(
+ name="images",
+ path="/images",
+ default_incremental_field="updated_at",
+ page_size=100,
+ sort="updated_at",
+ incremental_fields=[
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "web_feeds": KlaviyoEndpointConfig(
+ name="web_feeds",
+ path="/web-feeds",
+ default_incremental_field="updated",
+ partition_key="created",
+ page_size=20, # Web feeds endpoint max is 20
+ sort="updated",
+ incremental_fields=[
+ {
+ "label": "updated",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "created",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Klaviyo documents no timestamp filter on the collections below, so they are full refresh only.
+ "catalog_items": KlaviyoEndpointConfig(
+ name="catalog_items",
+ path="/catalog-items",
+ partition_key="created",
+ page_size=100,
+ sort="created",
+ incremental_fields=[],
+ ),
+ "catalog_variants": KlaviyoEndpointConfig(
+ name="catalog_variants",
+ path="/catalog-variants",
+ partition_key="created",
+ page_size=100,
+ sort="created",
+ incremental_fields=[],
+ ),
+ "catalog_categories": KlaviyoEndpointConfig(
+ name="catalog_categories",
+ path="/catalog-categories",
+ page_size=100,
+ sort="created",
+ incremental_fields=[],
+ ),
+ "coupons": KlaviyoEndpointConfig(
+ name="coupons",
+ path="/coupons",
+ page_size=100,
+ incremental_fields=[],
+ ),
+ "coupon_codes": KlaviyoEndpointConfig(
+ name="coupon_codes",
+ path="/coupon-codes",
+ page_size=100,
+ incremental_fields=[],
+ ),
+ "tags": KlaviyoEndpointConfig(
+ name="tags",
+ path="/tags",
+ page_size=50, # Tags endpoint max is 50
+ sort="id",
+ incremental_fields=[],
+ ),
+ "tag_groups": KlaviyoEndpointConfig(
+ name="tag_groups",
+ path="/tag-groups",
+ page_size=25, # Tag groups endpoint max is 25
+ sort="id",
+ incremental_fields=[],
+ ),
+ "push_tokens": KlaviyoEndpointConfig(
+ name="push_tokens",
+ path="/push-tokens",
+ partition_key="created",
+ page_size=100,
+ incremental_fields=[],
+ ),
+ "data_sources": KlaviyoEndpointConfig(
+ name="data_sources",
+ path="/data-sources",
+ page_size=100,
+ incremental_fields=[],
+ ),
+ # The endpoints below expose no page[size] param, so they are requested unsized and paged only
+ # through the cursor links Klaviyo returns.
+ "custom_metrics": KlaviyoEndpointConfig(
+ name="custom_metrics",
+ path="/custom-metrics",
+ page_size=0,
+ incremental_fields=[],
+ ),
+ "object_types": KlaviyoEndpointConfig(
+ name="object_types",
+ path="/object-types",
+ page_size=0,
+ incremental_fields=[],
+ ),
+ "webhooks": KlaviyoEndpointConfig(
+ name="webhooks",
+ path="/webhooks",
+ page_size=0,
+ incremental_fields=[],
+ ),
+ "accounts": KlaviyoEndpointConfig(
+ name="accounts",
+ path="/accounts",
+ page_size=0,
+ incremental_fields=[],
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py
index b4791a39dfb7..20a71ae69b76 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py
@@ -67,14 +67,29 @@ class KlaviyoSource(ResumableSource[KlaviyoSourceConfig, KlaviyoResumeConfig]):
You can create a private API key in your [Klaviyo account settings](https://www.klaviyo.com/settings/account/api-keys).
-Make sure to grant the following read permissions:
+Grant read permissions for the data you want to sync. Tables you have not granted access to are skipped:
- Accounts
- Campaigns
+- Catalogs
+- Coupon codes
+- Coupons
+- Custom objects
- Events
- Flows
+- Forms
+- Images
- Lists
- Metrics
- Profiles
+- Push tokens
+- Reviews
+- Segments
+- Tags
+- Templates
+- Web feeds
+- Webhooks
+
+The campaign and flow performance tables need a conversion metric. Leave the conversion metric ID blank to use your Placed Order metric, or paste the ID of another metric from [your Klaviyo metrics](https://www.klaviyo.com/analytics/metrics).
""",
iconPath="/static/services/klaviyo.png",
docsUrl="https://posthog.com/docs/cdp/sources/klaviyo",
@@ -89,6 +104,14 @@ Make sure to grant the following read permissions:
placeholder="pk_...",
secret=True,
),
+ SourceFieldInputConfig(
+ name="conversion_metric_id",
+ label="Conversion metric ID (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="RESQ6t",
+ secret=False,
+ ),
],
),
)
@@ -121,22 +144,11 @@ Make sure to grant the following read permissions:
) -> list[SourceSchema]:
# Events are immutable - append-only is the only sync mode
append_only_endpoints = {"events"}
- # The fan-out's incremental lookback intentionally re-pulls a window of rows each run; only
+ # An endpoint's incremental lookback intentionally re-pulls a window of rows each run; only
# merge dedupes those on the primary key, append would materialize them as duplicates.
- merge_only_endpoints = {"list_profiles"}
-
- def _description(endpoint: str) -> str | None:
- if endpoint == "events":
- return "Only syncs the last 365 days on initial sync"
- if KLAVIYO_ENDPOINTS[endpoint].fan_out_over_lists:
- return (
- "Maps which profiles belong to which list as {list_id, profile_id, joined_group_at} rows. "
- "Incremental syncs pick up new joins and re-joins; profiles removed from a list are only "
- "reflected on a full refresh. List membership is not the same as subscription: check the "
- "$consent array in the profiles table's properties column to see which channels (sms, "
- "email, push) a profile is currently subscribed to"
- )
- return None
+ merge_only_endpoints = {
+ name for name, endpoint_config in KLAVIYO_ENDPOINTS.items() if endpoint_config.incremental_lookback
+ }
def _build_schema(endpoint: str) -> SourceSchema:
endpoint_config = KLAVIYO_ENDPOINTS[endpoint]
@@ -147,7 +159,7 @@ Make sure to grant the following read permissions:
supports_append=has_incremental and endpoint not in merge_only_endpoints,
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
should_sync_default=endpoint_config.should_sync_default,
- description=_description(endpoint),
+ description=endpoint_config.description,
)
schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
@@ -188,4 +200,5 @@ Make sure to grant the following read permissions:
if inputs.should_use_incremental_field
else None,
incremental_field=inputs.incremental_field,
+ conversion_metric_id=config.conversion_metric_id,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
index 14702b86acd9..80802fb0b6a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
@@ -328,7 +328,8 @@ class TestListProfilesFanOut:
def test_config_is_opt_in_fan_out_with_composite_pk(self) -> None:
config = KLAVIYO_ENDPOINTS["list_profiles"]
- assert config.fan_out_over_lists is True
+ assert config.fan_out is not None
+ assert config.fan_out.membership_rows is True
assert config.should_sync_default is False
assert config.primary_keys == ["list_id", "profile_id"]
@@ -350,7 +351,9 @@ class TestListProfilesFanOut:
return {"data": [], "links": {"next": None}}
monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
- list(klaviyo._iter_list_ids(MagicMock(), {}, MagicMock()))
+ fan_out = KLAVIYO_ENDPOINTS["list_profiles"].fan_out
+ assert fan_out is not None
+ list(klaviyo._iter_fan_out_parents(MagicMock(), {}, MagicMock(), fan_out))
assert fetched_urls == ["https://a.klaviyo.com/api/lists?page[size]=10"]
@@ -495,8 +498,387 @@ class TestListProfilesFanOut:
self._collect(_FakeResumableManager(), monkeypatch, pages)
+def _collect_rows(endpoint: str, monkeypatch: Any, pages: dict[str, Any], **kwargs: Any) -> list[dict]:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None) -> dict:
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(
+ api_key="pk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestGeneralizedFanOut:
+ def test_segment_membership_uses_the_segment_parent_and_id_column(self, monkeypatch: Any) -> None:
+ # The fan-out was originally hardcoded to /lists and a list_id column; a regression there
+ # would silently emit list_id rows (or 400 on the wrong parent page size) for segments.
+ pages = {
+ "https://a.klaviyo.com/api/segments?page[size]=10": {
+ "data": [{"id": "S1"}],
+ "links": {"next": None},
+ },
+ (
+ "https://a.klaviyo.com/api/segments/S1/profiles"
+ "?page[size]=100&sort=-joined_group_at&fields[profile]=joined_group_at"
+ ): {
+ "data": [
+ {"type": "profile", "id": "P1", "attributes": {"joined_group_at": "2026-01-08T00:00:00+00:00"}}
+ ],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect_rows("segment_profiles", monkeypatch, pages)
+ assert rows == [{"segment_id": "S1", "profile_id": "P1", "joined_group_at": "2026-01-08T00:00:00+00:00"}]
+
+ def test_flow_actions_yield_the_flattened_resource_tagged_with_its_flow(self, monkeypatch: Any) -> None:
+ # Non-membership fan-out rows must keep the resource's own fields and gain the parent id;
+ # dropping flow_id makes the table impossible to join back to flows.
+ pages = {
+ "https://a.klaviyo.com/api/flows?page[size]=50": {
+ "data": [{"id": "F1"}],
+ "links": {"next": None},
+ },
+ "https://a.klaviyo.com/api/flows/F1/flow-actions?page[size]=50&sort=-updated": {
+ "data": [
+ {
+ "type": "flow-action",
+ "id": "A1",
+ "attributes": {
+ "created": "2026-01-01T00:00:00+00:00",
+ "updated": "2026-02-01T00:00:00+00:00",
+ },
+ }
+ ],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect_rows("flow_actions", monkeypatch, pages)
+ assert rows == [
+ {
+ "type": "flow-action",
+ "id": "A1",
+ "created": "2026-01-01T00:00:00+00:00",
+ "updated": "2026-02-01T00:00:00+00:00",
+ "flow_id": "F1",
+ }
+ ]
+
+ def test_flow_messages_walk_flows_then_actions_and_carry_both_ancestors(self, monkeypatch: Any) -> None:
+ # Two-level fan-out: the intermediate path must be formatted with the grandparent id, and
+ # each row must carry both ancestors or the flow -> action -> message chain can't be rebuilt.
+ pages = {
+ "https://a.klaviyo.com/api/flows?page[size]=50": {
+ "data": [{"id": "F1"}, {"id": "F2"}],
+ "links": {"next": None},
+ },
+ "https://a.klaviyo.com/api/flows/F1/flow-actions?page[size]=50": {
+ "data": [{"id": "A1"}],
+ "links": {"next": None},
+ },
+ "https://a.klaviyo.com/api/flows/F2/flow-actions?page[size]=50": {
+ "data": [{"id": "A2"}],
+ "links": {"next": None},
+ },
+ "https://a.klaviyo.com/api/flow-actions/A1/flow-messages?page[size]=50&sort=-updated": {
+ "data": [{"type": "flow-message", "id": "M1", "attributes": {"channel": "email"}}],
+ "links": {"next": None},
+ },
+ "https://a.klaviyo.com/api/flow-actions/A2/flow-messages?page[size]=50&sort=-updated": {
+ "data": [{"type": "flow-message", "id": "M2", "attributes": {"channel": "sms"}}],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect_rows("flow_messages", monkeypatch, pages)
+ assert rows == [
+ {"type": "flow-message", "id": "M1", "channel": "email", "flow_action_id": "A1", "flow_id": "F1"},
+ {"type": "flow-message", "id": "M2", "channel": "sms", "flow_action_id": "A2", "flow_id": "F2"},
+ ]
+
+ def test_deleted_flow_is_skipped_while_enumerating_two_level_parents(self, monkeypatch: Any) -> None:
+ # A flow deleted between enumeration and the action fetch must not fail the whole sync.
+ pages = {
+ "https://a.klaviyo.com/api/flows?page[size]=50": {
+ "data": [{"id": "GONE"}, {"id": "F2"}],
+ "links": {"next": None},
+ },
+ "https://a.klaviyo.com/api/flows/GONE/flow-actions?page[size]=50": requests.HTTPError(
+ response=_response_with_status(404)
+ ),
+ "https://a.klaviyo.com/api/flows/F2/flow-actions?page[size]=50": {
+ "data": [{"id": "A2"}],
+ "links": {"next": None},
+ },
+ "https://a.klaviyo.com/api/flow-actions/A2/flow-messages?page[size]=50&sort=-updated": {
+ "data": [{"type": "flow-message", "id": "M2", "attributes": {"channel": "sms"}}],
+ "links": {"next": None},
+ },
+ }
+ rows = _collect_rows("flow_messages", monkeypatch, pages)
+ assert rows == [{"type": "flow-message", "id": "M2", "channel": "sms", "flow_action_id": "A2", "flow_id": "F2"}]
+
+ @parameterized.expand(
+ [
+ ("list_profiles", ["list_id", "profile_id"]),
+ ("segment_profiles", ["segment_id", "profile_id"]),
+ ]
+ )
+ def test_membership_tables_key_on_parent_and_profile(self, endpoint: str, expected_keys: list[str]) -> None:
+ # A membership key that isn't unique table-wide seeds duplicates that every later merge
+ # multi-matches, which is how these fan-outs OOM.
+ assert KLAVIYO_ENDPOINTS[endpoint].primary_keys == expected_keys
+
+
+class TestValuesReports:
+ @staticmethod
+ def _pages(report_path: str, results: list[dict], next_url: str | None = None) -> dict[str, Any]:
+ return {
+ "https://a.klaviyo.com/api/metrics": {
+ "data": [
+ {"id": "M_OTHER", "attributes": {"name": "Viewed Product"}},
+ {"id": "M_ORDER", "attributes": {"name": "Placed Order"}},
+ ],
+ "links": {"next": None},
+ },
+ f"https://a.klaviyo.com/api{report_path}": {
+ "data": {"type": "campaign-values-report", "attributes": {"results": results}},
+ "links": {"next": next_url},
+ },
+ }
+
+ def test_groupings_and_statistics_flatten_into_one_row(self, monkeypatch: Any) -> None:
+ # The report nests groupings and statistics under separate objects; keeping that nesting
+ # would make the table unqueryable and break the declared primary key.
+ pages = self._pages(
+ "/campaign-values-reports",
+ [
+ {
+ "groupings": {"campaign_id": "C1", "campaign_message_id": "CM1", "send_channel": "email"},
+ "statistics": {"opens": 123, "open_rate": 0.8253},
+ }
+ ],
+ )
+ rows = _collect_rows("campaign_values_reports", monkeypatch, pages)
+ assert rows == [
+ {
+ "campaign_id": "C1",
+ "campaign_message_id": "CM1",
+ "send_channel": "email",
+ "opens": 123,
+ "open_rate": 0.8253,
+ "timeframe_key": "last_365_days",
+ "conversion_metric_id": "M_ORDER",
+ }
+ ]
+
+ def test_report_body_carries_the_required_query(self, monkeypatch: Any) -> None:
+ # Klaviyo 400s a values report that is missing statistics, timeframe, or conversion metric.
+ captured: dict[str, Any] = {}
+
+ def fake_fetch(
+ session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None
+ ) -> dict:
+ if json_body is not None:
+ captured["body"] = json_body
+ captured["content_type"] = headers.get("Content-Type")
+ return {"data": {"attributes": {"results": []}}, "links": {}}
+ return {"data": [{"id": "M_ORDER", "attributes": {"name": "Placed Order"}}], "links": {}}
+
+ monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
+ list(
+ get_rows(
+ api_key="pk_test",
+ endpoint="flow_values_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+
+ attributes = captured["body"]["data"]["attributes"]
+ assert captured["body"]["data"]["type"] == "flow-values-report"
+ assert captured["content_type"] == "application/vnd.api+json"
+ assert attributes["timeframe"] == {"key": "last_365_days"}
+ assert attributes["conversion_metric_id"] == "M_ORDER"
+ assert attributes["group_by"] == ["flow_id", "flow_message_id", "send_channel"]
+ assert "opens" in attributes["statistics"]
+
+ def test_configured_conversion_metric_skips_the_lookup(self, monkeypatch: Any) -> None:
+ # A user-set metric must win, and must not cost an extra /metrics walk on every sync.
+ fetched_urls: list[str] = []
+
+ def fake_fetch(
+ session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None
+ ) -> dict:
+ fetched_urls.append(url)
+ return {"data": {"attributes": {"results": []}}, "links": {}}
+
+ monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
+ list(
+ get_rows(
+ api_key="pk_test",
+ endpoint="campaign_values_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ conversion_metric_id="CHOSEN",
+ )
+ )
+
+ assert fetched_urls == ["https://a.klaviyo.com/api/campaign-values-reports"]
+
+ def test_falls_back_to_the_first_metric_when_placed_order_is_absent(self, monkeypatch: Any) -> None:
+ # Accounts without ecommerce have no Placed Order metric; the report still needs one.
+ def fake_fetch(
+ session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None
+ ) -> dict:
+ if json_body is not None:
+ return {
+ "data": {
+ "attributes": {"results": [{"groupings": {"campaign_id": "C1"}, "statistics": {"opens": 1}}]}
+ },
+ "links": {},
+ }
+ return {"data": [{"id": "M_FIRST", "attributes": {"name": "Viewed Product"}}], "links": {}}
+
+ monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
+ rows = [
+ row
+ for table in get_rows(
+ api_key="pk_test",
+ endpoint="campaign_values_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ for row in table.to_pylist()
+ ]
+
+ assert rows[0]["conversion_metric_id"] == "M_FIRST"
+
+ def test_account_with_no_metrics_yields_nothing_instead_of_posting_an_invalid_report(
+ self, monkeypatch: Any
+ ) -> None:
+ def fake_fetch(
+ session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None
+ ) -> dict:
+ assert json_body is None, "must not post a report without a conversion metric"
+ return {"data": [], "links": {}}
+
+ monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
+ assert (
+ list(
+ get_rows(
+ api_key="pk_test",
+ endpoint="campaign_values_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+ == []
+ )
+
+
+class TestEndpointRequestParams:
+ @parameterized.expand(
+ [
+ # Klaviyo caps page[size] per endpoint and 400s anything larger, which fails the table.
+ ("segments", 10),
+ ("templates", 10),
+ ("web_feeds", 20),
+ ("tag_groups", 25),
+ ("tags", 50),
+ ("flow_actions", 50),
+ ("flow_messages", 50),
+ ("forms", 100),
+ ("reviews", 100),
+ ("images", 100),
+ ("catalog_items", 100),
+ ("catalog_variants", 100),
+ ("catalog_categories", 100),
+ ("coupons", 100),
+ ("coupon_codes", 100),
+ ("push_tokens", 100),
+ ("data_sources", 100),
+ ("segment_profiles", 100),
+ ]
+ )
+ def test_page_size_stays_within_the_endpoint_cap(self, endpoint: str, expected: int) -> None:
+ params = _build_initial_params(
+ KLAVIYO_ENDPOINTS[endpoint],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert params["page[size]"] == expected
+
+ @parameterized.expand([("custom_metrics",), ("object_types",), ("webhooks",), ("accounts",)])
+ def test_unsized_endpoints_send_no_page_size(self, endpoint: str) -> None:
+ # These endpoints document no page[size] param; sending one is rejected.
+ params = _build_initial_params(
+ KLAVIYO_ENDPOINTS[endpoint],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert "page[size]" not in params
+
+ def test_reviews_use_the_inclusive_operator_klaviyo_documents(self) -> None:
+ # Klaviyo only accepts greater-or-equal on the review `created` filter; greater-than 400s.
+ params = _build_initial_params(
+ KLAVIYO_ENDPOINTS["reviews"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="created",
+ )
+ assert params["filter"] == "greater-or-equal(created,2026-03-04T02:58:14.000Z)"
+
+
+class TestNewSchemas:
+ @parameterized.expand(
+ [
+ ("segments", True),
+ ("segment_profiles", False),
+ ("flow_actions", True),
+ ("flow_messages", False),
+ ("campaign_values_reports", True),
+ ("templates", True),
+ ]
+ )
+ def test_expensive_fan_outs_are_opt_in(self, endpoint: str, expected_default: bool) -> None:
+ # A default-on fan-out silently multiplies API cost for accounts that opted into auto-sync.
+ schemas = {s.name: s for s in KlaviyoSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas[endpoint].should_sync_default is expected_default
+
+ @parameterized.expand([("segment_profiles",), ("flow_actions",), ("flow_messages",)])
+ def test_lookback_endpoints_are_merge_only(self, endpoint: str) -> None:
+ # Append mode would materialize the intentional lookback re-pulls as duplicate rows.
+ schemas = {s.name: s for s in KlaviyoSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas[endpoint].supports_append is False
+
+ def test_every_endpoint_is_exposed_as_a_schema(self) -> None:
+ schemas = {s.name for s in KlaviyoSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas == set(KLAVIYO_ENDPOINTS)
+
+
class TestSourceResponseSortMode:
- @parameterized.expand([("list_profiles", "desc"), ("events", "asc")])
+ @parameterized.expand(
+ [
+ ("list_profiles", "desc"),
+ ("segment_profiles", "desc"),
+ ("flow_actions", "desc"),
+ ("flow_messages", "desc"),
+ ("events", "asc"),
+ ("segments", "asc"),
+ ]
+ )
def test_source_response_sort_mode(self, endpoint: str, expected: str) -> None:
# "desc" defers watermark persistence to successful job end; reverting the fan-out to "asc"
# per-batch persistence lets a crashed run advance the watermark past lists it never fetched.