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): incremental sync for Klaviyo list_profiles (#69216)

Luke Belton3f2041d54d0f
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 c0703fae1e6e..a29db0b7b3c6 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
@@ -106,11 +106,12 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
},
"list_profiles": {
- "description": "A flat join table mapping which profiles belong to which Klaviyo list.",
- "docs_url": "https://developers.klaviyo.com/en/reference/get_list_relationships_profiles",
+ "description": "A flat join table mapping which profiles belong to which Klaviyo list. Rows for profiles removed from a list are only pruned by a full refresh.",
+ "docs_url": "https://developers.klaviyo.com/en/reference/get_profiles_for_list",
"columns": {
"list_id": "Identifier of the list.",
"profile_id": "Identifier of a profile that is a member of the list.",
+ "joined_group_at": "The datetime when the profile most recently joined the list. Updated if the profile re-joins.",
},
},
}
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 602a3dfd2830..5cb10045ebf7 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
@@ -72,6 +72,21 @@ def _clamp_future_value_to_now(value: Any) -> Any:
return value
+def _apply_lookback(value: Any, lookback: timedelta | None) -> Any:
+ """Shift a datetime/date incremental cursor back by `lookback` to re-pull a safety window.
+
+ The re-pulled rows are deduped by the endpoint's primary key on merge. No-op for
+ non-temporal values or when the endpoint declares no lookback.
+ """
+ if lookback is None:
+ return value
+ if isinstance(value, datetime):
+ return value - lookback
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC) - lookback
+ return value
+
+
def _build_filter(
config: KlaviyoEndpointConfig,
incremental_field: str | None,
@@ -144,8 +159,10 @@ def _build_initial_params(
db_incremental_field_last_value = datetime.now(UTC) - timedelta(days=config.default_lookback_days)
# Future-dated source data can push the cursor past now; Klaviyo 400s on a future filter value.
+ # The lookback must apply after the clamp, so a clamped cursor still re-pulls its safety window.
if should_use_incremental_field and db_incremental_field_last_value:
db_incremental_field_last_value = _clamp_future_value_to_now(db_incremental_field_last_value)
+ db_incremental_field_last_value = _apply_lookback(db_incremental_field_last_value, config.incremental_lookback)
formatted_last_value = (
_format_incremental_value(db_incremental_field_last_value)
@@ -159,6 +176,8 @@ def _build_initial_params(
if config.sort:
params["sort"] = config.sort
+ params.update(config.extra_params)
+
return params
@@ -215,13 +234,21 @@ def _get_list_profile_rows(
logger: FilteringBoundLogger,
batcher: Batcher,
resumable_source_manager: ResumableSourceManager[KlaviyoResumeConfig],
+ config: KlaviyoEndpointConfig,
+ params: dict[str, Any],
) -> Iterator[Any]:
- """Fan out over every list, materializing list<->profile membership as {list_id, profile_id} rows.
-
- Klaviyo's `/lists/{id}/relationships/profiles` returns bare {type, id} reference stubs, so each row
- is built explicitly rather than flattened. Full refresh only — the relationship API has no
- server-side incremental filter — so re-pulled rows on resume are deduped by the [list_id, profile_id]
- primary key on merge.
+ """Fan out over every list, materializing membership as {list_id, profile_id, joined_group_at} rows.
+
+ `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.
+
+ 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
+ re-fetches a wider window that merge dedupes.
"""
list_ids = list(_iter_list_ids(session, headers, logger))
@@ -237,10 +264,7 @@ def _get_list_profile_rows(
logger.debug(f"Klaviyo: resuming list_profiles from list_id={resume.list_id}, url={resume_url}")
for index, list_id in enumerate(remaining):
- # The relationships endpoint caps page size at 100 (larger values 400).
- url = resume_url or _build_url(
- f"{KLAVIYO_BASE_URL}/lists/{list_id}/relationships/profiles", {"page[size]": 100}
- )
+ 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
try:
@@ -250,7 +274,13 @@ 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"]})
+ batcher.batch(
+ {
+ "list_id": list_id,
+ "profile_id": item["id"],
+ "joined_group_at": item.get("attributes", {}).get("joined_group_at"),
+ }
+ )
if batcher.should_yield():
yield batcher.get_table()
@@ -292,16 +322,16 @@ def get_rows(
# connection alive instead of re-handshaking per request.
session = make_tracked_session()
+ params = _build_initial_params(
+ 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)
+ yield from _get_list_profile_rows(session, headers, logger, batcher, resumable_source_manager, config, params)
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
return
- params = _build_initial_params(
- config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
- )
-
# Check for resume state
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
@@ -365,6 +395,10 @@ def klaviyo_source(
incremental_field=incremental_field,
),
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",
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 61ca35716e9b..b80742d00fa7 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
@@ -1,4 +1,5 @@
from dataclasses import dataclass, field
+from datetime import timedelta
from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -19,8 +20,14 @@ class KlaviyoEndpointConfig:
default_lookback_days: Optional[int] = None # Limit first sync to last N days instead of full history
primary_keys: list[str] = field(default_factory=lambda: ["id"]) # Primary key columns for dedup
should_sync_default: bool = True # Whether the table is selected for sync by default in the UI
- # Fan out over every synced list, following /lists/{list_id}/relationships/profiles to materialize
- # the otherwise-unqueryable many-to-many list<->profile membership as {list_id, profile_id} rows.
+ # Extra query params merged into every request, e.g. a fields[...] sparse fieldset.
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # Safety overlap subtracted from the incremental watermark on every run, re-pulling a window of
+ # 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
@@ -149,14 +156,33 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
},
],
),
- # Klaviyo only exposes list membership as JSON:API relationship links on the profile/list
- # objects (API endpoints that can't be called from HogQL), so the many-to-many can't be joined.
- # This table follows those links to produce a flat {list_id, profile_id} join table. It fans out
- # one paginated request per list, so it's opt-in (off by default) to avoid the extra API cost.
+ # Klaviyo only exposes list membership through per-list endpoints (which can't be called from
+ # HogQL), so the many-to-many can't be joined. This table fans out one paginated request per list
+ # to produce a flat {list_id, profile_id, joined_group_at} join table; it's opt-in (off by
+ # default) to avoid the extra API cost.
+ #
+ # Incremental sync filters on `joined_group_at` (updated on re-join, so re-joins are picked up),
+ # but Klaviyo has no removal timestamp: profiles removed from a list only disappear on a full
+ # refresh. The 24h lookback re-pulls joins that landed in already-fetched lists mid-run; merge
+ # dedupes them on the primary key. No partition_key: the partitioned merge predicate includes
+ # partition equality, and a re-join moves the row's joined_group_at to a new partition, which
+ # would leave the old row behind as a duplicate.
"list_profiles": KlaviyoEndpointConfig(
name="list_profiles",
- path="/lists/{list_id}/relationships/profiles",
- incremental_fields=[],
+ path="/lists/{list_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=["list_id", "profile_id"],
should_sync_default=False,
fan_out_over_lists=True,
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 95a3df62796c..18bc1e9a1b85 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
@@ -106,24 +106,28 @@ 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
+ # 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} rows. Full refresh only"
+ 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"
+ )
return None
def _build_schema(endpoint: str) -> SourceSchema:
endpoint_config = KLAVIYO_ENDPOINTS[endpoint]
- # Fan-out endpoints have no server-side incremental filter, so they're full refresh only.
- has_incremental = (
- INCREMENTAL_FIELDS.get(endpoint, None) is not None and not endpoint_config.fan_out_over_lists
- )
+ has_incremental = INCREMENTAL_FIELDS.get(endpoint, None) is not None
return SourceSchema(
name=endpoint,
supports_incremental=has_incremental and endpoint not in append_only_endpoints,
- supports_append=has_incremental,
+ 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),
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 a2bcf2c6282a..d12ebed1aab4 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
@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.kl
_clamp_future_value_to_now,
_format_incremental_value,
get_rows,
+ klaviyo_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.settings import (
KLAVIYO_ENDPOINTS,
@@ -127,6 +128,42 @@ class TestBuildInitialParams:
)
assert params["filter"] == "greater-than(datetime,2026-03-04T02:58:14.000Z)"
+ def test_list_profiles_incremental_applies_lookback_and_extra_params(self) -> None:
+ # Dropping the 24h lookback silently loses joins that landed in already-fetched lists mid-run.
+ config = KLAVIYO_ENDPOINTS["list_profiles"]
+ params = _build_initial_params(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="joined_group_at",
+ )
+ assert params["filter"] == "greater-than(joined_group_at,2026-03-03T02:58:14.000Z)"
+ assert params["sort"] == "-joined_group_at"
+ assert params["fields[profile]"] == "joined_group_at"
+
+ def test_list_profiles_first_sync_has_no_filter(self) -> None:
+ # Mishandling a missing watermark (e.g. greater-than(joined_group_at,None)) 400s every first sync.
+ config = KLAVIYO_ENDPOINTS["list_profiles"]
+ params = _build_initial_params(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="joined_group_at",
+ )
+ assert "filter" not in params
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_lookback_applies_after_future_clamp(self) -> None:
+ # Clamping after the lookback would erase the overlap window for a future-dated cursor.
+ config = KLAVIYO_ENDPOINTS["list_profiles"]
+ params = _build_initial_params(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2027, 2, 5, 21, 46, 42, tzinfo=UTC),
+ incremental_field="joined_group_at",
+ )
+ assert params["filter"] == "greater-than(joined_group_at,2026-06-14T12:00:00.000Z)"
+
class TestClampFutureValueToNow:
@freeze_time("2026-06-15T12:00:00Z")
@@ -250,9 +287,19 @@ class _FakeResumableManager:
self.saved.append(data)
+def _list_url(list_id: str, filter_value: str | None = None) -> str:
+ filter_part = f"&filter={filter_value}" if filter_value else ""
+ return (
+ f"https://a.klaviyo.com/api/lists/{list_id}/profiles"
+ f"?page[size]=100{filter_part}&sort=-joined_group_at&fields[profile]=joined_group_at"
+ )
+
+
class TestListProfilesFanOut:
@staticmethod
- def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any]) -> list[dict]:
+ def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], **incremental: Any
+ ) -> list[dict]:
def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
result = pages[url]
if isinstance(result, Exception):
@@ -267,23 +314,25 @@ class TestListProfilesFanOut:
endpoint="list_profiles",
logger=MagicMock(),
resumable_source_manager=manager, # type: ignore[arg-type]
+ **incremental,
):
rows.extend(table.to_pylist())
return rows
- def test_config_is_fan_out_full_refresh(self) -> None:
+ 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.should_sync_default is False
assert config.primary_keys == ["list_id", "profile_id"]
- assert config.incremental_fields == []
- def test_schema_is_full_refresh_only_and_off_by_default(self) -> None:
+ def test_schema_supports_incremental_merge_but_not_append(self) -> None:
+ # Append mode would materialize the intentional 24h lookback re-pulls as duplicate rows.
schemas = {s.name: s for s in KlaviyoSource().get_schemas(MagicMock(), team_id=1)}
list_profiles = schemas["list_profiles"]
- assert list_profiles.supports_incremental is False
+ assert list_profiles.supports_incremental is True
assert list_profiles.supports_append is False
assert list_profiles.should_sync_default is False
+ assert [f["field"] for f in list_profiles.incremental_fields] == ["joined_group_at"]
def test_lists_request_stays_within_klaviyo_page_size_cap(self, monkeypatch: Any) -> None:
# Klaviyo's Get Lists endpoint caps page[size] at 10; a larger value 400s the whole fan-out.
@@ -304,42 +353,82 @@ class TestListProfilesFanOut:
"data": [{"id": "L1"}, {"id": "L2"}],
"links": {"next": None},
},
- "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=100": {
- "data": [{"type": "profile", "id": "P1"}, {"type": "profile", "id": "P2"}],
+ _list_url("L1"): {
+ "data": [
+ {"type": "profile", "id": "P1", "attributes": {"joined_group_at": "2025-11-08T00:00:00+00:00"}},
+ # An item without attributes must yield a null joined_group_at, not crash the sync.
+ {"type": "profile", "id": "P2"},
+ ],
"links": {"next": None},
},
- "https://a.klaviyo.com/api/lists/L2/relationships/profiles?page[size]=100": {
- "data": [{"type": "profile", "id": "P3"}],
+ _list_url("L2"): {
+ "data": [
+ {"type": "profile", "id": "P3", "attributes": {"joined_group_at": "2025-12-01T09:30:00+00:00"}}
+ ],
"links": {"next": None},
},
}
rows = self._collect(_FakeResumableManager(), monkeypatch, pages)
assert rows == [
- {"list_id": "L1", "profile_id": "P1"},
- {"list_id": "L1", "profile_id": "P2"},
- {"list_id": "L2", "profile_id": "P3"},
+ {"list_id": "L1", "profile_id": "P1", "joined_group_at": "2025-11-08T00:00:00+00:00"},
+ {"list_id": "L1", "profile_id": "P2", "joined_group_at": None},
+ {"list_id": "L2", "profile_id": "P3", "joined_group_at": "2025-12-01T09:30:00+00:00"},
]
+ def test_incremental_run_filters_with_lookback_on_every_list(self, monkeypatch: Any) -> None:
+ # Fixtures are keyed by exact URL, so this fails loudly (KeyError) if the fan-out stops
+ # forwarding the incremental inputs and silently reverts to a full refresh.
+ expected_filter = "greater-than(joined_group_at,2026-03-03T02:58:14.000Z)"
+ pages = {
+ "https://a.klaviyo.com/api/lists?page[size]=10": {
+ "data": [{"id": "L1"}, {"id": "L2"}],
+ "links": {"next": None},
+ },
+ _list_url("L1", filter_value=expected_filter): {
+ "data": [
+ {"type": "profile", "id": "P1", "attributes": {"joined_group_at": "2026-03-04T01:00:00+00:00"}}
+ ],
+ "links": {"next": None},
+ },
+ _list_url("L2", filter_value=expected_filter): {
+ "data": [],
+ "links": {"next": None},
+ },
+ }
+ rows = self._collect(
+ _FakeResumableManager(),
+ monkeypatch,
+ pages,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="joined_group_at",
+ )
+ assert rows == [{"list_id": "L1", "profile_id": "P1", "joined_group_at": "2026-03-04T01:00:00+00:00"}]
+
def test_follows_membership_pagination(self, monkeypatch: Any) -> None:
- next_url = "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[cursor]=abc"
+ next_url = "https://a.klaviyo.com/api/lists/L1/profiles?page[cursor]=abc"
pages = {
"https://a.klaviyo.com/api/lists?page[size]=10": {
"data": [{"id": "L1"}],
"links": {"next": None},
},
- "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=100": {
- "data": [{"type": "profile", "id": "P1"}],
+ _list_url("L1"): {
+ "data": [
+ {"type": "profile", "id": "P1", "attributes": {"joined_group_at": "2025-11-08T00:00:00+00:00"}}
+ ],
"links": {"next": next_url},
},
next_url: {
- "data": [{"type": "profile", "id": "P2"}],
+ "data": [
+ {"type": "profile", "id": "P2", "attributes": {"joined_group_at": "2025-11-07T00:00:00+00:00"}}
+ ],
"links": {"next": None},
},
}
rows = self._collect(_FakeResumableManager(), monkeypatch, pages)
assert rows == [
- {"list_id": "L1", "profile_id": "P1"},
- {"list_id": "L1", "profile_id": "P2"},
+ {"list_id": "L1", "profile_id": "P1", "joined_group_at": "2025-11-08T00:00:00+00:00"},
+ {"list_id": "L1", "profile_id": "P2", "joined_group_at": "2025-11-07T00:00:00+00:00"},
]
def test_resume_from_deleted_list_restarts_from_first(self, monkeypatch: Any) -> None:
@@ -348,14 +437,16 @@ class TestListProfilesFanOut:
"data": [{"id": "L1"}],
"links": {"next": None},
},
- "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=100": {
- "data": [{"type": "profile", "id": "P1"}],
+ _list_url("L1"): {
+ "data": [
+ {"type": "profile", "id": "P1", "attributes": {"joined_group_at": "2025-11-08T00:00:00+00:00"}}
+ ],
"links": {"next": None},
},
}
manager = _FakeResumableManager(KlaviyoResumeConfig(next_url=None, list_id="DELETED"))
rows = self._collect(manager, monkeypatch, pages)
- assert rows == [{"list_id": "L1", "profile_id": "P1"}]
+ assert rows == [{"list_id": "L1", "profile_id": "P1", "joined_group_at": "2025-11-08T00:00:00+00:00"}]
def test_list_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:
not_found = requests.HTTPError(response=_response_with_status(404))
@@ -364,20 +455,24 @@ class TestListProfilesFanOut:
"data": [{"id": "L1"}, {"id": "GONE"}, {"id": "L2"}],
"links": {"next": None},
},
- "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=100": {
- "data": [{"type": "profile", "id": "P1"}],
+ _list_url("L1"): {
+ "data": [
+ {"type": "profile", "id": "P1", "attributes": {"joined_group_at": "2025-11-08T00:00:00+00:00"}}
+ ],
"links": {"next": None},
},
- "https://a.klaviyo.com/api/lists/GONE/relationships/profiles?page[size]=100": not_found,
- "https://a.klaviyo.com/api/lists/L2/relationships/profiles?page[size]=100": {
- "data": [{"type": "profile", "id": "P2"}],
+ _list_url("GONE"): not_found,
+ _list_url("L2"): {
+ "data": [
+ {"type": "profile", "id": "P2", "attributes": {"joined_group_at": "2025-12-01T09:30:00+00:00"}}
+ ],
"links": {"next": None},
},
}
rows = self._collect(_FakeResumableManager(), monkeypatch, pages)
assert rows == [
- {"list_id": "L1", "profile_id": "P1"},
- {"list_id": "L2", "profile_id": "P2"},
+ {"list_id": "L1", "profile_id": "P1", "joined_group_at": "2025-11-08T00:00:00+00:00"},
+ {"list_id": "L2", "profile_id": "P2", "joined_group_at": "2025-12-01T09:30:00+00:00"},
]
def test_non_404_http_error_propagates(self, monkeypatch: Any) -> None:
@@ -387,7 +482,21 @@ class TestListProfilesFanOut:
"data": [{"id": "L1"}],
"links": {"next": None},
},
- "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=100": server_error,
+ _list_url("L1"): server_error,
}
with pytest.raises(requests.HTTPError):
self._collect(_FakeResumableManager(), monkeypatch, pages)
+
+
+class TestSourceResponseSortMode:
+ @parameterized.expand([("list_profiles", "desc"), ("events", "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.
+ response = klaviyo_source(
+ api_key="pk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.sort_mode == expected