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.

feat(data-warehouse): implement mixpanel import source (#61665)

Tom Owers7623ea32b263
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 919cc0933784..d1f486bba577 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -89,6 +89,7 @@ the row lists both.
| mailerlite | HTTP | requests | ✅ |
| mailjet | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
+| mixpanel | HTTP | requests | ✅ |
| mongodb | DB protocol | pymongo | ➖ |
| mssql | DB protocol | pyodbc / pymssql | ➖ |
| mysql | DB protocol | pymysql | ➖ |
@@ -201,7 +202,6 @@ doesn't conflict with concurrent PRs.
- lever
- marketo
- microsoft_teams
-- mixpanel
- monday
- netsuite
- onedrive
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index ded7043acfb8..848eebe943fd 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -556,7 +556,10 @@ class MicrosoftTeamsSourceConfig(config.Config):
@config.config
class MixpanelSourceConfig(config.Config):
- pass
+ project_id: str
+ service_account_username: str
+ service_account_secret: str
+ region: Literal["us", "eu", "in"] = config.value(default="us")
@config.config
diff --git a/posthog/temporal/data_imports/sources/mixpanel/mixpanel.py b/posthog/temporal/data_imports/sources/mixpanel/mixpanel.py
new file mode 100644
index 000000000000..37d766f06514
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mixpanel/mixpanel.py
@@ -0,0 +1,357 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import orjson
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.mixpanel.settings import (
+ DEFAULT_EXPORT_LOOKBACK_DAYS,
+ MIXPANEL_ENDPOINTS,
+ REGION_HOSTS,
+)
+
+# Rows buffered before yielding a batch. The pipeline batches again downstream, but
+# yielding in chunks keeps memory bounded while streaming the JSONL export.
+CHUNK_SIZE = 5000
+ENGAGE_PAGE_SIZE = 1000
+REQUEST_TIMEOUT = 120
+
+# Let tenacity be the only retry layer. The default tracked-session retry only retries
+# GET/HEAD/OPTIONS at the urllib3 level, which would give the GET endpoints a much larger
+# (and uneven) effective retry budget than the POST ones.
+NO_URLLIB_RETRY = Retry(total=0)
+
+
+class MixpanelRetryableError(Exception):
+ pass
+
+
+class MixpanelResumeConfig:
+ # Raw export resumes at the day window we have not yet completed.
+ from_date: Optional[str] = None
+ # Engage resumes at a session id + page from the previous query.
+ session_id: Optional[str] = None
+ page: Optional[int] = None
+
+
+def _hosts(region: str) -> tuple[str, str]:
+ return REGION_HOSTS.get(region, REGION_HOSTS["us"])
+
+
+def _query_base(region: str) -> str:
+ return _hosts(region)[0]
+
+
+def _export_base(region: str) -> str:
+ return _hosts(region)[1]
+
+
+def _flatten_event(event: dict[str, Any]) -> dict[str, Any]:
+ """Lift the `properties` sub-object of a raw export event to the top level.
+
+ The export API returns `{"event": "...", "properties": {"time": ..., "distinct_id":
+ ..., "$insert_id": ..., ...}}`. Flattening keeps `time` / `distinct_id` / `$insert_id`
+ addressable as columns (and as primary/partition keys)."""
+ row: dict[str, Any] = {"event": event.get("event")}
+ properties = event.get("properties")
+ if isinstance(properties, dict):
+ row.update(properties)
+ return row
+
+
+def _flatten_profile(profile: dict[str, Any]) -> dict[str, Any]:
+ """Lift the `$properties` sub-object of an Engage profile to the top level."""
+ row: dict[str, Any] = {"$distinct_id": profile.get("$distinct_id")}
+ properties = profile.get("$properties")
+ if isinstance(properties, dict):
+ row.update(properties)
+ return row
+
+
+def _to_date(value: Any) -> Optional[date]:
+ """Coerce a stored incremental cursor (epoch seconds, datetime, or ISO string) to a date."""
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, (int, float)):
+ return datetime.fromtimestamp(value, tz=UTC).date()
+ if isinstance(value, datetime):
+ return (value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)).date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, str) and value.strip():
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()
+ except ValueError:
+ return None
+ return None
+
+
+def validate_credentials(
+ region: str,
+ username: str,
+ secret: str,
+ project_id: str,
+ schema_name: Optional[str] = None,
+) -> tuple[bool, str | None]:
+ """Cheap probe to confirm the service account works.
+
+ Mixpanel returns 401 for a bad credential and 403 when the credential is valid but
+ lacks access to the requested resource. At source-create (`schema_name is None`) we
+ accept 403 — users may only have granted scope for the endpoints they want — and only
+ treat 401 as a hard failure."""
+ url = f"{_query_base(region)}/api/query/cohorts/list"
+ try:
+ response = make_tracked_session(retry=NO_URLLIB_RETRY).post(
+ url,
+ params={"project_id": project_id},
+ auth=(username, secret),
+ headers={"Accept": "application/json"},
+ timeout=30,
+ )
+ except Exception:
+ return False, "Could not reach Mixpanel. Check the region and try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Mixpanel rejected the service account credentials. Check the username, secret, and project ID."
+ if response.status_code == 403:
+ if schema_name is None:
+ return True, None
+ return False, "The service account does not have access to this resource in the selected project."
+
+ return False, f"Mixpanel returned an unexpected status ({response.status_code}) while validating credentials."
+
+
+def _check_response(response: requests.Response, url: str, logger: FilteringBoundLogger) -> requests.Response:
+ """Classify a Mixpanel response: 429/5xx are retryable, other 4xx are terminal."""
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MixpanelRetryableError(f"Mixpanel API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Mixpanel API error: status={response.status_code}, body={response.text[:500]}, url={url}")
+ response.raise_for_status()
+
+ return response
+
+
+@retry(
+ retry=retry_if_exception_type((MixpanelRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _request(
+ method: str,
+ url: str,
+ *,
+ username: str,
+ secret: str,
+ logger: FilteringBoundLogger,
+ params: Optional[dict[str, Any]] = None,
+ stream: bool = False,
+) -> requests.Response:
+ response = make_tracked_session(retry=NO_URLLIB_RETRY).request(
+ method,
+ url,
+ params=params,
+ auth=(username, secret),
+ headers={"Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT,
+ stream=stream,
+ )
+ return _check_response(response, url, logger)
+
+
+def _iter_export(
+ region: str,
+ username: str,
+ secret: str,
+ project_id: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[MixpanelResumeConfig],
+ start_date: date,
+ end_date: date,
+) -> Iterator[list[dict[str, Any]]]:
+ """Stream the raw event export one UTC day at a time.
+
+ The export API has no offset/cursor pagination, so day windows are both our
+ incremental granularity and our resume granularity. We save state pointing at the
+ *next* day only after a day's batches have been yielded, so a crash re-fetches the
+ in-flight day (merge dedupes on `$insert_id`)."""
+ url = f"{_export_base(region)}/api/2.0/export"
+
+ resume = manager.load_state() if manager.can_resume() else None
+ resumed_from = _to_date(resume.from_date) if resume and resume.from_date else None
+ current = resumed_from or start_date
+ if resumed_from:
+ logger.debug(f"Mixpanel export: resuming from {resumed_from.isoformat()}")
+
+ while current <= end_date:
+ from_date = current.isoformat()
+ params = {"from_date": from_date, "to_date": from_date, "project_id": project_id}
+
+ with _request(
+ "GET", url, username=username, secret=secret, logger=logger, params=params, stream=True
+ ) as response:
+ batch: list[dict[str, Any]] = []
+ for line in response.iter_lines():
+ if not line:
+ continue
+ batch.append(_flatten_event(orjson.loads(line)))
+ if len(batch) >= CHUNK_SIZE:
+ yield batch
+ batch = []
+ if batch:
+ yield batch
+
+ # Day complete: advance the resume cursor so a restart skips finished days.
+ next_day = current + timedelta(days=1)
+ manager.save_state(MixpanelResumeConfig(from_date=next_day.isoformat()))
+ current = next_day
+
+
+def _iter_engage(
+ region: str,
+ username: str,
+ secret: str,
+ project_id: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[MixpanelResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Page through user profiles using the Engage API's session-based pagination."""
+ url = f"{_query_base(region)}/api/query/engage"
+
+ resume = manager.load_state() if manager.can_resume() else None
+ page = resume.page if resume and resume.page is not None else 0
+ session_id = resume.session_id if resume else None
+ if resume and resume.page is not None:
+ logger.debug(f"Mixpanel engage: resuming from page {page}")
+
+ while True:
+ params: dict[str, Any] = {"project_id": project_id, "page": page}
+ if session_id:
+ params["session_id"] = session_id
+
+ response = _request("POST", url, username=username, secret=secret, logger=logger, params=params)
+ data = response.json()
+
+ results = data.get("results", [])
+ if not results:
+ break
+
+ session_id = data.get("session_id", session_id)
+ page_size = data.get("page_size", ENGAGE_PAGE_SIZE)
+
+ yield [_flatten_profile(profile) for profile in results]
+
+ page += 1
+ manager.save_state(MixpanelResumeConfig(session_id=session_id, page=page))
+
+ if len(results) < page_size:
+ break
+
+
+def _fetch_cohorts(
+ region: str, username: str, secret: str, project_id: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{_query_base(region)}/api/query/cohorts/list"
+ response = _request("POST", url, username=username, secret=secret, logger=logger, params={"project_id": project_id})
+ data = response.json()
+ # The cohorts endpoint returns a bare list; tolerate a `results` wrapper defensively.
+ rows = data if isinstance(data, list) else data.get("results", [])
+ if rows:
+ yield rows
+
+
+def _fetch_annotations(
+ region: str, username: str, secret: str, project_id: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{_query_base(region)}/api/app/projects/{project_id}/annotations"
+ response = _request("GET", url, username=username, secret=secret, logger=logger)
+ data = response.json()
+ rows = data if isinstance(data, list) else data.get("results", [])
+ if rows:
+ yield rows
+
+
+def get_rows(
+ region: str,
+ username: str,
+ secret: str,
+ project_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[MixpanelResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ if endpoint == "export":
+ last_value_date = _to_date(db_incremental_field_last_value) if should_use_incremental_field else None
+ end_date = datetime.now(UTC).date()
+ start_date = last_value_date or (end_date - timedelta(days=DEFAULT_EXPORT_LOOKBACK_DAYS))
+ # A future cursor (clock skew or bad event data) would make start_date > end_date and the
+ # day loop a no-op, silently skipping the sync. Clamp to today so we still sync the latest day.
+ if start_date > end_date:
+ logger.warning(
+ f"Mixpanel export: incremental cursor {start_date.isoformat()} is in the future; syncing today"
+ )
+ start_date = end_date
+ yield from _iter_export(
+ region, username, secret, project_id, logger, manager, start_date=start_date, end_date=end_date
+ )
+ elif endpoint == "engage":
+ yield from _iter_engage(region, username, secret, project_id, logger, manager)
+ elif endpoint == "cohorts":
+ yield from _fetch_cohorts(region, username, secret, project_id, logger)
+ elif endpoint == "annotations":
+ yield from _fetch_annotations(region, username, secret, project_id, logger)
+ else:
+ raise ValueError(f"Unknown Mixpanel endpoint: {endpoint}")
+
+
+def mixpanel_source(
+ region: str,
+ username: str,
+ secret: str,
+ project_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[MixpanelResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = MIXPANEL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ region=region,
+ username=username,
+ secret=secret,
+ project_id=project_id,
+ endpoint=endpoint,
+ logger=logger,
+ manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format=endpoint_config.partition_format if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/mixpanel/settings.py b/posthog/temporal/data_imports/sources/mixpanel/settings.py
new file mode 100644
index 000000000000..74de01fb8ae1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mixpanel/settings.py
@@ -0,0 +1,88 @@
+from dataclasses import dataclass, field
+from enum import StrEnum
+from typing import Optional
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+class MixpanelRegion(StrEnum):
+ US = "us"
+ EU = "eu"
+ IN = "in"
+
+
+# region -> (query/app API base, raw export API base). Mixpanel splits the heavy raw
+# export traffic onto a separate `data*` host per data-residency region.
+REGION_HOSTS: dict[str, tuple[str, str]] = {
+ MixpanelRegion.US: ("https://mixpanel.com", "https://data.mixpanel.com"),
+ MixpanelRegion.EU: ("https://eu.mixpanel.com", "https://data-eu.mixpanel.com"),
+ MixpanelRegion.IN: ("https://in.mixpanel.com", "https://data-in.mixpanel.com"),
+}
+
+# First sync of the raw export endpoint only pulls this far back to avoid replaying
+# the entire project history in one job. Subsequent incremental syncs advance from the
+# last-seen event time.
+DEFAULT_EXPORT_LOOKBACK_DAYS = 365
+
+
+@dataclass
+class MixpanelEndpointConfig:
+ name: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable timestamp used for datetime partitioning. Must never change after a row is
+ # written (event time / creation date), never `updated`/`last_seen`.
+ partition_key: Optional[str] = None
+ partition_format: PartitionFormat = "month"
+
+
+MIXPANEL_ENDPOINTS: dict[str, MixpanelEndpointConfig] = {
+ # Raw Event Export API: streams every event in a date window as JSONL. The only
+ # endpoint with a genuine server-side time filter (from_date/to_date), so the only
+ # one that supports incremental sync.
+ "export": MixpanelEndpointConfig(
+ name="export",
+ # Mixpanel has no single event id. `$insert_id` is the dedup key on modern events;
+ # the rest of the composite distinguishes legacy events that predate `$insert_id`.
+ primary_keys=["$insert_id", "event", "distinct_id", "time"],
+ partition_key="time",
+ partition_format="month",
+ incremental_fields=[
+ {
+ "label": "time",
+ "type": IncrementalFieldType.Integer,
+ "field": "time",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ ),
+ # Engage API: user profiles. Session-based pagination, no reliable server-side time
+ # filter -> full refresh only.
+ "engage": MixpanelEndpointConfig(
+ name="engage",
+ primary_keys=["$distinct_id"],
+ ),
+ # Query API: list of cohorts. Small, single request, full refresh.
+ "cohorts": MixpanelEndpointConfig(
+ name="cohorts",
+ primary_keys=["id"],
+ partition_key="created",
+ ),
+ # App API: project annotations. Small, single request, full refresh.
+ "annotations": MixpanelEndpointConfig(
+ name="annotations",
+ primary_keys=["id"],
+ ),
+}
+
+ENDPOINTS = tuple(MIXPANEL_ENDPOINTS.keys())
+
+# Only the raw export endpoint exposes a server-side date filter. Everything else is
+# full refresh (see API verification notes in mixpanel.py).
+SUPPORTS_INCREMENTAL: set[str] = {"export"}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: cfg.incremental_fields for name, cfg in MIXPANEL_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/mixpanel/source.py b/posthog/temporal/data_imports/sources/mixpanel/source.py
index 0ff3a9674355..8c7e7990009f 100644
--- a/posthog/temporal/data_imports/sources/mixpanel/source.py
+++ b/posthog/temporal/data_imports/sources/mixpanel/source.py
@@ -1,29 +1,167 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-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.common.base import FieldType, ResumableSource
from 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 SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import MixpanelSourceConfig
+from posthog.temporal.data_imports.sources.mixpanel.mixpanel import (
+ MixpanelResumeConfig,
+ mixpanel_source,
+ validate_credentials as validate_mixpanel_credentials,
+)
+from posthog.temporal.data_imports.sources.mixpanel.settings import ENDPOINTS, INCREMENTAL_FIELDS, SUPPORTS_INCREMENTAL
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MixpanelSource(SimpleSource[MixpanelSourceConfig]):
+class MixpanelSource(ResumableSource[MixpanelSourceConfig, MixpanelResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MIXPANEL
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `region` picks the host and `project_id` the project the stored service-account secret is
+ # sent to; retargeting either must re-require the secret so it can't be aimed elsewhere.
+ return ["region", "project_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.MIXPANEL,
label="Mixpanel",
+ caption="""Connect your Mixpanel project to pull events, user profiles, cohorts and annotations into the PostHog Data warehouse.
+
+Authenticate with a [Mixpanel Service Account](https://developer.mixpanel.com/reference/service-accounts). In Mixpanel, go to **Organization Settings → Service Accounts → Create Service Account** and grant it access to the project you want to sync. You'll need:
+
+- The service account **username** and **secret**
+- Your numeric **Project ID** (found under **Project Settings**)
+- The **data residency region** your project lives in (US, EU or India)
+""",
iconPath="/static/services/mixpanel.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/mixpanel",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Data residency region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (mixpanel.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (eu.mixpanel.com)", value="eu"),
+ SourceFieldSelectConfigOption(label="India (in.mixpanel.com)", value="in"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="project_id",
+ label="Project ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="1234567",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="service_account_username",
+ label="Service account username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-service-account.abc123.mp-service-account",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="service_account_secret",
+ label="Service account secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: MixpanelSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint in SUPPORTS_INCREMENTAL,
+ supports_append=endpoint in SUPPORTS_INCREMENTAL,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description="Only syncs the last 365 days on initial sync" if endpoint == "export" else None,
+ )
+ 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: MixpanelSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_mixpanel_credentials(
+ region=config.region,
+ username=config.service_account_username,
+ secret=config.service_account_secret,
+ project_id=config.project_id,
+ schema_name=schema_name,
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": (
+ "Mixpanel rejected the service account credentials. Create a new service account in "
+ "Organization Settings and reconnect."
+ ),
+ "403 Client Error: Forbidden": (
+ "The Mixpanel service account does not have access to this project or resource. Grant it "
+ "access to the project and reconnect."
+ ),
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MixpanelResumeConfig]:
+ return ResumableSourceManager[MixpanelResumeConfig](inputs, MixpanelResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MixpanelSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MixpanelResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return mixpanel_source(
+ region=config.region,
+ username=config.service_account_username,
+ secret=config.service_account_secret,
+ project_id=config.project_id,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ 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/mixpanel/test_mixpanel.py b/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel.py
new file mode 100644
index 000000000000..28de2006484f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel.py
@@ -0,0 +1,339 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+import orjson
+import requests
+import structlog
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.mixpanel import mixpanel as mp
+from posthog.temporal.data_imports.sources.mixpanel.mixpanel import (
+ MixpanelResumeConfig,
+ MixpanelRetryableError,
+ _check_response,
+ _export_base,
+ _flatten_event,
+ _flatten_profile,
+ _query_base,
+ _to_date,
+ mixpanel_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.mixpanel.settings import MIXPANEL_ENDPOINTS
+
+LOGGER = structlog.get_logger()
+
+
+class FakeResponse:
+ def __init__(
+ self,
+ *,
+ status_code: int = 200,
+ json_data: Any = None,
+ lines: Optional[list[bytes]] = None,
+ text: str = "",
+ ) -> None:
+ self.status_code = status_code
+ self._json = json_data
+ self._lines = lines or []
+ self.text = text
+
+ @property
+ def ok(self) -> bool:
+ return 200 <= self.status_code < 400
+
+ def json(self) -> Any:
+ return self._json
+
+ def iter_lines(self):
+ return iter(self._lines)
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise requests.HTTPError(f"{self.status_code} Client Error", response=self) # type: ignore[arg-type]
+
+ def __enter__(self) -> "FakeResponse":
+ return self
+
+ def __exit__(self, *args: Any) -> None:
+ return None
+
+
+class FakeManager:
+ """Stand-in for ResumableSourceManager that records saved state in memory."""
+
+ def __init__(self, resume_state: Optional[MixpanelResumeConfig] = None) -> None:
+ self._state = resume_state
+ self.saved: list[MixpanelResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> Optional[MixpanelResumeConfig]:
+ return self._state
+
+ def save_state(self, data: MixpanelResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestFlatten:
+ def test_flatten_event_lifts_properties(self) -> None:
+ row = _flatten_event(
+ {"event": "Signup", "properties": {"time": 1700000000, "distinct_id": "u1", "$insert_id": "abc"}}
+ )
+ assert row == {"event": "Signup", "time": 1700000000, "distinct_id": "u1", "$insert_id": "abc"}
+
+ def test_flatten_event_without_properties(self) -> None:
+ assert _flatten_event({"event": "Signup"}) == {"event": "Signup"}
+
+ def test_flatten_event_ignores_non_dict_properties(self) -> None:
+ assert _flatten_event({"event": "X", "properties": None}) == {"event": "X"}
+
+ def test_flatten_profile_lifts_properties(self) -> None:
+ row = _flatten_profile({"$distinct_id": "u1", "$properties": {"$email": "[email protected]", "plan": "pro"}})
+ assert row == {"$distinct_id": "u1", "$email": "[email protected]", "plan": "pro"}
+
+ def test_flatten_profile_without_properties(self) -> None:
+ assert _flatten_profile({"$distinct_id": "u1"}) == {"$distinct_id": "u1"}
+
+
+class TestToDate:
+ @parameterized.expand(
+ [
+ ("epoch_int", 1700000000, date(2023, 11, 14)),
+ ("epoch_float", 1700000000.0, date(2023, 11, 14)),
+ ("aware_datetime", datetime(2024, 5, 1, 23, 0, tzinfo=UTC), date(2024, 5, 1)),
+ ("naive_datetime", datetime(2024, 5, 1, 12, 0), date(2024, 5, 1)),
+ ("date_value", date(2024, 5, 1), date(2024, 5, 1)),
+ ("iso_string", "2024-05-01T10:00:00Z", date(2024, 5, 1)),
+ ("date_string", "2024-05-01", date(2024, 5, 1)),
+ ("none", None, None),
+ ("bad_string", "not-a-date", None),
+ ("bool", True, None),
+ ]
+ )
+ def test_to_date(self, _name: str, value: Any, expected: Optional[date]) -> None:
+ assert _to_date(value) == expected
+
+
+class TestRegionHosts:
+ @parameterized.expand(
+ [
+ ("us", "https://mixpanel.com", "https://data.mixpanel.com"),
+ ("eu", "https://eu.mixpanel.com", "https://data-eu.mixpanel.com"),
+ ("in", "https://in.mixpanel.com", "https://data-in.mixpanel.com"),
+ ("unknown", "https://mixpanel.com", "https://data.mixpanel.com"),
+ ]
+ )
+ def test_region_resolution(self, region: str, expected_query: str, expected_export: str) -> None:
+ assert _query_base(region) == expected_query
+ assert _export_base(region) == expected_export
+
+
+class TestCheckResponse:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ with pytest.raises(MixpanelRetryableError):
+ _check_response(FakeResponse(status_code=status), "http://x", LOGGER) # type: ignore[arg-type]
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_http_error(self, _name: str, status: int) -> None:
+ with pytest.raises(requests.HTTPError):
+ _check_response(FakeResponse(status_code=status), "http://x", LOGGER) # type: ignore[arg-type]
+
+ def test_ok_returns_response(self) -> None:
+ response = FakeResponse(status_code=200)
+ assert _check_response(response, "http://x", LOGGER) is response # type: ignore[arg-type, comparison-overlap]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, None, True),
+ ("unauthorized", 401, None, False),
+ ("forbidden_at_create", 403, None, True),
+ ("forbidden_with_schema", 403, "export", False),
+ ("unexpected", 500, None, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, schema_name: Optional[str], expected_ok: bool) -> None:
+ session = MagicMock()
+ session.post.return_value = FakeResponse(status_code=status)
+ with patch.object(mp, "make_tracked_session", return_value=session):
+ ok, error = validate_credentials("us", "user", "secret", "123", schema_name=schema_name)
+ assert ok is expected_ok
+ if expected_ok:
+ assert error is None
+ else:
+ assert error is not None
+
+ def test_network_error_returns_failure(self) -> None:
+ session = MagicMock()
+ session.post.side_effect = requests.ConnectionError("boom")
+ with patch.object(mp, "make_tracked_session", return_value=session):
+ ok, error = validate_credentials("eu", "user", "secret", "123")
+ assert ok is False
+ assert error is not None
+
+
+class TestExportIterator:
+ def _run(self, manager: FakeManager, start: date, end: date, responses: list[FakeResponse]) -> list[dict]:
+ with patch.object(mp, "_request", side_effect=responses) as mock_request:
+ batches = list(
+ mp._iter_export("us", "u", "s", "123", LOGGER, manager, start_date=start, end_date=end) # type: ignore[arg-type]
+ )
+ self._mock_request = mock_request
+ return [row for batch in batches for row in batch]
+
+ def test_streams_jsonl_per_day_and_saves_state(self) -> None:
+ manager = FakeManager()
+ day1 = [orjson.dumps({"event": "A", "properties": {"time": 1, "distinct_id": "u", "$insert_id": "i1"}})]
+ day2 = [orjson.dumps({"event": "B", "properties": {"time": 2, "distinct_id": "u", "$insert_id": "i2"}})]
+ rows = self._run(
+ manager,
+ date(2024, 1, 1),
+ date(2024, 1, 2),
+ [FakeResponse(lines=day1), FakeResponse(lines=day2)],
+ )
+
+ assert [r["event"] for r in rows] == ["A", "B"]
+ # One request per day window
+ assert self._mock_request.call_count == 2
+ first_call = self._mock_request.call_args_list[0]
+ assert first_call.kwargs["params"]["from_date"] == "2024-01-01"
+ assert first_call.kwargs["params"]["to_date"] == "2024-01-01"
+ # State advances to the day AFTER each completed window
+ assert [s.from_date for s in manager.saved] == ["2024-01-02", "2024-01-03"]
+
+ def test_resumes_from_saved_state(self) -> None:
+ manager = FakeManager(MixpanelResumeConfig(from_date="2024-01-02"))
+ rows = self._run(
+ manager,
+ date(2024, 1, 1),
+ date(2024, 1, 2),
+ [FakeResponse(lines=[orjson.dumps({"event": "B", "properties": {"time": 2}})])],
+ )
+ # Only the resumed day is fetched, the earlier day is skipped
+ assert self._mock_request.call_count == 1
+ assert self._mock_request.call_args_list[0].kwargs["params"]["from_date"] == "2024-01-02"
+ assert [r["event"] for r in rows] == ["B"]
+
+ def test_empty_day_still_advances(self) -> None:
+ manager = FakeManager()
+ rows = self._run(manager, date(2024, 1, 1), date(2024, 1, 1), [FakeResponse(lines=[])])
+ assert rows == []
+ assert [s.from_date for s in manager.saved] == ["2024-01-02"]
+
+
+class TestEngageIterator:
+ def test_paginates_with_session_id_and_saves_state(self) -> None:
+ manager = FakeManager()
+ page0 = FakeResponse(
+ json_data={
+ "page": 0,
+ "page_size": 2,
+ "session_id": "sess-1",
+ "results": [
+ {"$distinct_id": "a", "$properties": {"x": 1}},
+ {"$distinct_id": "b", "$properties": {"x": 2}},
+ ],
+ }
+ )
+ page1 = FakeResponse(
+ json_data={
+ "page": 1,
+ "page_size": 2,
+ "session_id": "sess-1",
+ "results": [{"$distinct_id": "c", "$properties": {"x": 3}}],
+ }
+ )
+ with patch.object(mp, "_request", side_effect=[page0, page1]) as mock_request:
+ batches = list(mp._iter_engage("us", "u", "s", "123", LOGGER, manager)) # type: ignore[arg-type]
+
+ rows = [row for batch in batches for row in batch]
+ assert [r["$distinct_id"] for r in rows] == ["a", "b", "c"]
+ # Second request carries the session_id and the next page
+ second_params = mock_request.call_args_list[1].kwargs["params"]
+ assert second_params["session_id"] == "sess-1"
+ assert second_params["page"] == 1
+ assert manager.saved[-1].page == 2
+ assert manager.saved[-1].session_id == "sess-1"
+
+ def test_resumes_from_saved_page(self) -> None:
+ manager = FakeManager(MixpanelResumeConfig(session_id="sess-9", page=3))
+ page = FakeResponse(json_data={"page": 3, "page_size": 10, "session_id": "sess-9", "results": []})
+ with patch.object(mp, "_request", side_effect=[page]) as mock_request:
+ list(mp._iter_engage("us", "u", "s", "123", LOGGER, manager)) # type: ignore[arg-type]
+ params = mock_request.call_args_list[0].kwargs["params"]
+ assert params["page"] == 3
+ assert params["session_id"] == "sess-9"
+
+
+class TestSingleRequestEndpoints:
+ def test_cohorts_handles_bare_list(self) -> None:
+ with patch.object(mp, "_request", return_value=FakeResponse(json_data=[{"id": 1}, {"id": 2}])):
+ batches = list(mp._fetch_cohorts("us", "u", "s", "123", LOGGER))
+ assert batches == [[{"id": 1}, {"id": 2}]]
+
+ def test_annotations_handles_results_wrapper(self) -> None:
+ with patch.object(mp, "_request", return_value=FakeResponse(json_data={"results": [{"id": 5}]})):
+ batches = list(mp._fetch_annotations("us", "u", "s", "123", LOGGER))
+ assert batches == [[{"id": 5}]]
+
+ def test_empty_results_yields_nothing(self) -> None:
+ with patch.object(mp, "_request", return_value=FakeResponse(json_data={"results": []})):
+ assert list(mp._fetch_annotations("us", "u", "s", "123", LOGGER)) == []
+
+
+@freeze_time("2024-06-04")
+class TestGetRowsExportWindow:
+ def _captured_window(self, **kwargs) -> tuple[date, date]:
+ with patch.object(mp, "_iter_export", return_value=iter([])) as mock_iter:
+ list(mp.get_rows("us", "u", "s", "123", "export", LOGGER, FakeManager(), **kwargs)) # type: ignore[arg-type]
+ call = mock_iter.call_args
+ return call.kwargs["start_date"], call.kwargs["end_date"]
+
+ def test_future_cursor_clamps_start_to_today(self) -> None:
+ future = int(datetime(2999, 1, 1, tzinfo=UTC).timestamp())
+ start_date, end_date = self._captured_window(
+ should_use_incremental_field=True, db_incremental_field_last_value=future
+ )
+ assert start_date == end_date == date(2024, 6, 4)
+
+ def test_past_cursor_used_as_start(self) -> None:
+ past = int(datetime(2020, 1, 1, tzinfo=UTC).timestamp())
+ start_date, end_date = self._captured_window(
+ should_use_incremental_field=True, db_incremental_field_last_value=past
+ )
+ assert start_date == date(2020, 1, 1)
+ assert end_date == date(2024, 6, 4)
+
+
+class TestMixpanelSource:
+ @parameterized.expand(
+ [
+ ("export", ["$insert_id", "event", "distinct_id", "time"], "datetime", "time"),
+ ("engage", ["$distinct_id"], None, None),
+ ("cohorts", ["id"], "datetime", "created"),
+ ("annotations", ["id"], None, None),
+ ]
+ )
+ def test_source_response_shape(
+ self, endpoint: str, primary_keys: list[str], partition_mode: Optional[str], partition_key: Optional[str]
+ ) -> None:
+ response = mixpanel_source("us", "u", "s", "123", endpoint, LOGGER, FakeManager()) # type: ignore[arg-type]
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.partition_mode == partition_mode
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+ assert response.sort_mode == "asc"
+
+ def test_endpoints_cover_settings(self) -> None:
+ # Guard against a settings/transport mismatch in the routing switch
+ for endpoint in MIXPANEL_ENDPOINTS:
+ response = mixpanel_source("us", "u", "s", "123", endpoint, LOGGER, FakeManager()) # type: ignore[arg-type]
+ assert response.name == endpoint
diff --git a/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py b/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py
new file mode 100644
index 000000000000..49ea2b782b0a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py
@@ -0,0 +1,176 @@
+from typing import Optional
+
+from unittest.mock import MagicMock, patch
+
+import structlog
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import MixpanelSourceConfig
+from posthog.temporal.data_imports.sources.mixpanel import source as source_module
+from posthog.temporal.data_imports.sources.mixpanel.mixpanel import MixpanelResumeConfig
+from posthog.temporal.data_imports.sources.mixpanel.source import MixpanelSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+LOGGER = structlog.get_logger()
+
+
+def _config() -> MixpanelSourceConfig:
+ return MixpanelSource().parse_config(
+ {
+ "project_id": "123456",
+ "service_account_username": "svc",
+ "service_account_secret": "shh",
+ "region": "eu",
+ }
+ )
+
+
+def _inputs(schema_name: str = "export", **overrides) -> SourceInputs:
+ defaults: dict = {
+ "schema_name": schema_name,
+ "schema_id": "schema-id",
+ "source_id": "source-id",
+ "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-id",
+ "logger": LOGGER,
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestSourceType:
+ def test_source_type(self) -> None:
+ assert MixpanelSource().source_type == ExternalDataSourceType.MIXPANEL
+
+
+class TestSourceConfig:
+ def test_basic_metadata(self) -> None:
+ config = MixpanelSource().get_source_config
+ assert config.label == "Mixpanel"
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == "alpha"
+
+ def test_fields(self) -> None:
+ fields = {f.name: f for f in MixpanelSource().get_source_config.fields}
+ assert set(fields) == {"region", "project_id", "service_account_username", "service_account_secret"}
+
+ assert isinstance(fields["region"], SourceFieldSelectConfig)
+ assert {o.value for o in fields["region"].options} == {"us", "eu", "in"}
+ assert fields["region"].defaultValue == "us"
+
+ secret = fields["service_account_secret"]
+ assert isinstance(secret, SourceFieldInputConfig)
+ assert secret.type == SourceFieldInputConfigType.PASSWORD
+ assert secret.secret is True
+
+ # The project id / username are not secret inputs
+ assert isinstance(fields["project_id"], SourceFieldInputConfig)
+ assert fields["project_id"].type == SourceFieldInputConfigType.TEXT
+
+
+class TestConnectionHostFields:
+ def test_region_and_project_require_secret_re_entry(self) -> None:
+ assert set(MixpanelSource().connection_host_fields) == {"region", "project_id"}
+
+
+class TestGetSchemas:
+ def test_all_schemas(self) -> None:
+ schemas = {s.name: s for s in MixpanelSource().get_schemas(_config(), team_id=1)}
+ assert set(schemas) == {"export", "engage", "cohorts", "annotations"}
+
+ @parameterized.expand(
+ [
+ ("export", True),
+ ("engage", False),
+ ("cohorts", False),
+ ("annotations", False),
+ ]
+ )
+ def test_incremental_support(self, endpoint: str, supports: bool) -> None:
+ schemas = {s.name: s for s in MixpanelSource().get_schemas(_config(), team_id=1)}
+ assert schemas[endpoint].supports_incremental is supports
+ assert schemas[endpoint].supports_append is supports
+
+ def test_export_has_time_incremental_field(self) -> None:
+ schemas = {s.name: s for s in MixpanelSource().get_schemas(_config(), team_id=1)}
+ fields = schemas["export"].incremental_fields
+ assert [f["field"] for f in fields] == ["time"]
+
+ def test_filter_by_names(self) -> None:
+ schemas = MixpanelSource().get_schemas(_config(), team_id=1, names=["engage"])
+ assert [s.name for s in schemas] == ["engage"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", (True, None)), ("bad", (False, "nope"))])
+ def test_delegates_to_transport(self, _name: str, result: tuple[bool, Optional[str]]) -> None:
+ with patch.object(source_module, "validate_mixpanel_credentials", return_value=result) as mock_validate:
+ assert MixpanelSource().validate_credentials(_config(), team_id=1, schema_name="export") == result
+ kwargs = mock_validate.call_args.kwargs
+ assert kwargs["region"] == "eu"
+ assert kwargs["project_id"] == "123456"
+ assert kwargs["username"] == "svc"
+ assert kwargs["secret"] == "shh"
+ assert kwargs["schema_name"] == "export"
+
+
+class TestNonRetryableErrors:
+ def test_auth_errors_present(self) -> None:
+ errors = MixpanelSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+
+class TestResumableManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ manager = MixpanelSource().get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MixpanelResumeConfig
+
+
+class TestSourceForPipeline:
+ def test_plumbs_arguments(self) -> None:
+ config = _config()
+ manager = MagicMock()
+ with patch.object(source_module, "mixpanel_source") as mock_source:
+ MixpanelSource().source_for_pipeline(config, manager, _inputs(schema_name="engage"))
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["region"] == "eu"
+ assert kwargs["project_id"] == "123456"
+ assert kwargs["username"] == "svc"
+ assert kwargs["secret"] == "shh"
+ assert kwargs["endpoint"] == "engage"
+ assert kwargs["manager"] is manager
+
+ def test_incremental_value_passed_only_when_incremental(self) -> None:
+ with patch.object(source_module, "mixpanel_source") as mock_source:
+ MixpanelSource().source_for_pipeline(
+ _config(),
+ MagicMock(),
+ _inputs(
+ schema_name="export", should_use_incremental_field=True, db_incremental_field_last_value=1700000000
+ ),
+ )
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] == 1700000000
+
+ def test_incremental_value_dropped_when_not_incremental(self) -> None:
+ with patch.object(source_module, "mixpanel_source") as mock_source:
+ MixpanelSource().source_for_pipeline(
+ _config(),
+ MagicMock(),
+ _inputs(
+ schema_name="export", should_use_incremental_field=False, db_incremental_field_last_value=1700000000
+ ),
+ )
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None