Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse): add mux data metric timeseries, breakdown and dimension tables (#115429)

Tom Owerse29244b99259
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 22abd70d2bf3..9cdeae1a853b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5737,9 +5737,9 @@ Today (9): `assets`, `errors`, `live_streams`, `metrics_comparison`, `playback_r
Diffed against: <https://storage.googleapis.com/stainless-sdk-openapi-specs/mux/mux-d9ec974ac41da39a8bc9920a266615453f948fec82e03a1d9d4ffc0ae5f372c5.yml>
- [ ] `/data/v1/exports/views` — daily raw video-view exports — the bulk path for getting full view-level data into a warehouse (high)
-- [ ] `/data/v1/metrics/{METRIC_ID}/breakdown` — Mux Data's headline output: any metric broken down by dimension (country, CDN, player) (high)
-- [ ] `/data/v1/metrics/{METRIC_ID}/timeseries` — metric over time — the core QoE trend series (high)
-- [ ] `/data/v1/dimensions and /data/v1/dimensions/{DIMENSION_ID}/elements` — lookup enumerating valid dimensions and their values, needed to interpret breakdowns and view rows (high)
+- [x] `/data/v1/metrics/{METRIC_ID}/breakdown` — Mux Data's headline output: any metric broken down by dimension (country, CDN, player) (high)
+- [x] `/data/v1/metrics/{METRIC_ID}/timeseries` — metric over time — the core QoE trend series (high)
+- [x] `/data/v1/dimensions and /data/v1/dimensions/{DIMENSION_ID}/elements` — lookup enumerating valid dimensions and their values, needed to interpret breakdowns and view rows (high)
- [ ] `/video/v1/delivery-usage` — delivery minutes per asset — the billing/usage fact table (high)
- [ ] `/data/v1/metrics/{METRIC_ID}/overall` — aggregate metric value plus total watch time and view count for a window (medium)
- [ ] `/data/v1/incidents (+ /incidents/{id}/related)` — detected delivery incidents with affected-view counts (medium)
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.py
index 380cbe76e4e3..5d7fd9d39ba6 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
@@ -135,4 +135,47 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"ended_views": "Number of views that finished playback.",
},
},
+ "metric_timeseries": {
+ "description": "Daily values of each Mux Data metric over the synced window — one row per metric per day.",
+ "docs_url": "https://www.mux.com/docs/api-reference/data/metrics/get-metric-timeseries-data",
+ "columns": {
+ "metric": "Identifier of the metric (e.g. viewer_experience_score, rebuffer_percentage).",
+ "interval_start": "Start of the interval the value covers (ISO 8601 timestamp).",
+ "value": "Value of the metric for the interval, using the metric's default measurement.",
+ "views": "Number of views in the interval with a valid value for the metric.",
+ "granularity": "Size of each interval (day).",
+ "aggregation": "Timestamp the views are bucketed by (e.g. view_end).",
+ },
+ },
+ "metric_breakdowns": {
+ "description": "Each Mux Data metric broken down by a viewer dimension (country, CDN, browser, operating system, player, device category) over the synced window.",
+ "docs_url": "https://www.mux.com/docs/api-reference/data/metrics/list-breakdown-values",
+ "columns": {
+ "metric": "Identifier of the metric being broken down.",
+ "dimension": "Dimension the metric is grouped by (e.g. country, cdn).",
+ "field": "Value of the dimension for this row (e.g. US, fastly).",
+ "value": "Value of the metric for views with this dimension value.",
+ "views": "Number of views with this dimension value.",
+ "negative_impact": "Rank of how much this dimension value drags the metric down relative to others.",
+ "total_watch_time": "Total watch time of views with this dimension value, in milliseconds.",
+ "total_playing_time": "Total playing time of views with this dimension value, in milliseconds.",
+ },
+ },
+ "dimensions": {
+ "description": "The Mux Data dimensions available to filter and break down views and metrics.",
+ "docs_url": "https://www.mux.com/docs/api-reference/data/dimensions/list-dimensions",
+ "columns": {
+ "name": "Identifier of the dimension (e.g. country, player_name).",
+ "tier": "Whether the dimension is a basic or an advanced dimension.",
+ },
+ },
+ "dimension_values": {
+ "description": "Values seen for each Mux Data dimension over the synced window, with the number of views for each value.",
+ "docs_url": "https://www.mux.com/docs/api-reference/data/dimensions/list-dimension-values",
+ "columns": {
+ "dimension": "Identifier of the dimension the value belongs to.",
+ "value": "A value of the dimension.",
+ "total_count": "Number of views with this value.",
+ },
+ },
}
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.py
index 5f1627d20ea3..f10a287b1b8f 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,7 +1,9 @@
+import logging
import dataclasses
+from collections.abc import Callable, Iterator
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
-from urllib.parse import urlencode
+from urllib.parse import quote, urlencode
import requests
from dateutil import parser
@@ -11,20 +13,34 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ make_parent_key_name,
)
from 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.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.mux.settings import (
+ BREAKDOWN_DIMENSIONS,
+ DATA_METRICS,
MUX_ENDPOINTS,
MuxEndpointConfig,
)
+logger = logging.getLogger(__name__)
+
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"
@@ -35,12 +51,15 @@ DEFAULT_VALIDATION_PATH = "/video/v1/assets"
INCREMENTAL_OVERLAP = timedelta(hours=1)
[email protected](frozen=True)
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
+ # Framework fan-out state (completed child paths plus the in-progress child page) for the
+ # metric and dimension fan-out endpoints.
+ fan_out: dict[str, Any] | None = None
class MuxPagePaginator(BasePaginator):
@@ -53,11 +72,14 @@ class MuxPagePaginator(BasePaginator):
via the next page number.
"""
- def __init__(self, page_size: int, page_param: str = "page", page: int = 1) -> None:
+ def __init__(
+ self, page_size: int, page_param: str = "page", page: int = 1, max_pages: Optional[int] = None
+ ) -> None:
super().__init__()
self.page_size = page_size
self.page_param = page_param
self.page = page
+ self.max_pages = max_pages
def _inject_page(self, request: Request) -> None:
if request.params is None:
@@ -71,6 +93,10 @@ class MuxPagePaginator(BasePaginator):
if not data or len(data) < self.page_size:
self._has_next_page = False
return
+ if self.max_pages is not None and self.page >= self.max_pages:
+ logger.warning("Mux page cap reached; truncating results. url=%s pages=%s", response.url, self.max_pages)
+ self._has_next_page = False
+ return
self.page += 1
self._has_next_page = True
@@ -174,6 +200,137 @@ def _timeframe_params(
return {"timeframe[]": [start, int(now.timestamp())]}
+def _to_number(value: Any, cast: Callable[[float], float | int]) -> float | int | None:
+ # Timeseries points carry numbers as strings or numbers depending on the metric.
+ if value is None or value == "":
+ return None
+ return cast(float(value))
+
+
+def _dimension_rows(data: dict[str, Any]) -> list[dict[str, Any]]:
+ """Flatten `{"basic": [...], "advanced": [...]}` into one row per dimension."""
+ rows: dict[str, dict[str, Any]] = {}
+ for tier in ("basic", "advanced"):
+ for name in data.get(tier) or []:
+ rows.setdefault(name, {"name": name, "tier": tier})
+ return list(rows.values())
+
+
+def _dimension_parent_rows(data: dict[str, Any]) -> list[dict[str, Any]]:
+ # Trace dimensions (e.g. `video_cdn_trace`) hold an array of values per view, and Mux lists their
+ # values through `/elements` instead of the plain dimension values endpoint.
+ # The name comes from the API response and is bound into the request path, so it is percent-encoded
+ # to keep a hostile value from rewriting the URL (and the host the credentials go to).
+ return [
+ {
+ "dimension": row["name"],
+ "values_path": quote(row["name"], safe="") + ("/elements" if row["name"].endswith("_trace") else ""),
+ }
+ for row in _dimension_rows(data)
+ ]
+
+
+def _static_pages(rows: list[dict[str, Any]]) -> Callable[[], Iterator[list[dict[str, Any]]]]:
+ def pages() -> Iterator[list[dict[str, Any]]]:
+ yield rows
+
+ return pages
+
+
+def _lift_parent_keys(parent: str, keys: list[str]) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ def lift(row: dict[str, Any]) -> dict[str, Any]:
+ lifted = dict(row)
+ for key in keys:
+ lifted[key] = lifted.pop(make_parent_key_name(parent, key))
+ return lifted
+
+ return lift
+
+
+def _timeseries_rows(body: dict[str, Any]) -> list[dict[str, Any]]:
+ """Explode a timeseries response into one row per `[interval, value, views]` point."""
+ metric = body[make_parent_key_name("metrics", "metric")]
+ meta = body.get("meta") or {}
+ return [
+ {
+ "metric": metric,
+ "interval_start": point[0],
+ "value": _to_number(point[1], float),
+ "views": _to_number(point[2], int) if len(point) > 2 else None,
+ "granularity": meta.get("granularity"),
+ "aggregation": meta.get("aggregation"),
+ }
+ for point in body.get("data") or []
+ ]
+
+
+def _fan_out_resource(
+ config: MuxEndpointConfig,
+ client: ClientConfig,
+ params: dict[str, Any],
+ paginator: BasePaginator,
+ team_id: int,
+ job_id: str,
+ resume_hook: Callable[[Optional[dict[str, Any]]], None],
+ initial_state: Optional[dict[str, Any]],
+) -> Resource:
+ """Build a Mux Data endpoint keyed by metric or dimension as a framework parent/child fan-out."""
+ parent: EndpointResource
+ if config.fan_out == "dimensions":
+ parent_name = "dimensions"
+ resolve_fields, keys = ["values_path"], ["dimension"]
+ parent = {
+ "name": parent_name,
+ "endpoint": {
+ "path": MUX_ENDPOINTS["dimensions"].path,
+ "paginator": SinglePagePaginator(),
+ "data_selector": "data",
+ },
+ "data_map": _dimension_parent_rows,
+ }
+ else:
+ parent_name = "metrics"
+ if config.fan_out == "metric_dimensions":
+ keys = ["metric", "dimension"]
+ parent_rows = [{"metric": m, "dimension": d} for m in DATA_METRICS for d in BREAKDOWN_DIMENSIONS]
+ else:
+ keys = ["metric"]
+ parent_rows = [{"metric": m} for m in DATA_METRICS]
+ resolve_fields = keys
+ parent = {
+ "name": parent_name,
+ "endpoint": {"path": "/data/v1/metrics"},
+ "data_iterator": _static_pages(parent_rows),
+ }
+
+ child_endpoint: Endpoint = {
+ "path": config.path,
+ "params": {
+ **params,
+ **{key: {"type": "resolve", "resource": parent_name, "field": key} for key in resolve_fields},
+ },
+ "paginator": paginator,
+ }
+ child: EndpointResource = {"name": config.name, "endpoint": child_endpoint, "include_from_parent": keys}
+ if config.fan_out == "metrics":
+ # The timeseries body holds `data` as `[interval, value, views]` arrays, so the whole body is
+ # selected and exploded into rows after the parent's metric is merged into it.
+ child["data_map"] = _timeseries_rows
+ else:
+ child_endpoint["data_selector"] = "data"
+ child["data_map"] = _lift_parent_keys(parent_name, keys)
+
+ resources = rest_api_resources(
+ {"client": client, "resources": [parent, child]},
+ team_id,
+ job_id,
+ None,
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_state,
+ )
+ return next(r for r in resources if r.name == config.name)
+
+
def mux_source(
access_token_id: str,
secret_key: str,
@@ -189,13 +346,13 @@ def mux_source(
paginator: BasePaginator
if not config.paginated:
- # errors / metric comparison return the whole aggregate in one response.
+ # Aggregate and lookup endpoints return their whole result 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)
+ paginator = MuxPagePaginator(page_size=config.page_size, max_pages=config.max_pages)
params: dict[str, Any] = {}
if config.paginated:
@@ -207,36 +364,28 @@ def mux_source(
# 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"
+ params.update(config.extra_params)
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)
- rest_config: RESTAPIConfig = {
- "client": {
- "base_url": MUX_BASE_URL,
- # Basic auth via the framework so the secret is redacted from logs and raised errors.
- "auth": {"type": "http_basic", "username": access_token_id, "password": secret_key},
- "paginator": paginator,
- },
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": params,
- "data_selector": "data",
- },
- "data_map": _map_row,
- }
- ],
+ client: ClientConfig = {
+ "base_url": MUX_BASE_URL,
+ # Pin every request to api.mux.com so the Basic credentials never go to another host.
+ "allowed_hosts": [],
+ # Basic auth via the framework so the secret is redacted from logs and raised errors.
+ "auth": {"type": "http_basic", "username": access_token_id, "password": secret_key},
+ "paginator": paginator,
}
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
if resume is not None:
- if config.use_cursor:
+ if config.fan_out is not None:
+ initial_paginator_state = resume.fan_out
+ elif config.use_cursor:
if resume.cursor is not None:
initial_paginator_state = {"cursor": resume.cursor}
elif resume.page is not None:
@@ -247,7 +396,9 @@ def mux_source(
# the last page (merge dedupes) rather than skipping it.
if not state:
return
- if config.use_cursor:
+ if config.fan_out is not None:
+ resumable_source_manager.save_state(MuxResumeConfig(fan_out=state))
+ elif config.use_cursor:
cursor = state.get("cursor")
if cursor is not None:
resumable_source_manager.save_state(MuxResumeConfig(cursor=cursor))
@@ -256,16 +407,36 @@ def mux_source(
if page is not None:
resumable_source_manager.save_state(MuxResumeConfig(page=int(page)))
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- # 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,
- )
+ resource: Resource
+ if config.fan_out is not None:
+ resource = _fan_out_resource(
+ config, client, params, paginator, team_id, job_id, save_checkpoint, initial_paginator_state
+ )
+ else:
+ rest_config: RESTAPIConfig = {
+ "client": client,
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": params,
+ "data_selector": "data",
+ },
+ "data_map": _dimension_rows if endpoint == "dimensions" else _map_row,
+ }
+ ],
+ }
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ # 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,
+ )
return SourceResponse(
name=endpoint,
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.py
index 839a3b908963..d5a518082674 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,6 +1,6 @@
from dataclasses import dataclass, field
from datetime import timedelta
-from typing import Optional
+from typing import Any, Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -15,8 +15,76 @@ VIDEO_VIEWS_INITIAL_LOOKBACK = timedelta(days=30)
# sync, so a wide window is cheap.
AGGREGATE_LOOKBACK = timedelta(days=90)
+# Every metric the Mux Data breakdown and timeseries endpoints accept (`METRIC_ID` in the API reference).
+DATA_METRICS: tuple[str, ...] = (
+ "aggregate_startup_time",
+ "downscale_percentage",
+ "exits_before_video_start",
+ "live_stream_latency",
+ "max_downscale_percentage",
+ "max_request_latency",
+ "max_upscale_percentage",
+ "page_load_time",
+ "playback_failure_percentage",
+ "playback_success_score",
+ "player_startup_time",
+ "playing_time",
+ "rebuffer_count",
+ "rebuffer_duration",
+ "rebuffer_frequency",
+ "rebuffer_percentage",
+ "request_latency",
+ "request_throughput",
+ "rebuffer_score",
+ "requests_for_first_preroll",
+ "seek_latency",
+ "startup_time_score",
+ "unique_viewers",
+ "upscale_percentage",
+ "video_quality_score",
+ "video_startup_preroll_load_time",
+ "video_startup_preroll_request_time",
+ "video_startup_time",
+ "viewer_experience_score",
+ "views",
+ "weighted_average_bitrate",
+ "video_startup_failure_percentage",
+ "ad_attempt_count",
+ "ad_break_count",
+ "ad_break_error_count",
+ "ad_break_error_percentage",
+ "ad_error_count",
+ "ad_error_percentage",
+ "ad_exit_before_start_count",
+ "ad_exit_before_start_percentage",
+ "ad_impression_count",
+ "ad_startup_error_count",
+ "ad_startup_error_percentage",
+ "playback_business_exception_percentage",
+ "video_startup_business_exception_percentage",
+ "view_content_startup_time",
+ "ad_preroll_startup_time",
+ "view_dropped_percentage",
+ "rendition_change_count",
+ "rendition_upshift_count",
+ "rendition_downshift_count",
+)
+# Mux accepts ~90 breakdown dimensions and the table issues one request per metric per dimension, so
+# it covers the dimensions QoE triage usually starts from rather than all of them.
+BREAKDOWN_DIMENSIONS: tuple[str, ...] = (
+ "country",
+ "cdn",
+ "browser",
+ "operating_system",
+ "player_name",
+ "viewer_device_category",
+)
+# Identifier dimensions (view_session_id, viewer_user_id, ...) can have one value per view, so a full
+# walk would re-read the whole view history. Cap each dimension at this many pages of values.
+DIMENSION_VALUES_MAX_PAGES = 50
-@dataclass
+
+@dataclass(frozen=True)
class MuxEndpointConfig:
name: str
path: str
@@ -49,6 +117,12 @@ class MuxEndpointConfig:
# 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_LOOKBACK
+ # Mux Data endpoints keyed by a metric or dimension in the path. The source issues one request
+ # stream per metric (`metrics`), per metric and breakdown dimension (`metric_dimensions`), or per
+ # dimension listed by `/data/v1/dimensions` (`dimensions`), and adds the key to each row.
+ fan_out: Optional[Literal["metrics", "metric_dimensions", "dimensions"]] = None
+ extra_params: dict[str, Any] = field(default_factory=dict)
+ max_pages: Optional[int] = None
MUX_ENDPOINTS: dict[str, MuxEndpointConfig] = {
@@ -114,6 +188,47 @@ MUX_ENDPOINTS: dict[str, MuxEndpointConfig] = {
primary_keys=["metric"],
use_timeframe=True,
),
+ "metric_timeseries": MuxEndpointConfig(
+ name="metric_timeseries",
+ path="/data/v1/metrics/{metric}/timeseries",
+ partition_key=None,
+ # One response per metric holds every interval in the window.
+ paginated=False,
+ primary_keys=["metric", "interval_start"],
+ use_timeframe=True,
+ fan_out="metrics",
+ # Without an explicit granularity Mux picks one from the window length and may change it.
+ extra_params={"group_by": "day"},
+ ),
+ "metric_breakdowns": MuxEndpointConfig(
+ name="metric_breakdowns",
+ path="/data/v1/metrics/{metric}/breakdown?group_by={dimension}",
+ partition_key=None,
+ primary_keys=["metric", "dimension", "field"],
+ use_timeframe=True,
+ fan_out="metric_dimensions",
+ # A stable order keeps page boundaries fixed while the walk runs.
+ extra_params={"order_by": "field", "order_direction": "asc"},
+ # Hundreds of requests per sync, so only on when the user picks it.
+ should_sync_default=False,
+ ),
+ "dimensions": MuxEndpointConfig(
+ name="dimensions",
+ path="/data/v1/dimensions",
+ partition_key=None,
+ paginated=False,
+ primary_keys=["name"],
+ ),
+ "dimension_values": MuxEndpointConfig(
+ name="dimension_values",
+ path="/data/v1/dimensions/{values_path}",
+ partition_key=None,
+ primary_keys=["dimension", "value"],
+ use_timeframe=True,
+ fan_out="dimensions",
+ max_pages=DIMENSION_VALUES_MAX_PAGES,
+ should_sync_default=False,
+ ),
}
ENDPOINTS = tuple(MUX_ENDPOINTS.keys())
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.py
index 756e5812bdb8..1f07f0e7d4ba 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
@@ -54,7 +54,7 @@ Create an access token under [Settings → Access Tokens](https://dashboard.mux.
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 Data** (read) — required for video views, errors, aggregate metrics (watch time, plays, viewer experience), metric timeseries and breakdowns, and dimensions
- **Mux System** (read) — required for signing keys
""",
iconPath="/static/services/mux.png",
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.py
index e446192026a0..722455bfc764 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
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mux.mux im
)
from products.warehouse_sources.backend.temporal.data_imports.sources.mux.settings import (
AGGREGATE_LOOKBACK,
+ DIMENSION_VALUES_MAX_PAGES,
MUX_ENDPOINTS,
)
@@ -58,7 +59,7 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
def _prepare(request: Any) -> mock.MagicMock:
param_snapshots.append(dict(request.params or {}))
- return mock.MagicMock()
+ return mock.MagicMock(url=request.url)
session.prepare_request.side_effect = _prepare
session.send.side_effect = responses
@@ -213,7 +214,7 @@ class TestRetryableErrors:
def test_retryable_status_eventually_raises(self, MockSession, _sleep) -> None:
session = MockSession.return_value
session.headers = {}
- session.prepare_request.side_effect = lambda request: mock.MagicMock()
+ session.prepare_request.side_effect = lambda request: mock.MagicMock(url=request.url)
session.send.return_value = _response(None, status=500, reason="err")
with pytest.raises(Exception):
@@ -280,3 +281,181 @@ class TestMuxDataEndpoints:
assert session.send.call_count == 1
assert "timeframe[]" in params[0]
assert "page" not in params[0]
+
+
+def _wire_urls(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:
+ session.headers = {}
+ requests_sent: list[tuple[str, dict[str, Any]]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ requests_sent.append((request.url, dict(request.params or {})))
+ return mock.MagicMock(url=request.url)
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return requests_sent
+
+
+class TestMuxDataFanOut:
+ @mock.patch.object(mux, "DATA_METRICS", ("views", "rebuffer_percentage"))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_metric_timeseries_explodes_points_per_metric(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire_urls(
+ session,
+ [
+ _response(
+ {
+ "data": [["2024-01-01T00:00:00Z", "10", "10"], ["2024-01-02T00:00:00Z", 12, None]],
+ "meta": {"granularity": "day", "aggregation": "view_end"},
+ }
+ ),
+ _response({"data": [["2024-01-01T00:00:00Z", "0.25", "40"]], "meta": {"granularity": "day"}}),
+ ],
+ )
+
+ rows = _run("metric_timeseries", _make_manager())
+
+ assert [url for url, _ in sent] == [
+ "https://api.mux.com/data/v1/metrics/views/timeseries",
+ "https://api.mux.com/data/v1/metrics/rebuffer_percentage/timeseries",
+ ]
+ assert sent[0][1]["group_by"] == "day"
+ assert "timeframe[]" in sent[0][1]
+ assert rows == [
+ {
+ "metric": "views",
+ "interval_start": "2024-01-01T00:00:00Z",
+ "value": 10.0,
+ "views": 10,
+ "granularity": "day",
+ "aggregation": "view_end",
+ },
+ {
+ "metric": "views",
+ "interval_start": "2024-01-02T00:00:00Z",
+ "value": 12.0,
+ "views": None,
+ "granularity": "day",
+ "aggregation": "view_end",
+ },
+ {
+ "metric": "rebuffer_percentage",
+ "interval_start": "2024-01-01T00:00:00Z",
+ "value": 0.25,
+ "views": 40,
+ "granularity": "day",
+ "aggregation": None,
+ },
+ ]
+
+ @mock.patch.object(mux, "DATA_METRICS", ("views",))
+ @mock.patch.object(mux, "BREAKDOWN_DIMENSIONS", ("country", "cdn"))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_metric_breakdowns_walk_pages_per_metric_and_dimension(self, MockSession) -> None:
+ session = MockSession.return_value
+ full_page = [{"field": f"c{i}", "value": 1, "views": 1} for i in range(100)]
+ sent = _wire_urls(
+ session,
+ [
+ _response({"data": full_page}),
+ _response({"data": [{"field": "US", "value": 2, "views": 5}]}),
+ _response({"data": [{"field": "fastly", "value": 3, "views": 7}]}),
+ ],
+ )
+
+ rows = _run("metric_breakdowns", _make_manager())
+
+ assert [(url, params["page"]) for url, params in sent] == [
+ ("https://api.mux.com/data/v1/metrics/views/breakdown?group_by=country", 1),
+ ("https://api.mux.com/data/v1/metrics/views/breakdown?group_by=country", 2),
+ ("https://api.mux.com/data/v1/metrics/views/breakdown?group_by=cdn", 1),
+ ]
+ assert sent[0][1]["order_by"] == "field"
+ assert len(rows) == 102
+ assert rows[100] == {"field": "US", "value": 2, "views": 5, "metric": "views", "dimension": "country"}
+ assert rows[101] == {"field": "fastly", "value": 3, "views": 7, "metric": "views", "dimension": "cdn"}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_dimension_values_fan_out_routes_trace_dimensions_to_elements(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire_urls(
+ session,
+ [
+ _response({"data": {"basic": ["country"], "advanced": ["country", "video_cdn_trace"]}}),
+ _response({"data": [{"value": "US", "total_count": 9}]}),
+ _response({"data": [{"value": "fastly", "total_count": 4}]}),
+ ],
+ )
+
+ rows = _run("dimension_values", _make_manager())
+
+ assert [url for url, _ in sent] == [
+ "https://api.mux.com/data/v1/dimensions",
+ "https://api.mux.com/data/v1/dimensions/country",
+ "https://api.mux.com/data/v1/dimensions/video_cdn_trace/elements",
+ ]
+ assert rows == [
+ {"value": "US", "total_count": 9, "dimension": "country"},
+ {"value": "fastly", "total_count": 4, "dimension": "video_cdn_trace"},
+ ]
+
+ def test_dimension_parent_rows_percent_encode_names_from_the_response(self) -> None:
+ rows = mux._dimension_parent_rows(
+ {"basic": ["https://attacker.example/x", "//attacker.example/x"], "advanced": ["video_cdn_trace"]}
+ )
+
+ assert [row["values_path"] for row in rows] == [
+ "https%3A%2F%2Fattacker.example%2Fx",
+ "%2F%2Fattacker.example%2Fx",
+ "video_cdn_trace/elements",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_dimension_values_stop_at_page_cap(self, MockSession) -> None:
+ session = MockSession.return_value
+ full_page = {"data": [{"value": str(i), "total_count": 1} for i in range(100)]}
+ _wire_urls(
+ session,
+ [_response({"data": {"basic": ["view_session_id"], "advanced": []}})]
+ + [_response(full_page) for _ in range(DIMENSION_VALUES_MAX_PAGES + 1)],
+ )
+
+ rows = _run("dimension_values", _make_manager())
+
+ assert len(rows) == DIMENSION_VALUES_MAX_PAGES * 100
+ assert session.send.call_count == DIMENSION_VALUES_MAX_PAGES + 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_dimensions_flatten_tiers(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire_urls(session, [_response({"data": {"basic": ["browser", "country"], "advanced": ["country", "asn"]}})])
+
+ rows = _run("dimensions", _make_manager())
+
+ assert rows == [
+ {"name": "browser", "tier": "basic"},
+ {"name": "country", "tier": "basic"},
+ {"name": "asn", "tier": "advanced"},
+ ]
+
+ @mock.patch.object(mux, "DATA_METRICS", ("views", "rebuffer_percentage"))
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fan_out_resumes_past_completed_metrics(self, MockSession) -> None:
+ session = MockSession.return_value
+ sent = _wire_urls(session, [_response({"data": [["2024-01-01T00:00:00Z", "0.5", "2"]]})])
+ manager = _make_manager(
+ MuxResumeConfig(
+ fan_out={"completed": ["/data/v1/metrics/views/timeseries"], "current": None, "child_state": None}
+ )
+ )
+
+ rows = _run("metric_timeseries", manager)
+
+ assert [url for url, _ in sent] == ["https://api.mux.com/data/v1/metrics/rebuffer_percentage/timeseries"]
+ assert [row["metric"] for row in rows] == ["rebuffer_percentage"]
+ saved = manager.save_state.call_args.args[0]
+ assert saved.fan_out["completed"] == [
+ "/data/v1/metrics/rebuffer_percentage/timeseries",
+ "/data/v1/metrics/views/timeseries",
+ ]