:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement mux import source (#65646)
Tom Owers8a8951924101
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 42772178b309..90ddecdc9977 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -138,6 +138,7 @@ the row lists both.| monday | HTTP (GraphQL) | requests | ✅ || mongodb | DB protocol | pymongo | ➖ || mssql | DB protocol | pyodbc / pymssql | ➖ |+| mux | HTTP | requests | ✅ || mysql | DB protocol | pymysql | ➖ || okta | HTTP | requests | ✅ || notion | HTTP | requests | ✅ |@@ -493,7 +494,6 @@ doesn't conflict with concurrent PRs.- missive- mixmax- mode-- mux- my_hours- n8n- nasadiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 2562ce5a77fa..0ee54fc00e74 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1947,7 +1947,8 @@ class MongoDBSourceConfig(config.Config):@config.configclass MuxSourceConfig(config.Config):- pass+ access_token_id: str+ secret_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/mux/canonical_descriptions.py b/posthog/temporal/data_imports/sources/mux/canonical_descriptions.pynew file mode 100644index 000000000000..0d053e243e5b--- /dev/null+++ b/posthog/temporal/data_imports/sources/mux/canonical_descriptions.py@@ -0,0 +1,87 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Descriptions sourced from the Mux API reference (https://www.mux.com/docs/api-reference).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "assets": {+ "description": "A Mux Video Asset: an encoded piece of video or audio ready for streaming.",+ "docs_url": "https://www.mux.com/docs/api-reference/video/assets/list-assets",+ "columns": {+ "id": "Unique identifier for the Asset.",+ "created_at": "Time the Asset was created, as a Unix timestamp (seconds since epoch).",+ "status": "Status of the Asset: preparing, ready, or errored.",+ "duration": "Duration of the Asset in seconds (max duration for a single Asset is 12 hours).",+ "max_stored_resolution": "Maximum resolution that has been stored for the Asset.",+ "max_stored_frame_rate": "Maximum frame rate (in frames per second) that has been stored for the Asset.",+ "aspect_ratio": "Aspect ratio of the Asset, as a string like '16:9'.",+ "playback_ids": "Array of Playback ID objects used to create playback URLs for the Asset.",+ "tracks": "The individual media tracks (video, audio, text) that make up the Asset.",+ "mp4_support": "Level of support for MP4 playback of the Asset.",+ "master_access": "Level of access to the master (highest-quality) version of the Asset.",+ "passthrough": "Arbitrary user-supplied metadata set when creating the Asset.",+ "live_stream_id": "Unique identifier of the live stream that created this Asset, if any.",+ "test": "True if this is a test Asset (created with a free Mux account).",+ },+ },+ "live_streams": {+ "description": "A Mux Video Live Stream: a configured RTMP/SRT ingest endpoint that produces Assets.",+ "docs_url": "https://www.mux.com/docs/api-reference/video/live-streams/list-live-streams",+ "columns": {+ "id": "Unique identifier for the Live Stream.",+ "created_at": "Time the Live Stream was created, as a Unix timestamp (seconds since epoch).",+ "status": "Status of the Live Stream: idle, active, or disabled.",+ "playback_ids": "Array of Playback ID objects used to create playback URLs for the Live Stream.",+ "new_asset_settings": "Settings applied to Assets created from this Live Stream.",+ "passthrough": "Arbitrary user-supplied metadata set when creating the Live Stream.",+ "reconnect_window": "Seconds Mux waits for a disconnected stream to reconnect before finishing.",+ "max_continuous_duration": "Maximum duration in seconds a single broadcast can run.",+ "latency_mode": "Latency mode of the Live Stream: low, reduced, or standard.",+ "active_asset_id": "Unique identifier of the Asset currently being recorded, if active.",+ "recent_asset_ids": "Asset IDs created from recent broadcasts of this Live Stream.",+ "test": "True if this is a test Live Stream.",+ },+ },+ "uploads": {+ "description": "A Mux Video Direct Upload: an authenticated URL for pushing source media directly to Mux.",+ "docs_url": "https://www.mux.com/docs/api-reference/video/direct-uploads/list-direct-uploads",+ "columns": {+ "id": "Unique identifier for the Direct Upload.",+ "status": "Status of the upload: waiting, asset_created, errored, cancelled, or timed_out.",+ "asset_id": "Unique identifier of the Asset created from this upload, once available.",+ "new_asset_settings": "Settings applied to the Asset created from this upload.",+ "cors_origin": "Origin allowed to use the upload URL from a browser.",+ "timeout": "Seconds the upload URL is valid for before it times out.",+ "error": "Object describing the error, if the upload failed.",+ "test": "True if this is a test Direct Upload.",+ },+ },+ "playback_restrictions": {+ "description": "A Mux Video Playback Restriction: rules controlling where and how videos can be played.",+ "docs_url": "https://www.mux.com/docs/api-reference/video/playback-restrictions/list-playback-restrictions",+ "columns": {+ "id": "Unique identifier for the Playback Restriction.",+ "created_at": "Time the Playback Restriction was created, as a Unix timestamp (seconds since epoch).",+ "updated_at": "Time the Playback Restriction was last updated, as a Unix timestamp (seconds since epoch).",+ "referrer": "Rules for which HTTP referrer domains are allowed to play videos.",+ "user_agent": "Rules for which user agents are allowed to play videos.",+ },+ },+ "transcription_vocabularies": {+ "description": "A Mux Video Transcription Vocabulary: a collection of phrases that improve transcription accuracy.",+ "docs_url": "https://www.mux.com/docs/api-reference/video/transcription-vocabularies/list-transcription-vocabularies",+ "columns": {+ "id": "Unique identifier for the Transcription Vocabulary.",+ "name": "Human-readable name for the Transcription Vocabulary.",+ "phrases": "Phrases, names, and other words to boost when transcribing audio.",+ "created_at": "Time the Transcription Vocabulary was created, as a Unix timestamp (seconds since epoch).",+ "updated_at": "Time the Transcription Vocabulary was last updated, as a Unix timestamp (seconds since epoch).",+ },+ },+ "signing_keys": {+ "description": "A Mux signing key: an RSA key pair used to sign JWTs for secured playback URLs.",+ "docs_url": "https://www.mux.com/docs/api-reference/system/signing-keys/list-signing-keys",+ "columns": {+ "id": "Unique identifier for the Signing Key (used as the JWT key ID).",+ "created_at": "Time the Signing Key was created, as a Unix timestamp (seconds since epoch).",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/mux/mux.py b/posthog/temporal/data_imports/sources/mux/mux.pynew file mode 100644index 000000000000..58424452f33e--- /dev/null+++ b/posthog/temporal/data_imports/sources/mux/mux.py@@ -0,0 +1,193 @@+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 posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+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.mux.settings import MUX_ENDPOINTS, MuxEndpointConfig++MUX_BASE_URL = "https://api.mux.com"+# Endpoint used to confirm a token is genuine when no specific schema is being validated.+DEFAULT_VALIDATION_PATH = "/video/v1/assets"+++class MuxRetryableError(Exception):+ pass+++class MuxResumeConfig:+ # Next offset page to fetch (offset/limit pagination). None for cursor-paginated endpoints.+ page: int | None = None+ # Next `next_cursor` value to fetch (cursor pagination, List Assets only).+ cursor: str | None = None+++def _make_session(access_token_id: str, secret_key: str) -> requests.Session:+ # Mux authenticates with HTTP Basic auth (Access Token ID as username, Secret as password).+ # Redact the secret wherever it might surface in tracked logs/samples.+ session = make_tracked_session(redact_values=(secret_key,))+ session.auth = (access_token_id, secret_key)+ return session+++@retry(+ retry=retry_if_exception_type((MuxRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:+ response = session.get(url, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise MuxRetryableError(f"Mux API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Mux API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_validation_status(access_token_id: str, secret_key: str, path: str) -> int | None:+ """Probe a list endpoint and return the HTTP status code, or None on a transport error."""+ url = f"{MUX_BASE_URL}{path}?{urlencode({'limit': 1})}"+ try:+ session = _make_session(access_token_id, secret_key)+ return session.get(url, timeout=10).status_code+ except Exception:+ return None+++def _strip_sensitive_fields(item: dict[str, Any], config: MuxEndpointConfig) -> dict[str, Any]:+ """Drop credential-bearing fields before the row is batched into the warehouse.++ Mux list responses embed live-stream ingest keys (`stream_key`) and direct-upload PUT URLs+ (`url`). Persisting them would expose a valid broadcast/upload credential to anyone who can+ query the imported table, crossing from analytics-read to write access in the customer's Mux+ account, so we remove them rather than import them. Live-stream simulcast targets carry their+ own per-destination `stream_key`, so those are stripped too.+ """+ if not config.sensitive_fields:+ return item+ cleaned = {k: v for k, v in item.items() if k not in config.sensitive_fields}+ targets = cleaned.get("simulcast_targets")+ if isinstance(targets, list):+ cleaned["simulcast_targets"] = [+ {k: v for k, v in target.items() if k != "stream_key"} if isinstance(target, dict) else target+ for target in targets+ ]+ return cleaned+++def _normalize_row(item: dict[str, Any], config: MuxEndpointConfig) -> dict[str, Any]:+ """Coerce the partition timestamp to an int so datetime partitioning can parse it.++ Mux returns `created_at` as a string-encoded Unix timestamp in seconds (e.g. "1609869152").+ The pipeline's datetime partitioner parses ints via `fromtimestamp` but would misparse the raw+ string, so convert it where it's the partition key.+ """+ if config.partition_key == "created_at":+ created_at = item.get("created_at")+ if isinstance(created_at, str) and created_at.isdigit():+ return {**item, "created_at": int(created_at)}+ return item+++def get_rows(+ access_token_id: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MuxResumeConfig],+) -> Iterator[Any]:+ config = MUX_ENDPOINTS[endpoint]+ session = _make_session(access_token_id, secret_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume and resume.page else 1+ cursor = resume.cursor if resume else None+ if resume is not None:+ logger.debug(f"Mux: resuming {endpoint} from page={page}, cursor={cursor}")++ while True:+ params: dict[str, Any] = {"limit": config.page_size}+ if config.use_cursor:+ if cursor:+ params["cursor"] = cursor+ else:+ params["page"] = page++ url = f"{MUX_BASE_URL}{config.path}?{urlencode(params)}"+ data = _fetch_page(session, url, logger)++ items = data.get("data") or []+ next_cursor = data.get("next_cursor") if config.use_cursor else None++ # A full offset page implies there may be another; a present `next_cursor` means more remain.+ if config.use_cursor:+ has_next = bool(next_cursor)+ next_state = MuxResumeConfig(cursor=next_cursor)+ else:+ has_next = len(items) >= config.page_size+ next_state = MuxResumeConfig(page=page + 1)++ for item in items:+ batcher.batch(_normalize_row(_strip_sensitive_fields(item, config), config))++ if batcher.should_yield():+ yield batcher.get_table()++ if not has_next or not items:+ break++ # Save state on the page boundary, once the whole page is batched/yielded, pointing at the+ # next page. The batcher can yield mid-page (its row threshold need not align with page_size),+ # so advancing the bookmark only at page boundaries means a crash re-fetches at most the+ # current page — merge dedupes the re-yielded rows — instead of skipping rows that were+ # batched but not yet yielded when a mid-page batch fired.+ resumable_source_manager.save_state(next_state)++ if config.use_cursor:+ cursor = next_cursor+ else:+ page += 1++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def mux_source(+ access_token_id: str,+ secret_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MuxResumeConfig],+) -> SourceResponse:+ config = MUX_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token_id=access_token_id,+ secret_key=secret_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/mux/settings.py b/posthog/temporal/data_imports/sources/mux/settings.pynew file mode 100644index 000000000000..289a0f4e007b--- /dev/null+++ b/posthog/temporal/data_imports/sources/mux/settings.py@@ -0,0 +1,68 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField+++@dataclass+class MuxEndpointConfig:+ name: str+ path: str+ # `created_at` is a stable Unix timestamp on most Mux objects, so it's a safe datetime partition key.+ # Endpoints whose objects have no `created_at` (e.g. uploads) leave this None and aren't partitioned.+ partition_key: Optional[str] = "created_at"+ # Mux caps list `limit` at 100 on most endpoints; transcription vocabularies cap it at 10.+ page_size: int = 100+ # Cursor pagination (`next_cursor`) is only available on List Assets today; every other+ # list endpoint is offset-based (`page` + `limit`).+ use_cursor: bool = False+ should_sync_default: bool = True+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Credential-bearing fields Mux returns in list responses but that must never reach the warehouse:+ # importing them would let anyone who can query the table broadcast or upload media into the+ # connected Mux environment (an analytics-read → Mux-write escalation). Stripped before batching.+ sensitive_fields: tuple[str, ...] = ()+++MUX_ENDPOINTS: dict[str, MuxEndpointConfig] = {+ "assets": MuxEndpointConfig(+ name="assets",+ path="/video/v1/assets",+ use_cursor=True,+ ),+ "live_streams": MuxEndpointConfig(+ name="live_streams",+ path="/video/v1/live-streams",+ # `stream_key` is the secret RTMP ingest key for broadcasting to the stream.+ sensitive_fields=("stream_key",),+ ),+ "uploads": MuxEndpointConfig(+ name="uploads",+ path="/video/v1/uploads",+ # The Direct Upload object has no `created_at`, so it can't be datetime-partitioned.+ partition_key=None,+ # `url` is the authenticated PUT URL for pushing media into the upload.+ sensitive_fields=("url",),+ ),+ "playback_restrictions": MuxEndpointConfig(+ name="playback_restrictions",+ path="/video/v1/playback-restrictions",+ ),+ "transcription_vocabularies": MuxEndpointConfig(+ name="transcription_vocabularies",+ path="/video/v1/transcription-vocabularies",+ page_size=10,+ ),+ "signing_keys": MuxEndpointConfig(+ name="signing_keys",+ path="/system/v1/signing-keys",+ ),+}++ENDPOINTS = tuple(MUX_ENDPOINTS.keys())++# Mux's list endpoints expose no server-side created/updated timestamp filter, so every stream is+# full refresh only — there are no advertised incremental fields. See the skill's incremental-sync+# guidance: a client-side `created_at` cursor would still page the whole collection, so it isn't+# genuine incremental sync.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/posthog/temporal/data_imports/sources/mux/source.py b/posthog/temporal/data_imports/sources/mux/source.pyindex 3efa4debc6fa..3b1002e11358 100644--- a/posthog/temporal/data_imports/sources/mux/source.py+++ b/posthog/temporal/data_imports/sources/mux/source.py@@ -1,20 +1,34 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import MuxSourceConfig+from posthog.temporal.data_imports.sources.mux.mux import (+ DEFAULT_VALIDATION_PATH,+ MuxResumeConfig,+ get_validation_status,+ mux_source,+)+from posthog.temporal.data_imports.sources.mux.settings import ENDPOINTS, INCREMENTAL_FIELDS, MUX_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class MuxSource(SimpleSource[MuxSourceConfig]):+class MuxSource(ResumableSource[MuxSourceConfig, MuxResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MUX@@ -23,9 +37,115 @@ class MuxSource(SimpleSource[MuxSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.MUX,- category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,+ category=DataWarehouseSourceCategory.ANALYTICS,label="Mux",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Mux Access Token ID and Secret Key to pull your Mux Video data into the PostHog Data warehouse.++Create an access token under [Settings → Access Tokens](https://dashboard.mux.com/settings/access-tokens) in your Mux dashboard. Tokens are scoped to a single Mux environment.++Grant the following read permissions:+- **Mux Video** (read) — required for assets, live streams, uploads, playback restrictions and transcription vocabularies+- **Mux System** (read) — required for signing keys+""",iconPath="/static/services/mux.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/mux",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token_id",+ label="Access Token ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="secret_key",+ label="Secret Key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.mux.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad/revoked token surfaces as a 401 when `_fetch_page` calls `raise_for_status()`;+ # a token missing the required read scope surfaces as a 403 at sync time. Neither can be+ # fixed by retrying. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.mux.com": "Your Mux access token is invalid or has been revoked. Create a new access token in your Mux dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.mux.com": "Your Mux access token is missing the read permissions needed to sync this data. Grant Mux Video and Mux System read access, then reconnect.",+ }++ def get_schemas(+ self,+ config: MuxSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Mux exposes no server-side timestamp filter on its list endpoints, so every stream is+ # full refresh only — no incremental/append support.+ def _build_schema(endpoint: str) -> SourceSchema:+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=MUX_ENDPOINTS[endpoint].should_sync_default,+ )++ 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: MuxSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ path = MUX_ENDPOINTS[schema_name].path if schema_name in MUX_ENDPOINTS else DEFAULT_VALIDATION_PATH+ status = get_validation_status(config.access_token_id, config.secret_key, path)++ if status == 200:+ return True, None++ # 401 means the token itself is bad. A 403 means the token is genuine but lacks the scope for+ # this endpoint — accept it at source-create (schema_name is None) since users may only grant+ # scopes for the streams they want; re-raise it only when validating a specific schema.+ if status == 403 and schema_name is None:+ return True, None++ if status == 403:+ return False, "Your Mux access token does not have permission to read this data."++ return False, "Invalid Mux access token. Check the Access Token ID and Secret Key."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MuxResumeConfig]:+ return ResumableSourceManager[MuxResumeConfig](inputs, MuxResumeConfig)++ def source_for_pipeline(+ self,+ config: MuxSourceConfig,+ resumable_source_manager: ResumableSourceManager[MuxResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return mux_source(+ access_token_id=config.access_token_id,+ secret_key=config.secret_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/posthog/temporal/data_imports/sources/mux/tests/test_mux.py b/posthog/temporal/data_imports/sources/mux/tests/test_mux.pynew file mode 100644index 000000000000..1f49f9a4e010--- /dev/null+++ b/posthog/temporal/data_imports/sources/mux/tests/test_mux.py@@ -0,0 +1,299 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.mux import mux+from posthog.temporal.data_imports.sources.mux.mux import (+ MuxResumeConfig,+ _normalize_row,+ _strip_sensitive_fields,+ get_rows,+ get_validation_status,+ mux_source,+)+from posthog.temporal.data_imports.sources.mux.settings import MUX_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: MuxResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[MuxResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> MuxResumeConfig | None:+ return self._state++ def save_state(self, data: MuxResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: dict[str, Any]+) -> tuple[list[dict], list[str]]:+ """Drive get_rows against a URL->response map, returning (rows, fetched_urls)."""+ fetched_urls: list[str] = []++ def fake_fetch(session: Any, url: str, logger: Any) -> dict:+ fetched_urls.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(mux, "_fetch_page", fake_fetch)+ monkeypatch.setattr(mux, "_make_session", lambda *a, **k: MagicMock())++ rows: list[dict] = []+ for table in get_rows(+ access_token_id="id",+ secret_key="secret",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ return rows, fetched_urls+++class TestNormalizeRow:+ @parameterized.expand(+ [+ ("digit_string_to_int", "assets", {"id": "a", "created_at": "1609869152"}, 1609869152),+ ("already_int_unchanged", "assets", {"id": "a", "created_at": 1609869152}, 1609869152),+ ("non_digit_string_unchanged", "assets", {"id": "a", "created_at": "not-a-ts"}, "not-a-ts"),+ ]+ )+ def test_created_at_coercion(self, _name: str, endpoint: str, item: dict, expected: Any) -> None:+ result = _normalize_row(item, MUX_ENDPOINTS[endpoint])+ assert result["created_at"] == expected++ def test_endpoint_without_partition_key_is_untouched(self) -> None:+ # Uploads have no created_at partition key, so the row passes through verbatim.+ item = {"id": "u1", "status": "waiting"}+ assert _normalize_row(item, MUX_ENDPOINTS["uploads"]) == item++ def test_missing_created_at_is_untouched(self) -> None:+ item = {"id": "a1"}+ assert _normalize_row(item, MUX_ENDPOINTS["assets"]) == item+++class TestStripSensitiveFields:+ def test_live_stream_stream_key_is_dropped(self) -> None:+ item = {"id": "ls1", "created_at": "1", "stream_key": "super-secret", "status": "idle"}+ cleaned = _strip_sensitive_fields(item, MUX_ENDPOINTS["live_streams"])+ assert "stream_key" not in cleaned+ assert cleaned == {"id": "ls1", "created_at": "1", "status": "idle"}++ def test_live_stream_simulcast_target_stream_keys_are_dropped(self) -> None:+ item = {+ "id": "ls1",+ "simulcast_targets": [+ {"id": "t1", "url": "rtmp://example", "stream_key": "secret", "status": "idle"},+ ],+ }+ cleaned = _strip_sensitive_fields(item, MUX_ENDPOINTS["live_streams"])+ assert cleaned["simulcast_targets"] == [{"id": "t1", "url": "rtmp://example", "status": "idle"}]++ def test_upload_url_is_dropped(self) -> None:+ item = {"id": "u1", "url": "https://storage.googleapis.com/upload?signature=secret", "status": "waiting"}+ cleaned = _strip_sensitive_fields(item, MUX_ENDPOINTS["uploads"])+ assert "url" not in cleaned+ assert cleaned == {"id": "u1", "status": "waiting"}++ def test_endpoint_without_sensitive_fields_is_untouched(self) -> None:+ item = {"id": "a1", "status": "ready"}+ assert _strip_sensitive_fields(item, MUX_ENDPOINTS["assets"]) is item++ def test_get_rows_never_yields_stripped_fields(self, monkeypatch: Any) -> None:+ # End-to-end guard: a secret present in the API response must not survive into batched rows.+ pages = {+ "https://api.mux.com/video/v1/live-streams?limit=100&page=1": {+ "data": [{"id": "ls1", "created_at": "1609869152", "stream_key": "leak"}],+ },+ }+ rows, _ = _collect(_FakeResumableManager(), monkeypatch, "live_streams", pages)+ assert rows == [{"id": "ls1", "created_at": 1609869152}]+ assert all("stream_key" not in row for row in rows)+++class TestGetValidationStatus:+ def test_returns_status_code(self, monkeypatch: Any) -> None:+ for status_code in (200, 401, 403):+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ monkeypatch.setattr(mux, "_make_session", lambda *a, _s=session, **k: _s)+ assert get_validation_status("id", "secret", "/video/v1/assets") == status_code++ def test_transport_error_returns_none(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(mux, "_make_session", lambda *a, **k: session)+ assert get_validation_status("id", "secret", "/video/v1/assets") is None+++class TestOffsetPagination:+ def test_walks_pages_until_short_page(self, monkeypatch: Any) -> None:+ # live_streams uses offset pagination with page_size 100; a page shorter than the limit ends it.+ pages = {+ "https://api.mux.com/video/v1/live-streams?limit=100&page=1": {+ "data": [{"id": str(i), "created_at": "1609869152"} for i in range(100)],+ },+ "https://api.mux.com/video/v1/live-streams?limit=100&page=2": {+ "data": [{"id": "100", "created_at": "1609869152"}],+ },+ }+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, "live_streams", pages)+ assert len(rows) == 101+ assert fetched == [+ "https://api.mux.com/video/v1/live-streams?limit=100&page=1",+ "https://api.mux.com/video/v1/live-streams?limit=100&page=2",+ ]+ # created_at coerced to int for partitioning.+ assert rows[0]["created_at"] == 1609869152++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ pages: dict[str, Any] = {"https://api.mux.com/video/v1/live-streams?limit=100&page=1": {"data": []}}+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, "live_streams", pages)+ assert rows == []+ assert fetched == ["https://api.mux.com/video/v1/live-streams?limit=100&page=1"]++ def test_full_final_page_triggers_one_more_empty_fetch(self, monkeypatch: Any) -> None:+ # An exact-multiple final page can't be distinguished from a full page, so we fetch once more.+ pages = {+ "https://api.mux.com/video/v1/live-streams?limit=100&page=1": {+ "data": [{"id": str(i), "created_at": "1609869152"} for i in range(100)],+ },+ "https://api.mux.com/video/v1/live-streams?limit=100&page=2": {"data": []},+ }+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, "live_streams", pages)+ assert len(rows) == 100+ assert len(fetched) == 2++ def test_resume_from_saved_page(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.mux.com/video/v1/live-streams?limit=100&page=3": {+ "data": [{"id": "x", "created_at": "1609869152"}],+ },+ }+ manager = _FakeResumableManager(MuxResumeConfig(page=3))+ rows, fetched = _collect(manager, monkeypatch, "live_streams", pages)+ assert rows == [{"id": "x", "created_at": 1609869152}]+ assert fetched == ["https://api.mux.com/video/v1/live-streams?limit=100&page=3"]++ def test_saves_next_page_after_yielding_a_batch(self, monkeypatch: Any) -> None:+ # The batcher only emits a table once it crosses its 2000-row threshold; the next-page bookmark+ # is saved right after that emission so a crash re-yields rather than skips the batch.+ manager = _FakeResumableManager()+ pages = {+ "https://api.mux.com/video/v1/live-streams?limit=100&page=1": {+ "data": [{"id": str(i), "created_at": "1609869152"} for i in range(2000)],+ },+ "https://api.mux.com/video/v1/live-streams?limit=100&page=2": {+ "data": [{"id": "last", "created_at": "1609869152"}],+ },+ }+ rows, _ = _collect(manager, monkeypatch, "live_streams", pages)+ assert len(rows) == 2001+ assert MuxResumeConfig(page=2) in manager.saved+++class TestCursorPagination:+ def test_assets_walk_via_next_cursor(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.mux.com/video/v1/assets?limit=100": {+ "data": [{"id": "a1", "created_at": "1609869152"}],+ "next_cursor": "CURSOR2",+ },+ "https://api.mux.com/video/v1/assets?limit=100&cursor=CURSOR2": {+ "data": [{"id": "a2", "created_at": "1609869152"}],+ "next_cursor": None,+ },+ }+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, "assets", pages)+ assert [r["id"] for r in rows] == ["a1", "a2"]+ assert fetched == [+ "https://api.mux.com/video/v1/assets?limit=100",+ "https://api.mux.com/video/v1/assets?limit=100&cursor=CURSOR2",+ ]++ def test_assets_stop_when_next_cursor_null(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.mux.com/video/v1/assets?limit=100": {+ "data": [{"id": "a1", "created_at": "1609869152"}],+ "next_cursor": None,+ },+ }+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, "assets", pages)+ assert [r["id"] for r in rows] == ["a1"]+ assert len(fetched) == 1++ def test_assets_resume_from_saved_cursor(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.mux.com/video/v1/assets?limit=100&cursor=SAVED": {+ "data": [{"id": "a9", "created_at": "1609869152"}],+ "next_cursor": None,+ },+ }+ manager = _FakeResumableManager(MuxResumeConfig(cursor="SAVED"))+ rows, fetched = _collect(manager, monkeypatch, "assets", pages)+ assert [r["id"] for r in rows] == ["a9"]+ assert fetched == ["https://api.mux.com/video/v1/assets?limit=100&cursor=SAVED"]++ def test_assets_save_cursor_after_yielding_a_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ "https://api.mux.com/video/v1/assets?limit=100": {+ "data": [{"id": str(i), "created_at": "1609869152"} for i in range(2000)],+ "next_cursor": "NEXT",+ },+ "https://api.mux.com/video/v1/assets?limit=100&cursor=NEXT": {+ "data": [{"id": "last", "created_at": "1609869152"}],+ "next_cursor": None,+ },+ }+ rows, _ = _collect(manager, monkeypatch, "assets", pages)+ assert len(rows) == 2001+ assert MuxResumeConfig(cursor="NEXT") in manager.saved+++class TestRetryableError:+ # Call the undecorated function so the test isn't slowed by tenacity's retry/backoff. tenacity+ # exposes the original via __wrapped__ (functools.wraps), which the type stub doesn't model.+ _fetch_once = staticmethod(mux._fetch_page.__wrapped__) # type: ignore[attr-defined]++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code, ok=False)+ with pytest.raises(mux.MuxRetryableError):+ self._fetch_once(session, "https://api.mux.com/video/v1/assets", MagicMock())++ def test_client_error_raises_for_status(self) -> None:+ response = MagicMock(status_code=403, ok=False)+ response.raise_for_status.side_effect = requests.HTTPError("403", response=MagicMock())+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(requests.HTTPError):+ self._fetch_once(session, "https://api.mux.com/video/v1/assets", MagicMock())+++class TestMuxSourceResponse:+ def test_partitioned_endpoint_sets_datetime_partitioning(self) -> None:+ response = mux_source("id", "secret", "assets", MagicMock(), MagicMock())+ assert response.name == "assets"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ assert response.partition_format == "month"++ def test_unpartitioned_endpoint_has_no_partitioning(self) -> None:+ response = mux_source("id", "secret", "uploads", MagicMock(), MagicMock())+ assert response.name == "uploads"+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/mux/tests/test_mux_source.py b/posthog/temporal/data_imports/sources/mux/tests/test_mux_source.pynew file mode 100644index 000000000000..d49a748c3882--- /dev/null+++ b/posthog/temporal/data_imports/sources/mux/tests/test_mux_source.py@@ -0,0 +1,151 @@+from typing import Any, Optional++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import MuxSourceConfig+from posthog.temporal.data_imports.sources.mux import source as source_module+from posthog.temporal.data_imports.sources.mux.mux import MuxResumeConfig+from posthog.temporal.data_imports.sources.mux.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.mux.source import MuxSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _config() -> MuxSourceConfig:+ return MuxSourceConfig(access_token_id="my-token-id", secret_key="my-secret")+++class TestMuxSourceConfig:+ def test_source_type(self) -> None:+ assert MuxSource().source_type == ExternalDataSourceType.MUX++ def test_source_config_fields(self) -> None:+ config = MuxSource().get_source_config+ assert config.name.value == "Mux"+ field_names = {f.name for f in config.fields}+ assert field_names == {"access_token_id", "secret_key"}++ def test_secret_key_is_marked_secret(self) -> None:+ fields = {f.name: f for f in MuxSource().get_source_config.fields}+ secret_field, token_field = fields["secret_key"], fields["access_token_id"]+ # Narrow the FieldType union so `.secret` is statically visible.+ assert isinstance(secret_field, SourceFieldInputConfig)+ assert isinstance(token_field, SourceFieldInputConfig)+ assert secret_field.secret is True+ assert token_field.secret is False+++class TestMuxSchemas:+ def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:+ schemas = MuxSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = MuxSource().get_schemas(_config(), team_id=1, names=["assets"])+ assert [s.name for s in schemas] == ["assets"]+++class TestMuxValidateCredentials:+ @parameterized.expand(+ [+ ("ok_no_schema", 200, None, True),+ ("ok_with_schema", 200, "assets", True),+ ("unauthorized_no_schema", 401, None, False),+ ("unauthorized_with_schema", 401, "assets", False),+ # 403 at source-create is accepted (token genuine, scope intentionally narrow)...+ ("forbidden_source_create", 403, None, True),+ # ...but rejected when validating a specific schema the user picked.+ ("forbidden_with_schema", 403, "assets", False),+ ("transport_error", None, None, False),+ ]+ )+ def test_validate_credentials(+ self, _name: str, status: Optional[int], schema_name: Optional[str], expected_ok: bool+ ) -> None:+ # patch (not the monkeypatch fixture) because parameterized.expand can't inject pytest fixtures.+ with patch.object(source_module, "get_validation_status", return_value=status):+ ok, _msg = MuxSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+ assert ok is expected_ok++ def test_validate_credentials_uses_endpoint_path_for_known_schema(self, monkeypatch: Any) -> None:+ captured: dict[str, str] = {}++ def fake_status(access_token_id: str, secret_key: str, path: str) -> int:+ captured["path"] = path+ return 200++ monkeypatch.setattr(source_module, "get_validation_status", fake_status)+ MuxSource().validate_credentials(_config(), team_id=1, schema_name="signing_keys")+ assert captured["path"] == "/system/v1/signing-keys"+++class TestMuxNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.mux.com/video/v1/assets?limit=100"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.mux.com/system/v1/signing-keys?limit=100"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = MuxSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.mux.com/video/v1/assets"),+ ("read_timeout", "HTTPSConnectionPool(host='api.mux.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = MuxSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestMuxResumableWiring:+ def test_get_resumable_source_manager_binds_to_resume_config(self) -> None:+ inputs = MagicMock()+ inputs.logger = MagicMock()+ manager = MuxSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MuxResumeConfig++ def test_source_for_pipeline_plumbs_config_and_schema(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}+ sentinel = MagicMock()++ def fake_mux_source(**kwargs: Any) -> Any:+ captured.update(kwargs)+ return sentinel++ monkeypatch.setattr(source_module, "mux_source", fake_mux_source)++ inputs = MagicMock()+ inputs.schema_name = "assets"+ manager = MagicMock()+ result = MuxSource().source_for_pipeline(_config(), manager, inputs)++ assert result is sentinel+ assert captured["access_token_id"] == "my-token-id"+ assert captured["secret_key"] == "my-secret"+ assert captured["endpoint"] == "assets"+ assert captured["resumable_source_manager"] is manager+++class TestMuxCanonicalDescriptions:+ def test_canonical_descriptions_cover_declared_endpoints(self) -> None:+ descriptions = MuxSource().get_canonical_descriptions()+ # Every endpoint we expose should have a curated description so the warehouse can describe it+ # deterministically rather than paying an LLM per team.+ assert set(descriptions.keys()) == set(ENDPOINTS)+ for endpoint, entry in descriptions.items():+ assert entry.get("description")+ assert entry.get("columns", {}).get("id"), f"{endpoint} missing id column description"