: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): add Mux Data engagement tables to Mux source (#72914)
Tom Owersff0655c9fd76
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/canonical_descriptions.pyindex 0962f973f2b4..380cbe76e4e3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/canonical_descriptions.py@@ -86,4 +86,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Time the Signing Key was created, as a Unix timestamp (seconds since epoch).",},},+ "video_views": {+ "description": "A Mux Data video view: one playback session, with viewer engagement and quality-of-experience metrics. Syncs incrementally on view_end.",+ "docs_url": "https://www.mux.com/docs/api-reference/data/views/list-video-views",+ "columns": {+ "id": "Unique identifier for the video view.",+ "view_start": "Time playback started for this view (ISO 8601 timestamp).",+ "view_end": "Time playback ended for this view (ISO 8601 timestamp); the incremental sync cursor.",+ "watch_time": "Total time the viewer spent watching this view, in milliseconds.",+ "viewer_experience_score": "Mux's overall quality-of-experience score for this view (0-100).",+ "video_title": "Title of the video watched, as reported by the player.",+ "playback_failure": "True if the view experienced a fatal playback failure.",+ "player_error_code": "Error code reported by the player, if playback failed.",+ "player_error_message": "Human-readable error message reported by the player, if playback failed.",+ "error_type_id": "Identifier of the error type experienced, if any.",+ "country_code": "Two-letter country code the view was played from.",+ "viewer_os_family": "Operating system family of the viewer's device (e.g. iOS, Android, Windows).",+ "viewer_application_name": "Name of the application or browser used for playback.",+ },+ },+ "errors": {+ "description": "A Mux Data playback error, aggregated across views in the synced window: how often it occurred and the share of views it affected.",+ "docs_url": "https://www.mux.com/docs/api-reference/data/errors/list-errors",+ "columns": {+ "id": "Unique identifier for the error.",+ "code": "Numeric error code.",+ "player_error_code": "String version of the error code.",+ "message": "Error message.",+ "description": "Human-readable description of the error.",+ "count": "Number of views that experienced this error in the window.",+ "percentage": "Share of views that experienced this error in the window.",+ "last_seen": "Most recent time this error was seen (ISO 8601 timestamp).",+ "notes": "Notes attached to this error.",+ },+ },+ "metrics_comparison": {+ "description": "Aggregate Mux Data engagement and quality metrics over the synced window — one row per metric, with the metric value alongside universal totals (watch time, plays, unique viewers).",+ "docs_url": "https://www.mux.com/docs/api-reference/data/metrics/list-all-metric-values",+ "columns": {+ "metric": "Identifier of the metric (e.g. views, playing_time, viewer_experience_score).",+ "name": "Human-readable name of the metric.",+ "value": "Aggregate value of the metric over the window.",+ "view_count": "Number of views the metric was aggregated over.",+ "watch_time": "Total watch time across the aggregated views, in milliseconds.",+ "total_playing_time": "Total playing time across the aggregated views, in milliseconds.",+ "unique_viewers": "Number of distinct viewers in the window.",+ "started_views": "Number of views that started playback.",+ "ended_views": "Number of views that finished playback.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/mux.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/mux.pyindex d4c373bd20bc..a332c3d39510 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/mux.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/mux.py@@ -1,8 +1,10 @@import dataclasses+from datetime import UTC, datetime, timedeltafrom typing import Any, Optionalfrom urllib.parse import urlencodeimport requests+from dateutil import parserfrom requests import Request, Responsefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse@@ -14,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,JSONResponseCursorPaginator,+ SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe@@ -26,6 +29,11 @@ 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"+# On incremental syncs, re-query slightly before the last `view_end` watermark. Mux Data can finish+# processing a view minutes after it ended, so a view can surface with a `view_end` we've already+# passed; the overlap re-fetches that boundary and the merge on `id` dedupes the repeats.+INCREMENTAL_OVERLAP = timedelta(hours=1)+@dataclasses.dataclassclass MuxResumeConfig:@@ -136,6 +144,36 @@ def _normalize_row(item: dict[str, Any], config: MuxEndpointConfig) -> dict[str,return item+def _as_epoch(value: Any) -> int:+ """Coerce a stored incremental watermark to Unix seconds for Mux's `timeframe[]` param.++ The pipeline hands back the DateTime watermark as a `datetime` (or, defensively, an ISO string).+ Naive values are treated as UTC, matching Mux's ISO 8601 UTC `view_end` timestamps.+ """+ dt = value if isinstance(value, datetime) else parser.parse(str(value))+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=UTC)+ return int(dt.timestamp())+++def _timeframe_params(+ config: MuxEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> dict[str, Any]:+ """Build the `timeframe[]=<start>&timeframe[]=<end>` window for a Mux Data endpoint.++ Incremental video-view syncs start just before the last `view_end` watermark; every other case+ (first sync, full refresh, aggregate endpoints) falls back to the default lookback window.+ """+ now = datetime.now(tz=UTC)+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None:+ start = _as_epoch(db_incremental_field_last_value) - int(INCREMENTAL_OVERLAP.total_seconds())+ else:+ start = int((now - config.lookback).timestamp())+ return {"timeframe[]": [start, int(now.timestamp())]}++def mux_source(access_token_id: str,secret_key: str,@@ -143,17 +181,33 @@ def mux_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[MuxResumeConfig],+ should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = MUX_ENDPOINTS[endpoint]+ is_incremental = config.supports_incremental and should_use_incremental_fieldpaginator: BasePaginator- if config.use_cursor:+ if not config.paginated:+ # errors / metric comparison return the whole aggregate in one response.+ paginator = SinglePagePaginator()+ elif config.use_cursor:# List Assets returns `next_cursor` in the body; a null/absent value ends pagination.paginator = JSONResponseCursorPaginator(cursor_path="next_cursor", cursor_param="cursor")else:paginator = MuxPagePaginator(page_size=config.page_size)+ params: dict[str, Any] = {}+ if config.paginated:+ params["limit"] = config.page_size+ if config.use_timeframe:+ params.update(_timeframe_params(config, should_use_incremental_field, db_incremental_field_last_value))+ if is_incremental:+ # Ask for oldest-first so the pipeline's `sort_mode="asc"` watermark advances monotonically.+ # The server-side `timeframe[]` filter (applied to every page) bounds the sync regardless of+ # order, and the merge on `id` dedupes the overlap re-fetch.+ params["order_direction"] = "asc"+def _map_row(item: dict[str, Any]) -> dict[str, Any]:# Strip credential-bearing fields, then coerce the partition timestamp — same order as before.return _normalize_row(_strip_sensitive_fields(item, config), config)@@ -170,7 +224,7 @@ def mux_source("name": endpoint,"endpoint": {"path": config.path,- "params": {"limit": config.page_size},+ "params": params,"data_selector": "data",},"data_map": _map_row,@@ -206,7 +260,9 @@ def mux_source(rest_config,team_id,job_id,- db_incremental_field_last_value,+ # We apply the incremental filter ourselves via `timeframe[]`, so the framework's own+ # incremental-param injection stays off; the pipeline advances the watermark from `view_end`.+ None,resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)@@ -220,5 +276,8 @@ def mux_source(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,+ # Oldest-first for incremental video views (see `order_direction` above); the default is fine+ # for full-refresh endpoints, where the watermark isn't tracked.+ sort_mode="asc",column_hints=resource.column_hints,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/settings.pyindex 1b6d03c308e1..7d643151ccc8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/settings.py@@ -1,30 +1,57 @@from dataclasses import dataclass, field+from datetime import timedeltafrom typing import Optional-from products.warehouse_sources.backend.types import IncrementalField+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# First-sync window for the incremental video-views endpoint. Raw per-view rows have much tighter+# retention than aggregates and the list endpoint isn't a bulk export, so we start modest; subsequent+# syncs track the `view_end` watermark forward from here.+VIDEO_VIEWS_INITIAL_LOOKBACK = timedelta(days=30)+# Window for the full-refresh aggregate endpoints (errors, metric comparison). Mux Data retains+# engagement/QoE metrics for ~13 months, so this pulls essentially everything Mux keeps; Mux clamps+# the window to what's actually retained rather than erroring. The responses are small and replaced+# each sync, so a wide window is cheap.+AGGREGATE_LOOKBACK = timedelta(days=395)@dataclassclass MuxEndpointConfig:name: strpath: 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.+ # `created_at` is a stable Unix timestamp on most Mux Video objects, so it's a safe datetime+ # partition key. Endpoints whose objects have no `created_at` (uploads, all Mux Data endpoints)+ # leave this None and aren't partitioned. Mux Data timestamps are ISO 8601 strings, which the+ # datetime partitioner (expects Unix ints) can't parse, so Data endpoints stay unpartitioned.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`).+ # paginated list endpoint is offset-based (`page` + `limit`).use_cursor: bool = False+ # False for Mux Data endpoints that return the whole result set in one response (errors,+ # metric comparison) — those use a single-page paginator instead of walking pages.+ paginated: bool = Trueshould_sync_default: bool = Trueprimary_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 Data endpoints scope results to a `timeframe[]` window (defaults to the last 24h if absent).+ # When True the source passes an explicit window so a sync captures a useful span, not just a day.+ use_timeframe: bool = False+ # Only video views expose a server-side timestamp filter (`view_end` via `timeframe[]`), so it's+ # the one Data endpoint that can sync incrementally; errors and metric aggregates are full refresh.+ supports_incremental: bool = False+ incremental_field: Optional[str] = None+ # How far back the `timeframe[]` window reaches when there's no watermark (first sync or a+ # full-refresh endpoint). Only meaningful when `use_timeframe` is set.+ lookback: timedelta = AGGREGATE_LOOKBACKMUX_ENDPOINTS: dict[str, MuxEndpointConfig] = {+ # --- Mux Video: content-level metadata (assets, live streams, uploads, ...) ---"assets": MuxEndpointConfig(name="assets",path="/video/v1/assets",@@ -57,12 +84,50 @@ MUX_ENDPOINTS: dict[str, MuxEndpointConfig] = {name="signing_keys",path="/system/v1/signing-keys",),+ # --- Mux Data: viewer engagement and quality-of-experience analytics ---+ "video_views": MuxEndpointConfig(+ name="video_views",+ path="/data/v1/video-views",+ # Timestamps are ISO 8601 strings (`view_start` / `view_end`), not the Unix `created_at`+ # the datetime partitioner understands, so this table is left unpartitioned.+ partition_key=None,+ use_timeframe=True,+ supports_incremental=True,+ incremental_field="view_end",+ lookback=VIDEO_VIEWS_INITIAL_LOOKBACK,+ ),+ "errors": MuxEndpointConfig(+ name="errors",+ path="/data/v1/errors",+ partition_key=None,+ # Aggregated over the window in a single response — no pagination.+ paginated=False,+ use_timeframe=True,+ ),+ "metrics_comparison": MuxEndpointConfig(+ name="metrics_comparison",+ path="/data/v1/metrics/comparison",+ partition_key=None,+ # One aggregate row per metric, returned in a single response.+ paginated=False,+ primary_keys=["metric"],+ use_timeframe=True,+ ),}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]] = {}+# Only video views support a server-side timestamp filter (`view_end` within `timeframe[]`), so it's+# the sole endpoint with genuine incremental sync. Its field type is DateTime because Mux Data returns+# ISO 8601 strings (e.g. "2023-01-01T00:00:00Z"), unlike the Unix-timestamp Mux Video endpoints. Every+# other endpoint has no server-side filter and is full refresh only — no advertised incremental fields.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "video_views": [+ {+ "label": "view_end",+ "type": IncrementalFieldType.DateTime,+ "field": "view_end",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/source.pyindex 64ea899a73bb..be8ed248eb44 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/source.py@@ -38,6 +38,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass MuxSource(ResumableSource[MuxSourceConfig, MuxResumeConfig]):api_docs_url = "https://www.mux.com/docs/api-reference"+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in the public docs without credentials.+ lists_tables_without_credentials = True@propertydef source_type(self) -> ExternalDataSourceType:@@ -50,12 +53,13 @@ class MuxSource(ResumableSource[MuxSourceConfig, MuxResumeConfig]):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.+ caption="""Enter your Mux Access Token ID and Secret Key to pull your Mux Video and Mux 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 Data** (read) — required for video views, errors and aggregate metrics (watch time, plays, viewer experience)- **Mux System** (read) — required for signing keys""",iconPath="/static/services/mux.png",@@ -96,7 +100,7 @@ Grant the following read permissions:# 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.",+ "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, Mux Data and Mux System read access, then reconnect.",}def get_schemas(@@ -107,15 +111,17 @@ Grant the following read permissions: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.+ # Only video views expose a server-side timestamp filter (`view_end`), so it can sync+ # incrementally; every other endpoint is full refresh. Append is never offered — the+ # incremental overlap re-fetches boundary rows, which only a merge (not append) can dedupe.def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = MUX_ENDPOINTS[endpoint]return SourceSchema(name=endpoint,- supports_incremental=False,+ supports_incremental=endpoint_config.supports_incremental,supports_append=False,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- should_sync_default=MUX_ENDPOINTS[endpoint].should_sync_default,+ should_sync_default=endpoint_config.should_sync_default,)schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]@@ -160,5 +166,6 @@ Grant the following read permissions:team_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,- db_incremental_field_last_value=None, # every Mux endpoint is full refresh+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux.pyindex 9f5315c00e2f..f61a76aaff8c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux.py@@ -1,5 +1,6 @@import jsonfrom collections.abc import Iterable+from datetime import UTC, datetimefrom typing import Any, castimport pytest@@ -11,13 +12,20 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.mux import muxfrom products.warehouse_sources.backend.temporal.data_imports.sources.mux.mux import (+ INCREMENTAL_OVERLAP,MuxResumeConfig,+ _as_epoch,_normalize_row,_strip_sensitive_fields,+ _timeframe_params,get_validation_status,mux_source,)-from products.warehouse_sources.backend.temporal.data_imports.sources.mux.settings import MUX_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mux.settings import (+ AGGREGATE_LOOKBACK,+ MUX_ENDPOINTS,+ VIDEO_VIEWS_INITIAL_LOOKBACK,+)# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -59,7 +67,13 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,return param_snapshots-def _run(endpoint: str, manager: mock.MagicMock) -> list[dict[str, Any]]:+def _run(+ endpoint: str,+ manager: mock.MagicMock,+ *,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> list[dict[str, Any]]:response = mux_source(access_token_id="id",secret_key="secret",@@ -67,6 +81,8 @@ def _run(endpoint: str, manager: mock.MagicMock) -> list[dict[str, Any]]:team_id=1,job_id="j",resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,)return [row for page in cast("Iterable[Any]", response.items()) for row in page]@@ -313,3 +329,102 @@ class TestMuxSourceResponse:assert response.name == "uploads"assert response.partition_mode is Noneassert response.partition_keys is None++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_metrics_comparison_keys_on_metric_and_is_unpartitioned(self, _MockSession) -> None:+ response = mux_source(+ "id", "secret", "metrics_comparison", team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ assert response.primary_keys == ["metric"]+ assert response.partition_mode is None+ assert response.sort_mode == "asc"+++class TestAsEpoch:+ def test_parses_iso_string_as_utc(self) -> None:+ # 2023-01-01T00:00:00Z == 1672531200 seconds since epoch.+ assert _as_epoch("2023-01-01T00:00:00Z") == 1672531200++ def test_accepts_datetime(self) -> None:+ assert _as_epoch(datetime(2023, 1, 1, tzinfo=UTC)) == 1672531200++ def test_naive_datetime_treated_as_utc(self) -> None:+ # Mux `view_end` values are UTC; a tz-naive watermark must not shift by the local offset.+ assert _as_epoch(datetime(2023, 1, 1)) == 1672531200+++class TestTimeframeParams:+ def test_incremental_window_starts_before_watermark(self) -> None:+ params = _timeframe_params(+ MUX_ENDPOINTS["video_views"],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2023-01-01T00:00:00Z",+ )+ start, end = params["timeframe[]"]+ assert start == 1672531200 - int(INCREMENTAL_OVERLAP.total_seconds())+ assert end >= start++ def test_first_video_views_sync_uses_short_lookback(self) -> None:+ params = _timeframe_params(+ MUX_ENDPOINTS["video_views"], should_use_incremental_field=True, db_incremental_field_last_value=None+ )+ start, end = params["timeframe[]"]+ # First incremental sync windows by the modest video-views lookback, not the wide aggregate one.+ assert abs((end - start) - int(VIDEO_VIEWS_INITIAL_LOOKBACK.total_seconds())) <= 5++ def test_full_refresh_aggregate_uses_wide_lookback(self) -> None:+ # Aggregate endpoints ignore any watermark and window by the wide (~13 month) retention lookback,+ # so a sync summarizes essentially all the history Mux keeps rather than a trailing month.+ params = _timeframe_params(+ MUX_ENDPOINTS["errors"],+ should_use_incremental_field=False,+ db_incremental_field_last_value="2023-01-01T00:00:00Z",+ )+ start, end = params["timeframe[]"]+ assert abs((end - start) - int(AGGREGATE_LOOKBACK.total_seconds())) <= 5+++class TestMuxDataEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_video_views_incremental_windows_from_watermark(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response({"data": [{"id": "v1", "view_end": "2023-02-01T00:00:00Z"}]})])++ rows = _run(+ "video_views",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2023-01-01T00:00:00Z",+ )++ assert [r["id"] for r in rows] == ["v1"]+ start, _end = params[0]["timeframe[]"]+ assert start == 1672531200 - int(INCREMENTAL_OVERLAP.total_seconds())+ # Oldest-first so the asc watermark advances safely, and page pagination still applies.+ assert params[0]["order_direction"] == "asc"+ assert params[0]["limit"] == 100+ assert params[0]["page"] == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_video_views_full_refresh_omits_order_direction(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response({"data": [{"id": "v1", "view_end": "2023-02-01T00:00:00Z"}]})])++ _run("video_views", _make_manager(), should_use_incremental_field=False)++ assert "timeframe[]" in params[0]+ assert "order_direction" not in params[0]++ @parameterized.expand([("errors",), ("metrics_comparison",)])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_single_response_endpoints_fetch_once_with_timeframe(self, endpoint: str, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response({"data": [{"id": 1, "code": 500}]})])++ rows = _run(endpoint, _make_manager())++ assert len(rows) == 1+ # Single-page paginator: exactly one request, no page/limit walking.+ assert session.send.call_count == 1+ assert "timeframe[]" in params[0]+ assert "page" not in params[0]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux_source.pyindex 5c09302fcd01..c8320be672d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mux/tests/test_mux_source.py@@ -10,7 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mux import MuxSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.mux import source as source_modulefrom products.warehouse_sources.backend.temporal.data_imports.sources.mux.mux import MuxResumeConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.mux.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mux.settings import ENDPOINTS, MUX_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.mux.source import MuxSourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -40,13 +40,22 @@ class TestMuxSourceConfig:class TestMuxSchemas:- def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:+ def test_get_schemas_returns_every_endpoint(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++ def test_get_schemas_incremental_matches_endpoint_config(self) -> None:+ # Only video views expose a server-side timestamp filter, so it's the one incremental table;+ # append is never offered because the incremental overlap needs merge-dedupe. This guards the+ # regression where every endpoint was reported as full refresh.+ schemas = {s.name: s for s in MuxSource().get_schemas(_config(), team_id=1)}+ for name, schema in schemas.items():+ assert schema.supports_incremental is MUX_ENDPOINTS[name].supports_incrementalassert schema.supports_append is False- assert schema.incremental_fields == []+ assert schemas["video_views"].supports_incremental is True+ assert [f["field"] for f in schemas["video_views"].incremental_fields] == ["view_end"]+ assert schemas["assets"].supports_incremental is False+ assert schemas["assets"].incremental_fields == []def test_get_schemas_filters_by_names(self) -> None:schemas = MuxSource().get_schemas(_config(), team_id=1, names=["assets"])@@ -128,15 +137,20 @@ class TestMuxResumableWiring:monkeypatch.setattr(source_module, "mux_source", fake_mux_source)inputs = MagicMock()- inputs.schema_name = "assets"+ inputs.schema_name = "video_views"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2023-01-01T00:00:00Z"manager = MagicMock()result = MuxSource().source_for_pipeline(_config(), manager, inputs)assert result is sentinelassert captured["access_token_id"] == "my-token-id"assert captured["secret_key"] == "my-secret"- assert captured["endpoint"] == "assets"+ assert captured["endpoint"] == "video_views"assert captured["resumable_source_manager"] is manager+ # Incremental context must reach the transport so it can build the `timeframe[]` lower bound.+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2023-01-01T00:00:00Z"class TestMuxCanonicalDescriptions:@@ -147,4 +161,7 @@ class TestMuxCanonicalDescriptions: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"+ columns = entry.get("columns", {})+ # Every primary-key column must be documented so joins/keys are self-describing.+ for pk in MUX_ENDPOINTS[endpoint].primary_keys:+ assert columns.get(pk), f"{endpoint} missing '{pk}' column description"