: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): implement churnkey import source (#66724)
Tom Owers39f29fe9be30
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3dcadab75eb4..523914290290 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -80,6 +80,7 @@ the row lists both.| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ || chargedesk | HTTP | requests | ✅ || checkout_com | HTTP | requests | ✅ |+| churnkey | HTTP | requests | ✅ || coda | HTTP | requests | ✅ || coin_api | HTTP | requests | ✅ || coingecko | HTTP | requests | ✅ |@@ -344,7 +345,6 @@ doesn't conflict with concurrent PRs.- chatwoot- chift- chorus-- churnkey- cin7- cisco_meraki- clarifaidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/canonical_descriptions.pynew file mode 100644index 000000000000..6ff67c84de24--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/canonical_descriptions.py@@ -0,0 +1,41 @@+"""Canonical, documentation-sourced descriptions for Churnkey Data API endpoints and columns.++Sourced from the official Churnkey Data API reference (https://docs.churnkey.co/data-api).+Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Churnkey table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Sessions": {+ "description": "A single cancel-flow session: one customer's pass through Churnkey's cancellation flow, including the offers presented, what they accepted, and the eventual outcome.",+ "docs_url": "https://docs.churnkey.co/data-api",+ "columns": {+ "_id": "Unique identifier for the session.",+ "org": "Identifier of the Churnkey organization the session belongs to.",+ "blueprintId": "Identifier of the cancel-flow blueprint used for this session.",+ "segmentId": "Identifier of the customer segment matched for this session.",+ "abtest": "Identifier of the A/B test variant the session was bucketed into, if any.",+ "customer": "Nested object describing the customer (id, email, subscription, plan, billing interval, currency).",+ "acceptedOffer": "Nested object describing the offer the customer accepted (guid, offerType, pause interval/duration), if any.",+ "provider": "Billing provider associated with the customer's subscription (e.g. Stripe).",+ "aborted": "Whether the customer abandoned the flow before completing it.",+ "canceled": "Whether the subscription was ultimately canceled.",+ "surveyId": "Identifier of the cancellation survey presented.",+ "surveyChoiceId": "Identifier of the survey answer the customer selected.",+ "surveyChoiceValue": "Human-readable value of the selected survey answer.",+ "feedback": "Free-text feedback the customer left during the flow.",+ "discountCooldownApplied": "Whether a discount cooldown prevented re-offering a discount.",+ "customActionHandler": "Identifier of a custom action handler invoked during the flow, if any.",+ "presentedOffers": "Array of every offer presented in the session, each with its type, configuration, and accepted/declined timestamps.",+ "mode": "Mode the session ran in (e.g. live or test).",+ "createdAt": "Time at which the session was created.",+ "updatedAt": "Time at which the session was last updated.",+ "recordingStartTime": "Start time of the associated session recording, if any.",+ "recordingEndTime": "End time of the associated session recording, if any.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/churnkey.docs.md b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/churnkey.docs.mdnew file mode 100644index 000000000000..3d3a3cc0d313--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/churnkey.docs.md@@ -0,0 +1,56 @@+---+title: Linking Churnkey as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Churnkey+---++import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"+import SyncModes from "../\_snippets/sync-modes.mdx"+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"+import AlphaRelease from "../\_snippets/alpha-release.mdx"++<AlphaRelease />++[Churnkey](https://churnkey.co) is a churn-prevention and failed-payment-recovery platform for subscription businesses. This source syncs your Churnkey cancel-flow **sessions** into the PostHog Data warehouse, so you can analyze why customers cancel, which retention offers they accept, and how your cancel flow performs alongside the rest of your product data.++## Prerequisites++To connect Churnkey, you need:++- A Churnkey account with cancel flows installed.+- A **Data API key**. This is distinct from your Cancel Flow API key and must be requested from Churnkey support at [[email protected]](mailto:[email protected]).+- Your **App ID**, found in Churnkey under **Settings → Account** (the Data API key is shown there too).++## Adding a data source++<SourceSetupIntro />++Provide the following credentials:++- **Data API key**: the `data_…` key issued by Churnkey support.+- **App ID**: your Churnkey application ID from **Settings → Account**.++Both are sent to the Churnkey Data API (`https://api.churnkey.co/v1/data`) on every request — the key in the `x-ck-api-key` header and the App ID in the `x-ck-app` header.++## Sync modes++<SyncModes />++The Churnkey Data API does not expose a per-record update cursor for sessions, so this source syncs **full refresh** only. Each sync re-pulls the sessions and de-duplicates on the session ID.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **"Invalid Churnkey Data API key"** — confirm you are using the **Data API key** (request it from [[email protected]](mailto:[email protected])), not your Cancel Flow API key.+- **"Churnkey App ID not recognized"** — copy the App ID exactly as shown under **Settings → Account**; an unknown App ID is rejected by the API.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/churnkey.py b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/churnkey.pynew file mode 100644index 000000000000..d1cc1991640e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/churnkey.py@@ -0,0 +1,138 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.settings import (+ CHURNKEY_BASE_URL,+ CHURNKEY_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++class ChurnkeyRetryableError(Exception):+ pass+++class ChurnkeyResumeConfig:+ # Offset (number of records to skip) for the next page to fetch. The API paginates via+ # `limit`/`skip`, so the offset is the only state we need to resume a full refresh.+ skip: int = 0+++def _get_headers(api_key: str, app_id: str) -> dict[str, str]:+ return {+ "x-ck-api-key": api_key,+ "x-ck-app": app_id,+ "content-type": "application/json",+ "accept": "application/json",+ }+++@retry(+ retry=retry_if_exception_type((ChurnkeyRetryableError, 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, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ response = session.get(url, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise ChurnkeyRetryableError(f"Churnkey API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Churnkey API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # The sessions endpoint returns a bare JSON array, not a `{"data": [...]}` envelope.+ if not isinstance(data, list):+ return []+ return data+++def validate_credentials(api_key: str, app_id: str) -> tuple[bool, Optional[int]]:+ """Probe the sessions endpoint with the smallest possible request.++ Returns ``(is_valid, status_code)``. A network failure surfaces as ``(False, None)``.+ """+ url = f"{CHURNKEY_BASE_URL}/sessions?{urlencode({'limit': 1})}"+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key, app_id), timeout=10)+ return response.status_code == 200, response.status_code+ except Exception:+ return False, None+++def get_rows(+ api_key: str,+ app_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChurnkeyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = CHURNKEY_ENDPOINTS[endpoint]+ headers = _get_headers(api_key, app_id)+ # One session reused across every page so urllib3 keeps the connection alive instead of+ # re-handshaking per request.+ session = make_tracked_session()+ limit = config.page_size++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ skip = resume.skip if resume else 0+ if resume:+ logger.debug(f"Churnkey: resuming {endpoint} from skip={skip}")++ while True:+ url = f"{CHURNKEY_BASE_URL}{config.path}?{urlencode({'limit': limit, 'skip': skip})}"+ page = _fetch_page(session, url, headers, logger)+ if not page:+ break++ yield page++ skip += limit+ # A short page means we've reached the end — stop without checkpointing further.+ if len(page) < limit:+ break++ # Save AFTER yielding so a crash resumes at the next page rather than skipping the+ # one we just emitted prematurely; merge dedupes any re-pulled rows on `_id`.+ resumable_source_manager.save_state(ChurnkeyResumeConfig(skip=skip))+++def churnkey_source(+ api_key: str,+ app_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChurnkeyResumeConfig],+) -> SourceResponse:+ config = CHURNKEY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ app_id=app_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/settings.pynew file mode 100644index 000000000000..86b9d27bd0a0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/settings.py@@ -0,0 +1,42 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField++CHURNKEY_BASE_URL = "https://api.churnkey.co/v1/data"++# The API caps a single response at 10,000 records. We page well below that so each+# response stays a reasonable size in memory (session records carry nested customer and+# presented-offer arrays).+DEFAULT_PAGE_SIZE = 1000+++@dataclass+class ChurnkeyEndpointConfig:+ name: str+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["_id"])+ # Stable creation timestamp used for datetime partitioning. Never an `updatedAt`-style+ # field — partitions must not move once written.+ partition_key: Optional[str] = "createdAt"+ page_size: int = DEFAULT_PAGE_SIZE+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++CHURNKEY_ENDPOINTS: dict[str, ChurnkeyEndpointConfig] = {+ # Raw cancel-flow session records. The API exposes `startDate`/`endDate` date-window+ # filters, but neither a per-record `updated` cursor nor a documented server-side sort,+ # and we have no credentials to curl-verify that the window actually filters server-side+ # — so this ships full-refresh only (see PR notes). `_id` is a globally-unique Mongo+ # ObjectId, safe as the primary key.+ "Sessions": ChurnkeyEndpointConfig(+ name="Sessions",+ path="/sessions",+ ),+}++ENDPOINTS = tuple(CHURNKEY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CHURNKEY_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/source.pyindex 129f770c1477..73a2b495de13 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/source.py@@ -1,30 +1,157 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.churnkey import (+ ChurnkeyResumeConfig,+ churnkey_source,+ validate_credentials as validate_churnkey_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChurnkeySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ChurnkeySource(SimpleSource[ChurnkeySourceConfig]):+class ChurnkeySource(ResumableSource[ChurnkeySourceConfig, ChurnkeyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CHURNKEY+ @property+ def connection_host_fields(self) -> list[str]:+ # app_id selects which Churnkey app the stored API key is used against; changing it must+ # require re-entering the secret so a preserved key can't be retargeted at another tenant.+ return ["app_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CHURNKEY,category=DataWarehouseSourceCategory.ANALYTICS,label="Churnkey",- iconPath="/static/services/churnkey.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ keywords=["churn", "retention", "cancellation"],+ caption="""Enter your Churnkey **Data API** key and App ID to pull your cancel-flow session data into the PostHog Data warehouse.++The Data API key is distinct from your Cancel Flow API key — request one from [[email protected]](mailto:[email protected]). Both the key and your App ID are shown in Churnkey under **Settings → Account**.""",+ iconPath="/static/services/churnkey.png",+ docsUrl="https://posthog.com/docs/cdp/sources/churnkey",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Data API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="data_...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="app_id",+ label="App ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.churnkey.co": "Your Churnkey Data API key is invalid or missing. Check the key (and App ID) under Settings → Account, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.churnkey.co": "Your Churnkey Data API key does not have access to this data. Confirm it is a Data API key (not a Cancel Flow key), then reconnect.",+ # An unknown App ID resolves to "Org not found" with a 404 — a permanent credential+ # problem, not a missing resource, so it must not retry.+ "404 Client Error: Not Found for url: https://api.churnkey.co": "Your Churnkey App ID was not recognized. Check the App ID under Settings → Account, then reconnect.",+ }++ def get_schemas(+ self,+ config: ChurnkeySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # No verified server-side timestamp cursor — full refresh only.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=["_id"],+ )+ 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: ChurnkeySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ is_valid, status_code = validate_churnkey_credentials(config.api_key, config.app_id)+ if is_valid:+ return True, None++ if status_code == 404:+ return False, "Churnkey App ID not recognized. Check the App ID under Settings → Account."+ if status_code in (401, 403):+ return False, "Invalid Churnkey Data API key. Request a Data API key from [email protected]."+ return False, "Could not connect to Churnkey. Check your Data API key and App ID."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ChurnkeyResumeConfig]:+ return ResumableSourceManager[ChurnkeyResumeConfig](inputs, ChurnkeyResumeConfig)++ def source_for_pipeline(+ self,+ config: ChurnkeySourceConfig,+ resumable_source_manager: ResumableSourceManager[ChurnkeyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return churnkey_source(+ api_key=config.api_key,+ app_id=config.app_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/tests/test_churnkey.py b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/tests/test_churnkey.pynew file mode 100644index 000000000000..5757cc552a28--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/tests/test_churnkey.py@@ -0,0 +1,166 @@+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.churnkey import (+ ChurnkeyResumeConfig,+ _get_headers,+ churnkey_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.settings import (+ CHURNKEY_ENDPOINTS,+ DEFAULT_PAGE_SIZE,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++_FETCH = "products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.churnkey._fetch_page"+++def _logger() -> MagicMock:+ log = MagicMock()+ log.debug = MagicMock()+ log.error = MagicMock()+ return log+++class TestHeaders:+ def test_get_headers(self) -> None:+ headers = _get_headers("data_abc", "app_123")+ assert headers["x-ck-api-key"] == "data_abc"+ assert headers["x-ck-app"] == "app_123"+ assert headers["content-type"] == "application/json"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected"),+ [+ (200, (True, 200)),+ (401, (False, 401)),+ (403, (False, 403)),+ (404, (False, 404)),+ (500, (False, 500)),+ ],+ )+ def test_status_mapping(self, status_code: int, expected: tuple[bool, int]) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.churnkey.make_tracked_session"+ ) as mock_session:+ response = MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ assert validate_credentials("key", "app") == expected++ def test_network_failure_returns_none_status(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.churnkey.make_tracked_session"+ ) as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key", "app") == (False, None)+++def _drive_rows(manager: MagicMock, pages: list[list[dict[str, Any]]]) -> tuple[list[list[dict[str, Any]]], list[str]]:+ """Run ``get_rows`` against ``pages`` (returned in order) with page size forced to 2.++ Returns ``(yielded_pages, requested_urls)``.+ """+ urls: list[str] = []+ page_iter = iter(pages)++ def fake_fetch(_session: Any, url: str, _headers: Any, _logger: Any) -> list[dict[str, Any]]:+ urls.append(url)+ return next(page_iter, [])++ with (+ patch.object(CHURNKEY_ENDPOINTS["Sessions"], "page_size", 2),+ patch(_FETCH, side_effect=fake_fetch),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.churnkey.make_tracked_session"+ ),+ ):+ yielded = list(get_rows("key", "app", "Sessions", _logger(), manager))+ return yielded, urls+++class TestGetRows:+ def test_fresh_run_pages_and_saves_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ pages = [+ [{"_id": "1"}, {"_id": "2"}],+ [{"_id": "3"}, {"_id": "4"}],+ [{"_id": "5"}], # short page → terminal+ ]+ yielded, urls = _drive_rows(manager, pages)++ assert yielded == pages+ # skip advances by the page size (2) each request, starting at 0.+ assert [u.split("?", 1)[1] for u in urls] == ["limit=2&skip=0", "limit=2&skip=2", "limit=2&skip=4"]+ # State saved only after the two full (non-terminal) pages, never after the short one.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [ChurnkeyResumeConfig(skip=2), ChurnkeyResumeConfig(skip=4)]+ manager.load_state.assert_not_called()++ def test_resume_starts_from_saved_skip(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = ChurnkeyResumeConfig(skip=4)++ yielded, urls = _drive_rows(manager, [[{"_id": "5"}]])++ assert yielded == [[{"_id": "5"}]]+ assert urls[0].split("?", 1)[1] == "limit=2&skip=4"+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ yielded, _ = _drive_rows(manager, [[{"_id": "only"}]])++ assert yielded == [[{"_id": "only"}]]+ manager.save_state.assert_not_called()++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ yielded, urls = _drive_rows(manager, [[]])++ assert yielded == []+ assert len(urls) == 1+ manager.save_state.assert_not_called()+++class TestChurnkeySource:+ def test_source_response_shape(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ response = churnkey_source("key", "app", "Sessions", _logger(), manager)++ assert response.name == "Sessions"+ assert response.primary_keys == ["_id"]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == ["createdAt"]++ def test_items_is_lazy(self) -> None:+ # Building the SourceResponse must not perform any HTTP — items is a thunk.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ with patch(_FETCH) as mock_fetch:+ response = churnkey_source("key", "app", "Sessions", _logger(), manager)+ mock_fetch.assert_not_called()+ # Draining the iterator (one empty page) then triggers a fetch.+ mock_fetch.return_value = []+ list(cast(Iterable[Any], response.items()))+ assert mock_fetch.called++ def test_default_page_size_within_api_cap(self) -> None:+ # The API rejects limit > 10,000.+ assert 0 < DEFAULT_PAGE_SIZE <= 10_000diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/tests/test_churnkey_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/tests/test_churnkey_source.pynew file mode 100644index 000000000000..6f280f533606--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/churnkey/tests/test_churnkey_source.py@@ -0,0 +1,140 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.churnkey import ChurnkeyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.source import ChurnkeySource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ChurnkeySourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++_VALIDATE = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.churnkey.source.validate_churnkey_credentials"+)+++def _config() -> ChurnkeySourceConfig:+ return ChurnkeySourceConfig.from_dict({"api_key": "data_key", "app_id": "app_123"})+++def _inputs() -> SourceInputs:+ return SourceInputs(+ schema_name="Sessions",+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestChurnkeySourceConfig:+ def test_source_type(self) -> None:+ assert ChurnkeySource().source_type == ExternalDataSourceType.CHURNKEY++ def test_source_config_fields(self) -> None:+ config = ChurnkeySource().get_source_config+ fields = {f.name: f for f in config.fields if isinstance(f, SourceFieldInputConfig)}++ assert set(fields) == {"api_key", "app_id"}+ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["api_key"].secret is True+ assert fields["app_id"].type == SourceFieldInputConfigType.TEXT+ assert fields["app_id"].secret is False++ def test_source_config_metadata(self) -> None:+ config = ChurnkeySource().get_source_config+ assert config.unreleasedSource is True+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/churnkey"++ def test_lists_tables_without_credentials(self) -> None:+ # Static catalog (no I/O), so the public docs can render the table list.+ assert ChurnkeySource.lists_tables_without_credentials is True++ def test_connection_host_fields_includes_app_id(self) -> None:+ # Changing app_id retargets where the stored API key is used, so editing it must+ # require re-entering the secret.+ assert ChurnkeySource().connection_host_fields == ["app_id"]+++class TestChurnkeySchemas:+ def test_get_schemas(self) -> None:+ schemas = ChurnkeySource().get_schemas(_config(), team_id=1)+ names = {s.name for s in schemas}+ assert "Sessions" in names++ sessions = next(s for s in schemas if s.name == "Sessions")+ assert sessions.supports_incremental is False+ assert sessions.supports_append is False+ assert sessions.detected_primary_keys == ["_id"]++ def test_get_schemas_name_filter(self) -> None:+ schemas = ChurnkeySource().get_schemas(_config(), team_id=1, names=["does-not-exist"])+ assert schemas == []++ def test_canonical_descriptions_cover_sessions(self) -> None:+ canonical = ChurnkeySource().get_canonical_descriptions()+ assert "Sessions" in canonical+ assert "_id" in canonical["Sessions"]["columns"]++ def test_documented_tables_render(self) -> None:+ # Exercises the public-docs path end to end (placeholder config, no credentials).+ tables = ChurnkeySource().get_documented_tables()+ assert [t["name"] for t in tables] == ["Sessions"]+ assert tables[0]["primary_keys"] == ["_id"]+ assert "Full refresh" in tables[0]["sync_methods"]+++class TestChurnkeyValidateCredentials:+ @pytest.mark.parametrize(+ ("validate_return", "expected_ok"),+ [+ ((True, 200), True),+ ((False, 401), False),+ ((False, 403), False),+ ((False, 404), False),+ ((False, None), False),+ ],+ )+ def test_validate_credentials(self, validate_return: tuple[bool, int | None], expected_ok: bool) -> None:+ with patch(_VALIDATE, return_value=validate_return):+ ok, error = ChurnkeySource().validate_credentials(_config(), team_id=1)+ assert ok is expected_ok+ if not expected_ok:+ assert error++ def test_app_id_error_is_specific(self) -> None:+ with patch(_VALIDATE, return_value=(False, 404)):+ _, error = ChurnkeySource().validate_credentials(_config(), team_id=1)+ assert error is not None and "App ID" in error+++class TestChurnkeyNonRetryableErrors:+ def test_auth_errors_present(self) -> None:+ errors = ChurnkeySource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)+ assert any("404" in key for key in errors)+++class TestChurnkeyPipeline:+ def test_get_resumable_source_manager(self) -> None:+ manager = ChurnkeySource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ChurnkeyResumeConfig++ def test_source_for_pipeline_plumbing(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ response = ChurnkeySource().source_for_pipeline(_config(), manager, _inputs())+ assert response.name == "Sessions"+ assert response.primary_keys == ["_id"]+ assert response.partition_keys == ["createdAt"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.pyindex e94ec0f03039..1b013f3e9d21 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/sampling.py@@ -76,6 +76,7 @@ _AUTH_HEADER_NAMES: frozenset[str] = frozenset("authorization","x-api-key","x-sn-apikey",+ "x-ck-api-key","x-auth-token","x-metabase-session","ob-token-v1",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 640ebf775970..bbf317933864 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -638,7 +638,8 @@ class ChorusSourceConfig(config.Config):@config.configclass ChurnkeySourceConfig(config.Config):- pass+ api_key: str+ app_id: str@config.config