: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(warehouse_sources): support Mixpanel API version 2.0 (#71672)
Tom Owers03db635e4e7e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.pyindex c5df441d4fab..08783b5d79cd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py@@ -17,6 +17,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.httfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.settings import (DEFAULT_EXPORT_LOOKBACK_DAYS,+ EXPORT_API_PATH_SEGMENT,+ MIXPANEL_API_VERSION_V1,MIXPANEL_ENDPOINTS,REGION_HOSTS,)@@ -108,6 +110,13 @@ def _export_base(region: str) -> str:return _hosts(region)[1]+def _export_url(region: str, api_version: str) -> str:+ # A pin is honored verbatim, so an unknown/future label can reach here; fall back to+ # Mixpanel's only raw-export path (`2.0`) rather than raising on the lookup.+ segment = EXPORT_API_PATH_SEGMENT.get(api_version, "2.0")+ return f"{_export_base(region)}/api/{segment}/export"++def _flatten_event(event: dict[str, Any]) -> dict[str, Any]:"""Lift the `properties` sub-object of a raw export event to the top level.@@ -306,6 +315,7 @@ def _iter_export(manager: ResumableSourceManager[MixpanelResumeConfig],start_date: date,end_date: date,+ api_version: str,) -> Iterator[list[dict[str, Any]]]:"""Stream the raw event export one UTC day at a time.@@ -313,7 +323,7 @@ def _iter_export(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 thein-flight day (merge dedupes on `$insert_id`)."""- url = f"{_export_base(region)}/api/2.0/export"+ url = _export_url(region, api_version)resume = manager.load_state() if manager.can_resume() else Noneresumed_from = _to_date(resume.from_date) if resume and resume.from_date else None@@ -411,6 +421,7 @@ def get_rows(manager: ResumableSourceManager[MixpanelResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,+ api_version: str = MIXPANEL_API_VERSION_V1,) -> 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@@ -424,7 +435,15 @@ def get_rows()start_date = end_dateyield from _iter_export(- region, username, secret, project_id, logger, manager, start_date=start_date, end_date=end_date+ region,+ username,+ secret,+ project_id,+ logger,+ manager,+ start_date=start_date,+ end_date=end_date,+ api_version=api_version,)elif endpoint == "engage":yield from _iter_engage(region, username, secret, project_id, logger, manager)@@ -446,6 +465,7 @@ def mixpanel_source(manager: ResumableSourceManager[MixpanelResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,+ api_version: str = MIXPANEL_API_VERSION_V1,) -> SourceResponse:endpoint_config = MIXPANEL_ENDPOINTS[endpoint]@@ -461,6 +481,7 @@ def mixpanel_source(manager=manager,should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,+ api_version=api_version,),primary_keys=endpoint_config.primary_keys,partition_count=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.pyindex 03ec9384377f..3e9196580b51 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py@@ -3,8 +3,26 @@ from enum import StrEnumfrom typing import Optionalfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSIONfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# Mixpanel vendor API version labels. `v1` is PostHog's legacy placeholder — the source+# predates explicit versioning — and `2.0` is Mixpanel's current published API version.+MIXPANEL_API_VERSION_V1 = UNVERSIONED_API_VERSION+MIXPANEL_API_VERSION_2_0 = "2.0"++SUPPORTED_API_VERSIONS: tuple[str, ...] = (MIXPANEL_API_VERSION_V1, MIXPANEL_API_VERSION_2_0)+DEFAULT_API_VERSION = MIXPANEL_API_VERSION_2_0++# Mixpanel serves the Raw Event Export under a versioned path segment (`/api/2.0/export`).+# Both supported labels currently resolve to Mixpanel's `2.0` export path; deriving the+# segment from the pin keeps a future export-API version a one-line change here rather than+# a hunt through the request layer.+EXPORT_API_PATH_SEGMENT: dict[str, str] = {+ MIXPANEL_API_VERSION_V1: "2.0",+ MIXPANEL_API_VERSION_2_0: "2.0",+}+class MixpanelRegion(StrEnum):US = "us"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.pyindex cbea3d72c059..0a82c1b94a37 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/source.py@@ -29,8 +29,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.mvalidate_credentials as validate_mixpanel_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.settings import (+ DEFAULT_API_VERSION,ENDPOINTS,INCREMENTAL_FIELDS,+ SUPPORTED_API_VERSIONS,SUPPORTS_INCREMENTAL,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -38,7 +40,10 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass MixpanelSource(ResumableSource[MixpanelSourceConfig, MixpanelResumeConfig]):- api_docs_url = "https://developer.mixpanel.com"+ api_docs_url = "https://developer.mixpanel.com/reference/raw-data-export-api"++ supported_versions = SUPPORTED_API_VERSIONS+ default_version = DEFAULT_API_VERSIONlists_tables_without_credentials = True # static endpoint catalog — safe for public docs@@ -191,4 +196,5 @@ Authenticate with a [Mixpanel Service Account](https://developer.mixpanel.com/redb_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,+ api_version=self.resolve_api_version(inputs.api_version),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.pyindex 3f6244a2b5be..e01691727fcb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel.py@@ -26,7 +26,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.mmixpanel_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.settings import MIXPANEL_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.settings import (+ MIXPANEL_API_VERSION_2_0,+ MIXPANEL_API_VERSION_V1,+ MIXPANEL_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.source import MixpanelSourceLOGGER = structlog.get_logger()@@ -285,14 +289,39 @@ class TestValidateCredentials:class TestExportIterator:- def _run(self, manager: FakeManager, start: date, end: date, responses: list[FakeResponse]) -> list[dict]:+ def _run(+ self,+ manager: FakeManager,+ start: date,+ end: date,+ responses: list[FakeResponse],+ api_version: str = MIXPANEL_API_VERSION_V1,+ ) -> 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]+ mp._iter_export(+ "us",+ "u",+ "s",+ "123",+ LOGGER,+ manager, # type: ignore[arg-type]+ start_date=start,+ end_date=end,+ api_version=api_version,+ ))self._mock_request = mock_requestreturn [row for batch in batches for row in batch]+ @parameterized.expand([("v1", MIXPANEL_API_VERSION_V1), ("2.0", MIXPANEL_API_VERSION_2_0)])+ def test_export_hits_versioned_path(self, _name: str, api_version: str) -> None:+ # Both supported versions resolve to Mixpanel's `2.0` raw-export path; the segment is+ # derived from the pin, so this guards the version -> URL wiring per supported version.+ self._run(FakeManager(), date(2024, 1, 1), date(2024, 1, 1), [FakeResponse(lines=[])], api_version=api_version)+ url = self._mock_request.call_args_list[0].args[1]+ assert url == "https://data.mixpanel.com/api/2.0/export"+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"}})]@@ -350,7 +379,17 @@ class TestExportStreamRetry:patch.object(mp.time, "sleep") as mock_sleep,):batches = list(- mp._iter_export("us", "u", "s", "123", LOGGER, manager, start_date=day, end_date=day) # type: ignore[arg-type]+ mp._iter_export(+ "us",+ "u",+ "s",+ "123",+ LOGGER,+ manager, # type: ignore[arg-type]+ start_date=day,+ end_date=day,+ api_version=MIXPANEL_API_VERSION_V1,+ ))rows = [row for batch in batches for row in batch]@@ -375,7 +414,17 @@ class TestExportStreamRetry:):with pytest.raises(requests.exceptions.ChunkedEncodingError):list(- mp._iter_export("us", "u", "s", "123", LOGGER, manager, start_date=day, end_date=day) # type: ignore[arg-type]+ mp._iter_export(+ "us",+ "u",+ "s",+ "123",+ LOGGER,+ manager, # type: ignore[arg-type]+ start_date=day,+ end_date=day,+ api_version=MIXPANEL_API_VERSION_V1,+ ))assert mock_request.call_count == mp.STREAM_MAX_ATTEMPTS@@ -393,7 +442,17 @@ class TestExportStreamRetry:):with pytest.raises(ValueError):list(- mp._iter_export("us", "u", "s", "123", LOGGER, manager, start_date=day, end_date=day) # type: ignore[arg-type]+ mp._iter_export(+ "us",+ "u",+ "s",+ "123",+ LOGGER,+ manager, # type: ignore[arg-type]+ start_date=day,+ end_date=day,+ api_version=MIXPANEL_API_VERSION_V1,+ ))assert mock_request.call_count == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.pyindex b582cc122a5e..226dd6969776 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/test_mixpanel_source.py@@ -138,6 +138,25 @@ class TestResumableManager:assert manager._data_class is MixpanelResumeConfig+class TestApiVersions:+ def test_new_sources_default_to_2_0(self) -> None:+ # New sources are stamped with `default_version`; existing pins are unaffected.+ assert MixpanelSource().default_version == "2.0"+ assert set(MixpanelSource().supported_versions) == {"v1", "2.0"}++ @parameterized.expand(+ [+ ("no_pin_uses_default", None, "2.0"),+ ("v1_pin_honored", "v1", "v1"),+ ("2_0_pin_honored", "2.0", "2.0"),+ ]+ )+ def test_source_for_pipeline_threads_resolved_version(self, _name: str, pin: Optional[str], expected: str) -> None:+ with patch.object(source_module, "mixpanel_source") as mock_source:+ MixpanelSource().source_for_pipeline(_config(), MagicMock(), _inputs(api_version=pin))+ assert mock_source.call_args.kwargs["api_version"] == expected++class TestSourceForPipeline:def test_plumbs_arguments(self) -> None:config = _config()