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.

14.0 KB
Raw Blame
from datetime import date
from typing import Optional, cast

from products.warehouse_sources.sources.klaviyo._config import KlaviyoSourceConfig
from products.warehouse_sources.sources.klaviyo.constants import (
    KLAVIYO_API_VERSION_2024_10_15,
    KLAVIYO_API_VERSION_2026_07_15,
)
from products.warehouse_sources.sources.klaviyo.klaviyo import (
    KlaviyoResumeConfig,
    klaviyo_source,
    validate_credentials as validate_klaviyo_credentials,
)
from products.warehouse_sources.sources.klaviyo.settings import ENDPOINTS, INCREMENTAL_FIELDS, KLAVIYO_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ProductKey,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    VersionDeprecation,
    detect,
)

# Shown in the schema picker against a table the source's API version does not serve.
KLAVIYO_NEWER_VERSION_REQUIRED = (
    "Needs a newer Klaviyo API version than your source uses. Contact PostHog support to upgrade the source."
)

# `_fetch_page` (klaviyo.py) already retries a read timeout, a dropped connection, or a mid-stream
# truncation via tenacity; requests/urllib3 report all three in this wording, with Klaviyo's fixed
# API host rather than anything the customer configured. A failure that outlives that retry budget
# still gets a full Temporal retry of the activity, so it must stay retryable.
KLAVIYO_TRANSIENT_CONNECTION_MARKERS = (
    "HTTPSConnectionPool(host='a.klaviyo.com'",
    "Connection broken:",
)

KLAVIYO_TRANSIENT_CONNECTION_MESSAGE = (
    "Klaviyo's API was slow to respond, so this sync run did not finish. This usually clears on "
    "its own and the next sync runs on schedule."
)


@SourceRegistry.register
class KlaviyoSource(ResumableSource[KlaviyoSourceConfig, KlaviyoResumeConfig]):
    codebase_detection = detect(
        env=("^KLAVIYO_",),
        script_hosts=(
            "static.klaviyo.com",
            "static-tracking.klaviyo.com",
            "static-forms.klaviyo.com",
            "fast.a.klaviyo.com",
            "a.klaviyo.com",
            "www.klaviyo.com",
        ),
        npm=("klaviyo-api", "klaviyo-react-native-sdk", "klaviyo-expo-plugin", "klaviyo-sdk", "node-klaviyo"),
        pypi=("klaviyo-api", "klaviyo", "klaviyo-sdk", "headless-klaviyo", "klaviyo-mcp-server"),
        cocoapods=("KlaviyoSwift", "KlaviyoCore", "KlaviyoForms", "KlaviyoSwiftExtension", "KlaviyoLocation"),
        composer=(
            "klaviyo/api",
            "klaviyo/php-sdk",
            "klaviyo/sdk",
            "klaviyo/magento2-extension",
            "klaviyo/shopware-klaviyo",
        ),
        go=("github.com/klaviyo/klaviyo-cli",),
        hex=("klaviyo",),
        maven=(
            "com.github.klaviyo.klaviyo-android-sdk:analytics",
            "com.github.klaviyo.klaviyo-android-sdk:push-fcm",
            "com.github.klaviyo.klaviyo-android-sdk:forms",
            "com.github.klaviyo.klaviyo-android-sdk:location",
            "com.github.klaviyo.klaviyo-android-sdk:core",
            "com.github.klaviyo.klaviyo-android-sdk:forms-core",
            "com.github.klaviyo.klaviyo-android-sdk:location-core",
        ),
        pub=("klaviyo_flutter_sdk", "klaviyo_flutter"),
        rubygems=("klaviyo-api-sdk", "klaviyo", "klaviyo_sdk"),
        swiftpm=("github.com/klaviyo/klaviyo-swift-sdk",),
        alternative_to=(ProductKey.WORKFLOWS,),
    )

    supported_versions = (KLAVIYO_API_VERSION_2024_10_15, KLAVIYO_API_VERSION_2026_07_15)
    default_version = KLAVIYO_API_VERSION_2026_07_15
    api_docs_url = "https://developers.klaviyo.com"
    # Klaviyo retires a revision two years after release, falling forward / returning 410 thereafter.
    deprecated_versions = (VersionDeprecation(version=KLAVIYO_API_VERSION_2024_10_15, sunset_at=date(2026, 10, 15)),)

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.KLAVIYO

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.KLAVIYO,
            category=DataWarehouseSourceCategory.MARKETING___EMAIL,
            label="Klaviyo",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Klaviyo API key to automatically pull your Klaviyo data into the PostHog Data warehouse.

You can create a private API key in your [Klaviyo account settings](https://www.klaviyo.com/settings/account/api-keys).

Grant read permissions for the data you want to sync. Tables you have not granted access to are skipped:
- Accounts
- Campaigns
- Catalogs
- Coupon codes
- Coupons
- Custom objects
- Events
- Flows
- Forms
- Images
- Lists
- Metrics
- Profiles
- Push tokens
- Reviews
- Segments
- Tags
- Templates
- Web feeds
- Webhooks (requires Klaviyo's Advanced KDP add-on)

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",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="pk_...",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="conversion_metric_id",
                        sync_setting=True,
                        label="Conversion metric ID (optional)",
                        type=SourceFieldInputConfigType.TEXT,
                        required=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.",
                    ),
                ],
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.klaviyo.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def 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 {
            # 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 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, not
            # the per-request path/query/timestamp.
            "401 Client Error: Unauthorized for url: https://a.klaviyo.com": "Your Klaviyo API key is invalid or has been revoked. Create a new private API key in your Klaviyo account settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://a.klaviyo.com": "Your Klaviyo API key is missing the read permissions needed to sync this data. Grant the required read scopes in your Klaviyo account settings, then reconnect.",
            # Raised by klaviyo_source for a table the source's pinned revision does not serve. Moving a
            # source to a newer revision is a support-run migration, so that is the next step.
            "requires Klaviyo API version": "This table needs a newer Klaviyo API version than your source uses. Contact PostHog support to upgrade the source, then re-enable this table.",
        }

    def get_retryable_errors(self) -> set[str]:
        return set(KLAVIYO_TRANSIENT_CONNECTION_MARKERS)

    def get_retry_exhausted_errors(self) -> dict[str, str]:
        return dict.fromkeys(KLAVIYO_TRANSIENT_CONNECTION_MARKERS, KLAVIYO_TRANSIENT_CONNECTION_MESSAGE)

    def get_schemas(
        self,
        config: KlaviyoSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Events are immutable - append-only is the only sync mode
        append_only_endpoints = {"events"}
        # An endpoint's incremental lookback intentionally re-pulls a window of rows each run, and a
        # report re-posts its whole window every run; only merge dedupes those on the primary key,
        # append would materialize them as duplicates.
        merge_only_endpoints = {
            name
            for name, endpoint_config in KLAVIYO_ENDPOINTS.items()
            if endpoint_config.incremental_lookback or endpoint_config.values_report is not None
        }

        resolved_version = self.resolve_api_version(api_version)

        def _build_schema(endpoint: str) -> SourceSchema:
            endpoint_config = KLAVIYO_ENDPOINTS[endpoint]
            has_incremental = INCREMENTAL_FIELDS.get(endpoint, None) is not None
            # A table the source's revision does not serve stays listed, because a schema-level version
            # override can still sync it, and discovery disables any enabled table it stops listing.
            # Default-off keeps auto-sync from enabling it into a sync that can only fail.
            served = endpoint_config.is_served_at(resolved_version)
            return SourceSchema(
                name=endpoint,
                supports_incremental=has_incremental and endpoint not in append_only_endpoints,
                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 and served,
                description=endpoint_config.description if served else KLAVIYO_NEWER_VERSION_REQUIRED,
            )

        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]
        return schemas

    def validate_credentials(
        self,
        config: KlaviyoSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_klaviyo_credentials(config.api_key, self.resolve_api_version(api_version))

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KlaviyoResumeConfig]:
        return ResumableSourceManager[KlaviyoResumeConfig](inputs, KlaviyoResumeConfig)

    def source_for_pipeline(
        self,
        config: KlaviyoSourceConfig,
        resumable_source_manager: ResumableSourceManager[KlaviyoResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return klaviyo_source(
            api_key=config.api_key,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            resumable_source_manager=resumable_source_manager,
            api_version=self.resolve_api_version(inputs.api_version),
            should_use_incremental_field=inputs.should_use_incremental_field,
            db_incremental_field_last_value=inputs.db_incremental_field_last_value
            if inputs.should_use_incremental_field
            else None,
            incremental_field=inputs.incremental_field,
            conversion_metric_id=config.conversion_metric_id,
        )