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(warehouse-sources): add mixpanel funnels, funnel steps and retention tables (#115409)

Tom Owers4f4c8ac21db1
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 6f07aed45b01..a10226531ee7 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -793,8 +793,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/metorial/metorial.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/metorial/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/mixmax.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/mixpanel.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/mollie/mollie.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/mollie/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/monday/settings.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index a6773c74f2cd..0ced75e4c345 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5653,11 +5653,11 @@ Today (4): `annotations`, `cohorts`, `engage`, `export`
Diffed against: <https://developer.mixpanel.com/reference/query-api>
-- [ ] `funnels query (GET /api/query/funnels — reference/funnels-query)` — funnel conversion is Mixpanel's headline metric and is entirely absent (high)
-- [ ] `saved funnels list (reference/funnels-list-saved)` — lookup table of saved funnel definitions and their IDs, required to drive the funnels query (high)
-- [ ] `retention query (reference/retention-query)` — cohort retention, a core Mixpanel report with no equivalent today (high)
+- [x] `funnels query (GET /api/query/funnels — reference/funnels-query)` — funnel conversion is Mixpanel's headline metric and is entirely absent (high) — added as `funnel_steps`, fanned out over every saved funnel
+- [x] `saved funnels list (reference/funnels-list-saved)` — lookup table of saved funnel definitions and their IDs, required to drive the funnels query (high) — added as `funnels`
+- [x] `retention query (reference/retention-query)` — cohort retention, a core Mixpanel report with no equivalent today (high) — added as `retention` (compounded retention across all events, because birth retention needs a user-chosen `born_event`)
- [ ] `segmentation query (reference/segmentation-query, plus numeric/sum/average variants)` — event counts broken down by property — the main breakdown dimension API (high)
-- [ ] `insights query (reference/insights-query)` — returns the data behind saved Insights reports (high)
+- [ ] `insights query (reference/insights-query)` — returns the data behind saved Insights reports (high). Not added: each call needs a report `bookmark_id`, no Query API endpoint lists saved reports, and the `series` shape varies per report.
- [ ] `Lexicon schemas (reference/list-all-schemas-for-project, list-schemas-for-entity)` — lookup table of event and property definitions that names and types everything in the export table (high)
- [ ] `lookup tables (reference/list-lookup-tables)` — literally the project's lookup tables, used to resolve IDs on synced events and profiles (high)
- [ ] `activity stream (reference/activity-stream-query)` — per-user chronological event feed joining engage profiles to their activity (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/canonical_descriptions.py
index 70f275468ded..5bd1ddc6c0a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixpanel/canonical_descriptions.py
@@ -62,4 +62,45 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"user": "User who created the annotation.",
},
},
+ "funnels": {
+ "description": "Saved funnels — the funnel reports defined in the Mixpanel project, by id and name.",
+ "docs_url": "https://developer.mixpanel.com/reference/funnels-list-saved",
+ "columns": {
+ "funnel_id": "Unique identifier for the saved funnel.",
+ "name": "The funnel's name.",
+ },
+ },
+ "funnel_steps": {
+ "description": "Daily conversion for each step of every saved funnel, over the last 90 days.",
+ "docs_url": "https://developer.mixpanel.com/reference/funnels-query",
+ "columns": {
+ "funnel_id": "Identifier of the saved funnel the step belongs to.",
+ "funnel_name": "Name of the saved funnel the step belongs to.",
+ "date": "Day the funnel conversions are bucketed into, as YYYY-MM-DD.",
+ "step_index": "Zero-based position of the step in the funnel.",
+ "count": "Number of users who converted through this step.",
+ "goal": "Name of the step's event.",
+ "event": "Name of the step's event.",
+ "step_label": "Display label of the step: the event name or the custom event name.",
+ "step_conv_ratio": "Conversion rate from the previous step.",
+ "overall_conv_ratio": "Conversion rate from the first step of the funnel.",
+ "avg_time": "Mean time to convert from the previous step; null for the first step.",
+ "avg_time_from_start": "Mean time to convert from the first step.",
+ "custom_event": "True when the step is a custom event.",
+ "custom_event_id": "Identifier of the custom event, when the step is a custom event.",
+ },
+ },
+ "retention": {
+ "description": (
+ "Daily recurring (compounded) retention across all events: for each day's cohort of active users, "
+ "how many were active again in each following day."
+ ),
+ "docs_url": "https://developer.mixpanel.com/reference/retention-query",
+ "columns": {
+ "date": "Day of the cohort, as YYYY-MM-DD.",
+ "interval_index": "Days since the cohort day. Interval 0 covers activity within one day of the first event.",
+ "count": "Number of users from the cohort who were active in this interval.",
+ "first": "Number of users in the cohort.",
+ },
+ },
}
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.py
index cafee3b3dbf1..edb439a22bd6 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
@@ -21,6 +21,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.s
MIXPANEL_API_VERSION_V1,
MIXPANEL_ENDPOINTS,
REGION_HOSTS,
+ REPORT_LOOKBACK_DAYS,
+ RETENTION_INTERVAL_COUNT,
RegionHosts,
)
@@ -90,13 +92,15 @@ def _retry_wait(retry_state: RetryCallState) -> float:
return _EXPONENTIAL_JITTER(retry_state)
[email protected](frozen=True)
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
+ # Funnel steps resume after the last saved funnel whose rows were handed to the pipeline.
+ funnel_id: Optional[int] = None
def _hosts(region: str) -> RegionHosts:
@@ -447,6 +451,133 @@ def _fetch_annotations(
yield rows
+def _fetch_funnel_list(
+ region: str, username: str, secret: str, project_id: str, logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ url = f"{_query_base(region)}/api/query/funnels/list"
+ response = _request("GET", url, username=username, secret=secret, logger=logger, params={"project_id": project_id})
+ data = response.json()
+ return data if isinstance(data, list) else []
+
+
+def _fetch_funnels(
+ region: str, username: str, secret: str, project_id: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ rows = _fetch_funnel_list(region, username, secret, project_id, logger)
+ if rows:
+ yield rows
+
+
+def _flatten_funnel_steps(funnel: dict[str, Any], data: dict[str, Any]) -> list[dict[str, Any]]:
+ """Unnest the `{date: {"steps": [...]}}` funnel response into one row per day and step."""
+ rows: list[dict[str, Any]] = []
+ buckets = data.get("data")
+ if not isinstance(buckets, dict):
+ return rows
+ for day in sorted(buckets):
+ bucket = buckets[day]
+ steps = bucket.get("steps") if isinstance(bucket, dict) else None
+ for index, step in enumerate(steps or []):
+ rows.append(
+ {
+ **step,
+ "funnel_id": funnel["funnel_id"],
+ "funnel_name": funnel.get("name"),
+ "date": day,
+ "step_index": index,
+ }
+ )
+ return rows
+
+
+def _iter_funnel_steps(
+ 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]]]:
+ """Query every saved funnel, one request per funnel, in ascending `funnel_id` order.
+
+ The Query API allows only a small number of queries per hour, so a project with many
+ funnels can exhaust the retries part-way through. Resuming after the last finished
+ funnel keeps the next attempt from spending its budget on funnels already synced."""
+ url = f"{_query_base(region)}/api/query/funnels"
+
+ resume = manager.load_state() if manager.can_resume() else None
+ last_funnel_id = resume.funnel_id if resume else None
+ if last_funnel_id is not None:
+ logger.debug(f"Mixpanel funnel_steps: resuming after funnel {last_funnel_id}")
+
+ funnels = sorted(
+ (f for f in _fetch_funnel_list(region, username, secret, project_id, logger) if f.get("funnel_id") is not None),
+ key=lambda f: f["funnel_id"],
+ )
+ for funnel in funnels:
+ funnel_id = funnel["funnel_id"]
+ if last_funnel_id is not None and funnel_id <= last_funnel_id:
+ continue
+
+ params = {
+ "project_id": project_id,
+ "funnel_id": funnel_id,
+ "from_date": start_date.isoformat(),
+ "to_date": end_date.isoformat(),
+ "unit": "day",
+ }
+ response = _request("GET", url, username=username, secret=secret, logger=logger, params=params)
+ rows = _flatten_funnel_steps(funnel, response.json())
+
+ manager.save_state(MixpanelResumeConfig(funnel_id=funnel_id))
+ if rows:
+ yield rows
+ else:
+ manager.safe_point()
+
+
+def _flatten_retention(data: dict[str, Any]) -> list[dict[str, Any]]:
+ """Unnest the `{date: {"counts": [...], "first": n}}` retention response into one row per
+ cohort day and interval."""
+ rows: list[dict[str, Any]] = []
+ for day in sorted(data):
+ cohort = data[day]
+ if not isinstance(cohort, dict):
+ continue
+ for index, count in enumerate(cohort.get("counts") or []):
+ rows.append({"date": day, "interval_index": index, "count": count, "first": cohort.get("first")})
+ return rows
+
+
+def _fetch_retention(
+ region: str,
+ username: str,
+ secret: str,
+ project_id: str,
+ logger: FilteringBoundLogger,
+ start_date: date,
+ end_date: date,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{_query_base(region)}/api/query/retention"
+ # Birth retention needs a `born_event` only the user can choose. Compounded retention with
+ # no `event` measures how often users active on a day come back for any event.
+ params = {
+ "project_id": project_id,
+ "from_date": start_date.isoformat(),
+ "to_date": end_date.isoformat(),
+ "retention_type": "compounded",
+ "unit": "day",
+ "interval_count": RETENTION_INTERVAL_COUNT,
+ }
+ response = _request("GET", url, username=username, secret=secret, logger=logger, params=params)
+ data = response.json()
+ rows = _flatten_retention(data) if isinstance(data, dict) else []
+ if rows:
+ yield rows
+
+
def get_rows(
region: str,
username: str,
@@ -487,6 +618,19 @@ def get_rows(
yield from _fetch_cohorts(region, username, secret, project_id, logger)
elif endpoint == "annotations":
yield from _fetch_annotations(region, username, secret, project_id, logger)
+ elif endpoint == "funnels":
+ yield from _fetch_funnels(region, username, secret, project_id, logger)
+ elif endpoint in ("funnel_steps", "retention"):
+ report_end = datetime.now(UTC).date()
+ report_start = report_end - timedelta(days=REPORT_LOOKBACK_DAYS)
+ if endpoint == "funnel_steps":
+ yield from _iter_funnel_steps(
+ region, username, secret, project_id, logger, manager, start_date=report_start, end_date=report_end
+ )
+ else:
+ yield from _fetch_retention(
+ region, username, secret, project_id, logger, start_date=report_start, end_date=report_end
+ )
else:
raise ValueError(f"Unknown Mixpanel endpoint: {endpoint}")
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.py
index 090149f1b643..1d118319fb77 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
@@ -51,8 +51,14 @@ REGION_HOSTS: dict[str, RegionHosts] = {
# last-seen event time.
DEFAULT_EXPORT_LOOKBACK_DAYS = 365
+# Funnel and retention reports are recomputed over a rolling window on every sync, because
+# Mixpanel keeps revising recent buckets while conversion and return windows are still open.
+REPORT_LOOKBACK_DAYS = 90
+# Daily retention intervals returned per cohort, on top of Mixpanel's 0th interval.
+RETENTION_INTERVAL_COUNT = 30
-@dataclass
+
+@dataclass(frozen=True)
class MixpanelEndpointConfig:
name: str
primary_keys: list[str]
@@ -61,6 +67,7 @@ class MixpanelEndpointConfig:
# written (event time / creation date), never `updated`/`last_seen`.
partition_key: Optional[str] = None
partition_format: PartitionFormat = "month"
+ description: Optional[str] = None
MIXPANEL_ENDPOINTS: dict[str, MixpanelEndpointConfig] = {
@@ -74,6 +81,7 @@ MIXPANEL_ENDPOINTS: dict[str, MixpanelEndpointConfig] = {
primary_keys=["$insert_id", "event", "distinct_id", "time"],
partition_key="time",
partition_format="month",
+ description="Only syncs the last 365 days on initial sync",
incremental_fields=[
{
"label": "time",
@@ -100,6 +108,25 @@ MIXPANEL_ENDPOINTS: dict[str, MixpanelEndpointConfig] = {
name="annotations",
primary_keys=["id"],
),
+ # Query API: saved funnel definitions (id + name). Single request, full refresh.
+ "funnels": MixpanelEndpointConfig(
+ name="funnels",
+ primary_keys=["funnel_id"],
+ ),
+ # Query API: daily step conversion for every saved funnel, one row per funnel, day and step.
+ "funnel_steps": MixpanelEndpointConfig(
+ name="funnel_steps",
+ description="Recomputes the last 90 days on every sync",
+ primary_keys=["funnel_id", "date", "step_index"],
+ partition_key="date",
+ ),
+ # Query API: daily recurring retention across all events, one row per cohort day and interval.
+ "retention": MixpanelEndpointConfig(
+ name="retention",
+ description="Recomputes the last 90 days on every sync",
+ primary_keys=["date", "interval_index"],
+ partition_key="date",
+ ),
}
ENDPOINTS = tuple(MIXPANEL_ENDPOINTS.keys())
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.py
index 26ef51bdbe47..d119fcc5b35d 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
@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mixpanel.s
DEFAULT_API_VERSION,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ MIXPANEL_ENDPOINTS,
SUPPORTED_API_VERSIONS,
SUPPORTS_INCREMENTAL,
)
@@ -61,7 +62,7 @@ class MixpanelSource(ResumableSource[MixpanelSourceConfig, MixpanelResumeConfig]
name=ExternalDataSourceType.MIXPANEL,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Mixpanel",
- caption="""Connect your Mixpanel project to pull events, user profiles, cohorts and annotations into the PostHog Data warehouse.
+ caption="""Connect your Mixpanel project to pull events, user profiles, cohorts, annotations, funnels and retention 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:
@@ -136,7 +137,7 @@ Authenticate with a [Mixpanel Service Account](https://developer.mixpanel.com/re
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,
+ description=MIXPANEL_ENDPOINTS[endpoint].description,
)
for endpoint in ENDPOINTS
]
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.py
index 9d28ef220865..12c44a5ff6a7 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
@@ -82,6 +82,7 @@ class FakeManager:
def __init__(self, resume_state: Optional[MixpanelResumeConfig] = None) -> None:
self._state = resume_state
self.saved: list[MixpanelResumeConfig] = []
+ self.safe_points = 0
def can_resume(self) -> bool:
return self._state is not None
@@ -92,6 +93,9 @@ class FakeManager:
def save_state(self, data: MixpanelResumeConfig) -> None:
self.saved.append(data)
+ def safe_point(self) -> None:
+ self.safe_points += 1
+
class TestToDate:
@parameterized.expand(
@@ -478,6 +482,74 @@ class TestSingleRequestEndpoints:
assert batches == [[{"id": 5}]]
+class TestReportEndpoints:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2024-06-04", tick=False):
+ yield
+
+ def _funnel_response(self) -> FakeResponse:
+ return FakeResponse(
+ json_data={
+ "meta": {"dates": ["2024-06-03", "2024-06-02"]},
+ "data": {
+ "2024-06-03": {"steps": [{"count": 5, "event": "Signup"}], "analysis": {"completion": 5}},
+ "2024-06-02": {
+ "steps": [{"count": 10, "event": "Visit"}, {"count": 4, "event": "Signup"}],
+ "analysis": {"completion": 4},
+ },
+ },
+ }
+ )
+
+ @parameterized.expand([("fresh", None, [7, 9]), ("resumed", 7, [9])])
+ def test_funnel_steps_walk_funnels_in_id_order(
+ self, _name: str, resume_funnel_id: Optional[int], expected_funnel_ids: list[int]
+ ) -> None:
+ manager = FakeManager(MixpanelResumeConfig(funnel_id=resume_funnel_id) if resume_funnel_id else None)
+ funnel_list = FakeResponse(json_data=[{"funnel_id": 9, "name": "Checkout"}, {"funnel_id": 7, "name": "Signup"}])
+ funnel_responses = {7: FakeResponse(json_data={"meta": {"dates": []}, "data": {}}), 9: self._funnel_response()}
+
+ def fake_request(method: str, url: str, **kwargs: Any) -> FakeResponse:
+ if url.endswith("/funnels/list"):
+ return funnel_list
+ return funnel_responses[kwargs["params"]["funnel_id"]]
+
+ with patch.object(mp, "_request", side_effect=fake_request) as mock_request:
+ batches = list(mp.get_rows("us", "u", "s", "123", "funnel_steps", LOGGER, manager)) # type: ignore[arg-type]
+
+ query_params = [c.kwargs["params"] for c in mock_request.call_args_list[1:]]
+ assert [p["funnel_id"] for p in query_params] == expected_funnel_ids
+ assert all((p["from_date"], p["to_date"]) == ("2024-03-06", "2024-06-04") for p in query_params)
+ assert [s.funnel_id for s in manager.saved] == expected_funnel_ids
+ assert manager.safe_points == (1 if 7 in expected_funnel_ids else 0)
+ rows = [row for batch in batches for row in batch]
+ assert [(r["funnel_id"], r["funnel_name"], r["date"], r["step_index"], r["event"]) for r in rows] == [
+ (9, "Checkout", "2024-06-02", 0, "Visit"),
+ (9, "Checkout", "2024-06-02", 1, "Signup"),
+ (9, "Checkout", "2024-06-03", 0, "Signup"),
+ ]
+
+ def test_retention_requests_compounded_retention_and_unnests_cohorts(self) -> None:
+ response = FakeResponse(
+ json_data={"2024-06-03": {"counts": [8], "first": 8}, "2024-06-02": {"counts": [10, 6], "first": 10}}
+ )
+ with patch.object(mp, "_request", return_value=response) as mock_request:
+ batches = list(mp.get_rows("us", "u", "s", "123", "retention", LOGGER, FakeManager())) # type: ignore[arg-type]
+
+ params = mock_request.call_args.kwargs["params"]
+ assert params["retention_type"] == "compounded"
+ assert "born_event" not in params
+ assert (params["from_date"], params["to_date"]) == ("2024-03-06", "2024-06-04")
+ assert batches == [
+ [
+ {"date": "2024-06-02", "interval_index": 0, "count": 10, "first": 10},
+ {"date": "2024-06-02", "interval_index": 1, "count": 6, "first": 10},
+ {"date": "2024-06-03", "interval_index": 0, "count": 8, "first": 8},
+ ]
+ ]
+
+
class TestGetRowsExportWindow:
@pytest.fixture(autouse=True)
def _frozen_clock(self):