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.

fix(klaviyo): skip values report when conversion metric is ineligible (#77321)

Tom Owers4c248c27d8c6
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 257cde31fa44..c34f28d98af9 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
@@ -28,6 +28,11 @@ 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
+# Klaviyo's exact detail string when a metric (configured or auto-resolved) can't be used as a
+# values report's conversion metric, e.g. a system metric Klaviyo doesn't allow for conversion
+# statistics. The same metric would be re-resolved on every retry, so this can never self-heal.
+CONVERSION_METRIC_INELIGIBLE_DETAIL = "does not support querying for values data"
+
class KlaviyoRetryableError(Exception):
pass
@@ -457,26 +462,39 @@ def _get_values_report_rows(
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,
- }
+ 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,
+ }
+ )
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ next_url = data.get("links", {}).get("next")
+ if not next_url:
+ break
+ url = next_url
+ except requests.HTTPError as exc:
+ if (
+ exc.response is not None
+ and exc.response.status_code == 400
+ and 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"
)
- if batcher.should_yield():
- yield batcher.get_table()
-
- next_url = data.get("links", {}).get("next")
- if not next_url:
- break
- url = next_url
+ return
+ raise
def get_rows(
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 4e5776e6cbbf..e4013e299188 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
@@ -793,6 +793,61 @@ 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:
+ # 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.
+ response = _response_with_status(400)
+ response._content = (
+ b'{"errors":[{"status":400,"code":"invalid","title":"Invalid input.",'
+ b'"detail":"Passed in conversion metric does not support querying for values data",'
+ b'"source":{"pointer":"/data/attributes/conversion_metric_id"}}]}'
+ )
+
+ 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:
+ raise requests.HTTPError(response=response)
+ return {"data": [{"id": "M_FIRST", "attributes": {"name": "Viewed Product"}}], "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]
+ )
+ )
+ == []
+ )
+
+ 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.
+ response = _response_with_status(500)
+ response._content = b'{"errors":[{"status":500,"title":"Internal Server Error"}]}'
+
+ 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:
+ raise requests.HTTPError(response=response)
+ return {"data": [{"id": "M_FIRST", "attributes": {"name": "Viewed Product"}}], "links": {}}
+
+ monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
+ with pytest.raises(requests.HTTPError):
+ list(
+ get_rows(
+ api_key="pk_test",
+ endpoint="campaign_values_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+
def test_account_with_no_metrics_yields_nothing_instead_of_posting_an_invalid_report(
self, monkeypatch: Any
) -> None: