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(warehouse): add Klaviyo series, form, and segment reporting tables (#79902)

posthog[bot]6abcc0f442ab
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 37e21f0167ef..e121ec752d2b 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
@@ -81,6 +81,37 @@ _VALUES_REPORT_STATISTIC_COLUMNS = {
"unsubscribes": "Total number of unsubscribes.",
}
+# Series reports bucket the same statistics by week; each row carries the bucket it covers.
+_SERIES_REPORT_DATE_TIME_COLUMN = {
+ "date_time": "Start of the weekly bucket the statistics in this row were computed over.",
+}
+
+# Form reports take their own statistic set. Rate statistics come back as fractions between 0 and 1.
+_FORM_REPORT_STATISTIC_COLUMNS = {
+ "timeframe_key": "The Klaviyo timeframe the statistics were computed over.",
+ "closed_form": "Number of times the form was closed.",
+ "closed_form_uniques": "Number of people who closed the form.",
+ "qualified_form": "Number of times the form qualified to show.",
+ "qualified_form_uniques": "Number of people the form qualified to show to.",
+ "submit_rate": "Share of form views that resulted in a submission.",
+ "submits": "Total number of form submissions.",
+ "submitted_form_step": "Number of form steps submitted.",
+ "submitted_form_step_uniques": "Number of people who submitted a form step.",
+ "viewed_form": "Total number of form views.",
+ "viewed_form_step": "Number of form steps viewed.",
+ "viewed_form_step_uniques": "Number of people who viewed a form step.",
+ "viewed_form_uniques": "Number of people who viewed the form.",
+}
+
+# Segment reports report on membership churn over the window.
+_SEGMENT_REPORT_STATISTIC_COLUMNS = {
+ "timeframe_key": "The Klaviyo timeframe the statistics were computed over.",
+ "members_added": "Number of profiles added to the segment.",
+ "members_removed": "Number of profiles removed from the segment.",
+ "net_members_changed": "Net change in the segment's membership (added minus removed).",
+ "total_members": "Total number of profiles in the segment.",
+}
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"email_campaigns": {
"description": "An email marketing campaign in Klaviyo sent to a target audience.",
@@ -284,6 +315,71 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
**_VALUES_REPORT_STATISTIC_COLUMNS,
},
},
+ "flow_series_reports": {
+ "description": (
+ "Klaviyo's own flow-message performance statistics bucketed by week over the last 365 "
+ "days, one row per flow message per week. Each sync updates the weeks Klaviyo still "
+ "reports and keeps the weeks it no longer returns, so the table builds a history past "
+ "Klaviyo's one-year limit."
+ ),
+ "docs_url": "https://developers.klaviyo.com/en/reference/query_flow_series",
+ "columns": {
+ "flow_id": "Identifier of the flow the statistics belong to.",
+ "flow_message_id": "Identifier of the flow message the statistics belong to.",
+ **_SERIES_REPORT_DATE_TIME_COLUMN,
+ **_VALUES_REPORT_STATISTIC_COLUMNS,
+ },
+ },
+ "form_values_reports": {
+ "description": (
+ "Klaviyo's own signup-form performance statistics per form 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_form_values",
+ "columns": {
+ "form_id": "Identifier of the form the statistics belong to.",
+ **_FORM_REPORT_STATISTIC_COLUMNS,
+ },
+ },
+ "form_series_reports": {
+ "description": (
+ "Klaviyo's own signup-form performance statistics bucketed by week over the last 365 "
+ "days, one row per form per week. Each sync updates the weeks Klaviyo still reports and "
+ "keeps the weeks it no longer returns, so the table builds a history past Klaviyo's "
+ "one-year limit."
+ ),
+ "docs_url": "https://developers.klaviyo.com/en/reference/query_form_series",
+ "columns": {
+ "form_id": "Identifier of the form the statistics belong to.",
+ **_SERIES_REPORT_DATE_TIME_COLUMN,
+ **_FORM_REPORT_STATISTIC_COLUMNS,
+ },
+ },
+ "segment_values_reports": {
+ "description": (
+ "Klaviyo's own segment membership statistics per segment 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_segment_values",
+ "columns": {
+ "segment_id": "Identifier of the segment the statistics belong to.",
+ **_SEGMENT_REPORT_STATISTIC_COLUMNS,
+ },
+ },
+ "segment_series_reports": {
+ "description": (
+ "Klaviyo's own segment membership statistics bucketed by week over the last 365 days, "
+ "one row per segment per week. Each sync updates the weeks Klaviyo still reports and "
+ "keeps the weeks it no longer returns, so the table builds a history past Klaviyo's "
+ "one-year limit."
+ ),
+ "docs_url": "https://developers.klaviyo.com/en/reference/query_segment_series",
+ "columns": {
+ "segment_id": "Identifier of the segment the statistics belong to.",
+ **_SERIES_REPORT_DATE_TIME_COLUMN,
+ **_SEGMENT_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",
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 bdd3ddee3482..0f49cdd17d21 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
@@ -459,6 +459,25 @@ def _resolve_conversion_metric_id(
return first_metric_id
+def _series_rows(
+ results: list[dict[str, Any]], date_times: list[Any], common: dict[str, Any]
+) -> Iterator[dict[str, Any]]:
+ """Expand a series report's per-bucket arrays into one flat row per (grouping, time bucket).
+
+ A series result holds each statistic as an array aligned by index to the report's top-level
+ date_times list. Keeping the arrays nested would leave the table unqueryable and break the
+ date_time primary key, so each bucket becomes its own row tagged with its date_time.
+ """
+ for result in results:
+ groupings = result.get("groupings", {})
+ statistics = result.get("statistics", {})
+ for index, date_time in enumerate(date_times):
+ row = {**groupings, "date_time": date_time, **common}
+ for statistic, values in statistics.items():
+ row[statistic] = values[index] if isinstance(values, list) and index < len(values) else None
+ yield row
+
+
def _get_values_report_rows(
session: requests.Session,
headers: dict[str, str],
@@ -467,50 +486,63 @@ def _get_values_report_rows(
config: KlaviyoEndpointConfig,
conversion_metric_id: str | None,
) -> Iterator[Any]:
- """Post a Klaviyo values report and flatten each grouping's statistics into one row.
+ """Post a Klaviyo reporting query and flatten each grouping's statistics into rows.
+
+ The report is an aggregate over a rolling window rather than a resource collection, so every
+ request asks for the whole window and there is no cursor to send. A values report yields one
+ scalar row per grouping; a series report yields one row per grouping per time bucket.
- 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.
+ A series table still syncs incrementally, because date_time identifies the bucket a row belongs
+ to. The write merges on the primary key, so re-posting the window corrects the buckets Klaviyo
+ still returns and leaves the ones it has dropped in place.
"""
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
+ metric_id: str | None = None
+ if report.requires_conversion_metric:
+ 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,
- },
- }
+ attributes: dict[str, Any] = {
+ "statistics": report.statistics,
+ "timeframe": {"key": report.timeframe_key},
}
+ if report.group_by:
+ attributes["group_by"] = report.group_by
+ if metric_id:
+ attributes["conversion_metric_id"] = metric_id
+ if report.interval:
+ attributes["interval"] = report.interval
+
+ body = {"data": {"type": report.report_type, "attributes": attributes}}
# 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}"
+ # Tagged onto every row so each row records the window (and conversion metric)
+ # it was computed over.
+ common: dict[str, Any] = {"timeframe_key": report.timeframe_key}
+ if metric_id:
+ common["conversion_metric_id"] = metric_id
+
try:
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,
- }
- )
+ attributes_resp = data.get("data", {}).get("attributes", {})
+ results = attributes_resp.get("results", [])
+
+ if report.interval:
+ rows = _series_rows(results, attributes_resp.get("date_times", []), common)
+ else:
+ rows = ({**r.get("groupings", {}), **r.get("statistics", {}), **common} for r in results)
+
+ for row in rows:
+ batcher.batch(row)
if batcher.should_yield():
yield batcher.get_table()
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 7946f2ac5808..fd0037b0794a 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
@@ -2,6 +2,8 @@ from dataclasses import dataclass, field
from datetime import timedelta
from typing import Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -24,7 +26,7 @@ class KlaviyoFanOutConfig:
grandparent: Optional["KlaviyoFanOutConfig"] = None
-@dataclass
+@frozen
class KlaviyoValuesReportConfig:
"""A Klaviyo reporting query: POST a statistics request, get one row back per grouping.
@@ -35,7 +37,15 @@ class KlaviyoValuesReportConfig:
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
+ group_by: list[str] # grouping attributes; empty means the report groups by its own default
+ # Set for a series report, which buckets the window by this interval and returns each grouping's
+ # statistics as arrays aligned to a top-level date_times list. The source expands them into one
+ # row per bucket tagged with `date_time`. Left None for a values report, which returns one scalar
+ # row per grouping.
+ interval: Optional[str] = None
+ # Campaign and flow reports require a conversion metric on every request; form and segment
+ # reports do not accept one, so their requests must omit it and skip the /metrics lookup.
+ requires_conversion_metric: bool = True
@dataclass
@@ -110,6 +120,49 @@ VALUES_REPORT_STATISTICS = [
# The widest window Klaviyo's reporting API allows is one year.
VALUES_REPORT_TIMEFRAME_KEY = "last_365_days"
+# Series reports bucket the window by an interval. Klaviyo caps an hourly interval at 7 days and a
+# daily one at 60, so a weekly interval is the finest that spans the full one-year window (52 rows
+# per grouping).
+SERIES_REPORT_INTERVAL = "weekly"
+
+# A series row is one time bucket, so date_time is a real per-row cursor even though the request
+# always asks for the whole window. Selecting it makes the sync merge on the primary key rather than
+# replace the table, so buckets that age out of Klaviyo's 365-day window stay in the warehouse while
+# the buckets still inside it keep getting corrected.
+SERIES_REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "date_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date_time",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+]
+
+# Form reports report on signup-form performance and take their own statistic set, which does not
+# overlap the campaign/flow set and carries no conversion metric.
+FORM_REPORT_STATISTICS = [
+ "closed_form",
+ "closed_form_uniques",
+ "qualified_form",
+ "qualified_form_uniques",
+ "submit_rate",
+ "submits",
+ "submitted_form_step",
+ "submitted_form_step_uniques",
+ "viewed_form",
+ "viewed_form_step",
+ "viewed_form_step_uniques",
+ "viewed_form_uniques",
+]
+
+# Segment reports report on membership churn and take only these four statistics.
+SEGMENT_REPORT_STATISTICS = [
+ "members_added",
+ "members_removed",
+ "net_members_changed",
+ "total_members",
+]
+
KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
"email_campaigns": KlaviyoEndpointConfig(
@@ -451,6 +504,112 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
"in the conversion_metric_id column"
),
),
+ # Series reports carry the same statistics as the values reports above, but bucketed weekly over
+ # the year instead of collapsed to a single total. They are opt-in because one row per grouping
+ # per week is ~52x the row count of the equivalent values report. Klaviyo exposes series variants
+ # for flows, forms, and segments only; campaigns have a values report but no series report.
+ # Each request asks for the whole window, so the sync merges on the primary key instead of
+ # replacing the table. A week Klaviyo no longer returns keeps the value captured while it was
+ # still in range, which is the only way to hold history past Klaviyo's one-year limit.
+ "flow_series_reports": KlaviyoEndpointConfig(
+ name="flow_series_reports",
+ path="/flow-series-reports",
+ incremental_fields=SERIES_REPORT_INCREMENTAL_FIELDS,
+ default_incremental_field="date_time",
+ primary_keys=["flow_id", "flow_message_id", "send_channel", "date_time"],
+ should_sync_default=False,
+ values_report=KlaviyoValuesReportConfig(
+ report_type="flow-series-report",
+ statistics=VALUES_REPORT_STATISTICS,
+ timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
+ group_by=["flow_id", "flow_message_id", "send_channel"],
+ interval=SERIES_REPORT_INTERVAL,
+ ),
+ description=(
+ "Klaviyo's own flow-message performance statistics bucketed by week over the last 365 "
+ "days, one row per flow message per week. Weeks stay in the table after Klaviyo stops "
+ "returning them"
+ ),
+ ),
+ # Form and segment reports need no conversion metric, so they sync even for keys scoped only to
+ # forms or segments. The values variants are one row per form/segment, so they sync by default.
+ "form_values_reports": KlaviyoEndpointConfig(
+ name="form_values_reports",
+ path="/form-values-reports",
+ incremental_fields=[],
+ primary_keys=["form_id"],
+ values_report=KlaviyoValuesReportConfig(
+ report_type="form-values-report",
+ statistics=FORM_REPORT_STATISTICS,
+ timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
+ group_by=["form_id"],
+ requires_conversion_metric=False,
+ ),
+ description=(
+ "Klaviyo's own signup-form performance statistics per form over the last 365 days, "
+ "replaced in full on every sync"
+ ),
+ ),
+ "segment_values_reports": KlaviyoEndpointConfig(
+ name="segment_values_reports",
+ path="/segment-values-reports",
+ incremental_fields=[],
+ primary_keys=["segment_id"],
+ values_report=KlaviyoValuesReportConfig(
+ report_type="segment-values-report",
+ statistics=SEGMENT_REPORT_STATISTICS,
+ timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
+ # Segment reports do not accept a group_by; they always group by segment_id.
+ group_by=[],
+ requires_conversion_metric=False,
+ ),
+ description=(
+ "Klaviyo's own segment membership statistics per segment over the last 365 days "
+ "(members added, removed, net change, and total). Replaced in full on every sync"
+ ),
+ ),
+ "form_series_reports": KlaviyoEndpointConfig(
+ name="form_series_reports",
+ path="/form-series-reports",
+ incremental_fields=SERIES_REPORT_INCREMENTAL_FIELDS,
+ default_incremental_field="date_time",
+ primary_keys=["form_id", "date_time"],
+ should_sync_default=False,
+ values_report=KlaviyoValuesReportConfig(
+ report_type="form-series-report",
+ statistics=FORM_REPORT_STATISTICS,
+ timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
+ group_by=["form_id"],
+ interval=SERIES_REPORT_INTERVAL,
+ requires_conversion_metric=False,
+ ),
+ description=(
+ "Klaviyo's own signup-form performance statistics bucketed by week over the last 365 "
+ "days, one row per form per week. Weeks stay in the table after Klaviyo stops returning "
+ "them"
+ ),
+ ),
+ "segment_series_reports": KlaviyoEndpointConfig(
+ name="segment_series_reports",
+ path="/segment-series-reports",
+ incremental_fields=SERIES_REPORT_INCREMENTAL_FIELDS,
+ default_incremental_field="date_time",
+ primary_keys=["segment_id", "date_time"],
+ should_sync_default=False,
+ values_report=KlaviyoValuesReportConfig(
+ report_type="segment-series-report",
+ statistics=SEGMENT_REPORT_STATISTICS,
+ timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
+ group_by=[],
+ interval=SERIES_REPORT_INTERVAL,
+ requires_conversion_metric=False,
+ ),
+ description=(
+ "Klaviyo's own segment membership statistics bucketed by week over the last 365 days, "
+ "one row per segment per week. Weeks stay in the table after Klaviyo stops returning "
+ "them"
+ ),
+ ),
"templates": KlaviyoEndpointConfig(
name="templates",
path="/templates",
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 097527b2a969..f1dd4d6fff1a 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
@@ -151,10 +151,13 @@ The campaign and flow performance tables need a conversion metric. Leave the con
) -> list[SourceSchema]:
# Events are immutable - append-only is the only sync mode
append_only_endpoints = {"events"}
- # 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.
+ # An endpoint's incremental lookback intentionally re-pulls a window of rows each run, and a
+ # report re-posts its whole window every run; only merge dedupes those on the primary key,
+ # append would materialize them as duplicates.
merge_only_endpoints = {
- name for name, endpoint_config in KLAVIYO_ENDPOINTS.items() if endpoint_config.incremental_lookback
+ name
+ for name, endpoint_config in KLAVIYO_ENDPOINTS.items()
+ if endpoint_config.incremental_lookback or endpoint_config.values_report is not None
}
def _build_schema(endpoint: str) -> SourceSchema:
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 71769d6b4021..bb3f7aaaaf96 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
@@ -1045,6 +1045,132 @@ class TestValuesReports:
)
+class TestReportVariants:
+ def test_series_report_carries_interval_and_expands_each_bucket_into_a_row(self, monkeypatch: Any) -> None:
+ # Series reports return each statistic as an array aligned to a top-level date_times list;
+ # keeping the arrays nested would leave the table unqueryable and collapse the weekly rows.
+ # Klaviyo also 400s a series report missing the interval, so the body must carry it.
+ 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
+ return {
+ "data": {
+ "attributes": {
+ "results": [
+ {
+ "groupings": {
+ "flow_id": "F1",
+ "flow_message_id": "FM1",
+ "send_channel": "email",
+ },
+ "statistics": {"opens": [1, 2]},
+ }
+ ],
+ "date_times": ["2026-01-05T00:00:00+00:00", "2026-01-12T00:00:00+00:00"],
+ }
+ },
+ "links": {},
+ }
+ return {"data": [{"id": "M_ORDER", "attributes": {"name": "Placed Order"}}], "links": {}}
+
+ monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
+ rows = [
+ row
+ for table in get_rows(
+ api_key="pk_test",
+ endpoint="flow_series_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ for row in table.to_pylist()
+ ]
+
+ assert captured["body"]["data"]["attributes"]["interval"] == "weekly"
+ assert rows == [
+ {
+ "flow_id": "F1",
+ "flow_message_id": "FM1",
+ "send_channel": "email",
+ "date_time": "2026-01-05T00:00:00+00:00",
+ "opens": 1,
+ "timeframe_key": "last_365_days",
+ "conversion_metric_id": "M_ORDER",
+ },
+ {
+ "flow_id": "F1",
+ "flow_message_id": "FM1",
+ "send_channel": "email",
+ "date_time": "2026-01-12T00:00:00+00:00",
+ "opens": 2,
+ "timeframe_key": "last_365_days",
+ "conversion_metric_id": "M_ORDER",
+ },
+ ]
+
+ @parameterized.expand(
+ [
+ ("form_values_reports", "form-values-report", "/form-values-reports", ["form_id"]),
+ ("segment_values_reports", "segment-values-report", "/segment-values-reports", None),
+ ]
+ )
+ def test_form_and_segment_reports_omit_the_conversion_metric_and_its_lookup(
+ self, endpoint: str, report_type: str, path: str, expected_group_by: list[str] | None
+ ) -> None:
+ # Form and segment reports don't accept a conversion_metric_id; sending one (or the group_by
+ # segment reports also reject) 400s the request, and resolving one would cost a needless
+ # /metrics walk on every sync.
+ captured: dict[str, Any] = {}
+ 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)
+ if json_body is not None:
+ captured["body"] = json_body
+ return {"data": {"attributes": {"results": []}}, "links": {}}
+
+ with patch.object(klaviyo, "_fetch_page", fake_fetch):
+ list(
+ get_rows(
+ api_key="pk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+
+ attributes = captured["body"]["data"]["attributes"]
+ assert captured["body"]["data"]["type"] == report_type
+ assert "conversion_metric_id" not in attributes
+ assert fetched_urls == [f"https://a.klaviyo.com/api{path}"]
+ if expected_group_by is None:
+ assert "group_by" not in attributes
+ else:
+ assert attributes["group_by"] == expected_group_by
+
+ @parameterized.expand(
+ [
+ ("flow_series_reports",),
+ ("form_series_reports",),
+ ("segment_series_reports",),
+ ]
+ )
+ def test_series_reports_key_on_the_time_bucket(self, endpoint: str) -> None:
+ # Without date_time in the primary key, the ~52 weekly rows per grouping collapse to one on
+ # merge, silently discarding the whole time series. Without date_time as a cursor the table
+ # syncs full refresh, so every sync rebuilds it from Klaviyo's rolling 365-day window and
+ # drops the weeks that have since left it, which no later sync can fetch again.
+ config = KLAVIYO_ENDPOINTS[endpoint]
+ assert "date_time" in config.primary_keys
+ assert [f["field"] for f in config.incremental_fields] == ["date_time"]
+ assert config.default_incremental_field == "date_time"
+
+
class TestEndpointRequestParams:
@parameterized.expand(
[
@@ -1141,9 +1267,20 @@ class TestNewSchemas:
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.
+ @parameterized.expand(
+ [
+ ("segment_profiles",),
+ ("flow_actions",),
+ ("flow_messages",),
+ ("campaign_values_reports",),
+ ("flow_series_reports",),
+ ("form_series_reports",),
+ ("segment_series_reports",),
+ ]
+ )
+ def test_endpoints_that_re_pull_a_window_are_merge_only(self, endpoint: str) -> None:
+ # Append mode would materialize the intentional re-pulls as duplicate rows. A lookback
+ # endpoint re-pulls a window of rows each run, and a report re-posts its whole window.
schemas = {s.name: s for s in KlaviyoSource().get_schemas(MagicMock(), team_id=1)}
assert schemas[endpoint].supports_append is False