: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
fix(warehouse): fail Klaviyo values reports without a conversion metric (#91825)
posthog[bot]a1ca0f5715da
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.pyindex e3d4d49a7dbc..04b548b3b539 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@@ -24,9 +24,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.seKLAVIYO_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"+# Klaviyo's reporting API only accepts a value-tracking metric (one that carries a monetary+# $value, like an order metric) as a values report's conversion metric; engagement metrics such as+# opens and clicks are rejected. Klaviyo has no "account default" flag to read and its /metrics+# response has no eligibility field, so resolution prefers these names its ecommerce integrations+# give the order metric, most likely first, before falling back to the account's first metric.+CONVERSION_METRIC_NAME_PREFERENCES = ("Placed Order", "Ordered Product")# Accounts have tens of metrics, so the fallback lookup stays bounded rather than walking forever.MAX_CONVERSION_METRIC_PAGES = 20@@ -40,6 +43,15 @@ class KlaviyoRetryableError(Exception):pass+class KlaviyoConversionMetricError(Exception):+ """A values report can't run because no eligible conversion metric is available.++ Raised instead of returning empty so the run fails visibly rather than finalizing green with+ zero rows. The outcome is deterministic — the same metric resolves on every retry — so it is+ registered as a non-retryable error that pauses the table with an actionable message.+ """++@dataclasses.dataclassclass KlaviyoResumeConfig:# Next page URL to fetch. None means "start the parent at its first page" — used when the@@ -439,26 +451,36 @@ def _resolve_conversion_metric_id("""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.+ read, so prefer a value-tracking metric by name (see CONVERSION_METRIC_NAME_PREFERENCES), then+ fall back to whatever metric the account defines first. A user who wants a different one, or+ whose account has no value-tracking metric, sets one on the source."""url = f"{KLAVIYO_BASE_URL}/metrics"first_metric_id: str | None = None+ # Best preferred-name match so far; a lower rank is a stronger preference.+ best_preferred_id: str | None = None+ best_preferred_rank: int | None = Nonefor _ 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"]+ name = item.get("attributes", {}).get("name")+ if name in CONVERSION_METRIC_NAME_PREFERENCES:+ rank = CONVERSION_METRIC_NAME_PREFERENCES.index(name)+ if rank == 0:+ return item["id"] # top preference, nothing can beat it+ if best_preferred_rank is None or rank < best_preferred_rank:+ best_preferred_rank = rank+ best_preferred_id = item["id"]next_url = data.get("links", {}).get("next")if not next_url:breakurl = next_url- return first_metric_id+ return best_preferred_id or first_metric_iddef _series_rows(@@ -540,10 +562,10 @@ def _get_values_report_rows(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"+ raise KlaviyoConversionMetricError(+ f"Klaviyo needs a conversion metric to sync {config.name}, but the account has none. "+ f"Set a conversion metric ID on the source, then re-enable this table.")- returnaccount_tz = _get_account_timezone(session, headers, logger) if report.timeframe_weeks is not None else UTCtimeframe, timeframe_label = _build_timeframe(report, datetime.now(account_tz))@@ -595,11 +617,11 @@ def _get_values_report_rows(and exc.response.status_code == 400and CONVERSION_METRIC_INELIGIBLE_DETAIL in exc.response.text):- logger.warning(- f"Klaviyo: conversion metric {metric_id} isn't eligible for values reporting on "- f"{config.name}; set a different conversion metric ID on the source, skipping"- )- return+ raise KlaviyoConversionMetricError(+ f"Klaviyo rejected conversion metric {metric_id} for {config.name}: it isn't eligible "+ f"for values reporting. Set an eligible conversion metric ID on the source, then "+ f"re-enable this table."+ ) from excraisediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.pyindex 94e1d97a5d59..41bb85a6d6cd 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@@ -527,8 +527,9 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {),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"+ "days, replaced in full on every sync. Needs a value-tracking conversion metric (such as "+ "Placed Order); set one on the source if your account has none. Conversion statistics use "+ "the conversion metric recorded in the conversion_metric_id column"),),"flow_values_reports": KlaviyoEndpointConfig(@@ -544,8 +545,9 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {),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"+ "replaced in full on every sync. Needs a value-tracking conversion metric (such as Placed "+ "Order); set one on the source if your account has none. Conversion statistics use the "+ "conversion metric recorded in the conversion_metric_id column"),),# Series reports carry the same statistics as the values reports above, but bucketed weekly over@@ -571,8 +573,10 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {),description=("Klaviyo's own flow-message performance statistics bucketed by week over the last 51 "- "weeks, one row per flow message per week. Weeks stay in the table after Klaviyo stops "- "returning them"+ "weeks, one row per flow message per week. Needs a value-tracking conversion metric (such "+ "as Placed Order); set one on the source if your account has none. Conversion statistics "+ "use the conversion metric recorded in the conversion_metric_id column. 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 todiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/source.pyindex f1dd4d6fff1a..a46b382cffea 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@@ -89,7 +89,7 @@ Grant read permissions for the data you want to sync. Tables you have not grante- Web feeds- Webhooks (requires Klaviyo's Advanced KDP add-on)-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).+The campaign and flow performance tables (campaign_values_reports, flow_values_reports, flow_series_reports) need a value-tracking conversion metric, such as Placed Order. Leave the conversion metric ID blank to select one automatically: your Placed Order metric, or Ordered Product if Placed Order is absent, and otherwise the first metric in your account. That last fallback may not be the metric you expect, so paste the ID of a specific value-tracking metric from [your Klaviyo metrics](https://www.klaviyo.com/analytics/metrics) to control the choice. If your account has no eligible metric, these tables pause with an error until you set one.""",iconPath="/static/services/klaviyo.png",docsUrl="https://posthog.com/docs/cdp/sources/klaviyo",@@ -111,6 +111,7 @@ The campaign and flow performance tables need a conversion metric. Leave the conrequired=False,placeholder="RESQ6t",secret=False,+ caption="Paste the ID of a value-tracking metric such as Placed Order from [your Klaviyo metrics](https://www.klaviyo.com/analytics/metrics). Engagement metrics such as opens and clicks are not eligible. Leave blank to auto-select one. Only the campaign and flow performance tables use it.",),],),@@ -127,6 +128,12 @@ The campaign and flow performance tables need a conversion metric. Leave the con# Ordered most-specific first: the first matching entry supplies the user-facing message# (see `update_external_data_job_model`), so plan gating must precede the blanket 403 entry.return {+ # The campaign and flow values reports need a value-tracking conversion metric. When the+ # account has none, or the resolved metric isn't eligible, the same result repeats on+ # every retry (see KlaviyoConversionMetricError), so classify it non-retryable and hand+ # the user the one action that fixes it rather than retrying into the same failure.+ "needs a conversion metric to sync": "This Klaviyo table needs a conversion metric, but your account has none that works. Set a conversion metric ID on the source (the ID of a value-tracking metric such as Placed Order), then re-enable this table.",+ "isn't eligible for values reporting": "The conversion metric used for this Klaviyo table isn't eligible for values reporting. Set the ID of a value-tracking metric (such as Placed Order) as the conversion metric ID on the source, then re-enable this table.",# Klaviyo gates some endpoints (webhooks today) behind its paid Advanced KDP add-on and# 403s with this body detail even when the key's read scope is granted. `_fetch_page`# appends the detail to the HTTPError message so it's matchable here; without this entrydiff --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.pyindex d035acd49644..9a5e2f725219 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@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.coKLAVIYO_API_VERSION_2026_07_15,)from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.klaviyo import (+ KlaviyoConversionMetricError,KlaviyoResumeConfig,_build_filter,_build_initial_params,@@ -240,6 +241,26 @@ class TestNonRetryableErrors:non_retryable_errors = KlaviyoSource().get_non_retryable_errors()assert not any(key in other_error for key in non_retryable_errors)+ @parameterized.expand(+ [+ # The conversion-metric messages KlaviyoConversionMetricError raises are deterministic, so+ # they must classify as non-retryable. The message wording and the source-side substring+ # live in two files; this locks them together so a reword can't silently make the failure+ # retry into the same result.+ (+ "no_metric",+ "Klaviyo needs a conversion metric to sync campaign_values_reports, but the account has none.",+ ),+ (+ "ineligible_metric",+ "Klaviyo rejected conversion metric M_X for flow_values_reports: it isn't eligible for values reporting.",+ ),+ ]+ )+ def test_conversion_metric_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable_errors = KlaviyoSource().get_non_retryable_errors()+ assert error_message_matches(observed_error, non_retryable_errors.keys())+@parameterized.expand([# A plan-gated 403 (e.g. webhooks without Advanced KDP) carries Klaviyo's body detail on@@ -969,10 +990,45 @@ class TestValuesReports:assert rows[0]["conversion_metric_id"] == "M_FIRST"- def test_ineligible_conversion_metric_skips_the_report_instead_of_failing_the_sync(self, monkeypatch: Any) -> None:+ def test_prefers_a_value_tracking_metric_over_the_accounts_first_metric(self, monkeypatch: Any) -> None:+ # Blindly taking the first metric picked an engagement metric that Klaviyo rejects for values+ # reporting. Resolution must prefer a value-tracking metric by name even when it is not first.+ 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_ENGAGEMENT", "attributes": {"name": "Viewed Product"}},+ {"id": "M_ORDERED", "attributes": {"name": "Ordered 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_ORDERED"++ def test_ineligible_conversion_metric_fails_the_sync_instead_of_finishing_empty(self, monkeypatch: Any) -> None:# Klaviyo rejects some metrics (e.g. system metrics) as conversion metrics for values- # reports; the same metric would be re-resolved on every retry, so this can never self-heal- # and must not fail the whole sync.+ # reports. Returning empty here finalized the run green with zero rows, so the broken table+ # looked healthy forever; the run must fail visibly with an actionable message instead.response = _response_with_status(400)response._content = (b'{"errors":[{"status":400,"code":"invalid","title":"Invalid input.",'@@ -988,7 +1044,7 @@ class TestValuesReports:return {"data": [{"id": "M_FIRST", "attributes": {"name": "Viewed Product"}}], "links": {}}monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)- assert (+ with pytest.raises(KlaviyoConversionMetricError, match="isn't eligible for values reporting"):list(get_rows(api_key="pk_test",@@ -997,12 +1053,10 @@ class TestValuesReports:resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]))- == []- )def test_unrelated_http_error_still_propagates(self, monkeypatch: Any) -> None:- # Only the specific ineligible-conversion-metric 400 should be swallowed; any other HTTP- # failure (e.g. a transient 500) must still fail the sync loudly rather than go silent.+ # Only the ineligible-conversion-metric 400 becomes a KlaviyoConversionMetricError; any other+ # HTTP failure (e.g. a transient 500) must propagate unchanged so it keeps its own handling.response = _response_with_status(500)response._content = b'{"errors":[{"status":500,"title":"Internal Server Error"}]}'@@ -1024,9 +1078,9 @@ class TestValuesReports:))- def test_account_with_no_metrics_yields_nothing_instead_of_posting_an_invalid_report(- self, monkeypatch: Any- ) -> None:+ def test_account_with_no_metrics_fails_instead_of_posting_an_invalid_report(self, monkeypatch: Any) -> None:+ # No conversion metric means no valid report to post. Failing loudly keeps the run from+ # finalizing green with zero rows against a table the user believes is syncing.def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None) -> dict:@@ -1034,7 +1088,7 @@ class TestValuesReports:return {"data": [], "links": {}}monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)- assert (+ with pytest.raises(KlaviyoConversionMetricError, match="needs a conversion metric"):list(get_rows(api_key="pk_test",@@ -1043,8 +1097,6 @@ class TestValuesReports:resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]))- == []- )class TestReportVariants: