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 mixmax import source (#67800)

Tom Owersc6906461f4dc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 2ff3f8fa94da..db995f9af9f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -197,6 +197,7 @@ the row lists both.
| matomo | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
| metabase | HTTP | requests | ✅ |
+| mixmax | HTTP | requests | ✅ |
| mixpanel | HTTP | requests | ✅ |
| mollie | HTTP | requests | ✅ |
| monday | HTTP (GraphQL) | requests | ✅ |
@@ -518,7 +519,6 @@ doesn't conflict with concurrent PRs.
- microsoft_teams
- miro
- missive
-- mixmax
- mode
- my_hours
- n8n
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 619e18b1c0bd..66a96e902665 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2032,7 +2032,7 @@ class MissiveSourceConfig(config.Config):
@config.config
class MixMaxSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/canonical_descriptions.py
new file mode 100644
index 000000000000..0c180a4b7f46
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/canonical_descriptions.py
@@ -0,0 +1,100 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://developer.mixmax.com/reference"
+
+# Curated from the public Mixmax API docs (https://developer.mixmax.com). Keyed by the schema/endpoint
+# name from `settings.ENDPOINTS`. Partial coverage is fine — anything missing falls back to LLM
+# enrichment. Mixmax objects are MongoDB documents, so the identifier column is `_id` everywhere
+# except live feed rows, which use `uid`.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "sequences": {
+ "description": "Automated multi-step outreach sequences the API token's user can access.",
+ "docs_url": f"{_DOCS}/sequences",
+ "columns": {
+ "_id": "Unique identifier for the sequence.",
+ "name": "Human-readable name of the sequence.",
+ },
+ },
+ "sequence_folders": {
+ "description": "Folders used to organize sequences.",
+ "docs_url": f"{_DOCS}/sequence-folders",
+ "columns": {
+ "_id": "Unique identifier for the sequence folder.",
+ "name": "Name of the folder.",
+ },
+ },
+ "messages": {
+ "description": "Tracked email messages sent through Mixmax.",
+ "docs_url": f"{_DOCS}/messages",
+ "columns": {
+ "_id": "Unique identifier for the message.",
+ "subject": "Subject line of the message.",
+ },
+ },
+ "rules": {
+ "description": "Automation rules that trigger Mixmax actions.",
+ "docs_url": f"{_DOCS}/rules",
+ "columns": {"_id": "Unique identifier for the rule."},
+ },
+ "code_snippets": {
+ "description": "Reusable code snippets injected into emails.",
+ "docs_url": f"{_DOCS}/code-snippets",
+ "columns": {"_id": "Unique identifier for the code snippet."},
+ },
+ "snippet_tags": {
+ "description": "Tags used to categorize snippets.",
+ "docs_url": f"{_DOCS}/snippet-tags",
+ "columns": {
+ "_id": "Unique identifier for the snippet tag.",
+ "name": "Name of the tag.",
+ },
+ },
+ "meeting_types": {
+ "description": "Configured meeting/appointment types used for scheduling.",
+ "docs_url": f"{_DOCS}/meeting-types",
+ "columns": {"_id": "Unique identifier for the meeting type."},
+ },
+ "insights_reports": {
+ "description": "Saved insights reports.",
+ "docs_url": f"{_DOCS}/insights",
+ "columns": {"_id": "Unique identifier for the report."},
+ },
+ "polls": {
+ "description": "Polls embedded in Mixmax emails.",
+ "docs_url": f"{_DOCS}/polls",
+ "columns": {"_id": "Unique identifier for the poll."},
+ },
+ "file_requests": {
+ "description": "File requests sent through Mixmax.",
+ "docs_url": f"{_DOCS}/file-requests",
+ "columns": {"_id": "Unique identifier for the file request."},
+ },
+ "live_feed": {
+ "description": "Real-time email tracking events such as opens, clicks and downloads.",
+ "docs_url": f"{_DOCS}/live-feed",
+ "columns": {"uid": "Unique identifier for the live feed event."},
+ },
+ "appointment_links": {
+ "description": "The authenticated user's appointment (scheduling) links.",
+ "docs_url": f"{_DOCS}/appointment-links",
+ "columns": {
+ "_id": "Unique identifier for the appointment link.",
+ "userId": "Identifier of the user the appointment links belong to.",
+ },
+ },
+ "users": {
+ "description": "The authenticated Mixmax user's profile.",
+ "docs_url": f"{_DOCS}/users",
+ "columns": {
+ "_id": "Unique identifier for the user.",
+ "email": "The user's email address.",
+ },
+ },
+ "user_preferences": {
+ "description": "The authenticated user's Mixmax preferences.",
+ "docs_url": f"{_DOCS}/user-preferences",
+ "columns": {"_id": "Unique identifier for the preferences document."},
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/mixmax.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/mixmax.py
new file mode 100644
index 000000000000..399010ed2692
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/mixmax.py
@@ -0,0 +1,181 @@
+"""Mixmax REST transport.
+
+Mixmax is a sales-engagement / email-productivity API served at https://api.mixmax.com/v1 with
+`X-API-Token` header auth. List endpoints are cursor-paginated behind a `{results, next, hasNext,
+previous, hasPrevious}` wrapper; `/…/me` endpoints return a single caller-scoped object with no
+wrapper. Collections are returned newest-first (by creation time).
+
+Incremental note: the API exposes no server-side timestamp filter (no `updated_after`/`since`), so
+every endpoint is full-refresh only. A "client-side cursor walk" would still fetch every page each
+run, so it buys nothing over full refresh and we don't advertise incremental for any table. We do
+persist the pagination cursor between Temporal heartbeats (via `ResumableSourceManager`) so a sync
+interrupted mid-pagination resumes from the last page rather than restarting the whole endpoint.
+
+Rate limits: 120 requests / 60s per user+IP, `429` with `Retry-After`. The tracked session's default
+`urllib3` retry already honors `Retry-After` and backs off on 429/5xx; the tenacity wrapper below adds
+resilience for transient network failures and a few extra 429/5xx attempts.
+"""
+
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.settings import (
+ MIXMAX_ENDPOINTS,
+ MixmaxEndpointConfig,
+)
+
+MIXMAX_BASE_URL = "https://api.mixmax.com/v1"
+# Docs default the page size to 50 and cap it around 300; 100 keeps request volume low against the
+# 120 req/min ceiling without risking a rejected oversized page.
+PAGE_SIZE = 100
+
+
+class MixmaxRetryableError(Exception):
+ pass
+
+
+class MixmaxResumeConfig:
+ # Fully-built URL of the next page to fetch. None means "start at the endpoint's first page".
+ next_url: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "X-API-Token": api_key,
+ "Accept": "application/json",
+ }
+
+
+def _build_url(path: str, single_object: bool, next_cursor: str | None = None) -> str:
+ """Build a Mixmax list URL. `/…/me` single-object endpoints take no pagination params."""
+ if single_object:
+ return f"{MIXMAX_BASE_URL}{path}"
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if next_cursor:
+ # `next`/`previous` are documented as URL-safe strings, but urlencode keeps us correct
+ # regardless of what the server hands back.
+ params["next"] = next_cursor
+ return f"{MIXMAX_BASE_URL}{path}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Probe the cheapest always-available endpoint (`/users/me`) to confirm the token is genuine."""
+ try:
+ # redact_values masks the token in logged URLs and captured HTTP samples — the sampler's
+ # name-based header denylist doesn't recognise `X-API-Token`.
+ with make_tracked_session(redact_values=(api_key,)) as session:
+ response = session.get(f"{MIXMAX_BASE_URL}/users/me", headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ MixmaxRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MixmaxRetryableError(f"Mixmax API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Mixmax API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _extract_page(data: Any) -> tuple[list[dict], str | None]:
+ """Return (rows, next_cursor) for a single response.
+
+ List endpoints wrap rows in `{results: [...], next, hasNext}`. `/…/me` endpoints return the
+ object directly (or, defensively, a bare list). Only the wrapped shape paginates.
+ """
+ if isinstance(data, dict) and "results" in data:
+ rows = data.get("results") or []
+ next_cursor = data.get("next") if data.get("hasNext") else None
+ return rows, next_cursor
+ if isinstance(data, list):
+ return data, None
+ # Single-object endpoint (e.g. /users/me): treat the whole body as one record.
+ return [data], None
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MixmaxResumeConfig],
+) -> Iterator[list[dict]]:
+ config = MIXMAX_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_url:
+ url = resume.next_url
+ logger.debug(f"Mixmax: resuming {endpoint} from URL: {url}")
+ else:
+ url = _build_url(config.path, config.single_object)
+
+ # redact_values masks the token in logged URLs and captured HTTP samples; the `with` block
+ # closes the session's pooled connections once the generator is exhausted.
+ with make_tracked_session(redact_values=(api_key,)) as session:
+ while True:
+ data = _fetch_page(session, url, headers, logger)
+ rows, next_cursor = _extract_page(data)
+
+ if rows:
+ yield rows
+
+ if not next_cursor:
+ break
+
+ next_url = _build_url(config.path, config.single_object, next_cursor)
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge
+ # dedupes the re-pulled rows on the primary key.
+ resumable_source_manager.save_state(MixmaxResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def mixmax_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MixmaxResumeConfig],
+) -> SourceResponse:
+ endpoint_config: MixmaxEndpointConfig = MIXMAX_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Collections arrive newest-first; declaring it honestly keeps full-refresh page ordering
+ # transparent (no incremental watermark is derived for these tables).
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/posthog_com_doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/posthog_com_doc.md
new file mode 100644
index 000000000000..e36ddfd98ebc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/posthog_com_doc.md
@@ -0,0 +1,64 @@
+---
+title: Linking Mixmax as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: MixMax
+beta: true
+---
+
+import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"
+import SyncModes from "../\_snippets/sync-modes.mdx"
+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"
+import AlphaRelease from "../\_snippets/alpha-release.mdx"
+
+<AlphaRelease />
+
+[Mixmax](https://www.mixmax.com) is a sales-engagement and email-productivity platform for Gmail (sequences, meeting scheduling, snippets, and live email tracking). This connector syncs your Mixmax sequences, messages, snippets, rules, live feed, and related resources into the PostHog Data warehouse so you can join outreach activity with your product and revenue data.
+
+## Prerequisites
+
+Before connecting Mixmax, make sure you have:
+
+- A Mixmax **Growth+ or Enterprise** plan — the API is not available on Free, and API access must be enabled on your workspace.
+- An **API token**, created per user under **Settings ▸ Integrations ▸ API** in Mixmax. The token is scoped to the user that creates it, so it can only sync data that user can access.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+You'll need:
+
+- **API token** — from **Settings ▸ Integrations ▸ API** in your Mixmax account. The token is shown only once at creation, so copy it before leaving the page.
+
+PostHog authenticates every request with this token (sent as the `X-API-Token` header).
+
+## Sync modes
+
+<SyncModes />
+
+Mixmax's API does not expose a server-side "modified since" filter, so every table is synced as **full refresh** — each sync re-reads the resource and replaces the table. Because of Mixmax's fixed rate limit (120 requests per minute), prefer a modest sync frequency, especially for high-volume tables like the live feed.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **"Invalid Mixmax API token"** — the token is wrong, was revoked, or was never enabled. Create a new token under **Settings ▸ Integrations ▸ API** and reconnect.
+- **API access not enabled** — the Mixmax API requires a Growth+ or Enterprise plan with the API feature enabled on your workspace. Confirm your plan and workspace settings, then reconnect.
+- **Slow or throttled syncs** — Mixmax caps API usage at 120 requests per minute per user and IP address and is optimized for lightweight, real-time use rather than bulk export. Large tables can take a while to sync; lower your sync frequency if you hit rate limits.
+
+<TroubleshootingLink />
+
+<!--
+STAGING NOTE (delete when relocating): this file is the user-facing posthog.com doc for the Mixmax
+source. It is staged in this repo because no posthog.com checkout was available during implementation.
+Before shipping, move it to the posthog.com repo at contents/docs/cdp/sources/mixmax.md (served at
+/docs/cdp/sources/mixmax and /docs/data-warehouse/sources/mixmax), then run from the posthog repo:
+python manage.py audit_source_docs --docs-dir ../posthog.com/contents/docs/cdp/sources
+-->
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/settings.py
new file mode 100644
index 000000000000..e076c6c4b50c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/settings.py
@@ -0,0 +1,103 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class MixmaxEndpointConfig:
+ name: str
+ path: str
+ # Primary key columns for dedup. Mixmax objects are MongoDB documents keyed by `_id`;
+ # a few resources expose a different unique field (e.g. live feed rows use `uid`).
+ primary_keys: list[str] = field(default_factory=lambda: ["_id"])
+ # `/…/me` endpoints return a single object (or a small caller-scoped payload) with no
+ # `results`/`next` cursor wrapper. The transport treats an un-wrapped body as one record,
+ # so this flag only documents intent and skips the `limit` query param.
+ single_object: bool = False
+ # Whether the table is selected for sync by default in the UI.
+ should_sync_default: bool = True
+ description: str | None = None
+
+
+# Mixmax exposes no server-side timestamp filter (`updated_after`/`since`), so every endpoint is
+# full-refresh only — see the module docstring in `mixmax.py`. Collections use cursor pagination
+# (`results` + `next` + `hasNext`); the `/…/me` endpoints return a single caller-scoped object.
+MIXMAX_ENDPOINTS: dict[str, MixmaxEndpointConfig] = {
+ "sequences": MixmaxEndpointConfig(
+ name="sequences",
+ path="/sequences",
+ description="Automated multi-step outreach sequences you have access to.",
+ ),
+ "sequence_folders": MixmaxEndpointConfig(
+ name="sequence_folders",
+ path="/sequencefolders",
+ description="Folders used to organize sequences.",
+ ),
+ "messages": MixmaxEndpointConfig(
+ name="messages",
+ path="/messages",
+ description="Tracked email messages sent through Mixmax.",
+ ),
+ "rules": MixmaxEndpointConfig(
+ name="rules",
+ path="/rules",
+ description="Automation rules that trigger Mixmax actions.",
+ ),
+ "code_snippets": MixmaxEndpointConfig(
+ name="code_snippets",
+ path="/codesnippets",
+ description="Reusable code snippets injected into emails.",
+ ),
+ "snippet_tags": MixmaxEndpointConfig(
+ name="snippet_tags",
+ path="/snippettags",
+ description="Tags used to categorize snippets.",
+ ),
+ "meeting_types": MixmaxEndpointConfig(
+ name="meeting_types",
+ path="/meetingtypes",
+ description="Configured meeting/appointment types.",
+ ),
+ "insights_reports": MixmaxEndpointConfig(
+ name="insights_reports",
+ path="/insightsreports",
+ description="Saved insights reports.",
+ ),
+ "polls": MixmaxEndpointConfig(
+ name="polls",
+ path="/polls",
+ description="Polls embedded in Mixmax emails.",
+ ),
+ "file_requests": MixmaxEndpointConfig(
+ name="file_requests",
+ path="/filerequests",
+ description="File requests sent through Mixmax.",
+ ),
+ "live_feed": MixmaxEndpointConfig(
+ name="live_feed",
+ path="/livefeed",
+ primary_keys=["uid"],
+ description="Real-time email tracking events (opens, clicks, downloads). Full refresh only.",
+ ),
+ "appointment_links": MixmaxEndpointConfig(
+ name="appointment_links",
+ path="/appointmentlinks/me",
+ # `/…/me` but the name/description imply a collection of individual links. Without live-API
+ # verification, key on `_id` (unique per document for either shape) rather than `userId`,
+ # which would collapse a per-user collection to a single row. Left as a normal collection so
+ # the paginator handles both a wrapped list and a single object defensively.
+ description="The authenticated user's appointment (scheduling) links.",
+ ),
+ "users": MixmaxEndpointConfig(
+ name="users",
+ path="/users/me",
+ single_object=True,
+ description="The authenticated Mixmax user's profile.",
+ ),
+ "user_preferences": MixmaxEndpointConfig(
+ name="user_preferences",
+ path="/userpreferences/me",
+ single_object=True,
+ description="The authenticated user's Mixmax preferences.",
+ ),
+}
+
+ENDPOINTS = tuple(MIXMAX_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/source.py
index 20b4544dce2b..ae77af410cf2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/source.py
@@ -1,19 +1,39 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MixMaxSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.mixmax import (
+ MixmaxResumeConfig,
+ mixmax_source,
+ validate_credentials as validate_mixmax_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.settings import ENDPOINTS, MIXMAX_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MixMaxSource(SimpleSource[MixMaxSourceConfig]):
+class MixMaxSource(ResumableSource[MixMaxSourceConfig, MixmaxResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MIXMAX
@@ -23,8 +43,95 @@ class MixMaxSource(SimpleSource[MixMaxSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.MIX_MAX,
category=DataWarehouseSourceCategory.SALES,
- label="MixMax",
- iconPath="/static/services/mixmax.png",
- fields=cast(list[FieldType], []),
+ label="Mixmax",
+ releaseStatus=ReleaseStatus.ALPHA,
+ # Kept hidden while the source lands without live-API credential verification; flip off
+ # (delete this) once it has synced end-to-end against a real Mixmax workspace.
unreleasedSource=True,
+ caption="""Enter your Mixmax API token to sync your Mixmax data into the PostHog Data warehouse.
+
+Create an API token under **Settings ▸ Integrations ▸ API** in Mixmax. The token is scoped to the user that creates it, so it can only sync data that user can access.
+
+API access requires a Growth+ or Enterprise plan with the API feature enabled on your workspace.""",
+ iconPath="/static/services/mixmax.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/mixmax",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
+ # Retrying can never satisfy a credential/permission problem, so stop the sync. Match the
+ # stable status text and base host, not the per-request path.
+ "401 Client Error: Unauthorized for url: https://api.mixmax.com": "Your Mixmax API token is invalid or has been revoked. Create a new token under Settings ▸ Integrations ▸ API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.mixmax.com": "Your Mixmax API token does not have access to this data, or API access is not enabled on your plan. Check your Mixmax plan and workspace API settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: MixMaxSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Mixmax exposes no server-side timestamp filter, so every endpoint is full refresh only.
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = MIXMAX_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+
+ schemas = [_build_schema(endpoint) 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: MixMaxSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_mixmax_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Mixmax API token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MixmaxResumeConfig]:
+ return ResumableSourceManager[MixmaxResumeConfig](inputs, MixmaxResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MixMaxSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MixmaxResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return mixmax_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/tests/test_mixmax.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/tests/test_mixmax.py
new file mode 100644
index 000000000000..9e25b1d722cf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/tests/test_mixmax.py
@@ -0,0 +1,206 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax import mixmax
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.mixmax import (
+ MixmaxResumeConfig,
+ _build_url,
+ _extract_page,
+ get_rows,
+ mixmax_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.settings import MIXMAX_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: MixmaxResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[MixmaxResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> MixmaxResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: MixmaxResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestExtractPage:
+ @parameterized.expand(
+ [
+ # Wrapped collection with more pages: rows plus the next cursor.
+ ("wrapped_has_next", {"results": [{"_id": "1"}], "next": "cur2", "hasNext": True}, [{"_id": "1"}], "cur2"),
+ # Wrapped collection on its last page: hasNext False means stop, even if `next` echoes a value.
+ ("wrapped_last_page", {"results": [{"_id": "1"}], "next": "cur2", "hasNext": False}, [{"_id": "1"}], None),
+ # `hasNext` missing is treated as no more pages.
+ ("wrapped_no_flag", {"results": [{"_id": "1"}]}, [{"_id": "1"}], None),
+ ("wrapped_empty", {"results": [], "hasNext": False}, [], None),
+ # `/…/me` single-object endpoints return the object directly — one record, no pagination.
+ ("single_object", {"_id": "u1", "email": "[email protected]"}, [{"_id": "u1", "email": "[email protected]"}], None),
+ # A bare array (defensive) is treated as a full, unpaginated page.
+ ("bare_list", [{"_id": "1"}, {"_id": "2"}], [{"_id": "1"}, {"_id": "2"}], None),
+ ]
+ )
+ def test_extract_page(self, _name: str, data: Any, expected_rows: list[dict], expected_cursor: str | None) -> None:
+ assert _extract_page(data) == (expected_rows, expected_cursor)
+
+
+class TestBuildUrl:
+ def test_collection_url_has_page_limit(self) -> None:
+ url = _build_url("/sequences", single_object=False)
+ assert url == "https://api.mixmax.com/v1/sequences?limit=100"
+
+ def test_collection_url_carries_next_cursor(self) -> None:
+ url = _build_url("/sequences", single_object=False, next_cursor="abc123")
+ assert url == "https://api.mixmax.com/v1/sequences?limit=100&next=abc123"
+
+ def test_single_object_url_has_no_pagination_params(self) -> None:
+ # `/users/me` must not receive limit/next — it isn't a paginated collection.
+ url = _build_url("/users/me", single_object=True)
+ assert url == "https://api.mixmax.com/v1/users/me"
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str) -> list[dict]:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:
+ return pages[url]
+
+ monkeypatch.setattr(mixmax, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_walks_cursor_pages_and_saves_state_after_each_yield(self, monkeypatch: Any) -> None:
+ next_url = "https://api.mixmax.com/v1/sequences?limit=100&next=cur2"
+ pages = {
+ "https://api.mixmax.com/v1/sequences?limit=100": {
+ "results": [{"_id": "1"}],
+ "next": "cur2",
+ "hasNext": True,
+ },
+ next_url: {"results": [{"_id": "2"}], "hasNext": False},
+ }
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, pages, "sequences")
+
+ assert rows == [{"_id": "1"}, {"_id": "2"}]
+ # State is saved only when another page follows, pointing at the next page URL — so a crash
+ # re-yields the last page rather than skipping it.
+ assert manager.saved == [MixmaxResumeConfig(next_url=next_url)]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ resume_url = "https://api.mixmax.com/v1/sequences?limit=100&next=cur2"
+ pages = {resume_url: {"results": [{"_id": "2"}], "hasNext": False}}
+ manager = _FakeResumableManager(MixmaxResumeConfig(next_url=resume_url))
+ rows = self._collect(manager, monkeypatch, pages, "sequences")
+
+ # The first page is skipped entirely — only the saved cursor's page is fetched.
+ assert rows == [{"_id": "2"}]
+ assert manager.saved == []
+
+ def test_single_object_endpoint_yields_once_without_saving_state(self, monkeypatch: Any) -> None:
+ pages = {"https://api.mixmax.com/v1/users/me": {"_id": "u1", "email": "[email protected]"}}
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, pages, "users")
+
+ assert rows == [{"_id": "u1", "email": "[email protected]"}]
+ assert manager.saved == []
+
+
+class TestFetchPageRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_status_is_retried_then_succeeds(self, _name: str, status: int) -> None:
+ bad = MagicMock()
+ bad.status_code = status
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"results": [], "hasNext": False}
+
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(mixmax._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = mixmax._fetch_page(session, "https://api.mixmax.com/v1/sequences", {}, MagicMock())
+
+ assert result == {"results": [], "hasNext": False}
+ assert session.get.call_count == 2
+
+ @parameterized.expand(
+ [
+ ("read_timeout", requests.ReadTimeout("Read timed out.")),
+ ("connection_error", requests.ConnectionError("Connection reset by peer")),
+ ]
+ )
+ def test_transient_network_errors_are_retried(self, _name: str, transient: Exception) -> None:
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"results": [], "hasNext": False}
+
+ session = MagicMock()
+ session.get.side_effect = [transient, good]
+
+ with patch.object(mixmax._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = mixmax._fetch_page(session, "https://api.mixmax.com/v1/sequences", {}, MagicMock())
+
+ assert result == {"results": [], "hasNext": False}
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_immediately(self) -> None:
+ # A 401 is not retryable — it must surface as an HTTPError so the sync fails fast.
+ error_response = requests.Response()
+ error_response.status_code = 401
+ bad = MagicMock()
+ bad.status_code = 401
+ bad.ok = False
+ bad.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=error_response)
+
+ session = MagicMock()
+ session.get.return_value = bad
+
+ with pytest.raises(requests.HTTPError):
+ mixmax._fetch_page(session, "https://api.mixmax.com/v1/sequences", {}, MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestMixmaxSource:
+ @parameterized.expand(
+ [
+ ("sequences", ["_id"]),
+ ("messages", ["_id"]),
+ ("live_feed", ["uid"]),
+ ("appointment_links", ["_id"]),
+ ]
+ )
+ def test_source_response_carries_endpoint_primary_keys(self, endpoint: str, expected_pks: list[str]) -> None:
+ response = mixmax_source(
+ api_key="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pks
+ # Collections arrive newest-first; declared honestly so full-refresh ordering isn't misread.
+ assert response.sort_mode == "desc"
+
+ def test_every_endpoint_declares_a_unique_primary_key(self) -> None:
+ # A non-unique/empty primary key seeds duplicate rows and makes every merge multi-match (OOM risk).
+ for config in MIXMAX_ENDPOINTS.values():
+ assert config.primary_keys, f"{config.name} has no primary key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/tests/test_mixmax_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/tests/test_mixmax_source.py
new file mode 100644
index 000000000000..89d55634bc85
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mixmax/tests/test_mixmax_source.py
@@ -0,0 +1,126 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MixMaxSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.mixmax import MixmaxResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.source import MixMaxSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> MixMaxSourceConfig:
+ return MixMaxSourceConfig(api_key="tok")
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert MixMaxSource().source_type == ExternalDataSourceType.MIXMAX
+
+ def test_config_advertises_a_single_password_api_token_field(self) -> None:
+ config = MixMaxSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.SALES
+ assert len(config.fields) == 1
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+
+ def test_source_is_alpha_and_still_hidden(self) -> None:
+ # Ships as alpha and stays hidden (unreleasedSource) until verified against a live workspace.
+ config = MixMaxSource().get_source_config
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+
+ def test_docs_url_matches_published_doc_slug(self) -> None:
+ assert MixMaxSource().get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/mixmax"
+
+
+class TestGetSchemas:
+ def test_all_schemas_are_full_refresh_only(self) -> None:
+ # Mixmax exposes no server-side timestamp filter, so nothing may advertise incremental/append.
+ schemas = MixMaxSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_names_filter_restricts_returned_schemas(self) -> None:
+ schemas = MixMaxSource().get_schemas(_config(), team_id=1, names=["sequences", "live_feed"])
+ assert {s.name for s in schemas} == {"sequences", "live_feed"}
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ # `lists_tables_without_credentials` lets the posthog.com Supported tables section render
+ # without connecting — the catalog must come back non-empty and carry curated descriptions.
+ tables = MixMaxSource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ sequences = next(t for t in tables if t["name"] == "sequences")
+ assert sequences["sync_methods"] == ["Full refresh"]
+ assert sequences["description"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Mixmax API token"))])
+ def test_validate_credentials(self, _name: str, probe_result: bool, expected: tuple[bool, str | None]) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.source.validate_mixmax_credentials",
+ return_value=probe_result,
+ ):
+ assert MixMaxSource().validate_credentials(_config(), team_id=1) == expected
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.mixmax.com/v1/sequences?limit=100"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.mixmax.com/v1/messages?limit=100"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ errors = MixMaxSource().get_non_retryable_errors()
+ assert any(key in observed for key in errors)
+
+ @parameterized.expand(
+ [
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.mixmax.com/v1/sequences"),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.mixmax.com/v1/sequences"),
+ ("read_timeout", "HTTPSConnectionPool(host='api.mixmax.com', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:
+ errors = MixMaxSource().get_non_retryable_errors()
+ assert not any(key in observed for key in errors)
+
+
+class TestResumableWiring:
+ def test_resumable_manager_is_bound_to_mixmax_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = MixMaxSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MixmaxResumeConfig
+
+ def test_source_for_pipeline_plumbs_selected_endpoint(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "messages"
+ inputs.logger = MagicMock()
+ manager = MagicMock()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mixmax.source.mixmax_source"
+ ) as mock_source:
+ MixMaxSource().source_for_pipeline(_config(), manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["api_key"] == "tok"
+ assert kwargs["endpoint"] == "messages"
+ assert kwargs["resumable_source_manager"] is manager