: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add opt-in Klaviyo list_profiles join table (#65150)
Luke Belton91d3f36603fe
diff --git a/posthog/temporal/data_imports/sources/klaviyo/klaviyo.py b/posthog/temporal/data_imports/sources/klaviyo/klaviyo.pyindex 2649fff5ba80..d50eea7cd2eb 100644--- a/posthog/temporal/data_imports/sources/klaviyo/klaviyo.py+++ b/posthog/temporal/data_imports/sources/klaviyo/klaviyo.py@@ -22,7 +22,13 @@ class KlaviyoRetryableError(Exception):@dataclasses.dataclassclass KlaviyoResumeConfig:- next_url: str+ # 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_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.+ list_id: str | None = Nonedef _format_datetime_z(dt: datetime) -> str:@@ -153,6 +159,109 @@ def _build_initial_params(return params+@retry(+ retry=retry_if_exception_type((KlaviyoRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict:+ response = session.get(page_url, headers=headers, 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).+ 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()++ 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."""+ url = _build_url(f"{KLAVIYO_BASE_URL}/lists", {"page[size]": 100})+ while True:+ data = _fetch_page(session, url, headers, logger)+ for item in data.get("data", []):+ yield item["id"]++ next_url = data.get("links", {}).get("next")+ if not next_url:+ break+ url = next_url+++def _get_list_profile_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[KlaviyoResumeConfig],+) -> 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.+ """+ 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.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = list_ids+ 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) :]+ resume_url = resume.next_url+ logger.debug(f"Klaviyo: resuming list_profiles from list_id={resume.list_id}, url={resume_url}")++ for index, list_id in enumerate(remaining):+ url = resume_url or _build_url(+ f"{KLAVIYO_BASE_URL}/lists/{list_id}/relationships/profiles", {"page[size]": 1000}+ )+ resume_url = None # only the resumed-into list uses the saved URL; the rest start fresh++ try:+ while True:+ data = _fetch_page(session, url, headers, logger)+ items = data.get("data", [])+ next_url = data.get("links", {}).get("next")++ for item in items:+ batcher.batch({"list_id": list_id, "profile_id": item["id"]})++ 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))++ 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.+ 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")+ 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.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(KlaviyoResumeConfig(next_url=None, list_id=remaining[index + 1]))++def get_rows(api_key: str,endpoint: str,@@ -165,6 +274,15 @@ def get_rows(config = KLAVIYO_ENDPOINTS[endpoint]headers = _get_headers(api_key)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+ # connection alive instead of re-handshaking per request.+ session = make_tracked_session()++ if config.fan_out_over_lists:+ yield from _get_list_profile_rows(session, headers, logger, batcher, resumable_source_manager)+ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+ returnparams = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field@@ -173,32 +291,14 @@ def get_rows(# Check for resume stateresume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- if resume_config is not None:+ if resume_config is not None and resume_config.next_url:url = resume_config.next_urllogger.debug(f"Klaviyo: resuming from URL: {url}")else:url = _build_url(f"{KLAVIYO_BASE_URL}{config.path}", params)- @retry(- retry=retry_if_exception_type((KlaviyoRetryableError, requests.ReadTimeout, requests.ConnectionError)),- stop=stop_after_attempt(5),- wait=wait_exponential_jitter(initial=1, max=30),- reraise=True,- )- def fetch_page(page_url: str) -> dict:- response = make_tracked_session().get(page_url, headers=headers, 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:- logger.error(f"Klaviyo API error: status={response.status_code}, body={response.text}, url={page_url}")- response.raise_for_status()-- return response.json()-while True:- data = fetch_page(url)+ data = _fetch_page(session, url, headers, logger)items = data.get("data", [])if not items:@@ -250,7 +350,7 @@ def klaviyo_source(db_incremental_field_last_value=db_incremental_field_last_value,incremental_field=incremental_field,),- primary_keys=["id"],+ primary_keys=endpoint_config.primary_keys,partition_count=1,partition_size=1,partition_mode="datetime" if endpoint_config.partition_key else None,diff --git a/posthog/temporal/data_imports/sources/klaviyo/settings.py b/posthog/temporal/data_imports/sources/klaviyo/settings.pyindex bd6a415b0ba3..2921e603152c 100644--- a/posthog/temporal/data_imports/sources/klaviyo/settings.py+++ b/posthog/temporal/data_imports/sources/klaviyo/settings.py@@ -1,4 +1,4 @@-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Optionalfrom products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType@@ -17,6 +17,12 @@ class KlaviyoEndpointConfig:page_size: Optional[int] = None # Override default page size (100)sort: Optional[str] = None # Sort field for the endpointdefault_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.+ # When True, `path` is a template with a `{list_id}` placeholder.+ fan_out_over_lists: bool = FalseKLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {@@ -143,6 +149,18 @@ 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.+ "list_profiles": KlaviyoEndpointConfig(+ name="list_profiles",+ path="/lists/{list_id}/relationships/profiles",+ incremental_fields=[],+ primary_keys=["list_id", "profile_id"],+ should_sync_default=False,+ fan_out_over_lists=True,+ ),}ENDPOINTS = tuple(KLAVIYO_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/klaviyo/source.py b/posthog/temporal/data_imports/sources/klaviyo/source.pyindex 1f567fbdd35e..82c8ac539008 100644--- a/posthog/temporal/data_imports/sources/klaviyo/source.py+++ b/posthog/temporal/data_imports/sources/klaviyo/source.py@@ -20,7 +20,7 @@ from posthog.temporal.data_imports.sources.klaviyo.klaviyo import (klaviyo_source,validate_credentials as validate_klaviyo_credentials,)-from posthog.temporal.data_imports.sources.klaviyo.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.klaviyo.settings import ENDPOINTS, INCREMENTAL_FIELDS, KLAVIYO_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -89,17 +89,29 @@ Make sure to grant the following read permissions:# Events are immutable - append-only is the only sync modeappend_only_endpoints = {"events"}- schemas = [- SourceSchema(+ 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 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+ )+ return SourceSchema(name=endpoint,- supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None- and endpoint not in append_only_endpoints,- supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ supports_incremental=has_incremental and endpoint not in append_only_endpoints,+ supports_append=has_incremental,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- description="Only syncs the last 365 days on initial sync" if endpoint == "events" else None,+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),)- for endpoint in list(ENDPOINTS)- ]++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]if names is not None:names_set = set(names)schemas = [s for s in schemas if s.name in names_set]diff --git a/posthog/temporal/data_imports/sources/klaviyo/test_klaviyo.py b/posthog/temporal/data_imports/sources/klaviyo/test_klaviyo.pyindex dd23133cc695..1f7c379a3acc 100644--- a/posthog/temporal/data_imports/sources/klaviyo/test_klaviyo.py+++ b/posthog/temporal/data_imports/sources/klaviyo/test_klaviyo.py@@ -1,14 +1,21 @@from datetime import UTC, date, datetime+from typing import Any+import pytestfrom freezegun import freeze_time+from unittest.mock import MagicMock+import requestsfrom parameterized import parameterized+from posthog.temporal.data_imports.sources.klaviyo import klaviyofrom posthog.temporal.data_imports.sources.klaviyo.klaviyo import (+ KlaviyoResumeConfig,_build_filter,_build_initial_params,_clamp_future_value_to_now,_format_incremental_value,+ get_rows,)from posthog.temporal.data_imports.sources.klaviyo.settings import KLAVIYO_ENDPOINTS, KlaviyoEndpointConfigfrom posthog.temporal.data_imports.sources.klaviyo.source import KlaviyoSource@@ -181,3 +188,154 @@ class TestNonRetryableErrors:def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:non_retryable_errors = KlaviyoSource().get_non_retryable_errors()assert not any(key in other_error for key in non_retryable_errors)+++def _response_with_status(status_code: int) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ return response+++class _FakeResumableManager:+ def __init__(self, state: KlaviyoResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[KlaviyoResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> KlaviyoResumeConfig | None:+ return self._state++ def save_state(self, data: KlaviyoResumeConfig) -> None:+ self.saved.append(data)+++class TestListProfilesFanOut:+ @staticmethod+ def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any]) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> 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="list_profiles",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ return rows++ def test_config_is_fan_out_full_refresh(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:+ 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_append is False+ assert list_profiles.should_sync_default is False++ def test_fans_out_over_every_list_into_membership_rows(self, monkeypatch: Any) -> None:+ pages = {+ "https://a.klaviyo.com/api/lists?page[size]=100": {+ "data": [{"id": "L1"}, {"id": "L2"}],+ "links": {"next": None},+ },+ "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=1000": {+ "data": [{"type": "profile", "id": "P1"}, {"type": "profile", "id": "P2"}],+ "links": {"next": None},+ },+ "https://a.klaviyo.com/api/lists/L2/relationships/profiles?page[size]=1000": {+ "data": [{"type": "profile", "id": "P3"}],+ "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"},+ ]++ def test_follows_membership_pagination(self, monkeypatch: Any) -> None:+ next_url = "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[cursor]=abc"+ pages = {+ "https://a.klaviyo.com/api/lists?page[size]=100": {+ "data": [{"id": "L1"}],+ "links": {"next": None},+ },+ "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=1000": {+ "data": [{"type": "profile", "id": "P1"}],+ "links": {"next": next_url},+ },+ next_url: {+ "data": [{"type": "profile", "id": "P2"}],+ "links": {"next": None},+ },+ }+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [+ {"list_id": "L1", "profile_id": "P1"},+ {"list_id": "L1", "profile_id": "P2"},+ ]++ def test_resume_from_deleted_list_restarts_from_first(self, monkeypatch: Any) -> None:+ pages = {+ "https://a.klaviyo.com/api/lists?page[size]=100": {+ "data": [{"id": "L1"}],+ "links": {"next": None},+ },+ "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=1000": {+ "data": [{"type": "profile", "id": "P1"}],+ "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"}]++ def test_list_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:+ not_found = requests.HTTPError(response=_response_with_status(404))+ pages = {+ "https://a.klaviyo.com/api/lists?page[size]=100": {+ "data": [{"id": "L1"}, {"id": "GONE"}, {"id": "L2"}],+ "links": {"next": None},+ },+ "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=1000": {+ "data": [{"type": "profile", "id": "P1"}],+ "links": {"next": None},+ },+ "https://a.klaviyo.com/api/lists/GONE/relationships/profiles?page[size]=1000": not_found,+ "https://a.klaviyo.com/api/lists/L2/relationships/profiles?page[size]=1000": {+ "data": [{"type": "profile", "id": "P2"}],+ "links": {"next": None},+ },+ }+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [+ {"list_id": "L1", "profile_id": "P1"},+ {"list_id": "L2", "profile_id": "P2"},+ ]++ def test_non_404_http_error_propagates(self, monkeypatch: Any) -> None:+ server_error = requests.HTTPError(response=_response_with_status(500))+ pages = {+ "https://a.klaviyo.com/api/lists?page[size]=100": {+ "data": [{"id": "L1"}],+ "links": {"next": None},+ },+ "https://a.klaviyo.com/api/lists/L1/relationships/profiles?page[size]=1000": server_error,+ }+ with pytest.raises(requests.HTTPError):+ self._collect(_FakeResumableManager(), monkeypatch, pages)