: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 chartmogul import source (#61147)
Tom Owerscb6e70366d08
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 37249f95fd19..78e5e7e7cc21 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -50,6 +50,7 @@ the row lists both.| buildbetter | HTTP | requests | ✅ || calendly | HTTP | requests | ✅ || chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |+| chartmogul | HTTP | requests | ✅ || clerk | HTTP | requests + `rest_source.RESTClient` | ✅ || clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ || convertkit | HTTP | requests | ✅ |@@ -147,7 +148,6 @@ doesn't conflict with concurrent PRs.- braze- brevo- campaign_monitor-- chartmogul- circleci- clickup- closediff --git a/posthog/temporal/data_imports/sources/chartmogul/api_inventory.md b/posthog/temporal/data_imports/sources/chartmogul/api_inventory.mdnew file mode 100644index 000000000000..04e495a13c44--- /dev/null+++ b/posthog/temporal/data_imports/sources/chartmogul/api_inventory.md@@ -0,0 +1,38 @@+# ChartMogul API inventory++- **API:** ChartMogul REST API v1 — <https://dev.chartmogul.com/reference>+- **Base URL:** `https://api.chartmogul.com`+- **Auth:** HTTP Basic. The API key is the username, the password is empty (`auth=(api_key, "")`).+- **Pagination:** cursor-based. List responses wrap rows under a per-resource key and expose+ `has_more` (bool) + `cursor` (opaque string). Pass `?cursor=<cursor>&per_page=200` for the next page;+ stop when `has_more` is `false`.+- **Rate limit:** 40 req/sec globally, max 20 parallel connections (we sync serially per schema).++## Verification status++The pagination, sort order, and `start-date` filter behavior below are taken from the public docs.+They could **not** be smoke-tested with curl against the live API during implementation because no+ChartMogul API key was available in the build environment. The conservative choices (full refresh on+every endpoint except activities; `start-date` server-side filter only on activities) reflect that:+only the activities endpoint documents a genuine server-side date filter, so it is the single endpoint+marked incremental.++## Endpoints++| Schema | Path | Data key | Primary key | Partition key | Incremental |+| ------------ | ------------------ | -------------- | ----------- | ------------- | ---------------------------- |+| customers | `/v1/customers` | `entries` | `uuid` | — | full refresh (no timestamp) |+| plans | `/v1/plans` | `plans` | `uuid` | — | full refresh |+| plan_groups | `/v1/plan_groups` | `plan_groups` | `uuid` | — | full refresh |+| invoices | `/v1/invoices` | `invoices` | `uuid` | `date` | full refresh |+| activities | `/v1/activities` | `entries` | `uuid` | `date` | `start-date` server filter |+| data_sources | `/v1/data_sources` | `data_sources` | `uuid` | `created_at` | full refresh (not paginated) |++Notes:++- **Customers** expose no update timestamp and no server-side creation/update date filter, so true+ incremental sync is impossible — Airbyte's connector also only supports full refresh here.+- **Activities** is the only endpoint with a documented server-side `start-date` / `end-date` filter,+ and is documented to return rows in ascending chronological order, so it is synced incrementally on+ the `date` field with `sort_mode="asc"`.+- **data_sources** returns the full list in a single response (no cursor), so it is fetched once.diff --git a/posthog/temporal/data_imports/sources/chartmogul/chartmogul.py b/posthog/temporal/data_imports/sources/chartmogul/chartmogul.pynew file mode 100644index 000000000000..11660be62b4b--- /dev/null+++ b/posthog/temporal/data_imports/sources/chartmogul/chartmogul.py@@ -0,0 +1,167 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+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 posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.chartmogul.settings import CHARTMOGUL_ENDPOINTS, ChartMogulEndpointConfig+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++CHARTMOGUL_BASE_URL = "https://api.chartmogul.com"+DEFAULT_PAGE_SIZE = 200+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+++class ChartMogulRetryableError(Exception):+ pass+++class ChartMogulResumeConfig:+ # ChartMogul cursor pagination: each page returns an opaque `cursor` that+ # encodes the next page. We persist only the cursor — the static query+ # params (page size, incremental start-date) are deterministically rebuilt+ # from the config and the job inputs on resume.+ cursor: str+++def _get_session(api_key: str) -> requests.Session:+ # ChartMogul uses HTTP Basic auth with the API key as the username and an+ # empty password. Redact the key from logged URLs / captured samples.+ return make_tracked_session(redact_values=(api_key,))+++def _format_start_date(value: Any) -> str:+ """Format an incremental cursor value for ChartMogul's `start-date` filter (ISO 8601)."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d")+ return str(value)+++def validate_credentials(api_key: str) -> bool:+ url = f"{CHARTMOGUL_BASE_URL}/v1/data_sources"+ try:+ response = _get_session(api_key).get(url, auth=(api_key, ""), timeout=REQUEST_TIMEOUT_SECONDS)+ return response.status_code == 200+ except Exception:+ return False+++def _build_initial_params(+ config: ChartMogulEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {}++ if config.paginated:+ params["per_page"] = DEFAULT_PAGE_SIZE++ if config.incremental_param and should_use_incremental_field and db_incremental_field_last_value:+ params[config.incremental_param] = _format_start_date(db_incremental_field_last_value)++ return params+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChartMogulResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CHARTMOGUL_ENDPOINTS[endpoint]+ session = _get_session(api_key)+ base_url = f"{CHARTMOGUL_BASE_URL}{config.path}"++ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ params["cursor"] = resume_config.cursor+ logger.debug(f"ChartMogul: resuming {endpoint} from cursor: {resume_config.cursor}")++ @retry(+ retry=retry_if_exception_type((ChartMogulRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_params: dict[str, Any]) -> dict[str, Any]:+ url = f"{base_url}?{urlencode(page_params)}" if page_params else base_url+ response = session.get(url, auth=(api_key, ""), timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise ChartMogulRetryableError(+ f"ChartMogul API error (retryable): status={response.status_code}, url={base_url}"+ )++ if not response.ok:+ logger.error(f"ChartMogul API error: status={response.status_code}, body={response.text}, url={base_url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(params)++ items = data.get(config.data_key, [])+ if items:+ yield items++ if not config.paginated:+ break++ has_more = data.get("has_more", False)+ cursor = data.get("cursor")+ if not has_more or not cursor:+ break++ # Save state AFTER yielding the page so a crash re-yields the last page+ # (merge dedupes on primary key) rather than skipping it.+ resumable_source_manager.save_state(ChartMogulResumeConfig(cursor=cursor))+ params["cursor"] = cursor+++def chartmogul_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ChartMogulResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CHARTMOGUL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[config.primary_key],+ 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,+ # ChartMogul activities are returned in chronological (ascending) order+ # within the start-date window, so the incremental watermark advances+ # correctly. Non-incremental endpoints default to asc as well.+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/chartmogul/settings.py b/posthog/temporal/data_imports/sources/chartmogul/settings.pynew file mode 100644index 000000000000..15b1aed1f772--- /dev/null+++ b/posthog/temporal/data_imports/sources/chartmogul/settings.py@@ -0,0 +1,85 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class ChartMogulEndpointConfig:+ name: str+ path: str+ # Body key the list of rows lives under (ChartMogul wraps results per resource:+ # customers/activities use "entries", plans use "plans", etc.).+ data_key: str+ primary_key: str = "uuid"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable field to partition by — must never change for a given row.+ partition_key: Optional[str] = None+ # Query param used to push the incremental cursor server-side. Only set for+ # endpoints with a genuine server-side date filter (today: activities).+ incremental_param: Optional[str] = None+ # Some endpoints (data_sources) return the full list without pagination.+ paginated: bool = True+++CHARTMOGUL_ENDPOINTS: dict[str, ChartMogulEndpointConfig] = {+ "customers": ChartMogulEndpointConfig(+ name="customers",+ path="/v1/customers",+ data_key="entries",+ primary_key="uuid",+ # Customers expose no update timestamp and no server-side date filter, so+ # full refresh is the only honest sync mode here.+ ),+ "plans": ChartMogulEndpointConfig(+ name="plans",+ path="/v1/plans",+ data_key="plans",+ primary_key="uuid",+ ),+ "plan_groups": ChartMogulEndpointConfig(+ name="plan_groups",+ path="/v1/plan_groups",+ data_key="plan_groups",+ primary_key="uuid",+ ),+ "invoices": ChartMogulEndpointConfig(+ name="invoices",+ path="/v1/invoices",+ data_key="invoices",+ primary_key="uuid",+ partition_key="date",+ ),+ "activities": ChartMogulEndpointConfig(+ name="activities",+ path="/v1/activities",+ data_key="entries",+ primary_key="uuid",+ partition_key="date",+ # ChartMogul's Activities endpoint documents a server-side `start-date`+ # filter, so this is the one endpoint we can sync incrementally.+ incremental_param="start-date",+ incremental_fields=[+ {+ "label": "date",+ "type": IncrementalFieldType.DateTime,+ "field": "date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "data_sources": ChartMogulEndpointConfig(+ name="data_sources",+ path="/v1/data_sources",+ data_key="data_sources",+ primary_key="uuid",+ partition_key="created_at",+ paginated=False,+ ),+}++ENDPOINTS = tuple(CHARTMOGUL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CHARTMOGUL_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/chartmogul/source.py b/posthog/temporal/data_imports/sources/chartmogul/source.pyindex 77413ba4f7ef..9b937ca70d7f 100644--- a/posthog/temporal/data_imports/sources/chartmogul/source.py+++ b/posthog/temporal/data_imports/sources/chartmogul/source.py@@ -1,19 +1,31 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.chartmogul.chartmogul import (+ ChartMogulResumeConfig,+ chartmogul_source,+ validate_credentials as validate_chartmogul_credentials,+)+from posthog.temporal.data_imports.sources.chartmogul.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import ChartMogulSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class ChartMogulSource(SimpleSource[ChartMogulSourceConfig]):+class ChartMogulSource(ResumableSource[ChartMogulSourceConfig, ChartMogulResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CHARTMOGUL@@ -23,7 +35,79 @@ class ChartMogulSource(SimpleSource[ChartMogulSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.CHART_MOGUL,label="ChartMogul",+ caption="""Enter your ChartMogul API key to pull your subscription analytics data into the PostHog Data warehouse.++You can find your API key in your [ChartMogul admin settings](https://app.chartmogul.com/#/admin/api).""",iconPath="/static/services/chartmogul.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/chartmogul",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: ChartMogulSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: ChartMogulSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_chartmogul_credentials(config.api_key):+ return True, None++ return False, "Invalid ChartMogul API key"++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.chartmogul.com": "Your ChartMogul API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error: Forbidden for url: https://api.chartmogul.com": "Your ChartMogul API key does not have the required permissions. Please check the key and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ChartMogulResumeConfig]:+ return ResumableSourceManager[ChartMogulResumeConfig](inputs, ChartMogulResumeConfig)++ def source_for_pipeline(+ self,+ config: ChartMogulSourceConfig,+ resumable_source_manager: ResumableSourceManager[ChartMogulResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return chartmogul_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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,)diff --git a/posthog/temporal/data_imports/sources/chartmogul/tests/test_chartmogul.py b/posthog/temporal/data_imports/sources/chartmogul/tests/test_chartmogul.pynew file mode 100644index 000000000000..f2fa5924ea93--- /dev/null+++ b/posthog/temporal/data_imports/sources/chartmogul/tests/test_chartmogul.py@@ -0,0 +1,231 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.temporal.data_imports.sources.chartmogul.chartmogul import (+ ChartMogulResumeConfig,+ _build_initial_params,+ _format_start_date,+ chartmogul_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.chartmogul.settings import CHARTMOGUL_ENDPOINTS+++class _FakeResponse:+ def __init__(self, status_code: int, body: dict[str, Any] | None = None, text: str = "") -> None:+ self.status_code = status_code+ self._body = body or {}+ self.text = text++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> dict[str, Any]:+ return self._body++ def raise_for_status(self) -> None:+ if not self.ok:+ raise AssertionError(f"HTTP {self.status_code}")+++def _fake_session(responses: list[_FakeResponse]) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = list(responses)+ return session+++def _manager(can_resume: bool = False, resume_state: ChartMogulResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = resume_state+ return manager+++class TestFormatStartDate:+ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ (date(2026, 3, 4), "2026-03-04"),+ ("2026-03-04", "2026-03-04"),+ ],+ )+ def test_format_start_date(self, value: object, expected: str) -> None:+ assert _format_start_date(value) == expected++ def test_no_tz_offset_in_output(self) -> None:+ assert "+00:00" not in _format_start_date(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+++class TestBuildInitialParams:+ def test_paginated_endpoint_sets_per_page(self) -> None:+ params = _build_initial_params(CHARTMOGUL_ENDPOINTS["customers"], False, None)+ assert params["per_page"] == 200+ assert "start-date" not in params++ def test_non_paginated_endpoint_omits_per_page(self) -> None:+ params = _build_initial_params(CHARTMOGUL_ENDPOINTS["data_sources"], False, None)+ assert "per_page" not in params++ def test_activities_incremental_sets_start_date(self) -> None:+ params = _build_initial_params(+ CHARTMOGUL_ENDPOINTS["activities"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, 0, 0, 0, tzinfo=UTC),+ )+ assert params["start-date"] == "2026-01-01T00:00:00"++ def test_no_start_date_when_incremental_disabled(self) -> None:+ params = _build_initial_params(+ CHARTMOGUL_ENDPOINTS["activities"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert "start-date" not in params++ def test_non_incremental_endpoint_never_sets_start_date(self) -> None:+ params = _build_initial_params(+ CHARTMOGUL_ENDPOINTS["customers"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert "start-date" not in params+++class TestGetRows:+ def test_paginates_across_cursors(self) -> None:+ responses = [+ _FakeResponse(200, {"entries": [{"uuid": "a"}], "has_more": True, "cursor": "c1"}),+ _FakeResponse(200, {"entries": [{"uuid": "b"}], "has_more": False, "cursor": None}),+ ]+ manager = _manager()+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=_fake_session(responses),+ ):+ batches = list(get_rows("key", "customers", MagicMock(), manager))++ assert batches == [[{"uuid": "a"}], [{"uuid": "b"}]]++ def test_saves_state_after_each_page(self) -> None:+ responses = [+ _FakeResponse(200, {"entries": [{"uuid": "a"}], "has_more": True, "cursor": "c1"}),+ _FakeResponse(200, {"entries": [{"uuid": "b"}], "has_more": False, "cursor": None}),+ ]+ manager = _manager()+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=_fake_session(responses),+ ):+ list(get_rows("key", "customers", MagicMock(), manager))++ manager.save_state.assert_called_once_with(ChartMogulResumeConfig(cursor="c1"))++ def test_resumes_from_saved_cursor(self) -> None:+ session = _fake_session([_FakeResponse(200, {"entries": [{"uuid": "b"}], "has_more": False, "cursor": None})])+ manager = _manager(can_resume=True, resume_state=ChartMogulResumeConfig(cursor="resume-cursor"))+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=session,+ ):+ list(get_rows("key", "customers", MagicMock(), manager))++ called_url = session.get.call_args_list[0].args[0]+ assert "cursor=resume-cursor" in called_url++ def test_non_paginated_endpoint_fetches_once(self) -> None:+ session = _fake_session(+ [_FakeResponse(200, {"data_sources": [{"uuid": "ds1"}], "has_more": True, "cursor": "ignored"})]+ )+ manager = _manager()+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=session,+ ):+ batches = list(get_rows("key", "data_sources", MagicMock(), manager))++ assert batches == [[{"uuid": "ds1"}]]+ assert session.get.call_count == 1+ manager.save_state.assert_not_called()++ def test_empty_page_is_not_yielded(self) -> None:+ session = _fake_session([_FakeResponse(200, {"plans": [], "has_more": False, "cursor": None})])+ manager = _manager()+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=session,+ ):+ batches = list(get_rows("key", "plans", MagicMock(), manager))++ assert batches == []++ @pytest.mark.parametrize("status", [429, 503])+ @patch("tenacity.nap.time.sleep", return_value=None)+ def test_retryable_status_codes_recover(self, _mock_sleep: MagicMock, status: int) -> None:+ # A single retryable response then success: the tenacity retry should+ # recover and still yield the data. tenacity's backoff sleep is patched+ # out to keep the test fast and deterministic.+ responses = [+ _FakeResponse(status, {}),+ _FakeResponse(200, {"plans": [{"uuid": "p1"}], "has_more": False, "cursor": None}),+ ]+ manager = _manager()+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=_fake_session(responses),+ ):+ batches = list(get_rows("key", "plans", MagicMock(), manager))++ assert batches == [[{"uuid": "p1"}]]+++class TestValidateCredentials:+ @pytest.mark.parametrize("status,expected", [(200, True), (401, False), (403, False)])+ def test_status_mapping(self, status: int, expected: bool) -> None:+ session = _fake_session([_FakeResponse(status, {})])+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=session,+ ):+ assert validate_credentials("key") is expected++ def test_exception_returns_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.chartmogul._get_session",+ return_value=session,+ ):+ assert validate_credentials("key") is False+++class TestChartmogulSource:+ @pytest.mark.parametrize(+ "endpoint,primary_keys,partition_key",+ [+ ("customers", ["uuid"], None),+ ("plans", ["uuid"], None),+ ("plan_groups", ["uuid"], None),+ ("invoices", ["uuid"], "date"),+ ("activities", ["uuid"], "date"),+ ("data_sources", ["uuid"], "created_at"),+ ],+ )+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: str | None) -> None:+ response = chartmogul_source("key", endpoint, MagicMock(), _manager())++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == "asc"+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is Nonediff --git a/posthog/temporal/data_imports/sources/chartmogul/tests/test_chartmogul_source.py b/posthog/temporal/data_imports/sources/chartmogul/tests/test_chartmogul_source.pynew file mode 100644index 000000000000..904736d4090b--- /dev/null+++ b/posthog/temporal/data_imports/sources/chartmogul/tests/test_chartmogul_source.py@@ -0,0 +1,119 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+)++from posthog.temporal.data_imports.sources.chartmogul.chartmogul import ChartMogulResumeConfig+from posthog.temporal.data_imports.sources.chartmogul.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.chartmogul.source import ChartMogulSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import ChartMogulSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestChartMogulSource:+ def setup_method(self) -> None:+ self.source = ChartMogulSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CHARTMOGUL++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name == SchemaExternalDataSourceType.CHART_MOGUL+ assert config.label == "ChartMogul"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.fields is not None+ field_names = [f.name for f in config.fields]+ assert field_names == ["api_key"]++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(ChartMogulSourceConfig(api_key="k"), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(ChartMogulSourceConfig(api_key="k"), team_id=1, names=["customers"])+ assert [s.name for s in schemas] == ["customers"]++ @pytest.mark.parametrize(+ "endpoint,expected_incremental",+ [+ ("activities", True),+ ("customers", False),+ ("plans", False),+ ("invoices", False),+ ("data_sources", False),+ ],+ )+ def test_supports_incremental_only_for_activities(self, endpoint: str, expected_incremental: bool) -> None:+ schemas = self.source.get_schemas(ChartMogulSourceConfig(api_key="k"), team_id=1, names=[endpoint])+ assert schemas[0].supports_incremental is expected_incremental++ def test_validate_credentials_success(self) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.source.validate_chartmogul_credentials",+ return_value=True,+ ):+ valid, error = self.source.validate_credentials(ChartMogulSourceConfig(api_key="k"), team_id=1)+ assert valid is True+ assert error is None++ def test_validate_credentials_failure(self) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.chartmogul.source.validate_chartmogul_credentials",+ return_value=False,+ ):+ valid, error = self.source.validate_credentials(ChartMogulSourceConfig(api_key="bad"), team_id=1)+ assert valid is False+ assert error == "Invalid ChartMogul API key"++ @pytest.mark.parametrize(+ "pattern",+ [+ "401 Client Error: Unauthorized for url: https://api.chartmogul.com",+ "403 Client Error: Forbidden for url: https://api.chartmogul.com",+ ],+ )+ def test_non_retryable_errors_includes_pattern(self, pattern: str) -> None:+ assert pattern in self.source.get_non_retryable_errors()++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is ChartMogulResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "activities"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01"+ manager = MagicMock()++ with patch("posthog.temporal.data_imports.sources.chartmogul.source.chartmogul_source") as mock_source:+ self.source.source_for_pipeline(ChartMogulSourceConfig(api_key="k"), manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "k"+ assert kwargs["endpoint"] == "activities"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_drops_incremental_value_when_disabled(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "customers"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01"++ with patch("posthog.temporal.data_imports.sources.chartmogul.source.chartmogul_source") as mock_source:+ self.source.source_for_pipeline(ChartMogulSourceConfig(api_key="k"), MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 0cd5839d7943..005593fda272 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -218,7 +218,7 @@ class ChargebeeSourceConfig(config.Config):@config.configclass ChartMogulSourceConfig(config.Config):- pass+ api_key: str@config.config