: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 Microsoft Clarity source (#73198)
Tom Owersdd2a7fac4ed9
diff --git a/frontend/public/services/microsoft_clarity.png b/frontend/public/services/microsoft_clarity.pngindex 198166f8fedc..d04883e8db2f 100644Binary files a/frontend/public/services/microsoft_clarity.png and b/frontend/public/services/microsoft_clarity.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b860dda0e2b0..971c4ffe0c2c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -361,6 +361,7 @@ the row lists both.| metabase | HTTP | requests | ✅ || metaplane | HTTP | requests | ✅ || metorial | HTTP | requests | ✅ |+| microsoft_clarity | HTTP | requests | ✅ || mistral_ai | HTTP | requests | ✅ || mixmax | HTTP | requests | ✅ || mixpanel | HTTP | requests | ✅ |@@ -1077,7 +1078,6 @@ doesn't conflict with concurrent PRs.- mezmo- microsoft_365_usage_reports- microsoft_advertising-- microsoft_clarity- microsoft_dataverse- microsoft_defender_cloud_apps- microsoft_defender_endpointdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/microsoftclarity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/microsoftclarity.pyindex fed41ce8a2e6..1a45d87b82c0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/microsoftclarity.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/microsoftclarity.py@@ -1,9 +1,24 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass MicrosoftClaritySourceConfig(config.Config):- pass+ api_token: str+ num_of_days: Literal["1", "2", "3"] = config.value(default="1")+ dimension1: (+ Literal["none", "Browser", "Device", "Country/Region", "OS", "Source", "Medium", "Campaign", "Channel", "URL"]+ | None+ ) = config.value(default="none")+ dimension2: (+ Literal["none", "Browser", "Device", "Country/Region", "OS", "Source", "Medium", "Campaign", "Channel", "URL"]+ | None+ ) = config.value(default="none")+ dimension3: (+ Literal["none", "Browser", "Device", "Country/Region", "OS", "Source", "Medium", "Campaign", "Channel", "URL"]+ | None+ ) = config.value(default="none")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/canonical_descriptions.pynew file mode 100644index 000000000000..1229c8f74229--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/canonical_descriptions.py@@ -0,0 +1,34 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.settings import ENDPOINT_NAME++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ ENDPOINT_NAME: {+ "description": (+ "Engagement and frustration-signal metrics (traffic, scroll depth, engagement time, "+ "popular pages, dead/rage/quickback/error clicks, script errors) from the Microsoft "+ "Clarity Data Export API, aggregated over the requested reporting window and optionally "+ "broken down by up to three dimensions. Each sync appends a new snapshot rather than "+ "replacing prior data, since the API only ever returns the last 1-3 days."+ ),+ "docs_url": "https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-data-export-api",+ "columns": {+ "metric_name": (+ "The Clarity metric this row belongs to (e.g. Traffic, ScrollDepth, EngagementTime, "+ "PopularPages, DeadClickCount, RageClickCount, QuickbackClick, ScriptErrorCount, "+ "ErrorClickCount)."+ ),+ "synced_at": (+ "UTC timestamp this row was pulled at. Used to distinguish daily snapshots, since the "+ "API has no historical cursor and only ever returns the trailing 1-3 day window."+ ),+ "num_of_days": "The reporting window requested: 1, 2, or 3 (last 24/48/72 hours).",+ "row_index": "Position of this row within its metric's result set for this sync.",+ "totalSessionCount": "Number of sessions counted for this metric/dimension combination.",+ "totalBotSessionCount": "Number of bot sessions counted for this metric/dimension combination.",+ "distantUserCount": "Number of distinct users counted for this metric/dimension combination.",+ "PagesPerSessionPercentage": "Average pages-per-session percentage for this metric/dimension combination.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/microsoft_clarity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/microsoft_clarity.pynew file mode 100644index 000000000000..4016a4f3254c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/microsoft_clarity.py@@ -0,0 +1,123 @@+from datetime import UTC, datetime+from typing import Any, Optional++import requests++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.settings import (+ ENDPOINT_NAME,+ NO_DIMENSION,+)++BASE_URL = "https://www.clarity.ms"+INSIGHTS_PATH = "/export-data/api/v1/project-live-insights"++# Cheapest possible probe to confirm a token is genuine: one day, no breakdown dimensions. Still+# counts against the project's 10-requests/day quota, which is an accepted tradeoff for validating+# credentials at source-create time.+_VALIDATION_NUM_OF_DAYS = "1"++_REQUEST_TIMEOUT = 30+++def _build_params(num_of_days: str, dimensions: list[str]) -> dict[str, str]:+ params: dict[str, str] = {"numOfDays": num_of_days}+ for index, dimension in enumerate(dimensions, start=1):+ params[f"dimension{index}"] = dimension+ return params+++def _fetch(token: str, num_of_days: str, dimensions: list[str]) -> requests.Response:+ # make_tracked_session already retries 429/5xx with backoff; the daily quota is a hard cap so a+ # 429 that survives those retries is genuine and should surface, not be retried again here.+ session = make_tracked_session(redact_values=(token,))+ return session.get(+ f"{BASE_URL}{INSIGHTS_PATH}",+ params=_build_params(num_of_days, dimensions),+ headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},+ timeout=_REQUEST_TIMEOUT,+ )+++def validate_credentials(token: str) -> tuple[bool, str | None]:+ try:+ response = _fetch(token, _VALIDATION_NUM_OF_DAYS, [])+ except requests.RequestException:+ return False, "Could not reach Microsoft Clarity. Please try again."++ if response.ok:+ return True, None+ if response.status_code == 401:+ return False, "Invalid or expired Microsoft Clarity API token."+ if response.status_code == 403:+ return False, "This Microsoft Clarity API token is not authorized for this project."+ if response.status_code == 429:+ # The project's 10-requests/day quota is already exhausted (possibly by other tooling), but+ # that doesn't mean the token itself is invalid — don't block source creation over it.+ return True, None+ return False, f"Microsoft Clarity returned status {response.status_code}."+++def _resolve_dimensions(dimension1: Optional[str], dimension2: Optional[str], dimension3: Optional[str]) -> list[str]:+ dimensions: list[str] = []+ for dimension in (dimension1, dimension2, dimension3):+ if dimension and dimension != NO_DIMENSION and dimension not in dimensions:+ dimensions.append(dimension)+ return dimensions+++def microsoft_clarity_source(+ token: str,+ num_of_days: str,+ dimension1: Optional[str],+ dimension2: Optional[str],+ dimension3: Optional[str],+) -> SourceResponse:+ dimensions = _resolve_dimensions(dimension1, dimension2, dimension3)+ response = _fetch(token, num_of_days, dimensions)+ response.raise_for_status()+ payload = response.json()++ # Shared across every row from this call so a sync's snapshot rows all land together, and+ # repeated syncs (the only way to accumulate history against this API) append rather than+ # collide on the primary key.+ synced_at = datetime.now(UTC).isoformat()++ def _rows() -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ if not isinstance(payload, list):+ return rows++ for metric in payload:+ if not isinstance(metric, dict):+ continue+ metric_name = metric.get("metricName")+ information = metric.get("information")+ if not isinstance(information, list):+ continue++ for row_index, item in enumerate(information):+ row: dict[str, Any] = {+ "metric_name": metric_name,+ "synced_at": synced_at,+ "num_of_days": int(num_of_days),+ # Metric rows carry no vendor-issued id, and which fields identify a row varies+ # by metric/dimension combination — the index within this call's group is the+ # only value guaranteed unique table-wide.+ "row_index": row_index,+ }+ if isinstance(item, dict):+ row.update(item)+ rows.append(row)+ return rows++ return SourceResponse(+ name=ENDPOINT_NAME,+ items=lambda: _rows(),+ primary_keys=["metric_name", "synced_at", "row_index"],+ partition_mode="datetime",+ partition_format="month",+ partition_keys=["synced_at"],+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/settings.pynew file mode 100644index 000000000000..622f70083615--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/settings.py@@ -0,0 +1,45 @@+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Clarity's Data Export API always returns every metric type (Traffic, ScrollDepth, EngagementTime,+# PopularPages, dead/rage/quickback/error clicks, ScriptErrorCount, ...) in a single response — there+# is no per-metric filter — so the whole payload is modeled as one always-available table.+ENDPOINT_NAME = "project_live_insights"+ENDPOINTS = (ENDPOINT_NAME,)++# Sentinel value for an unset breakdown-dimension select field.+NO_DIMENSION = "none"++# Exact dimension labels the API expects (case-sensitive), per the Clarity Data Export API docs.+DIMENSION_OPTIONS: tuple[str, ...] = (+ "Browser",+ "Device",+ "Country/Region",+ "OS",+ "Source",+ "Medium",+ "Campaign",+ "Channel",+ "URL",+)++NUM_OF_DAYS_OPTIONS: tuple[str, ...] = ("1", "2", "3")+DEFAULT_NUM_OF_DAYS = "1"++# The API has no server-side "since"/"updated after" filter: `numOfDays` is a fixed rolling window+# relative to the call, not a resumable cursor. `synced_at` is a client-captured timestamp so that+# recurring syncs append daily snapshots (accumulating history downstream) instead of overwriting+# the same rows — it is not pushed down to the API as a filter.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ ENDPOINT_NAME: [+ {+ "label": "Synced at",+ "type": IncrementalFieldType.DateTime,+ "field": "synced_at",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+}++# Append-only: the API can only return the last 1-3 days (aggregated as of the call), so there is no+# stable, reusable primary key to merge on across syncs — every sync's rows are new snapshot rows.+APPEND_ONLY_ENDPOINTS = frozenset({ENDPOINT_NAME})diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.pyindex c1b9f5a1dbba..4ee73fd5114d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/source.py@@ -1,32 +1,161 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.microsoftclarity import (MicrosoftClaritySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.microsoft_clarity import (+ microsoft_clarity_source,+ validate_credentials as validate_clarity_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.settings import (+ APPEND_ONLY_ENDPOINTS,+ DEFAULT_NUM_OF_DAYS,+ DIMENSION_OPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NO_DIMENSION,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _dimension_options() -> list[SourceFieldSelectConfigOption]:+ return [+ SourceFieldSelectConfigOption(label="None", value=NO_DIMENSION),+ *(SourceFieldSelectConfigOption(label=dimension, value=dimension) for dimension in DIMENSION_OPTIONS),+ ]++@SourceRegistry.registerclass MicrosoftClaritySource(SimpleSource[MicrosoftClaritySourceConfig]):+ lists_tables_without_credentials = True # static, single endpoint — safe for public docs+ api_docs_url = "https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-data-export-api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MICROSOFTCLARITY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Microsoft Clarity API token is invalid or expired. Generate a new token in Clarity under Settings -> Data Export and reconnect.",+ "403 Client Error": "This Microsoft Clarity API token is not authorized for this project.",+ "429 Client Error": "The Microsoft Clarity daily quota (10 requests per project) has been used up. Try again after the quota resets.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: MicrosoftClaritySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, append_only=APPEND_ONLY_ENDPOINTS)++ def validate_credentials(+ self,+ config: MicrosoftClaritySourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_clarity_credentials(config.api_token)++ def source_for_pipeline(self, config: MicrosoftClaritySourceConfig, inputs: SourceInputs) -> SourceResponse:+ return microsoft_clarity_source(+ token=config.api_token,+ num_of_days=config.num_of_days,+ dimension1=config.dimension1,+ dimension2=config.dimension2,+ dimension3=config.dimension3,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.MICROSOFT_CLARITY,category=DataWarehouseSourceCategory.ANALYTICS,label="Microsoft Clarity",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Generate an API token in your Clarity project under **Settings -> Data Export -> Generate new API token**, then paste it below.++Microsoft Clarity's export API allows a maximum of 10 requests per project per day and only returns the last 1-3 days of data (no historical backfill), so PostHog syncs a rolling snapshot on each run rather than pulling full history.""",+ docsUrl="https://posthog.com/docs/cdp/sources/microsoft-clarity",iconPath="/static/services/microsoft_clarity.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="num_of_days",+ label="Reporting window",+ required=True,+ defaultValue=DEFAULT_NUM_OF_DAYS,+ options=[+ SourceFieldSelectConfigOption(label="Last 24 hours", value="1"),+ SourceFieldSelectConfigOption(label="Last 48 hours", value="2"),+ SourceFieldSelectConfigOption(label="Last 72 hours", value="3"),+ ],+ ),+ SourceFieldSelectConfig(+ name="dimension1",+ label="Breakdown dimension 1 (optional)",+ required=False,+ defaultValue=NO_DIMENSION,+ options=_dimension_options(),+ ),+ SourceFieldSelectConfig(+ name="dimension2",+ label="Breakdown dimension 2 (optional)",+ required=False,+ defaultValue=NO_DIMENSION,+ options=_dimension_options(),+ ),+ SourceFieldSelectConfig(+ name="dimension3",+ label="Breakdown dimension 3 (optional)",+ required=False,+ defaultValue=NO_DIMENSION,+ options=_dimension_options(),+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.pynew file mode 100644index 000000000000..a0d3595b538a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity.py@@ -0,0 +1,219 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.microsoft_clarity import (+ BASE_URL,+ INSIGHTS_PATH,+ _build_params,+ _resolve_dimensions,+ microsoft_clarity_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.settings import (+ ENDPOINT_NAME,+ NO_DIMENSION,+)++SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.microsoft_clarity.make_tracked_session"+++def _make_response(status_code: int, *, json_body: Any = None, text: str | None = None) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response.url = f"{BASE_URL}{INSIGHTS_PATH}"+ if json_body is not None:+ response._content = json.dumps(json_body).encode()+ elif text is not None:+ response._content = text.encode()+ else:+ response._content = b""+ return response+++class TestBuildParams:+ def test_no_dimensions(self) -> None:+ assert _build_params("1", []) == {"numOfDays": "1"}++ def test_with_dimensions_numbered_in_order(self) -> None:+ params = _build_params("2", ["OS", "Browser"])+ assert params == {"numOfDays": "2", "dimension1": "OS", "dimension2": "Browser"}+++class TestResolveDimensions:+ def test_all_none_returns_empty(self) -> None:+ assert _resolve_dimensions(NO_DIMENSION, NO_DIMENSION, NO_DIMENSION) == []++ def test_none_values_are_skipped(self) -> None:+ assert _resolve_dimensions(None, None, None) == []++ def test_selected_dimensions_are_kept_in_order(self) -> None:+ assert _resolve_dimensions("OS", "Browser", NO_DIMENSION) == ["OS", "Browser"]++ def test_gap_in_selection_is_compacted(self) -> None:+ assert _resolve_dimensions("OS", NO_DIMENSION, "Device") == ["OS", "Device"]++ def test_duplicate_selection_is_deduplicated(self) -> None:+ assert _resolve_dimensions("OS", "OS", "Device") == ["OS", "Device"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, [], True, None),+ ("unauthorized", 401, None, False, "Invalid or expired Microsoft Clarity API token."),+ ("forbidden", 403, None, False, "This Microsoft Clarity API token is not authorized for this project."),+ ("quota_exceeded_still_valid", 429, None, True, None),+ ("unexpected_status", 400, None, False, "Microsoft Clarity returned status 400."),+ ]+ )+ @mock.patch(SESSION_PATCH)+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ json_body: Any,+ expected_valid: bool,+ expected_error: str | None,+ MockSession: Any,+ ) -> None:+ session = MockSession.return_value+ session.get.return_value = _make_response(status, json_body=json_body)++ valid, error = validate_credentials("token")++ assert valid is expected_valid+ assert error == expected_error++ @mock.patch(SESSION_PATCH)+ def test_transport_exception_is_invalid(self, MockSession: Any) -> None:+ session = MockSession.return_value+ session.get.side_effect = requests.ConnectionError("down")++ valid, error = validate_credentials("token")++ assert valid is False+ assert error == "Could not reach Microsoft Clarity. Please try again."+++SAMPLE_PAYLOAD = [+ {+ "metricName": "Traffic",+ "information": [+ {+ "totalSessionCount": "9554",+ "totalBotSessionCount": "8369",+ "distantUserCount": "189733",+ "PagesPerSessionPercentage": 1.0931,+ "OS": "Other",+ },+ {+ "totalSessionCount": "291942",+ "totalBotSessionCount": "31076",+ "distantUserCount": "212836",+ "PagesPerSessionPercentage": 2.2609,+ "OS": "Android",+ },+ ],+ },+ {+ "metricName": "ScrollDepth",+ "information": [{"averageScrollDepthPercentage": 45.2, "OS": "Other"}],+ },+]+++class TestMicrosoftClaritySource:+ @freeze_time("2026-07-23T12:00:00Z")+ @mock.patch(SESSION_PATCH)+ def test_flattens_every_metric_and_information_row(self, MockSession: Any) -> None:+ session = MockSession.return_value+ session.get.return_value = _make_response(200, json_body=SAMPLE_PAYLOAD)++ response = microsoft_clarity_source(+ token="token", num_of_days="1", dimension1="OS", dimension2=NO_DIMENSION, dimension3=NO_DIMENSION+ )+ rows = list(cast("Iterable[Any]", response.items()))++ assert len(rows) == 3+ assert rows[0]["metric_name"] == "Traffic"+ assert rows[0]["row_index"] == 0+ assert rows[0]["OS"] == "Other"+ assert rows[0]["synced_at"] == "2026-07-23T12:00:00+00:00"+ assert rows[1]["metric_name"] == "Traffic"+ assert rows[1]["row_index"] == 1+ assert rows[1]["OS"] == "Android"+ assert rows[2]["metric_name"] == "ScrollDepth"+ assert rows[2]["row_index"] == 0++ @mock.patch(SESSION_PATCH)+ def test_num_of_days_is_recorded_on_every_row(self, MockSession: Any) -> None:+ session = MockSession.return_value+ session.get.return_value = _make_response(200, json_body=SAMPLE_PAYLOAD)++ response = microsoft_clarity_source(+ token="token", num_of_days="3", dimension1=NO_DIMENSION, dimension2=NO_DIMENSION, dimension3=NO_DIMENSION+ )+ rows = list(cast("Iterable[Any]", response.items()))++ assert all(row["num_of_days"] == 3 for row in rows)++ @mock.patch(SESSION_PATCH)+ def test_source_response_shape(self, MockSession: Any) -> None:+ session = MockSession.return_value+ session.get.return_value = _make_response(200, json_body=SAMPLE_PAYLOAD)++ response = microsoft_clarity_source(+ token="token", num_of_days="1", dimension1=NO_DIMENSION, dimension2=NO_DIMENSION, dimension3=NO_DIMENSION+ )++ assert response.name == ENDPOINT_NAME+ assert response.primary_keys == ["metric_name", "synced_at", "row_index"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["synced_at"]++ @mock.patch(SESSION_PATCH)+ def test_dimension_params_are_sent_to_the_api(self, MockSession: Any) -> None:+ session = MockSession.return_value+ session.get.return_value = _make_response(200, json_body=[])++ microsoft_clarity_source(+ token="token", num_of_days="2", dimension1="Browser", dimension2="Device", dimension3=NO_DIMENSION+ )++ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"numOfDays": "2", "dimension1": "Browser", "dimension2": "Device"}++ @mock.patch(SESSION_PATCH)+ def test_non_list_payload_yields_no_rows(self, MockSession: Any) -> None:+ session = MockSession.return_value+ session.get.return_value = _make_response(200, json_body={"unexpected": "shape"})++ response = microsoft_clarity_source(+ token="token", num_of_days="1", dimension1=NO_DIMENSION, dimension2=NO_DIMENSION, dimension3=NO_DIMENSION+ )++ assert list(cast("Iterable[Any]", response.items())) == []++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("quota_exceeded", 429), ("server_error", 500)])+ @mock.patch(SESSION_PATCH)+ def test_error_status_raises(self, _name: str, status: int, MockSession: Any) -> None:+ session = MockSession.return_value+ session.get.return_value = _make_response(status, text="boom")++ with pytest.raises(requests.HTTPError):+ microsoft_clarity_source(+ token="token",+ num_of_days="1",+ dimension1=NO_DIMENSION,+ dimension2=NO_DIMENSION,+ dimension3=NO_DIMENSION,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity_source.pynew file mode 100644index 000000000000..183a2cf0d04d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/microsoft_clarity/tests/test_microsoft_clarity_source.py@@ -0,0 +1,192 @@+from types import SimpleNamespace+from typing import Any++from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.settings import (+ DIMENSION_OPTIONS,+ ENDPOINT_NAME,+ ENDPOINTS,+ NO_DIMENSION,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.microsoft_clarity.source import (+ MicrosoftClaritySource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(+ api_token: str = "token",+ num_of_days: str = "1",+ dimension1: str | None = NO_DIMENSION,+ dimension2: str | None = NO_DIMENSION,+ dimension3: str | None = NO_DIMENSION,+) -> Any:+ return SimpleNamespace(+ api_token=api_token,+ num_of_days=num_of_days,+ dimension1=dimension1,+ dimension2=dimension2,+ dimension3=dimension3,+ )+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert MicrosoftClaritySource().source_type == ExternalDataSourceType.MICROSOFTCLARITY++ def test_get_source_config(self) -> None:+ config = MicrosoftClaritySource().get_source_config+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.fields is not None+ assert len(config.fields) == 5++ token_field = config.fields[0]+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.name == "api_token"+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True++ def test_num_of_days_field_options(self) -> None:+ config = MicrosoftClaritySource().get_source_config+ num_of_days_field = next(f for f in config.fields if f.name == "num_of_days")+ assert isinstance(num_of_days_field, SourceFieldSelectConfig)+ assert num_of_days_field.required is True+ assert num_of_days_field.defaultValue == "1"+ assert {option.value for option in num_of_days_field.options} == {"1", "2", "3"}++ @parameterized.expand([("dimension1",), ("dimension2",), ("dimension3",)])+ def test_dimension_fields_are_optional_with_none_default(self, field_name: str) -> None:+ config = MicrosoftClaritySource().get_source_config+ dimension_field = next(f for f in config.fields if f.name == field_name)+ assert isinstance(dimension_field, SourceFieldSelectConfig)+ assert dimension_field.required is False+ assert dimension_field.defaultValue == NO_DIMENSION+ option_values = {option.value for option in dimension_field.options}+ assert option_values == {NO_DIMENSION, *DIMENSION_OPTIONS}+++class TestGetSchemas:+ def test_returns_single_endpoint(self) -> None:+ schemas = MicrosoftClaritySource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert ENDPOINTS == (ENDPOINT_NAME,)++ def test_filters_by_names(self) -> None:+ schemas = MicrosoftClaritySource().get_schemas(MagicMock(), team_id=1, names=[ENDPOINT_NAME])+ assert {s.name for s in schemas} == {ENDPOINT_NAME}++ schemas = MicrosoftClaritySource().get_schemas(MagicMock(), team_id=1, names=["not-a-real-endpoint"])+ assert schemas == []++ def test_endpoint_is_append_only_not_incremental(self) -> None:+ # The API has no server-side "since" filter, so this must never be treated as truly+ # incremental — but it should still append daily snapshots rather than overwrite them.+ schema = MicrosoftClaritySource().get_schemas(MagicMock(), team_id=1)[0]+ assert schema.supports_incremental is False+ assert schema.supports_append is True+ assert [f["field"] for f in schema.incremental_fields] == ["synced_at"]+++class TestValidateCredentials:+ def test_success(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(source_module, "validate_clarity_credentials", lambda *a, **k: (True, None))+ valid, error = MicrosoftClaritySource().validate_credentials(_config(), team_id=1)+ assert valid is True+ assert error is None++ def test_failure(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(+ source_module, "validate_clarity_credentials", lambda *a, **k: (False, "Invalid or expired token")+ )+ valid, error = MicrosoftClaritySource().validate_credentials(_config(), team_id=1)+ assert valid is False+ assert error == "Invalid or expired token"++ def test_passes_configured_token(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_validate(token: str) -> tuple[bool, str | None]:+ captured["token"] = token+ return True, None++ monkeypatch.setattr(source_module, "validate_clarity_credentials", fake_validate)+ MicrosoftClaritySource().validate_credentials(_config(api_token="my-token"), team_id=1)+ assert captured["token"] == "my-token"+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://www.clarity.ms/export-data/api/v1/project-live-insights",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://www.clarity.ms/export-data/api/v1/project-live-insights",+ ),+ (+ "quota_exceeded",+ "429 Client Error: Too Many Requests for url: https://www.clarity.ms/export-data/api/v1/project-live-insights",+ ),+ ]+ )+ def test_known_error_is_non_retryable(self, _name: str, observed: str) -> None:+ errors = MicrosoftClaritySource().get_non_retryable_errors()+ assert any(key in observed for key in errors)++ def test_transient_error_remains_retryable(self) -> None:+ errors = MicrosoftClaritySource().get_non_retryable_errors()+ observed = "HTTPSConnectionPool(host='www.clarity.ms', port=443): Read timed out."+ assert not any(key in observed for key in errors)+++class TestCanonicalDescriptions:+ def test_covers_the_endpoint(self) -> None:+ descriptions = MicrosoftClaritySource().get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)+ assert "docs_url" in descriptions[ENDPOINT_NAME]+++class TestSourceForPipeline:+ def test_plumbs_config_into_transport(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}+ sentinel = object()++ def fake_source(**kwargs: Any) -> Any:+ captured.update(kwargs)+ return sentinel++ monkeypatch.setattr(source_module, "microsoft_clarity_source", fake_source)++ inputs = SimpleNamespace(schema_name=ENDPOINT_NAME, team_id=1, job_id="job", logger=MagicMock())+ result = MicrosoftClaritySource().source_for_pipeline(+ _config(+ api_token="tok", num_of_days="3", dimension1="OS", dimension2=NO_DIMENSION, dimension3=NO_DIMENSION+ ),+ inputs, # type: ignore[arg-type]+ )++ assert result is sentinel+ assert captured == {+ "token": "tok",+ "num_of_days": "3",+ "dimension1": "OS",+ "dimension2": NO_DIMENSION,+ "dimension3": NO_DIMENSION,+ }