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 (#70029)

Tom Owers99916cc16a31
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
index 6091404e5b85..258f17285eca 100644
--- 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
@@ -1,143 +1,134 @@
+"""Canonical, documentation-sourced descriptions for Metorial endpoints and columns.
+
+Sourced from the official Metorial API reference (https://metorial.com/api). Keyed by the endpoint
+names in `settings.py` `METORIAL_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+Metorial table. Columns absent here fall back to LLM enrichment.
+"""
+
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.",
+ "description": "Connections to providers that let clients interact with MCP servers.",
"docs_url": "https://metorial.com/api/sessions",
"columns": {
- "id": "Unique session identifier (e.g. ses_...).",
+ "id": "Unique session identifier (prefixed `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.",
+ "name": "Human-readable name for the session.",
+ "description": "Description of the session.",
+ "metadata": "Arbitrary key/value metadata attached to the session.",
+ "connection_state": "Current connection state of the session.",
"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.",
+ "usage": "Productive client and provider message counts for the session.",
+ "providers": "The providers connected to the session.",
+ "has_errors": "Whether the session recorded any errors.",
+ "has_warnings": "Whether the session recorded any warnings.",
+ "identity_actor_id": "Identity actor associated with the session.",
+ "identity_id": "Identity associated with the session.",
+ "created_at": "Timestamp when the session was created.",
+ "updated_at": "Timestamp when the session was last updated.",
},
},
"session_messages": {
- "description": "A single message exchanged within an MCP session, including MCP protocol messages and tool calls.",
+ "description": "The MCP protocol messages exchanged during a session (read-only).",
"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.",
+ "id": "Unique session message identifier (prefixed `smg_`).",
+ "type": "Message type (e.g. tool_call).",
+ "status": "Message status.",
+ "source": "Where the message originated (e.g. client).",
+ "session_id": "Session the message belongs to.",
+ "tool_call": "Tool call details when the message represents a tool invocation.",
+ "created_at": "Timestamp when the message was created.",
},
},
"session_errors": {
- "description": "An error recorded during an MCP session, grouped with similar errors for triage.",
+ "description": "Errors that occurred during a session (read-only).",
"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).",
+ "id": "Unique session error identifier (prefixed `ser_`).",
+ "code": "Machine-readable error code.",
"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.",
+ "data": "Additional structured error data.",
+ "status": "Processing status of the error.",
+ "session_id": "Session the error belongs to.",
+ "provider_run_id": "Provider run the error occurred in, if any.",
+ "connection_id": "Connection the error occurred on.",
+ "group_id": "Group of similar errors this error belongs to.",
+ "similar_error_count": "Number of similar errors grouped with this one.",
+ "created_at": "Timestamp when the error was recorded.",
},
},
"provider_runs": {
- "description": "A run of a deployed MCP provider serving a session — the unit of provider execution.",
+ "description": "Executions of provider operations within a session (read-only).",
"docs_url": "https://metorial.com/api/provider-runs",
"columns": {
- "id": "Unique provider run identifier (e.g. prn_...).",
+ "id": "Unique provider run identifier (prefixed `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.",
+ "session_id": "Session the run belongs to.",
+ "session_provider_id": "Session provider the run belongs to.",
+ "provider_id": "Provider that was run.",
+ "connection_id": "Connection the run used.",
+ "completed_at": "Timestamp when the run completed (null while running).",
+ "created_at": "Timestamp when the run was created.",
+ "updated_at": "Timestamp when the run was last updated.",
+ },
+ },
+ "tool_calls": {
+ "description": "Individual tool invocations within a session, tracking input, output, and status.",
+ "docs_url": "https://metorial.com/api/tool-calls",
+ "columns": {
+ "id": "Unique tool call identifier (prefixed `tcl_`).",
+ "tool_key": "Key of the tool that was invoked.",
+ "type": "Tool call type.",
+ "status": "Tool call status: waiting_for_response, failed, or succeeded.",
+ "source": "Where the tool call originated (e.g. client).",
+ "session_id": "Session the tool call belongs to.",
+ "message_id": "Session message that carried the tool call.",
+ "provider_run_id": "Provider run the tool call belongs to.",
+ "tool": "Details of the invoked tool.",
+ "input": "Input arguments passed to the tool.",
+ "output": "Output returned by the tool.",
+ "error": "Error details if the tool call failed.",
+ "created_at": "Timestamp when the tool call was created.",
},
},
"provider_deployments": {
- "description": "A deployment of an MCP provider — the configured, runnable instance sessions connect to.",
+ "description": "Running provider instances pinned to a specific provider version.",
"docs_url": "https://metorial.com/api/provider-deployments",
"columns": {
- "id": "Unique deployment identifier (e.g. pde_...).",
+ "id": "Unique provider deployment identifier (prefixed `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.",
+ "name": "Human-readable name for the deployment.",
+ "description": "Description of the deployment.",
+ "metadata": "Arbitrary key/value metadata attached to the deployment.",
+ "tool_filter": "Filter controlling which tools the deployment exposes.",
+ "provider_id": "Provider this deployment runs.",
+ "locked_version": "The pinned provider version the deployment runs.",
+ "default_config": "Default configuration for the deployment.",
+ "created_at": "Timestamp when the deployment was created.",
+ "updated_at": "Timestamp 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.",
+ "description": "Read-only catalog of MCP server integration templates available on Metorial.",
"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.",
+ "id": "Unique provider identifier (prefixed `pro_`).",
+ "access": "Provider access level (e.g. public).",
+ "status": "Provider status.",
+ "publisher": "Publisher of the provider.",
+ "current_version": "The current published version of the provider.",
+ "oauth": "OAuth configuration for the provider, if any.",
+ "identifier": "Stable identifier for the provider.",
"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.",
+ "slug": "URL-friendly slug for the provider.",
+ "metadata": "Arbitrary key/value metadata attached to the provider.",
+ "created_at": "Timestamp when the provider was created.",
+ "updated_at": "Timestamp 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
index 08bdeca82d38..d62a72db9c15 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/metorial.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/metorial.py
@@ -1,30 +1,28 @@
import dataclasses
from collections.abc import Iterator
-from datetime import UTC, datetime
+from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlencode
+from urllib.parse import urlsplit
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,
+ MetorialEndpointConfig,
)
-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
+METORIAL_BASE_URL = "https://api.metorial.com"
+# Pin the API version so response shapes don't shift under us when Metorial changes an environment's
+# default version. See https://metorial.com/api ("Versioning").
+METORIAL_API_VERSION = "2025-01-01"
+# Default page size. Metorial doesn't document a max, so stay conservatively within a value cursor
+# APIs commonly accept while keeping request counts down against the tight per-key rate limit.
+DEFAULT_PAGE_SIZE = 100
class MetorialRetryableError(Exception):
@@ -33,82 +31,119 @@ class MetorialRetryableError(Exception):
@dataclasses.dataclass
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.
+ # Cursor (a record id) to fetch the next page from. None means "start at the first page".
after: str | None = None
-def _headers(api_key: str) -> dict[str, str]:
- return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+def _format_datetime_z(dt: datetime) -> str:
+ """Format a datetime as ISO 8601 with a millisecond precision and a Z suffix (Metorial's format)."""
+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+def _format_incremental_value(value: Any) -> str:
+ if isinstance(value, datetime):
+ return _format_datetime_z(value)
+ if isinstance(value, date):
+ return _format_datetime_z(datetime.combine(value, datetime.min.time(), tzinfo=UTC))
+ return str(value)
-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.
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Metorial-Version": METORIAL_API_VERSION,
+ "Accept": "application/json",
+ }
- 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.
+
+def _build_params(
+ config: MetorialEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ """Build the base query params reused on every page of a list request.
+
+ `order=asc` paginates deterministically by record id. The incremental filter is re-sent on every
+ page so pagination can never walk back past the watermark. Note this orders by id, not by the
+ incremental field: `created_at` tracks id order (safe to checkpoint per batch), but `updated_at`
+ does not, so `updated_at` syncs run in `sort_mode="desc"` (see `metorial_source`).
"""
- 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)
+ params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE, "order": "asc"}
- 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")
+ if config.incremental_fields and should_use_incremental_field and db_incremental_field_last_value:
+ field_name = incremental_field or config.default_incremental_field
+ # Metorial documents these as `created_at`/`updated_at` objects with `.gt`/`.lt` operators.
+ # Bracket notation is the standard query-string encoding for such nested filter objects on a
+ # JSON/Node backend; confirm against the live API before relying on it in anger.
+ params[f"{field_name}[gt]"] = _format_incremental_value(db_incremental_field_last_value)
+ return params
-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)}"
+
+def validate_credentials(api_key: str) -> bool:
+ # A single cheap probe: list one session. 200 => the secret key is genuine and project-scoped.
+ try:
+ response = make_tracked_session().get(
+ f"{METORIAL_BASE_URL}/sessions",
+ params={"limit": 1},
+ headers=_get_headers(api_key),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
@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),
+ retry=retry_if_exception_type(
+ (
+ MetorialRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
reraise=True,
)
def _fetch_page(
session: requests.Session,
- url: str,
+ path: str,
+ params: dict[str, Any],
+ headers: dict[str, str],
logger: FilteringBoundLogger,
-) -> tuple[list[dict[str, Any]], bool]:
- response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+) -> dict:
+ response = session.get(f"{METORIAL_BASE_URL}{path}", params=params, headers=headers, timeout=60)
+ # 429 (rate limited) and 5xx are transient; back off and retry rather than failing the sync.
if response.status_code == 429 or response.status_code >= 500:
- raise MetorialRetryableError(f"Metorial API error (retryable): status={response.status_code}, url={url}")
+ raise MetorialRetryableError(f"Metorial API error (retryable): status={response.status_code}, path={path}")
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()
+ logger.error(f"Metorial API error: status={response.status_code}, path={path}")
+ # raise_for_status() would embed the full request URL (including the query string, which
+ # carries the incremental watermark and cursor) in the exception, and response.text can echo
+ # synced session content, tool-call payloads, or secret values. Both are surfaced as the
+ # schema's latest_error outside the warehouse table ACLs. Rebuild the error from
+ # scheme/host/path only so no response body or query string can leak into stored error state.
+ # The "<status> Client Error: <reason> for url: https://api.metorial.com" prefix stays stable
+ # for get_non_retryable_errors() matching.
+ safe = urlsplit(response.url)
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {safe.scheme}://{safe.netloc}{safe.path}",
+ response=response,
+ )
- 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__}")
+ return response.json()
- pagination = data.get("pagination") or {}
- return data["items"], bool(pagination.get("has_more_after"))
+
+def _normalize(item: dict[str, Any], drop_fields: list[str]) -> dict[str, Any]:
+ if not drop_fields:
+ return item
+ return {key: value for key, value in item.items() if key not in drop_fields}
def get_rows(
@@ -116,36 +151,40 @@ def get_rows(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[MetorialResumeConfig],
- incremental_field: str | None = None,
+ should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
) -> Iterator[list[dict[str, Any]]]:
config = METORIAL_ENDPOINTS[endpoint]
- session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ headers = _get_headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- after = resume.after if resume is not None else None
+ after: str | None = resume.after if resume else None
if after:
- logger.debug(f"Metorial: resuming {endpoint} from after={after}")
+ logger.debug(f"Metorial: resuming {endpoint} from cursor {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)
+ page_params = dict(params)
+ if after:
+ page_params["after"] = after
- if items:
- yield items
+ data = _fetch_page(session, config.path, page_params, headers, logger)
- if not has_more_after or not items:
- break
+ raw_items = data.get("items", [])
+ if raw_items:
+ yield [_normalize(item, config.drop_fields) for item in raw_items]
- 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")
+ pagination = data.get("pagination", {})
+ if not raw_items or not pagination.get("has_more_after", False):
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.
+ after = raw_items[-1]["id"]
+ # Save AFTER yielding the page so a crash re-fetches the last page (merge dedupes on the
+ # primary key) rather than skipping it.
resumable_source_manager.save_state(MetorialResumeConfig(after=after))
@@ -160,16 +199,12 @@ def metorial_source(
) -> 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.
+ # Pagination is `order=asc` by record id. Metorial ids are time-sorted, so a `created_at` sync
+ # genuinely arrives oldest-first and the pipeline can safely checkpoint the watermark after each
+ # batch. `updated_at` is NOT monotonic in id order (a row created long ago can be updated
+ # recently), so those syncs run `desc`: the pipeline then commits the watermark only after a full
+ # successful run, so an interrupted sync can't advance past rows it hasn't fetched yet.
+ chosen_field = incremental_field or config.default_incremental_field
sort_mode: SortMode = "asc" if chosen_field in (None, "created_at") else "desc"
return SourceResponse(
@@ -179,35 +214,15 @@ def metorial_source(
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,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
),
- primary_keys=list(config.primary_keys),
+ primary_keys=config.primary_keys,
+ sort_mode=sort_mode,
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.",
+ partition_mode="datetime",
+ partition_format="week",
+ partition_keys=[config.partition_key],
)
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
index 469722660715..770002874087 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metorial/settings.py
@@ -1,87 +1,101 @@
from dataclasses import dataclass, field
+from typing import Optional
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,
-}
+def _incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "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.
+ incremental_fields: list[IncrementalField]
+ # Field used to build the server-side `<field>[gt]` filter when the user hasn't picked one.
+ default_incremental_field: Optional[str] = None
+ # Stable datetime column to partition by. Never `updated_at` (partitions would rewrite each sync).
+ partition_key: str = "created_at"
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"
+ should_sync_default: bool = True
+ # Whether append is a safe sync mode. False for resources whose rows mutate (they carry an
+ # `updated_at`, so a later version re-appears under the same id and append would duplicate it),
+ # True only for immutable append-only event streams.
+ supports_append: bool = False
+ # Fields stripped from every row before it lands in the warehouse (e.g. live client secrets).
+ drop_fields: list[str] = field(default_factory=list)
-# 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 carry an `updated_at`, so sync incrementally on it and merge (append would duplicate a
+ # session each time its status/usage changes). `client_secret` is a live credential we never want
+ # to persist to the warehouse.
"sessions": MetorialEndpointConfig(
name="sessions",
path="/sessions",
- incremental_fields=[_UPDATED_AT_INCREMENTAL, _CREATED_AT_INCREMENTAL],
+ default_incremental_field="updated_at",
+ incremental_fields=[_incremental_field("updated_at"), _incremental_field("created_at")],
+ drop_fields=["client_secret"],
),
+ # MCP protocol messages are immutable events keyed on `created_at` (the object exposes no
+ # `updated_at`), so append is safe and cheap.
"session_messages": MetorialEndpointConfig(
name="session_messages",
path="/session-messages",
- incremental_fields=[_CREATED_AT_INCREMENTAL],
+ default_incremental_field="created_at",
+ incremental_fields=[_incremental_field("created_at")],
+ supports_append=True,
),
+ # Session errors are append-only diagnostic records keyed on `created_at`.
"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],
+ default_incremental_field="created_at",
+ incremental_fields=[_incremental_field("created_at")],
+ supports_append=True,
),
+ # Provider runs carry an `updated_at` (and a `completed_at` that lands after creation), so merge on
+ # `updated_at` to pick up completions rather than appending duplicate rows.
"provider_runs": MetorialEndpointConfig(
name="provider_runs",
path="/provider-runs",
- incremental_fields=[_UPDATED_AT_INCREMENTAL, _CREATED_AT_INCREMENTAL],
+ default_incremental_field="updated_at",
+ incremental_fields=[_incremental_field("updated_at"), _incremental_field("created_at")],
+ ),
+ # Tool calls transition status (waiting_for_response -> succeeded/failed) but the object exposes no
+ # `updated_at`, so we sync incrementally on `created_at` and merge: a status change after the
+ # watermark has passed isn't re-captured (documented limitation), but merge keeps re-pulled
+ # overlap rows deduped rather than duplicated.
+ "tool_calls": MetorialEndpointConfig(
+ name="tool_calls",
+ path="/tool-calls",
+ default_incremental_field="created_at",
+ incremental_fields=[_incremental_field("created_at")],
),
+ # Provider deployments are long-lived, mutable config objects with an `updated_at`.
"provider_deployments": MetorialEndpointConfig(
name="provider_deployments",
path="/provider-deployments",
- incremental_fields=[_UPDATED_AT_INCREMENTAL, _CREATED_AT_INCREMENTAL],
+ default_incremental_field="updated_at",
+ incremental_fields=[_incremental_field("updated_at"), _incremental_field("created_at")],
),
+ # The provider catalog exposes no server-side timestamp filter, so it can only be full-refreshed.
+ # It's a global reference catalog (not project-specific), so it's off by default.
"providers": MetorialEndpointConfig(
name="providers",
path="/providers",
- # `GET /providers` accepts no `created_at`/`updated_at` filters, so full refresh only.
incremental_fields=[],
+ should_sync_default=False,
),
}
-ENDPOINTS = tuple(METORIAL_ENDPOINTS)
+ENDPOINTS = tuple(METORIAL_ENDPOINTS.keys())
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 ad256a7ffc7f..d682d9e07b5d 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
@@ -29,39 +29,64 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.m
from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ METORIAL_ENDPOINTS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
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
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
@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.",
- }
+ @property
+ def get_source_config(self) -> SourceConfig:
+ return SourceConfig(
+ name=SchemaExternalDataSourceType.METORIAL,
+ category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
+ label="Metorial",
+ releaseStatus=ReleaseStatus.ALPHA,
+ unreleasedSource=True,
+ caption="""Enter your Metorial secret API key to pull your Metorial MCP data into the PostHog Data warehouse.
+
+Create a secret API key (`metorial_sk_...`) in your [Metorial dashboard](https://metorial.com). Keys are project-scoped, so connect one source per project you want to sync. A publishable key (`metorial_pk_...`) only exposes public data and will not work here.""",
+ iconPath="/static/services/metorial.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/metorial",
+ keywords=["mcp", "ai infrastructure", "agents", "observability"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="metorial_sk_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
def get_canonical_descriptions(self) -> CanonicalDescriptions:
- from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.canonical_descriptions import ( # noqa: PLC0415
+ from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.canonical_descriptions import (
CANONICAL_DESCRIPTIONS,
)
return CANONICAL_DESCRIPTIONS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError from `raise_for_status()`. Retrying can never fix
+ # a bad key or a key missing project scope, so stop the sync. Match the stable status text
+ # and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.metorial.com": "Your Metorial API key is invalid or has been revoked. Create a new secret API key in your Metorial dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.metorial.com": "Your Metorial API key does not have access to this project's data. Use a secret key (metorial_sk_...) for the project you want to sync, then reconnect.",
+ }
+
def get_schemas(
self,
config: MetorialSourceConfig,
@@ -70,27 +95,30 @@ class MetorialSource(ResumableSource[MetorialSourceConfig, MetorialResumeConfig]
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,
- )
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = METORIAL_ENDPOINTS[endpoint]
+ has_incremental = len(endpoint_config.incremental_fields) > 0
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=endpoint_config.supports_append,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
)
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
return schemas
def validate_credentials(
self, config: MetorialSourceConfig, team_id: int, schema_name: Optional[str] = None
) -> tuple[bool, str | None]:
- return validate_metorial_credentials(api_key=config.api_key)
+ if validate_metorial_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Metorial API key"
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MetorialResumeConfig]:
return ResumableSourceManager[MetorialResumeConfig](inputs, MetorialResumeConfig)
@@ -112,33 +140,3 @@ class MetorialSource(ResumableSource[MetorialSourceConfig, MetorialResumeConfig]
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],
- [
- 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
index 535c3f07cc76..d32da6b15758 100644
--- 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
@@ -1,6 +1,5 @@
-from datetime import UTC, datetime
-from typing import Any, Optional
-from urllib.parse import parse_qs, urlparse
+from datetime import UTC, date, datetime
+from typing import Any
import pytest
from unittest.mock import MagicMock, patch
@@ -11,21 +10,12 @@ 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,
+ _build_params,
+ _format_incremental_value,
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]
+from products.warehouse_sources.backend.temporal.data_imports.sources.metorial.settings import METORIAL_ENDPOINTS
class _FakeResumableManager:
@@ -43,264 +33,216 @@ class _FakeResumableManager:
self.saved.append(data)
-def _query(url: str) -> dict[str, list[str]]:
- return parse_qs(urlparse(url).query)
+def _collect(manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: list[dict], **incremental: Any):
+ calls: list[dict] = []
+
+ def fake_fetch(session: Any, path: str, params: dict, headers: dict, logger: Any) -> dict:
+ calls.append(dict(params))
+ return pages[len(calls) - 1]
+ monkeypatch.setattr(metorial, "_fetch_page", fake_fetch)
-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
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="metorial_sk_x",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **incremental,
+ ):
+ rows.extend(batch)
+ return rows, calls
- 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"]
+class TestFormatIncrementalValue:
@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"),
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("string_passthrough", "ses_cursor", "ses_cursor"),
]
)
- 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
+ def test_format(self, _name: str, value: object, expected: str) -> None:
+ # The server filter rejects a +00:00 offset; the watermark must serialize with a Z suffix.
+ result = _format_incremental_value(value)
+ assert result == expected
+ assert "+00:00" not in result
+
+
+class TestBuildParams:
+ def test_incremental_endpoint_builds_gt_filter_for_chosen_field(self) -> None:
+ # Dropping or misnaming this filter turns every "incremental" sync into a full refresh.
+ params = _build_params(
+ METORIAL_ENDPOINTS["sessions"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="updated_at",
)
- 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}}
+ assert params["updated_at[gt]"] == "2026-03-04T02:58:14.000Z"
+ assert params["order"] == "asc"
+
+ def test_honors_user_incremental_field_over_default(self) -> None:
+ # sessions default is updated_at; the user picking created_at must be respected.
+ params = _build_params(
+ METORIAL_ENDPOINTS["sessions"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="created_at",
)
- response.text = ""
- response.raise_for_status.side_effect = (
- requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ assert "created_at[gt]" in params
+ assert "updated_at[gt]" not in params
+
+ def test_first_sync_has_no_filter(self) -> None:
+ # No watermark yet: sending an empty gt filter would 400 (or silently sync nothing).
+ params = _build_params(
+ METORIAL_ENDPOINTS["sessions"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updated_at",
)
- 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
+ assert not any(k.endswith("[gt]") for k in params)
+
+ def test_full_refresh_endpoint_never_filters(self) -> None:
+ # providers exposes no server-side timestamp filter; it must not fabricate one.
+ params = _build_params(
+ METORIAL_ENDPOINTS["providers"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert not any(k.endswith("[gt]") for k in params)
- 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"]
+class TestPagination:
+ def test_follows_cursor_until_has_more_after_false(self, monkeypatch: Any) -> None:
+ pages = [
+ {"items": [{"id": "tcl_1"}, {"id": "tcl_2"}], "pagination": {"has_more_after": True}},
+ {"items": [{"id": "tcl_3"}], "pagination": {"has_more_after": False}},
+ ]
+ rows, calls = _collect(_FakeResumableManager(), monkeypatch, "tool_calls", pages)
+ assert [r["id"] for r in rows] == ["tcl_1", "tcl_2", "tcl_3"]
+ # Page one carries no cursor; page two pages from the last id of page one.
+ assert "after" not in calls[0]
+ assert calls[1]["after"] == "tcl_2"
+
+ def test_stops_on_empty_first_page(self, monkeypatch: Any) -> None:
+ pages = [{"items": [], "pagination": {"has_more_after": False}}]
+ rows, calls = _collect(_FakeResumableManager(), monkeypatch, "tool_calls", pages)
+ assert rows == []
+ assert len(calls) == 1
- 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)})
+ def test_drops_sensitive_fields_on_sessions(self, monkeypatch: Any) -> None:
+ # A live client_secret must never be persisted to the warehouse.
+ pages = [
+ {"items": [{"id": "ses_1", "client_secret": "metorial_fk_x"}], "pagination": {"has_more_after": False}}
+ ]
+ rows, _ = _collect(_FakeResumableManager(), monkeypatch, "sessions", pages)
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:
+class TestResume:
+ def test_saves_next_cursor_after_each_page(self, monkeypatch: Any) -> None:
+ # Saving after (not before) yielding means a crash re-fetches the page rather than skipping it.
+ pages = [
+ {"items": [{"id": "prn_1"}], "pagination": {"has_more_after": True}},
+ {"items": [{"id": "prn_2"}], "pagination": {"has_more_after": False}},
+ ]
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)
+ _collect(manager, monkeypatch, "provider_runs", pages)
+ # Only the page that had a successor persists a cursor; the terminal page does not.
+ assert [s.after for s in manager.saved] == ["prn_1"]
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ # A resumed run must continue from the persisted cursor, not restart the whole stream.
+ pages = [{"items": [{"id": "prn_9"}], "pagination": {"has_more_after": False}}]
+ manager = _FakeResumableManager(MetorialResumeConfig(after="prn_8"))
+ rows, calls = _collect(manager, monkeypatch, "provider_runs", pages)
+ assert calls[0]["after"] == "prn_8"
+ assert [r["id"] for r in rows] == ["prn_9"]
-class TestMetorialSource:
- def _source(self, endpoint: str, **kwargs: Any):
- return metorial_source(
- api_key="metorial_sk_test",
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ # Pagination is by record id (order=asc). `updated_at` is not monotonic in id order, so
+ # those syncs must run "desc" (the pipeline then commits the watermark only after a full
+ # run). An "asc" claim here lets an interrupted sync advance the watermark past rows it
+ # hasn't fetched, silently losing them from the warehouse.
+ ("sessions_default_updated_at", "sessions", None, "desc"),
+ ("provider_runs_default_updated_at", "provider_runs", None, "desc"),
+ ("provider_deployments_default_updated_at", "provider_deployments", None, "desc"),
+ # A user overriding sessions onto created_at makes per-batch checkpointing safe again.
+ ("sessions_user_picks_created_at", "sessions", "created_at", "asc"),
+ # created_at tracks id order, so append-only streams checkpoint safely per batch.
+ ("session_messages_created_at", "session_messages", None, "asc"),
+ ("tool_calls_created_at", "tool_calls", None, "asc"),
+ # Full-refresh-only endpoint has no incremental field.
+ ("providers_full_refresh", "providers", None, "asc"),
+ ]
+ )
+ def test_sort_mode_matches_incremental_field(
+ self, _name: str, endpoint: str, incremental_field: str | None, expected_sort_mode: str
+ ) -> None:
+ response = metorial_source(
+ api_key="metorial_sk_x",
endpoint=endpoint,
logger=MagicMock(),
resumable_source_manager=MagicMock(),
- **kwargs,
+ incremental_field=incremental_field,
)
-
- @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.sort_mode == expected_sort_mode
assert response.primary_keys == ["id"]
+ # Partition key must be the stable created_at, never updated_at (partitions would rewrite each sync).
+ assert response.partition_keys == ["created_at"]
- 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)
+class TestFetchPageRetries:
+ @parameterized.expand(
+ [
+ ("rate_limited", 429),
+ ("server_error", 503),
+ ]
+ )
+ def test_retryable_status_codes_retry(self, _name: str, status: int) -> None:
+ # 429/5xx are transient: back off and retry rather than failing the sync.
+ bad = MagicMock(status_code=status, ok=False)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"items": []}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
- 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"
+ with patch.object(metorial._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = metorial._fetch_page(session, "/sessions", {}, {}, MagicMock())
- 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
+ assert result == {"items": []}
+ assert session.get.call_count == 2
+ def test_client_error_is_not_retried(self) -> None:
+ # A 401 can never be fixed by retrying; it must surface immediately as an HTTPError.
+ resp = requests.Response()
+ resp.status_code = 401
+ resp.url = "https://api.metorial.com/sessions"
+ session = MagicMock()
+ session.get.return_value = resp
-class TestValidateCredentials:
- def _session(self, response: Any) -> MagicMock:
+ with pytest.raises(requests.HTTPError):
+ metorial._fetch_page(session, "/sessions", {}, {}, MagicMock())
+ assert session.get.call_count == 1
+
+ def test_client_error_scrubs_query_string_and_keeps_non_retryable_prefix(self) -> None:
+ # The incremental watermark/cursor ride in the query string and the body can echo synced
+ # session content; neither may reach the rebuilt HTTPError (surfaced as the schema's
+ # latest_error outside warehouse ACLs). The status + host prefix stays stable so
+ # get_non_retryable_errors() still matches.
+ resp = requests.Response()
+ resp.status_code = 401
+ resp.reason = "Unauthorized"
+ resp.url = "https://api.metorial.com/sessions?updated_at%5Bgt%5D=2026-03-04T00%3A00%3A00.000Z&after=ses_secret"
+ resp._content = b'{"error":"leaked session content and secrets"}'
session = MagicMock()
- if isinstance(response, Exception):
- session.get.side_effect = response
- else:
- session.get.return_value = response
- return session
+ session.get.return_value = resp
- @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()
+ with pytest.raises(requests.HTTPError) as exc:
+ metorial._fetch_page(session, "/sessions", {}, {}, MagicMock())
+ assert str(exc.value) == "401 Client Error: Unauthorized for url: https://api.metorial.com/sessions"
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
index 481488fa6767..210654f3fab1 100644
--- 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
@@ -1,160 +1,162 @@
-import pytest
-from unittest import mock
+from typing import Any
+
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
-from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
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",
-)
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.metorial.source"
+
+def _config() -> MetorialSourceConfig:
+ return MetorialSourceConfig.from_dict({"api_key": "metorial_sk_test"})
-class TestMetorialSource:
- def setup_method(self) -> None:
- self.source = MetorialSource()
- self.team_id = 123
- self.config = MetorialSourceConfig(api_key="metorial_sk_test")
+class TestSourceConfig:
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"]
+ assert MetorialSource().source_type.value == "Metorial"
+
+ def test_api_key_is_a_required_secret_field(self) -> None:
+ # A non-secret key field would be stored unencrypted; a non-required one would let a source be
+ # created with no credentials.
+ fields = MetorialSource().get_source_config.fields
+ api_key = next(f for f in fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+ assert api_key.secret is True
+
+class TestSchemas:
@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",),
+ # Mutable resources (carry updated_at) must merge, never append — append duplicates a row
+ # every time its status/usage changes.
+ ("sessions", True, False),
+ ("provider_runs", True, False),
+ ("provider_deployments", True, False),
+ # tool_calls mutate status but expose no updated_at, so incremental-merge on created_at.
+ ("tool_calls", True, False),
+ # Immutable event streams keyed on created_at: append is safe.
+ ("session_messages", True, True),
+ ("session_errors", True, True),
+ # No server-side timestamp filter: full refresh only.
+ ("providers", False, False),
]
)
- 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)
-
+ def test_incremental_and_append_support(self, endpoint: str, incremental: bool, append: bool) -> None:
+ schemas = {s.name: s for s in MetorialSource().get_schemas(_config(), team_id=1)}
+ assert schemas[endpoint].supports_incremental is incremental
+ assert schemas[endpoint].supports_append is append
+
+ def test_providers_is_off_by_default(self) -> None:
+ # providers is a global catalog, not project data — syncing it every time by default would
+ # burn the tight rate limit for little value.
+ schemas = {s.name: s for s in MetorialSource().get_schemas(_config(), team_id=1)}
+ assert schemas["providers"].should_sync_default is False
+
+ def test_names_filter(self) -> None:
+ schemas = MetorialSource().get_schemas(_config(), team_id=1, names=["sessions"])
+ assert [s.name for s in schemas] == ["sessions"]
+
+ def test_lists_documented_tables_without_credentials(self) -> None:
+ # The static catalog powers the public docs "Supported tables" section.
+ source = MetorialSource()
+ assert source.lists_tables_without_credentials is True
+ assert {t["name"] for t in source.get_documented_tables()} == {
+ s.name for s in source.get_schemas(_config(), team_id=1)
+ }
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", True), ("invalid", False)])
+ def test_maps_probe_result(self, _name: str, probe_ok: bool) -> None:
+ with patch(f"{_SOURCE_MODULE}.validate_metorial_credentials", return_value=probe_ok):
+ ok, error = MetorialSource().validate_credentials(_config(), team_id=1)
+ assert ok is probe_ok
+ assert (error is None) is probe_ok
+
+
+class TestNonRetryableErrors:
@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",),
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.metorial.com/sessions?limit=1"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.metorial.com/provider-runs"),
]
)
- 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)
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ keys = MetorialSource().get_non_retryable_errors()
+ assert any(key in observed for key in keys)
- @mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.metorial.source.validate_metorial_credentials"
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.metorial.com', port=443): Read timed out."),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.metorial.com/sessions"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.metorial.com/tool-calls"),
+ ]
)
- 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)
+ def test_transient_errors_stay_retryable(self, _name: str, observed: str) -> None:
+ keys = MetorialSource().get_non_retryable_errors()
+ assert not any(key in observed for key in keys)
+
+
+class TestSourceForPipeline:
+ def test_threads_incremental_inputs_into_transport(self) -> None:
+ # Guards the wiring: the user's chosen endpoint, cursor field, and watermark must reach the
+ # transport, and the watermark must be suppressed when incremental sync is off.
+ inputs = SourceInputs(
+ schema_name="sessions",
+ schema_id="sid",
+ source_id="src",
+ team_id=1,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-03-04T00:00:00.000Z",
+ db_incremental_field_earliest_value=None,
+ incremental_field="updated_at",
+ incremental_field_type=None,
+ job_id="job",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+ manager = MagicMock()
+ with patch(f"{_SOURCE_MODULE}.metorial_source") as mock_source:
+ MetorialSource().source_for_pipeline(_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 kwargs["db_incremental_field_last_value"] == "2026-03-04T00:00:00.000Z"
+
+ def test_suppresses_watermark_when_not_incremental(self) -> None:
+ inputs = SourceInputs(
+ schema_name="providers",
+ schema_id="sid",
+ source_id="src",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="should-be-ignored",
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+ with patch(f"{_SOURCE_MODULE}.metorial_source") as mock_source:
+ MetorialSource().source_for_pipeline(_config(), 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)
+
+class TestResumableManager:
+ def test_manager_is_bound_to_resume_config(self) -> None:
+ inputs: Any = MagicMock()
+ manager = MetorialSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MetorialResumeConfig