Skip to content

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

feat(data-warehouse): implement metorial import source (#69616)

Tom Owersf7cc74bec49c
diff --git a/frontend/public/services/metorial.png b/frontend/public/services/metorial.png
new file mode 100644
index 000000000000..0286494297ef
Binary files /dev/null and b/frontend/public/services/metorial.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 2a02b1e8e836..37497a78a2d6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -243,6 +243,7 @@ the row lists both.
| mention | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
| metabase | HTTP | requests | ✅ |
+| metorial | HTTP | requests | ✅ |
| mixmax | HTTP | requests | ✅ |
| mixpanel | HTTP | requests | ✅ |
| mollie | HTTP | requests | ✅ |
@@ -640,7 +641,6 @@ doesn't conflict with concurrent PRs.
- mercado_ads
- mercury
- merge
-- metorial
- metricool
- metriport
- metronome
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index c4f760a17ed4..c3e293f62a67 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2284,7 +2284,7 @@ class MetabaseSourceConfig(config.Config):
@config.config
class MetorialSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/canonical_descriptions.py
new file mode 100644
index 000000000000..6091404e5b85
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/canonical_descriptions.py
@@ -0,0 +1,143 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official Metorial API reference (https://metorial.com/api).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "sessions": {
+ "description": "An MCP session on Metorial — a client connection to one or more deployed MCP providers, with usage counters and error/warning flags.",
+ "docs_url": "https://metorial.com/api/sessions",
+ "columns": {
+ "id": "Unique session identifier (e.g. ses_...).",
+ "status": "Session status: active, archived, or deleted.",
+ "name": "Optional display name of the session.",
+ "description": "Optional description of the session.",
+ "metadata": "Custom key-value pairs attached to the session.",
+ "connection_state": "Whether the session is currently connected or disconnected.",
+ "connection_url": "MCP connection URL for the session.",
+ "usage": "Usage counters: total productive client and provider message counts.",
+ "providers": "Providers attached to the session, including deployment, config, and auth config references.",
+ "from_templates_ids": "Session template ids this session was created from.",
+ "has_errors": "Whether the session has recorded errors.",
+ "has_warnings": "Whether the session has recorded warnings.",
+ "identity_id": "Identity associated with the session, if any.",
+ "identity_actor_id": "Identity actor associated with the session, if any.",
+ "created_at": "When the session was created.",
+ "updated_at": "When the session was last updated.",
+ },
+ },
+ "session_messages": {
+ "description": "A single message exchanged within an MCP session, including MCP protocol messages and tool calls.",
+ "docs_url": "https://metorial.com/api/session-messages",
+ "columns": {
+ "id": "Unique message identifier (e.g. smg_...).",
+ "type": "Message type: tool_call, mcp_control, mcp_message, or unknown.",
+ "status": "Message status: waiting_for_response, failed, or succeeded.",
+ "source": "Whether the message came from the client or the provider.",
+ "session_id": "The session this message belongs to.",
+ "session_provider_id": "The session provider that handled the message, if any.",
+ "connection_id": "The session connection the message was sent over, if any.",
+ "provider_run_id": "The provider run that processed the message, if any.",
+ "hierarchy": "Parent/child relationship of the message (parent_message_id, child_message_ids).",
+ "transport": "Transport details: mcp, tool_call, metorial_protocol, or system.",
+ "input": "Message input payload, if any.",
+ "output": "Message output payload, if any.",
+ "tool_call": "Full tool call details when the message is a tool call.",
+ "sender_participant": "Participant that sent the message.",
+ "responder_participant": "Participant that responded to the message, if any.",
+ "error": "Session error attached to the message, if any.",
+ "created_at": "When the message was created.",
+ },
+ },
+ "session_errors": {
+ "description": "An error recorded during an MCP session, grouped with similar errors for triage.",
+ "docs_url": "https://metorial.com/api/session-errors",
+ "columns": {
+ "id": "Unique error identifier (e.g. ser_...).",
+ "code": "Machine-readable error code (e.g. CONNECTION_TIMEOUT).",
+ "message": "Human-readable error message.",
+ "data": "Structured error payload.",
+ "status": "Whether error grouping has finished: processing or processed.",
+ "session_id": "The session the error occurred in.",
+ "provider_run_id": "The provider run the error occurred in, if any.",
+ "connection_id": "The session connection the error occurred on, if any.",
+ "group_id": "The error group this error was assigned to, if any.",
+ "similar_error_count": "Number of similar errors in the same group.",
+ "created_at": "When the error was recorded.",
+ },
+ },
+ "tool_calls": {
+ "description": "A tool call made within an MCP session, with the tool, input, output, and any error.",
+ "docs_url": "https://metorial.com/api/tool-calls",
+ "columns": {
+ "id": "Unique tool call identifier (e.g. tcl_...).",
+ "tool_key": "Key of the tool that was called.",
+ "type": "Call type: tool_call, mcp_control, mcp_message, or unknown.",
+ "status": "Call status: waiting_for_response, failed, or succeeded.",
+ "source": "Whether the call came from the client or the provider.",
+ "transport": "Transport used: tool_call, mcp, metorial_protocol, or system.",
+ "session_id": "The session the tool call belongs to.",
+ "message_id": "The session message carrying the tool call.",
+ "session_provider_id": "The session provider that handled the call, if any.",
+ "connection_id": "The session connection the call was made over, if any.",
+ "provider_run_id": "The provider run that executed the call, if any.",
+ "tool": "Details of the tool that was called.",
+ "input": "Tool call input payload, if any.",
+ "output": "Tool call output payload, if any.",
+ "error": "Error attached to the call, if any.",
+ "created_at": "When the tool call was made.",
+ },
+ },
+ "provider_runs": {
+ "description": "A run of a deployed MCP provider serving a session — the unit of provider execution.",
+ "docs_url": "https://metorial.com/api/provider-runs",
+ "columns": {
+ "id": "Unique provider run identifier (e.g. prn_...).",
+ "status": "Run status: running or stopped.",
+ "session_id": "The session the run served.",
+ "session_provider_id": "The session provider the run belongs to.",
+ "provider_id": "The provider that was run.",
+ "connection_id": "The session connection the run served, if any.",
+ "completed_at": "When the run completed, if it has.",
+ "created_at": "When the run started.",
+ "updated_at": "When the run was last updated.",
+ },
+ },
+ "provider_deployments": {
+ "description": "A deployment of an MCP provider — the configured, runnable instance sessions connect to.",
+ "docs_url": "https://metorial.com/api/provider-deployments",
+ "columns": {
+ "id": "Unique deployment identifier (e.g. pde_...).",
+ "status": "Deployment status: active, archived, or deleted.",
+ "is_default": "Whether this is the provider's default deployment.",
+ "name": "Optional display name of the deployment.",
+ "description": "Optional description of the deployment.",
+ "metadata": "Custom key-value pairs attached to the deployment.",
+ "tool_filter": "Tool filter applied to the deployment (allow-all or explicit filters).",
+ "provider_id": "The provider this deployment belongs to.",
+ "locked_version": "Provider version the deployment is pinned to, if any.",
+ "default_config": "Default provider config used by the deployment, if any.",
+ "created_at": "When the deployment was created.",
+ "updated_at": "When the deployment was last updated.",
+ },
+ },
+ "providers": {
+ "description": "An MCP provider available to the project — a server in Metorial's catalog or a custom one.",
+ "docs_url": "https://metorial.com/api/providers",
+ "columns": {
+ "id": "Unique provider identifier.",
+ "access": "Whether the provider is public or tenant-scoped.",
+ "status": "Provider status: active, archived, or deleted.",
+ "publisher": "Publisher of the provider (name, description, image).",
+ "current_version": "The provider's current version, if any.",
+ "oauth": "OAuth configuration status for the provider, if any.",
+ "identifier": "Stable provider identifier.",
+ "name": "Display name of the provider.",
+ "description": "Description of the provider.",
+ "slug": "URL-friendly identifier.",
+ "metadata": "Custom key-value pairs attached to the provider.",
+ "created_at": "When the provider was created.",
+ "updated_at": "When the provider was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/metorial.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/metorial.py
new file mode 100644
index 000000000000..08bdeca82d38
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/metorial.py
@@ -0,0 +1,213 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.settings import (
+ METORIAL_BASE_URL,
+ METORIAL_ENDPOINTS,
+ PAGE_SIZE,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+# Production keys allow 5000 requests / 10 min (development keys only 100 / 10 min), so a large
+# backfill can hit 429s — back off generously rather than failing the sync.
+RETRY_ATTEMPTS = 6
+RETRY_MAX_WAIT_SECONDS = 120
+
+
+class MetorialRetryableError(Exception):
+ pass
+
+
+class MetorialResumeConfig:
+ # `after` cursor for the next page: the id of the last record already yielded. None starts at
+ # page one. Metorial pages by record id, so the cursor stays valid across a crash/retry.
+ after: str | None = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _format_watermark(value: Any) -> str:
+ """Format the incremental watermark for Metorial's `<field>[gt]` filter.
+
+ Truncates to whole seconds, rounding the lower bound *down* — an incremental sync re-fetches at
+ most a few boundary rows (merge dedupes them on `id`) rather than skipping any.
+
+ Accepts the shapes the pipeline can hand back for a DateTime field (datetime/date, ISO-8601
+ string, epoch seconds) and raises for anything else — a malformed filter value would make
+ Metorial silently return unfiltered/unexpected results rather than erroring.
+ """
+ if isinstance(value, str):
+ try:
+ value = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ raise ValueError(f"Unsupported Metorial incremental watermark value: {value!r}")
+ elif isinstance(value, int | float) and not isinstance(value, bool):
+ value = datetime.fromtimestamp(value, tz=UTC)
+
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ raise ValueError(f"Unsupported Metorial incremental watermark value: {value!r}")
+ return normalized.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _build_url(
+ path: str,
+ after: str | None,
+ incremental_field: str | None,
+ db_incremental_field_last_value: Any,
+) -> str:
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "order": "asc"}
+ if after:
+ params["after"] = after
+ if incremental_field and db_incremental_field_last_value is not None:
+ # Metorial parses the query string with `qs`, so the nested date filter uses bracket
+ # syntax: `created_at[gt]=...` -> `{created_at: {gt: ...}}`. The filter is a plain
+ # where-clause resent on every page, so pagination terminates at the watermark server-side.
+ params[f"{incremental_field}[gt]"] = _format_watermark(db_incremental_field_last_value)
+ return f"{METORIAL_BASE_URL}{path}?{urlencode(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type((MetorialRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=RETRY_MAX_WAIT_SECONDS),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], bool]:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MetorialRetryableError(f"Metorial API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Metorial API error: status={response.status_code}, body={response.text[:200]!r}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ if not isinstance(data, dict) or not isinstance(data.get("items"), list):
+ raise MetorialRetryableError(f"Metorial returned an unexpected payload for {url}: {type(data).__name__}")
+
+ pagination = data.get("pagination") or {}
+ return data["items"], bool(pagination.get("has_more_after"))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MetorialResumeConfig],
+ incremental_field: str | None = None,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = METORIAL_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ after = resume.after if resume is not None else None
+ if after:
+ logger.debug(f"Metorial: resuming {endpoint} from after={after}")
+
+ while True:
+ url = _build_url(config.path, after, incremental_field, db_incremental_field_last_value)
+ items, has_more_after = _fetch_page(session, url, logger)
+
+ if items:
+ yield items
+
+ if not has_more_after or not items:
+ break
+
+ last_id = items[-1].get("id")
+ if not isinstance(last_id, str) or not last_id or last_id == after:
+ # Defensive: without an advancing id cursor we'd refetch the same page forever.
+ logger.warning(f"Metorial: {endpoint} page did not advance the `after` cursor, stopping")
+ break
+
+ after = last_id
+ # Save AFTER yielding so a crash re-fetches from the last yielded page's cursor (never
+ # skipping a page); merge dedupes any re-pulled rows on the `id` primary key.
+ resumable_source_manager.save_state(MetorialResumeConfig(after=after))
+
+
+def metorial_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MetorialResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = METORIAL_ENDPOINTS[endpoint]
+
+ chosen_field = incremental_field if should_use_incremental_field else None
+ if chosen_field is not None:
+ allowed = {f["field"] for f in config.incremental_fields}
+ if chosen_field not in allowed:
+ raise ValueError(f"Incremental field '{chosen_field}' is not supported for Metorial '{endpoint}'")
+
+ # `order=asc` sorts by record id, and Metorial ids are time-sorted, so `created_at` arrives
+ # ascending and the pipeline's per-batch watermark checkpointing is safe. `updated_at` is NOT
+ # monotonic in id order, so those syncs declare `desc` — the pipeline then commits the
+ # watermark only when the run completes, never mid-run past unseen rows.
+ sort_mode: SortMode = "asc" if chosen_field in (None, "created_at") else "desc"
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ incremental_field=chosen_field,
+ db_incremental_field_last_value=db_incremental_field_last_value if chosen_field else None,
+ ),
+ primary_keys=list(config.primary_keys),
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode=sort_mode,
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ # One cheap probe confirms the key is genuine. Secret keys are project-scoped with full read
+ # access, so a single endpoint validates every stream; 401/403 are the only conclusive
+ # "invalid" signals (429/5xx would push users to rotate a working key, so they get a retry
+ # message instead).
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{METORIAL_BASE_URL}/sessions?{urlencode({'limit': 1})}", timeout=15)
+ except requests.RequestException:
+ return False, "Could not reach Metorial to validate the API key. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid Metorial API key. Use a secret key (`metorial_sk_...`) from your project dashboard."
+ return (
+ False,
+ f"Metorial could not validate the API key right now (status {response.status_code}). Please try again.",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/settings.py
new file mode 100644
index 000000000000..469722660715
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/settings.py
@@ -0,0 +1,88 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Single base URL for every project — Metorial has no regional hosts; the API key is
+# project-scoped, so the project is inferred from the key.
+METORIAL_BASE_URL = "https://api.metorial.com"
+
+# Metorial's paginator caps `limit` at 100 server-side.
+PAGE_SIZE = 100
+
+_CREATED_AT_INCREMENTAL: IncrementalField = {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+_UPDATED_AT_INCREMENTAL: IncrementalField = {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+
+@dataclass
+class MetorialEndpointConfig:
+ name: str
+ path: str
+ # Fields with a genuine server-side `<field>[gt]` date-range filter on the list endpoint,
+ # AND present on the response object (the pipeline computes the watermark from row values).
+ # Empty list = full refresh only.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Metorial ids are globally unique (type-prefixed, e.g. `ses_...`), so `id` is safe table-wide.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # `created_at` never changes once a record exists, unlike `updated_at`, so partitions are stable.
+ partition_key: str | None = "created_at"
+
+
+# Warehouse-worthy Metorial streams: the MCP-session observability resources (sessions, their
+# messages/errors/tool calls, provider runs) plus the provider catalog and deployments.
+# `session_messages`, `session_errors`, and `tool_calls` objects expose no `updated_at` field, so
+# they sync incrementally on `created_at` (append-only); `providers` has no date filters at all.
+METORIAL_ENDPOINTS: dict[str, MetorialEndpointConfig] = {
+ "sessions": MetorialEndpointConfig(
+ name="sessions",
+ path="/sessions",
+ incremental_fields=[_UPDATED_AT_INCREMENTAL, _CREATED_AT_INCREMENTAL],
+ ),
+ "session_messages": MetorialEndpointConfig(
+ name="session_messages",
+ path="/session-messages",
+ incremental_fields=[_CREATED_AT_INCREMENTAL],
+ ),
+ "session_errors": MetorialEndpointConfig(
+ name="session_errors",
+ path="/session-errors",
+ incremental_fields=[_CREATED_AT_INCREMENTAL],
+ ),
+ "tool_calls": MetorialEndpointConfig(
+ name="tool_calls",
+ path="/tool-calls",
+ incremental_fields=[_CREATED_AT_INCREMENTAL],
+ ),
+ "provider_runs": MetorialEndpointConfig(
+ name="provider_runs",
+ path="/provider-runs",
+ incremental_fields=[_UPDATED_AT_INCREMENTAL, _CREATED_AT_INCREMENTAL],
+ ),
+ "provider_deployments": MetorialEndpointConfig(
+ name="provider_deployments",
+ path="/provider-deployments",
+ incremental_fields=[_UPDATED_AT_INCREMENTAL, _CREATED_AT_INCREMENTAL],
+ ),
+ "providers": MetorialEndpointConfig(
+ name="providers",
+ path="/providers",
+ # `GET /providers` accepts no `created_at`/`updated_at` filters, so full refresh only.
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(METORIAL_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in METORIAL_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/source.py
index 437b44fa125d..ad256a7ffc7f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/source.py
@@ -1,31 +1,144 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MetorialSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.metorial import (
+ MetorialResumeConfig,
+ metorial_source,
+ validate_credentials as validate_metorial_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MetorialSource(SimpleSource[MetorialSourceConfig]):
+class MetorialSource(ResumableSource[MetorialSourceConfig, MetorialResumeConfig]):
+ """Metorial (MCP hosting platform) import source.
+
+ Pull-only: Metorial's callback destinations are CRUD-manageable webhooks, but they deliver
+ provider *trigger* events (e.g. an upstream MCP provider's `message.created`), not change
+ events for the resources we sync — so the WebhookSource mixin doesn't apply here.
+ """
+
+ # Static endpoint catalog with no I/O — safe to render in public docs.
+ lists_tables_without_credentials = True
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.METORIAL
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid or expired Metorial API key. Please generate a new secret key and reconnect.",
+ "403 Client Error": "Your Metorial API key does not have the required permissions. Use a secret key (metorial_sk_...) from your project dashboard.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: MetorialSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas: list[SourceSchema] = []
+ for endpoint in ENDPOINTS:
+ if names is not None and endpoint not in names:
+ continue
+
+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint, [])
+ supports_incremental = bool(incremental_fields)
+ schemas.append(
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=supports_incremental,
+ supports_append=supports_incremental,
+ incremental_fields=incremental_fields,
+ )
+ )
+ return schemas
+
+ def validate_credentials(
+ self, config: MetorialSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_metorial_credentials(api_key=config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MetorialResumeConfig]:
+ return ResumableSourceManager[MetorialResumeConfig](inputs, MetorialResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MetorialSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MetorialResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return metorial_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.METORIAL,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Metorial",
+ caption="""Sync MCP sessions, messages, tool calls, errors, provider runs, providers, and deployments from your Metorial project.
+
+Use a **secret** API key (`metorial_sk_...`) generated from your Metorial dashboard — publishable keys (`metorial_pk_...`) cannot read project data.
+""",
+ docsUrl="https://posthog.com/docs/cdp/sources/metorial",
iconPath="/static/services/metorial.png",
keywords=["mcp", "ai infrastructure", "agents", "observability"],
- fields=cast(list[FieldType], []),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="metorial_sk_...",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/tests/test_metorial.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/tests/test_metorial.py
new file mode 100644
index 000000000000..535c3f07cc76
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/tests/test_metorial.py
@@ -0,0 +1,306 @@
+from datetime import UTC, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial import metorial
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.metorial import (
+ MetorialResumeConfig,
+ MetorialRetryableError,
+ _build_url,
+ get_rows,
+ metorial_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.settings import (
+ ENDPOINTS,
+ METORIAL_BASE_URL,
+ METORIAL_ENDPOINTS,
+ PAGE_SIZE,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = metorial._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: MetorialResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[MetorialResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> MetorialResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: MetorialResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+class TestBuildUrl:
+ def test_first_page_has_limit_and_asc_order_but_no_cursor(self) -> None:
+ url = _build_url("/sessions", after=None, incremental_field=None, db_incremental_field_last_value=None)
+ assert url.startswith(f"{METORIAL_BASE_URL}/sessions?")
+ query = _query(url)
+ assert query["limit"] == [str(PAGE_SIZE)]
+ assert query["order"] == ["asc"]
+ assert "after" not in query
+
+ def test_after_cursor_is_sent(self) -> None:
+ url = _build_url("/sessions", after="ses_123", incremental_field=None, db_incremental_field_last_value=None)
+ assert _query(url)["after"] == ["ses_123"]
+
+ @parameterized.expand(
+ [
+ # Sub-second precision must be truncated DOWN so boundary rows are re-fetched, never skipped.
+ ("aware_datetime", datetime(2025, 6, 1, 12, 30, 45, 999999, tzinfo=UTC), "2025-06-01T12:30:45Z"),
+ ("naive_datetime", datetime(2025, 6, 1, 12, 30, 45), "2025-06-01T12:30:45Z"),
+ # The pipeline can hand the stored watermark back as an ISO-8601 string or epoch seconds.
+ ("iso_string_z", "2025-06-01T12:30:45.999Z", "2025-06-01T12:30:45Z"),
+ ("iso_string_offset", "2025-06-01T14:30:45+02:00", "2025-06-01T12:30:45Z"),
+ ("epoch_seconds", 1748781045, "2025-06-01T12:30:45Z"),
+ ]
+ )
+ def test_incremental_filter_uses_bracket_gt_syntax(self, _name: str, watermark: Any, expected: str) -> None:
+ url = _build_url(
+ "/sessions", after=None, incremental_field="updated_at", db_incremental_field_last_value=watermark
+ )
+ assert _query(url)["updated_at[gt]"] == [expected]
+
+ def test_unparseable_watermark_raises_instead_of_sending_garbage(self) -> None:
+ # A malformed filter value would make Metorial silently return unexpected results.
+ with pytest.raises(ValueError, match="Unsupported Metorial incremental watermark"):
+ _build_url(
+ "/sessions", after=None, incremental_field="updated_at", db_incremental_field_last_value="not-a-date"
+ )
+
+ def test_no_filter_when_watermark_is_none(self) -> None:
+ url = _build_url("/sessions", after=None, incremental_field="updated_at", db_incremental_field_last_value=None)
+ assert "updated_at" not in _query(url)
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = (
+ body if body is not None else {"items": [], "pagination": {"has_more_after": False}}
+ )
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])
+ def test_transient_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(MetorialRetryableError):
+ _fetch_page_unwrapped(session, f"{METORIAL_BASE_URL}/sessions", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, f"{METORIAL_BASE_URL}/sessions", MagicMock())
+
+ def test_success_returns_items_and_has_more_after(self) -> None:
+ body = {"items": [{"id": "ses_1"}], "pagination": {"has_more_after": True, "has_more_before": False}}
+ session = self._session_returning(200, body)
+ items, has_more = _fetch_page_unwrapped(session, f"{METORIAL_BASE_URL}/sessions", MagicMock())
+ assert items == [{"id": "ses_1"}]
+ assert has_more is True
+
+ @parameterized.expand([("bare_list", [{"id": "a"}]), ("missing_items", {"pagination": {}})])
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(MetorialRetryableError):
+ _fetch_page_unwrapped(session, f"{METORIAL_BASE_URL}/sessions", MagicMock())
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[Optional[str], tuple[list[dict], bool]],
+ endpoint: str = "sessions",
+ incremental_field: str | None = None,
+ db_incremental_field_last_value: Any = None,
+ ) -> tuple[list[dict], list[str]]:
+ """Pages are keyed by the `after` cursor the request carries (None = first page)."""
+ requested_urls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> tuple[list[dict], bool]:
+ requested_urls.append(url)
+ after = _query(url).get("after", [None])[0]
+ return pages[after]
+
+ monkeypatch.setattr(metorial, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(metorial, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="metorial_sk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ incremental_field=incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ):
+ rows.extend(batch)
+ return rows, requested_urls
+
+ def test_single_page_yields_and_stops_without_saving_state(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, _ = self._collect(manager, monkeypatch, {None: ([{"id": "ses_1"}, {"id": "ses_2"}], False)})
+ assert rows == [{"id": "ses_1"}, {"id": "ses_2"}]
+ assert manager.saved == []
+
+ def test_follows_after_cursor_until_has_more_is_false(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ None: ([{"id": "ses_1"}], True),
+ "ses_1": ([{"id": "ses_2"}], True),
+ "ses_2": ([{"id": "ses_3"}], False),
+ }
+ rows, _ = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "ses_1"}, {"id": "ses_2"}, {"id": "ses_3"}]
+ # State is saved after each yielded page that has a successor, pointing at the next cursor.
+ assert [s.after for s in manager.saved] == ["ses_1", "ses_2"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(MetorialResumeConfig(after="ses_5"))
+ # The un-cursored first page must never be fetched on resume.
+ rows, urls = self._collect(manager, monkeypatch, {"ses_5": ([{"id": "ses_6"}], False)})
+ assert rows == [{"id": "ses_6"}]
+ assert len(urls) == 1
+
+ def test_stops_when_cursor_does_not_advance(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(MetorialResumeConfig(after="ses_1"))
+ # Server keeps claiming more pages but returns the same last id — must terminate, not loop.
+ rows, urls = self._collect(manager, monkeypatch, {"ses_1": ([{"id": "ses_1"}], True)})
+ assert rows == [{"id": "ses_1"}]
+ assert len(urls) == 1
+
+ def test_empty_page_with_has_more_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, _ = self._collect(manager, monkeypatch, {None: ([], True)})
+ assert rows == []
+
+ def test_incremental_watermark_is_sent_on_every_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ watermark = datetime(2025, 6, 1, tzinfo=UTC)
+ pages = {None: ([{"id": "ses_1"}], True), "ses_1": ([{"id": "ses_2"}], False)}
+ _, urls = self._collect(
+ manager,
+ monkeypatch,
+ pages,
+ incremental_field="updated_at",
+ db_incremental_field_last_value=watermark,
+ )
+ assert all(_query(url)["updated_at[gt]"] == ["2025-06-01T00:00:00Z"] for url in urls)
+
+
+class TestMetorialSource:
+ def _source(self, endpoint: str, **kwargs: Any):
+ return metorial_source(
+ api_key="metorial_sk_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ **kwargs,
+ )
+
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = self._source(endpoint)
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+
+ def test_full_refresh_and_created_at_use_asc_sort(self) -> None:
+ assert self._source("sessions").sort_mode == "asc"
+ assert (
+ self._source(
+ "sessions",
+ should_use_incremental_field=True,
+ incremental_field="created_at",
+ ).sort_mode
+ == "asc"
+ )
+
+ def test_updated_at_incremental_uses_desc_sort(self) -> None:
+ # `order=asc` sorts by id (creation order), which is NOT monotonic in updated_at — the
+ # pipeline must only commit the updated_at watermark at end of run.
+ response = self._source("sessions", should_use_incremental_field=True, incremental_field="updated_at")
+ assert response.sort_mode == "desc"
+
+ @parameterized.expand([("providers", "updated_at"), ("tool_calls", "updated_at"), ("sessions", "completed_at")])
+ def test_unsupported_incremental_field_is_rejected(self, endpoint: str, field: str) -> None:
+ with pytest.raises(ValueError, match="is not supported for Metorial"):
+ self._source(endpoint, should_use_incremental_field=True, incremental_field=field)
+
+ def test_partition_key_is_stable_created_at(self) -> None:
+ response = self._source("sessions")
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_mode == "datetime"
+
+ def test_incremental_fields_only_where_server_side_filter_exists(self) -> None:
+ # `/providers` has no created_at/updated_at list filters; every other stream does.
+ assert METORIAL_ENDPOINTS["providers"].incremental_fields == []
+ for name in set(ENDPOINTS) - {"providers"}:
+ fields = {f["field"] for f in METORIAL_ENDPOINTS[name].incremental_fields}
+ assert "created_at" in fields, name
+
+
+class TestValidateCredentials:
+ def _session(self, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, expected_valid: bool) -> None:
+ response = MagicMock()
+ response.status_code = status
+ with patch.object(metorial, "make_tracked_session", return_value=self._session(response)):
+ valid, message = validate_credentials("metorial_sk_test")
+ assert valid is expected_valid
+ assert (message is None) is expected_valid
+
+ def test_auth_failure_mentions_secret_key(self) -> None:
+ response = MagicMock()
+ response.status_code = 401
+ with patch.object(metorial, "make_tracked_session", return_value=self._session(response)):
+ _, message = validate_credentials("metorial_pk_wrong_key_type")
+ assert message is not None and "metorial_sk_" in message
+
+ def test_connection_error_returns_retry_message(self) -> None:
+ session = self._session(requests.ConnectionError("boom"))
+ with patch.object(metorial, "make_tracked_session", return_value=session):
+ valid, message = validate_credentials("metorial_sk_test")
+ assert valid is False
+ assert message is not None and "try again" in message.lower()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/tests/test_metorial_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/tests/test_metorial_source.py
new file mode 100644
index 000000000000..481488fa6767
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/tests/test_metorial_source.py
@@ -0,0 +1,160 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MetorialSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.metorial import MetorialResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.source import MetorialSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = (
+ "sessions",
+ "session_messages",
+ "session_errors",
+ "tool_calls",
+ "provider_runs",
+ "provider_deployments",
+)
+
+
+class TestMetorialSource:
+ def setup_method(self) -> None:
+ self.source = MetorialSource()
+ self.team_id = 123
+ self.config = MetorialSourceConfig(api_key="metorial_sk_test")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.METORIAL
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Metorial"
+ assert config.label == "Metorial"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/metorial"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another project.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand([(e,) for e in INCREMENTAL_ENDPOINTS])
+ def test_incremental_endpoints_advertise_incremental(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ assert schema.supports_incremental is True
+ assert schema.supports_append is True
+ assert {f["field"] for f in schema.incremental_fields} <= {"created_at", "updated_at"}
+
+ def test_providers_is_full_refresh_only(self) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == "providers")
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["sessions"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "sessions"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ sessions = next(t for t in tables if t["name"] == "sessions")
+ assert "Incremental" in sessions["sync_methods"]
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.metorial.com/sessions",),
+ ("403 Client Error: Forbidden for url: https://api.metorial.com/tool-calls",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.metorial.com/sessions",),
+ ("429 Client Error: Too Many Requests for url: https://api.metorial.com/sessions",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.metorial.source.validate_metorial_credentials"
+ )
+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (False, "Invalid Metorial API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ assert result == (False, "Invalid Metorial API key")
+ mock_validate.assert_called_once_with(api_key="metorial_sk_test")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MetorialResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.metorial.source.metorial_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "sessions"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "updated_at"
+ inputs.db_incremental_field_last_value = "2025-06-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "metorial_sk_test"
+ assert kwargs["endpoint"] == "sessions"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["incremental_field"] == "updated_at"
+ assert kwargs["db_incremental_field_last_value"] == "2025-06-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.metorial.source.metorial_source")
+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ # A stale watermark left on the schema must not leak into a full-refresh sync as a filter.
+ inputs = mock.MagicMock()
+ inputs.schema_name = "sessions"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2025-06-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ inputs.should_use_incremental_field = False
+ with pytest.raises(KeyError):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)