: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(klaviyo): distinguish plan-gated 403s from missing key scopes (#78134)
jake sciottoac736f80f5b8
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.pyindex 4807c1e99e86..03e5f21631d0 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@@ -461,7 +461,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {},},"webhooks": {- "description": "A webhook Klaviyo posts events to.",+ "description": "A webhook Klaviyo posts events to. Requires Klaviyo's Advanced KDP add-on.","docs_url": "https://developers.klaviyo.com/en/reference/get_webhooks","columns": {"id": "Unique identifier for the webhook.",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 c34f28d98af9..373d2fc57a64 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@@ -202,6 +202,38 @@ def _build_initial_params(return params+def _extract_error_detail(response: requests.Response) -> str | None:+ """Pull the human-readable reason out of a Klaviyo JSON:API error body, if there is one."""+ try:+ errors = response.json().get("errors", [])+ details = [+ str(detail)+ for error in errors+ if isinstance(error, dict) and (detail := error.get("detail") or error.get("title"))+ ]+ return "; ".join(details)[:500] if details else None+ except Exception:+ return None+++def _raise_for_status_with_detail(response: requests.Response) -> None:+ """`raise_for_status`, with Klaviyo's error detail appended to the exception message.++ requests builds the HTTPError message from the status and URL alone, but a Klaviyo 403 carries+ the actual denial reason only in the body — a key missing a read scope and an endpoint the+ account's plan doesn't include (e.g. webhooks without Advanced KDP) are indistinguishable+ without it. Non-retryable classification matches on the exception message, so the detail must+ ride along. The response stays attached for handlers that branch on `exc.response`.+ """+ try:+ response.raise_for_status()+ except requests.HTTPError as exc:+ detail = _extract_error_detail(response)+ if detail:+ raise requests.HTTPError(f"{exc} ({detail})", response=response) from exc+ raise++@retry(# ChunkedEncodingError is a mid-stream connection break (the server truncated a chunked# response body); it's transient like ConnectionError/ReadTimeout, not a ConnectionError subclass.@@ -237,7 +269,7 @@ def _fetch_page(# 404 is expected and handled during a fan-out (a parent deleted mid-sync).log = logger.warning if response.status_code == 404 else logger.errorlog(f"Klaviyo API error: status={response.status_code}, body={response.text}, url={page_url}")- response.raise_for_status()+ _raise_for_status_with_detail(response)return response.json()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.pyindex b69864abcded..4f8361e62e1d 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@@ -633,6 +633,11 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {path="/webhooks",page_size=0,incremental_fields=[],+ # Klaviyo only offers the webhooks API to accounts with its paid Advanced KDP add-on and+ # 403s for everyone else even with the webhooks read scope granted, so a default-on table+ # would fail the first sync for most connections.+ should_sync_default=False,+ description="Requires Klaviyo's Advanced KDP add-on",),"accounts": KlaviyoEndpointConfig(name="accounts",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.pyindex 20a71ae69b76..097527b2a969 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@@ -87,7 +87,7 @@ Grant read permissions for the data you want to sync. Tables you have not grante- Tags- Templates- Web feeds-- Webhooks+- 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).""",@@ -124,7 +124,14 @@ The campaign and flow performance tables need a conversion metric. Leave the conreturn CANONICAL_DESCRIPTIONSdef get_non_retryable_errors(self) -> dict[str, str | None]:+ # 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 {+ # 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 entry+ # the blanket 403 mapping below blames the key's scopes, which the user can never fix.+ "You must have Advanced KDP enabled": "Your Klaviyo plan does not include API access to this table. Klaviyo limits this endpoint to accounts with the Advanced KDP add-on, even when the API key has the required read scope. Syncing is paused for this table; re-enable it if you add Advanced KDP to your Klaviyo account.",# An invalid, revoked, or insufficiently-scoped Klaviyo API key surfaces as a requests# HTTPError when `fetch_page` calls `raise_for_status()`. Retrying can never satisfy a# credential problem, so stop the sync. Match the stable status text and base host, notdiff --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 52319f3924b4..4fdccb8df8af 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@@ -1,3 +1,4 @@+import jsonfrom datetime import UTC, date, datetimefrom typing import Any@@ -8,6 +9,7 @@ from unittest.mock import MagicMock, patchimport requestsfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.klaviyo import (KlaviyoSourceConfig,)@@ -236,6 +238,36 @@ 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(+ [+ # A plan-gated 403 (e.g. webhooks without Advanced KDP) carries Klaviyo's body detail on+ # the message and must map to the plan message, not the scope one the user can't act on.+ (+ "plan_gated",+ "HTTPError: 403 Client Error: Forbidden for url: https://a.klaviyo.com/api/webhooks (You must have Advanced KDP enabled to use this endpoint.)",+ "Advanced KDP add-on",+ ),+ # A scope-denied 403 keeps pointing at the key's read scopes.+ (+ "scope_missing",+ "HTTPError: 403 Client Error: Forbidden for url: https://a.klaviyo.com/api/metrics",+ "missing the read permissions",+ ),+ ]+ )+ def test_first_matching_entry_supplies_the_user_facing_message(+ self, _name: str, observed_error: str, expected_snippet: str+ ) -> None:+ # Mirrors update_external_data_job_model: the first matching entry becomes the user-facing+ # error, so reordering the dict (or broadening a pattern) regresses the shown message.+ matches = [+ friendly+ for pattern, friendly in KlaviyoSource().get_non_retryable_errors().items()+ if error_message_matches(observed_error, [pattern])+ ]+ assert matches and matches[0] is not None+ assert expected_snippet in matches[0]+class TestFetchPageRetries:@parameterized.expand(@@ -273,12 +305,69 @@ class TestFetchPageRetries:assert session.get.call_count == 5-def _response_with_status(status_code: int) -> requests.Response:+def _response_with_status(status_code: int, body: bytes | None = None, url: str | None = None) -> requests.Response:response = requests.Response()response.status_code = status_code+ if body is not None:+ response._content = body+ if url is not None:+ response.url = urlreturn response+class TestFetchPageErrorDetail:+ _url = "https://a.klaviyo.com/api/webhooks"++ def _session_returning(self, response: requests.Response) -> MagicMock:+ session = MagicMock()+ session.get.return_value = response+ return session++ def test_klaviyo_detail_rides_on_the_http_error(self) -> None:+ # A 403's status and URL alone can't distinguish a key missing a read scope from an endpoint+ # the account's Klaviyo plan doesn't include; without the body detail on the message, the+ # non-retryable mapping blames scopes the user may have already granted.+ body = json.dumps(+ {+ "errors": [+ {+ "code": "permission_denied",+ "title": "You do not have permission to perform this action.",+ "detail": "You must have Advanced KDP enabled to use this endpoint.",+ }+ ]+ }+ ).encode()++ with pytest.raises(requests.HTTPError) as exc_info:+ klaviyo._fetch_page(+ self._session_returning(_response_with_status(403, body=body, url=self._url)),+ self._url,+ {},+ MagicMock(),+ )++ assert "You must have Advanced KDP enabled to use this endpoint." in str(exc_info.value)+ assert "403 Client Error" in str(exc_info.value)+ assert self._url in str(exc_info.value)+ # Fan-out handlers branch on `exc.response.status_code`, so the response must stay attached.+ assert exc_info.value.response is not None+ assert exc_info.value.response.status_code == 403++ def test_non_json_error_body_still_raises_the_plain_error(self) -> None:+ # A gateway HTML error page must not crash detail extraction and mask the real HTTPError.+ with pytest.raises(requests.HTTPError) as exc_info:+ klaviyo._fetch_page(+ self._session_returning(_response_with_status(403, body=b"<html>denied</html>", url=self._url)),+ self._url,+ {},+ MagicMock(),+ )++ assert "403 Client Error" in str(exc_info.value)+ assert self._url in str(exc_info.value)++class _FakeResumableManager:def __init__(self, state: KlaviyoResumeConfig | None = None) -> None:self._state = state@@ -977,6 +1066,12 @@ class TestNewSchemas:schemas = {s.name for s in KlaviyoSource().get_schemas(MagicMock(), team_id=1)}assert schemas == set(KLAVIYO_ENDPOINTS)+ def test_plan_gated_webhooks_is_opt_in(self) -> None:+ # Klaviyo only offers the webhooks API with its paid Advanced KDP add-on, so a default-on+ # table would fail the first sync for every other account.+ schemas = {s.name: s for s in KlaviyoSource().get_schemas(MagicMock(), team_id=1)}+ assert schemas["webhooks"].should_sync_default is False+class TestSourceResponseSortMode:@parameterized.expand(