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 metaplane import source (#71162)

Tom Owers70bfb7edf053
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 a751bd5c1108..361ce617be3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -336,6 +336,7 @@ the row lists both.
| mention | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
| metabase | HTTP | requests | ✅ |
+| metaplane | HTTP | requests | ✅ |
| metorial | HTTP | requests | ✅ |
| mistral_ai | HTTP | requests | ✅ |
| mixmax | HTTP | requests | ✅ |
@@ -794,7 +795,6 @@ doesn't conflict with concurrent PRs.
- mercado_ads
- mercury
- merge
-- metaplane
- 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 15e368ef83fc..a007bfee7c71 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
@@ -2711,7 +2711,7 @@ class MetabaseSourceConfig(config.Config):
@config.config
class MetaplaneSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/canonical_descriptions.py
new file mode 100644
index 000000000000..21e00dfa01f7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/canonical_descriptions.py
@@ -0,0 +1,75 @@
+"""Canonical, documentation-sourced descriptions for Metaplane endpoints and columns.
+
+Sourced from the official Metaplane API reference (https://docs.metaplane.dev/reference).
+Keyed by the endpoint names in `settings.py` `METAPLANE_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Metaplane table. Columns absent here fall back to LLM
+enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "connections": {
+ "description": "A data source or tool connected to Metaplane (warehouse, transformation tool, BI tool, ...).",
+ "docs_url": "https://docs.metaplane.dev/reference/getallconnections",
+ "columns": {
+ "id": "Unique identifier (UUID) for the connection.",
+ "name": "Display name of the connection.",
+ "type": "Kind of connected system (e.g. SNOWFLAKE, BIGQUERY, POSTGRES, DBT, LOOKER).",
+ "isEnabled": "Whether the connection is currently enabled.",
+ "createdAt": "Time at which the connection was created.",
+ "updatedAt": "Time at which the connection was last updated.",
+ "status": "Lifecycle status of the connection (ACTIVE or DELETED).",
+ },
+ },
+ "monitors": {
+ "description": "A data-quality monitor watching a database, schema, table, or column (row count, freshness, nullness, ...).",
+ "docs_url": "https://docs.metaplane.dev/reference/getallmonitorsforsource",
+ "columns": {
+ "id": "Unique identifier (UUID) for the monitor.",
+ "type": "Metric the monitor tracks (e.g. ROW_COUNT, FRESHNESS, NULLNESS, CARDINALITY, CUSTOM).",
+ "valueType": "Data type of the monitored value.",
+ "cronTab": "Cron expression controlling when the monitor runs.",
+ "name": "Display name of the monitor.",
+ "description": "User-supplied description of the monitor.",
+ "isEnabled": "Whether the monitor is currently enabled.",
+ "config": "Monitor configuration (custom SQL, incremental clause, where clause, alert rule, group-by columns, time zone).",
+ "createdAt": "Time at which the monitor was created.",
+ "updatedAt": "Time at which the monitor was last updated.",
+ "absolutePath": "Absolute path of the monitored entity, like {database}.{schema}.{table}.{column}.",
+ "entityType": "Kind of entity the monitor targets (database, schema, table, or column).",
+ "connectionId": "ID of the connection the monitored entity belongs to.",
+ "monitorTags": "Tags applied to the monitor.",
+ "monitorGroups": "Group-by groupings for group-by monitors.",
+ },
+ },
+ "monitor_evaluations": {
+ "description": "A single evaluation (run) of a monitor: the measured value, the model's expected bounds, and whether it passed.",
+ "docs_url": "https://docs.metaplane.dev/reference/getevaluationhistory",
+ "columns": {
+ "monitorId": "ID of the monitor this evaluation belongs to.",
+ "createdAt": "Time at which the evaluation was created.",
+ "result": "Measured value of the monitored metric at evaluation time.",
+ "lowerBound": "Lower bound of the model's expected range for this evaluation.",
+ "upperBound": "Upper bound of the model's expected range for this evaluation.",
+ "predicted": "Value the model predicted for this evaluation.",
+ "passed": "Whether the evaluation passed (the measured value fell within the expected bounds).",
+ "status": "Outcome of the evaluation (PASS, FAIL, IN_TRAINING, FAILED_TO_PREDICT, NOT_ENOUGH_DATA, ERROR, INVALID_INPUT).",
+ "openRelatedIncidents": "IDs of currently active incidents related to this evaluation.",
+ "errorMessage": "Error message when the evaluation failed to run.",
+ "annotation": "Optional user annotation applied to this datapoint (e.g. FALSE_POSITIVE, NEW_BASELINE).",
+ },
+ },
+ "connection_sync_statuses": {
+ "description": "The latest metadata-sync outcome for each connection.",
+ "docs_url": "https://docs.metaplane.dev/reference/getconnectionstatus",
+ "columns": {
+ "connectionId": "ID of the connection the sync status belongs to.",
+ "status": "Outcome of the most recent sync (STARTED, SUCCEEDED, or ERRORED).",
+ "errorMessage": "Error message when the most recent sync errored.",
+ "timestamp": "Time of the most recent sync status change.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/docs/metaplane.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/docs/metaplane.mdx
new file mode 100644
index 000000000000..7390d08bdef7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/docs/metaplane.mdx
@@ -0,0 +1,68 @@
+---
+title: Linking Metaplane as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Metaplane
+---
+
+<!--
+This is the user-facing posthog.com source doc. It lives here only because no posthog.com
+checkout was available when the source was implemented. Move it to
+`posthog.com/contents/docs/cdp/sources/metaplane.mdx` and delete this copy, then run
+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.
+-->
+
+import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'
+import SyncModes from '../_snippets/sync-modes.mdx'
+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'
+import AlphaRelease from '../_snippets/alpha-release.mdx'
+
+<AlphaRelease />
+
+[Metaplane by Datadog](https://www.metaplane.dev) is a data observability platform that monitors the
+tables and columns in your warehouse for anomalies (row counts, freshness, nullness, and more). Linking
+it as a source syncs your monitors and their full evaluation history into the PostHog Data warehouse, so
+you can report on data-quality SLAs, track when monitors ran, and analyze pass/fail rates and
+expected-vs-actual bounds over time.
+
+## Prerequisites
+
+To connect Metaplane, you need:
+
+- A paid Metaplane plan (API access is not available on the free tier).
+- An API key generated in your Metaplane account settings.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+1. Open Metaplane and generate an API key in your account settings.
+2. Copy the key and paste it into the **API key** field in PostHog.
+
+## Sync modes
+
+<SyncModes />
+
+The `monitor_evaluations` table supports **incremental** sync: each sync pulls only evaluations created
+since the last one, across all of your monitors. Monitors added after the initial sync are picked up
+from that point forward — run a full refresh if you need their complete history. The other tables
+(connections, monitors, and the latest sync status per connection) are small and sync as a full refresh.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+Tag endpoints aren't synced: Metaplane's API only returns tag data for tag names you already know, so
+there is no way to enumerate them.
+
+## Troubleshooting
+
+- **"Invalid Metaplane API key"** when connecting: the key is wrong or has been revoked, or your plan
+ doesn't include API access. Generate a new key in your Metaplane account settings and re-enter it.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/metaplane.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/metaplane.py
new file mode 100644
index 000000000000..3e282b0bf90c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/metaplane.py
@@ -0,0 +1,343 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+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 SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.settings import METAPLANE_ENDPOINTS
+
+# "dev" is part of the vendor's production domain, not a sandbox.
+METAPLANE_BASE_URL = "https://dev.api.metaplane.dev/v1"
+
+# The evaluation-history endpoint caps pages at 500 records.
+EVALUATION_PAGE_LIMIT = 500
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class MetaplaneRetryableError(Exception):
+ pass
+
+
+class MetaplaneResumeConfig:
+ # Bookmark into the monitor fan-out of the `monitor_evaluations` endpoint. A stable
+ # monitor-ID bookmark (not a positional index) so monitors added/removed between a crash
+ # and the retry can't resume us into the wrong monitor. None for the other endpoints,
+ # which complete in a handful of requests and just restart on retry.
+ monitor_id: str | None = None
+ # `createdAt` of the last evaluation fetched for that monitor — the next page starts here.
+ cursor: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # Metaplane expects the raw API key in the Authorization header (no Bearer prefix).
+ return {
+ "Authorization": api_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+def _make_session(api_key: str) -> requests.Session:
+ """Session for all Metaplane traffic. Response capture is disabled because the bodies carry
+ free-form tenant data — user-supplied monitor descriptions, `config` (custom SQL and where
+ clauses), and evaluation/sync error messages — that the name-based sample scrubbers can't
+ reliably recognise, so they must never land in the shared HTTP sample store. The API key is
+ redacted as defense in depth."""
+ return make_tracked_session(capture=False, redact_values=(api_key,))
+
+
+def _format_datetime(value: Any) -> str:
+ """Format an incremental value as the ISO 8601 / RFC 3339 timestamp Metaplane returns."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.000Z")
+ return str(value)
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Probe the connection list to confirm the API key is genuine.
+
+ Metaplane API keys are account-wide (no per-endpoint scopes), so one cheap probe
+ covers every endpoint.
+ """
+ try:
+ response = _make_session(api_key).get(
+ f"{METAPLANE_BASE_URL}/connections",
+ headers=_get_headers(api_key),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type((MetaplaneRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _request(
+ session: requests.Session,
+ method: str,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ json_body: dict[str, Any] | None = None,
+) -> Any:
+ response = session.request(method, url, headers=headers, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MetaplaneRetryableError(f"Metaplane API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 is expected during fan-out (a monitor/connection deleted mid-sync) and handled
+ # by callers; anything else is a hard failure.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Metaplane API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _get_connections(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ data = _request(session, "GET", f"{METAPLANE_BASE_URL}/connections", headers, logger)
+ return data if isinstance(data, list) else []
+
+
+def _get_monitors_for_connection(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, connection_id: str
+) -> list[dict[str, Any]]:
+ try:
+ data = _request(
+ session,
+ "GET",
+ f"{METAPLANE_BASE_URL}/monitors/connection/{connection_id}?includeDisabled=true",
+ headers,
+ logger,
+ )
+ except requests.HTTPError as exc:
+ # A connection deleted between enumeration and this fetch 404s — skip it rather than
+ # failing the sync; its monitors are genuinely gone.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Metaplane: connection {connection_id} not found while listing monitors, skipping")
+ return []
+ raise
+ return data.get("data", []) if isinstance(data, dict) else []
+
+
+def _get_monitor_rows(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ for connection in _get_connections(session, headers, logger):
+ monitors = _get_monitors_for_connection(session, headers, logger, connection["id"])
+ if monitors:
+ yield monitors
+
+
+def _get_connection_sync_status_rows(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ rows: list[dict[str, Any]] = []
+ for connection in _get_connections(session, headers, logger):
+ try:
+ status = _request(
+ session,
+ "GET",
+ f"{METAPLANE_BASE_URL}/connections/{connection['id']}/sync/status",
+ headers,
+ logger,
+ )
+ except requests.HTTPError as exc:
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Metaplane: no sync status for connection {connection['id']}, skipping")
+ continue
+ raise
+ if isinstance(status, dict):
+ # Some connection types never sync; make sure the row still keys on the connection.
+ status.setdefault("connectionId", connection["id"])
+ rows.append(status)
+ if rows:
+ yield rows
+
+
+def _get_evaluation_page(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ monitor_id: str,
+ cursor: str | None,
+) -> list[dict[str, Any]]:
+ body: dict[str, Any] = {"sortOrder": "ASC", "limit": EVALUATION_PAGE_LIMIT}
+ if cursor:
+ body["createdAt"] = cursor
+ try:
+ data = _request(
+ session,
+ "POST",
+ f"{METAPLANE_BASE_URL}/monitors/evaluation-history/{monitor_id}",
+ headers,
+ logger,
+ json_body=body,
+ )
+ except requests.HTTPError as exc:
+ # A monitor deleted (or never run/modeled) 404s — treat as an empty history.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Metaplane: no evaluation history for monitor {monitor_id}, skipping")
+ return []
+ raise
+ return data if isinstance(data, list) else []
+
+
+def _get_evaluation_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MetaplaneResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every monitor, paging each monitor's evaluation history ascending.
+
+ Incremental runs start each monitor's history from the table-wide `createdAt` watermark.
+ This runs report sort_mode="desc" (see metaplane_source) so the watermark persists only
+ at successful job end — mid-run, monitor B's old evaluations arrive after monitor A's new
+ ones, so per-batch ascending checkpoints would corrupt the watermark. One consequence:
+ monitors created after the initial sync only backfill evaluations from the current
+ watermark forward; a full refresh re-pulls complete history.
+ """
+ monitor_ids: list[str] = []
+ for connection in _get_connections(session, headers, logger):
+ monitor_ids.extend(
+ monitor["id"] for monitor in _get_monitors_for_connection(session, headers, logger, connection["id"])
+ )
+
+ initial_cursor = (
+ _format_datetime(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value is not None
+ else None
+ )
+
+ # Resolve the saved monitor-ID bookmark to the slice of monitors still to process. If the
+ # bookmarked monitor no longer exists, start over — merge dedupes re-pulled rows on the
+ # primary key. `resume_cursor` is consumed by the first monitor only.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = monitor_ids
+ resume_cursor: str | None = None
+ if resume is not None and resume.monitor_id is not None and resume.monitor_id in monitor_ids:
+ remaining = monitor_ids[monitor_ids.index(resume.monitor_id) :]
+ resume_cursor = resume.cursor
+ logger.debug(f"Metaplane: resuming monitor_evaluations from monitor_id={resume.monitor_id}")
+
+ for index, monitor_id in enumerate(remaining):
+ cursor = resume_cursor or initial_cursor
+ resume_cursor = None # only the resumed-into monitor uses the saved cursor
+
+ while True:
+ rows = _get_evaluation_page(session, headers, logger, monitor_id, cursor)
+ if not rows:
+ break
+
+ for row in rows:
+ row["monitorId"] = monitor_id
+ yield rows
+
+ # A page shorter than the limit is the last one.
+ if len(rows) < EVALUATION_PAGE_LIMIT:
+ break
+
+ next_cursor = rows[-1].get("createdAt")
+ if not next_cursor or next_cursor == cursor:
+ # The cursor didn't advance — a full page of identical timestamps would
+ # otherwise loop forever (the API docs don't state cursor inclusivity).
+ logger.warning(
+ f"Metaplane: evaluation cursor did not advance for monitor {monitor_id}, stopping pagination"
+ )
+ break
+
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
+ # merge dedupes on the primary key.
+ resumable_source_manager.save_state(MetaplaneResumeConfig(monitor_id=monitor_id, cursor=next_cursor))
+ cursor = next_cursor
+
+ # Advance the bookmark to the next monitor so a crash between monitors resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(MetaplaneResumeConfig(monitor_id=remaining[index + 1], cursor=None))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MetaplaneResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ headers = _get_headers(api_key)
+ # One session reused across every request so urllib3 keeps the connection alive
+ # instead of re-handshaking per request.
+ session = _make_session(api_key)
+
+ if endpoint == "connections":
+ connections = _get_connections(session, headers, logger)
+ if connections:
+ yield connections
+ elif endpoint == "monitors":
+ yield from _get_monitor_rows(session, headers, logger)
+ elif endpoint == "connection_sync_statuses":
+ yield from _get_connection_sync_status_rows(session, headers, logger)
+ elif endpoint == "monitor_evaluations":
+ yield from _get_evaluation_rows(
+ session,
+ headers,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ else:
+ raise ValueError(f"Unknown Metaplane endpoint: {endpoint}")
+
+
+def metaplane_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MetaplaneResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = METAPLANE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # The evaluation fan-out persists the incremental watermark only at successful job end
+ # (desc mode): a partial run's max says nothing about monitors it never reached, so
+ # per-batch persistence could advance the watermark past rows a crashed run still owes.
+ sort_mode="desc" if endpoint == "monitor_evaluations" else "asc",
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/settings.py
new file mode 100644
index 000000000000..268443d9c997
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/settings.py
@@ -0,0 +1,72 @@
+from dataclasses import dataclass
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class MetaplaneEndpointConfig:
+ name: str
+ primary_keys: list[str]
+ incremental_fields: list[IncrementalField]
+ # Stable datetime field used for partitioning. Must never change for a row
+ # (so `createdAt`, never `updatedAt`). `None` disables partitioning.
+ partition_key: Optional[str] = None
+
+
+def _created_at_incremental_field() -> list[IncrementalField]:
+ return [
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+# Metaplane's public API has no list-all-monitors endpoint — monitors hang off connections
+# (`/v1/monitors/connection/{connectionId}`) and evaluations hang off monitors
+# (`/v1/monitors/evaluation-history/{monitorId}`), so every endpoint below except
+# `connections` fans out from the connection list. Tag endpoints are excluded: they
+# require tag names as input and expose no way to enumerate tags.
+METAPLANE_ENDPOINTS: dict[str, MetaplaneEndpointConfig] = {
+ # GET /v1/connections — one row per connected source (warehouse, BI tool, ...).
+ # Single unpaginated response, no server-side time filter -> full refresh only.
+ "connections": MetaplaneEndpointConfig(
+ name="connections",
+ primary_keys=["id"],
+ incremental_fields=[],
+ ),
+ # GET /v1/monitors/connection/{connectionId} per connection. Monitor ids are UUIDs
+ # (globally unique). No pagination or time filter -> full refresh only.
+ "monitors": MetaplaneEndpointConfig(
+ name="monitors",
+ primary_keys=["id"],
+ incremental_fields=[],
+ ),
+ # POST /v1/monitors/evaluation-history/{monitorId} per monitor. Evaluations carry no id
+ # of their own, so the key is the injected monitorId plus the evaluation timestamp.
+ # The endpoint accepts a server-side `createdAt` cursor with ASC ordering, enabling
+ # incremental sync. Merge-only (no append): the cursor's inclusivity is undocumented, so
+ # incremental runs may re-pull the watermark row and rely on merge to dedupe it.
+ "monitor_evaluations": MetaplaneEndpointConfig(
+ name="monitor_evaluations",
+ primary_keys=["monitorId", "createdAt"],
+ partition_key="createdAt",
+ incremental_fields=_created_at_incremental_field(),
+ ),
+ # GET /v1/connections/{connectionId}/sync/status per connection — the latest sync
+ # outcome only (no history endpoint exists), so one row per connection, full refresh.
+ "connection_sync_statuses": MetaplaneEndpointConfig(
+ name="connection_sync_statuses",
+ primary_keys=["connectionId"],
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(METAPLANE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in METAPLANE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/source.py
index c67cf683d6ee..d7c2794e6009 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/source.py
@@ -1,19 +1,44 @@
-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 MetaplaneSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.metaplane import (
+ METAPLANE_BASE_URL,
+ MetaplaneResumeConfig,
+ metaplane_source,
+ validate_credentials as validate_metaplane_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ METAPLANE_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MetaplaneSource(SimpleSource[MetaplaneSourceConfig]):
+class MetaplaneSource(ResumableSource[MetaplaneSourceConfig, MetaplaneResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.METAPLANE
@@ -24,7 +49,117 @@ class MetaplaneSource(SimpleSource[MetaplaneSourceConfig]):
name=SchemaExternalDataSourceType.METAPLANE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Metaplane by Datadog",
+ keywords=["data observability", "data quality", "datadog"],
+ caption="""Enter your Metaplane API key to pull your data observability monitors and their evaluation history into the PostHog Data warehouse.
+
+You can generate an API key in your Metaplane account settings. A paid Metaplane plan is required for API access.
+""",
iconPath="/static/services/metaplane.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/metaplane",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # An invalid or revoked key surfaces as a requests HTTPError when `_request` calls
+ # `raise_for_status()`. Match the stable status text and base host, not the
+ # per-request path.
+ return {
+ f"401 Client Error: Unauthorized for url: {METAPLANE_BASE_URL}": (
+ "Your Metaplane API key is invalid or has been revoked. Generate a new key in "
+ "your Metaplane account settings, then reconnect."
+ ),
+ f"403 Client Error: Forbidden for url: {METAPLANE_BASE_URL}": (
+ "Your Metaplane API key does not have access to this data. Check the key in "
+ "your Metaplane account settings, then reconnect."
+ ),
+ }
+
+ def get_schemas(
+ self,
+ config: MetaplaneSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "monitor_evaluations":
+ return (
+ "One row per monitor evaluation (pass/fail, value, expected bounds). Incremental "
+ "syncs pull evaluations newer than the last-seen creation time across all monitors; "
+ "monitors added after the initial sync backfill from that watermark forward — run a "
+ "full refresh to pull their complete history"
+ )
+ if endpoint == "connection_sync_statuses":
+ return "The latest sync outcome per connection (not a history)"
+ return None
+
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ # Merge-only: the evaluation-history cursor's inclusivity is undocumented, so
+ # incremental runs may re-pull the watermark row; append would duplicate it.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=_description(endpoint),
+ detected_primary_keys=METAPLANE_ENDPOINTS[endpoint].primary_keys,
+ )
+ 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: MetaplaneSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Metaplane API keys are account-wide (no per-endpoint scopes), so the same probe
+ # covers source-create and per-schema validation.
+ if validate_metaplane_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Metaplane API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MetaplaneResumeConfig]:
+ return ResumableSourceManager[MetaplaneResumeConfig](inputs, MetaplaneResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MetaplaneSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MetaplaneResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return metaplane_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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/tests/test_metaplane.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/tests/test_metaplane.py
new file mode 100644
index 000000000000..d8ce9c99b8d5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/tests/test_metaplane.py
@@ -0,0 +1,362 @@
+import re
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.metaplane import (
+ EVALUATION_PAGE_LIMIT,
+ METAPLANE_BASE_URL,
+ MetaplaneResumeConfig,
+ _format_datetime,
+ _make_session,
+ get_rows,
+ metaplane_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.settings import METAPLANE_ENDPOINTS
+
+METAPLANE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.metaplane"
+
+
+def _response(body: Any, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ resp.url = f"{METAPLANE_BASE_URL}/test"
+ return resp
+
+
+class _FakeAPI:
+ """Routes tracked-session requests to canned Metaplane responses, recording every call."""
+
+ def __init__(
+ self,
+ connections: list[dict[str, Any]] | None = None,
+ monitors_by_connection: dict[str, Any] | None = None,
+ evaluation_pages_by_monitor: dict[str, list[Any]] | None = None,
+ sync_status_by_connection: dict[str, Any] | None = None,
+ ) -> None:
+ self.connections = connections or []
+ self.monitors_by_connection = monitors_by_connection or {}
+ self.evaluation_pages_by_monitor = {k: list(v) for k, v in (evaluation_pages_by_monitor or {}).items()}
+ self.sync_status_by_connection = sync_status_by_connection or {}
+ self.calls: list[tuple[str, str, Any]] = []
+
+ def request(self, method: str, url: str, headers: Any = None, json: Any = None, timeout: Any = None) -> Response:
+ self.calls.append((method, url, json))
+
+ if url == f"{METAPLANE_BASE_URL}/connections":
+ return _response(self.connections)
+
+ match = re.fullmatch(rf"{METAPLANE_BASE_URL}/monitors/connection/([^/?]+)\?includeDisabled=true", url)
+ if match:
+ monitors = self.monitors_by_connection.get(match.group(1))
+ if monitors is None:
+ return _response({}, status_code=404)
+ return _response({"data": monitors})
+
+ match = re.fullmatch(rf"{METAPLANE_BASE_URL}/monitors/evaluation-history/([^/?]+)", url)
+ if match:
+ pages = self.evaluation_pages_by_monitor.get(match.group(1))
+ if pages is None:
+ return _response({}, status_code=404)
+ return _response(pages.pop(0) if pages else [])
+
+ match = re.fullmatch(rf"{METAPLANE_BASE_URL}/connections/([^/?]+)/sync/status", url)
+ if match:
+ status = self.sync_status_by_connection.get(match.group(1))
+ if status is None:
+ return _response({}, status_code=404)
+ return _response(status)
+
+ raise AssertionError(f"Unexpected request: {method} {url}")
+
+ def evaluation_bodies(self, monitor_id: str) -> list[Any]:
+ return [
+ body
+ for method, url, body in self.calls
+ if method == "POST" and url == f"{METAPLANE_BASE_URL}/monitors/evaluation-history/{monitor_id}"
+ ]
+
+
+def _make_manager(resume: MetaplaneResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _drive(
+ api: _FakeAPI,
+ endpoint: str,
+ manager: MagicMock | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> list[list[dict[str, Any]]]:
+ with patch(f"{METAPLANE_MODULE}.make_tracked_session", return_value=api):
+ return list(
+ get_rows(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager if manager is not None else _make_manager(),
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ )
+
+
+def _evaluation(created_at: str, **extra: Any) -> dict[str, Any]:
+ return {"createdAt": created_at, "result": 1.0, "passed": True, **extra}
+
+
+class TestFormatDatetime:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ ("naive_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ (
+ "microseconds_truncated_to_millis",
+ datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC),
+ "2026-01-15T10:30:45.123Z",
+ ),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("string_passthrough", "2026-03-04T02:58:14.000Z", "2026-03-04T02:58:14.000Z"),
+ ]
+ )
+ def test_format_datetime(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_datetime(value) == expected
+
+
+class TestMakeSession:
+ def test_disables_sample_capture_and_redacts_key(self) -> None:
+ # Metaplane response bodies carry free-form tenant data (monitor descriptions, custom SQL
+ # config, error messages) the name-based scrubbers can't recognise, so sample capture must
+ # stay off and the API key is redacted as defense in depth.
+ with patch(f"{METAPLANE_MODULE}.make_tracked_session") as mock_make:
+ _make_session("mp-secret")
+ assert mock_make.call_args.kwargs["capture"] is False
+ assert mock_make.call_args.kwargs["redact_values"] == ("mp-secret",)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_code_mapping(self, _name: str, status_code: int, expected: bool) -> None:
+ with patch(f"{METAPLANE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response([], status_code=status_code)
+ assert validate_credentials("key") is expected
+
+ def test_network_error_returns_invalid(self) -> None:
+ with patch(f"{METAPLANE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+ def test_raw_api_key_in_authorization_header(self) -> None:
+ # Metaplane expects the bare key, not a Bearer-prefixed one — a prefix breaks auth.
+ with patch(f"{METAPLANE_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response([], status_code=200)
+ validate_credentials("mp-key")
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "mp-key"
+
+
+class TestConnectionsEndpoint:
+ def test_yields_connection_rows(self) -> None:
+ api = _FakeAPI(connections=[{"id": "c1"}, {"id": "c2"}])
+ assert _drive(api, "connections") == [[{"id": "c1"}, {"id": "c2"}]]
+
+ def test_empty_account_yields_nothing(self) -> None:
+ assert _drive(_FakeAPI(connections=[]), "connections") == []
+
+
+class TestMonitorsEndpoint:
+ def test_fans_out_over_connections(self) -> None:
+ api = _FakeAPI(
+ connections=[{"id": "c1"}, {"id": "c2"}],
+ monitors_by_connection={"c1": [{"id": "m1"}], "c2": [{"id": "m2"}, {"id": "m3"}]},
+ )
+ batches = _drive(api, "monitors")
+ assert [row["id"] for batch in batches for row in batch] == ["m1", "m2", "m3"]
+
+ def test_deleted_connection_is_skipped(self) -> None:
+ # c1 404s (deleted between enumeration and fetch); the sync must continue with c2.
+ api = _FakeAPI(connections=[{"id": "c1"}, {"id": "c2"}], monitors_by_connection={"c2": [{"id": "m2"}]})
+ batches = _drive(api, "monitors")
+ assert [row["id"] for batch in batches for row in batch] == ["m2"]
+
+
+class TestConnectionSyncStatusesEndpoint:
+ def test_rows_keyed_on_connection(self) -> None:
+ # The API response carries connectionId itself, but a missing one must still be
+ # filled in — it's the table's primary key.
+ api = _FakeAPI(
+ connections=[{"id": "c1"}, {"id": "c2"}],
+ sync_status_by_connection={
+ "c1": {"status": "SUCCEEDED", "connectionId": "c1"},
+ "c2": {"status": "ERRORED"},
+ },
+ )
+ batches = _drive(api, "connection_sync_statuses")
+ assert [(row["connectionId"], row["status"]) for batch in batches for row in batch] == [
+ ("c1", "SUCCEEDED"),
+ ("c2", "ERRORED"),
+ ]
+
+ def test_connection_without_status_is_skipped(self) -> None:
+ api = _FakeAPI(
+ connections=[{"id": "c1"}, {"id": "c2"}],
+ sync_status_by_connection={"c2": {"status": "SUCCEEDED", "connectionId": "c2"}},
+ )
+ batches = _drive(api, "connection_sync_statuses")
+ assert [row["connectionId"] for batch in batches for row in batch] == ["c2"]
+
+
+class TestEvaluationHistory:
+ def _single_monitor_api(self, pages: list[Any]) -> _FakeAPI:
+ return _FakeAPI(
+ connections=[{"id": "c1"}],
+ monitors_by_connection={"c1": [{"id": "m1"}]},
+ evaluation_pages_by_monitor={"m1": pages},
+ )
+
+ def test_rows_carry_injected_monitor_id(self) -> None:
+ api = self._single_monitor_api([[_evaluation("2026-01-01T00:00:00.000Z")]])
+ batches = _drive(api, "monitor_evaluations")
+ assert batches == [
+ [{"createdAt": "2026-01-01T00:00:00.000Z", "result": 1.0, "passed": True, "monitorId": "m1"}]
+ ]
+
+ def test_full_page_requests_next_page_from_last_created_at(self) -> None:
+ full_page = [_evaluation(f"2026-01-01T00:00:{i:02d}.000Z") for i in range(EVALUATION_PAGE_LIMIT)]
+ api = self._single_monitor_api([full_page, [_evaluation("2026-01-01T01:00:00.000Z")]])
+ manager = _make_manager()
+
+ _drive(api, "monitor_evaluations", manager)
+
+ bodies = api.evaluation_bodies("m1")
+ assert "createdAt" not in bodies[0]
+ assert bodies[0]["sortOrder"] == "ASC"
+ assert bodies[1]["createdAt"] == full_page[-1]["createdAt"]
+ # State is saved after yielding the full page so a crash re-yields it (merge dedupes).
+ manager.save_state.assert_called_once_with(
+ MetaplaneResumeConfig(monitor_id="m1", cursor=full_page[-1]["createdAt"])
+ )
+
+ def test_short_page_terminates_pagination(self) -> None:
+ api = self._single_monitor_api([[_evaluation("2026-01-01T00:00:00.000Z")]])
+ _drive(api, "monitor_evaluations")
+ assert len(api.evaluation_bodies("m1")) == 1
+
+ def test_non_advancing_cursor_stops_pagination(self) -> None:
+ # A full page of identical timestamps would otherwise re-request the same page forever.
+ same_ts_page = [_evaluation("2026-01-01T00:00:00.000Z") for _ in range(EVALUATION_PAGE_LIMIT)]
+ api = self._single_monitor_api([same_ts_page, same_ts_page])
+ manager = _make_manager(MetaplaneResumeConfig(monitor_id="m1", cursor="2026-01-01T00:00:00.000Z"))
+
+ batches = _drive(api, "monitor_evaluations", manager)
+
+ assert len(api.evaluation_bodies("m1")) == 1
+ assert len(batches) == 1
+
+ def test_incremental_watermark_seeds_initial_cursor(self) -> None:
+ api = self._single_monitor_api([[_evaluation("2026-03-05T00:00:00.000Z")]])
+ _drive(
+ api,
+ "monitor_evaluations",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert api.evaluation_bodies("m1")[0]["createdAt"] == "2026-03-04T02:58:14.000Z"
+
+ def test_full_refresh_omits_cursor(self) -> None:
+ api = self._single_monitor_api([[_evaluation("2026-03-05T00:00:00.000Z")]])
+ _drive(api, "monitor_evaluations")
+ assert "createdAt" not in api.evaluation_bodies("m1")[0]
+
+ def test_bookmark_advances_to_next_monitor(self) -> None:
+ api = _FakeAPI(
+ connections=[{"id": "c1"}],
+ monitors_by_connection={"c1": [{"id": "m1"}, {"id": "m2"}]},
+ evaluation_pages_by_monitor={
+ "m1": [[_evaluation("2026-01-01T00:00:00.000Z")]],
+ "m2": [[_evaluation("2026-01-02T00:00:00.000Z")]],
+ },
+ )
+ manager = _make_manager()
+
+ batches = _drive(api, "monitor_evaluations", manager)
+
+ assert [row["monitorId"] for batch in batches for row in batch] == ["m1", "m2"]
+ # After finishing m1 the bookmark moves to m2 so a crash between monitors resumes there.
+ manager.save_state.assert_called_once_with(MetaplaneResumeConfig(monitor_id="m2", cursor=None))
+
+ def test_resume_skips_completed_monitors_and_uses_saved_cursor(self) -> None:
+ api = _FakeAPI(
+ connections=[{"id": "c1"}],
+ monitors_by_connection={"c1": [{"id": "m1"}, {"id": "m2"}]},
+ evaluation_pages_by_monitor={
+ "m1": [[_evaluation("2026-01-01T00:00:00.000Z")]],
+ "m2": [[_evaluation("2026-01-02T00:00:00.000Z")]],
+ },
+ )
+ manager = _make_manager(MetaplaneResumeConfig(monitor_id="m2", cursor="2026-01-01T12:00:00.000Z"))
+
+ batches = _drive(api, "monitor_evaluations", manager)
+
+ assert api.evaluation_bodies("m1") == []
+ assert api.evaluation_bodies("m2")[0]["createdAt"] == "2026-01-01T12:00:00.000Z"
+ assert [row["monitorId"] for batch in batches for row in batch] == ["m2"]
+
+ def test_resume_with_deleted_bookmark_monitor_starts_over(self) -> None:
+ api = self._single_monitor_api([[_evaluation("2026-01-01T00:00:00.000Z")]])
+ manager = _make_manager(MetaplaneResumeConfig(monitor_id="gone", cursor="2026-01-01T12:00:00.000Z"))
+
+ batches = _drive(api, "monitor_evaluations", manager)
+
+ assert [row["monitorId"] for batch in batches for row in batch] == ["m1"]
+ assert "createdAt" not in api.evaluation_bodies("m1")[0]
+
+ def test_monitor_without_history_is_skipped(self) -> None:
+ # A monitor that was deleted (or never modeled) 404s; the sync continues with the rest.
+ api = _FakeAPI(
+ connections=[{"id": "c1"}],
+ monitors_by_connection={"c1": [{"id": "m1"}, {"id": "m2"}]},
+ evaluation_pages_by_monitor={"m2": [[_evaluation("2026-01-02T00:00:00.000Z")]]},
+ )
+ batches = _drive(api, "monitor_evaluations")
+ assert [row["monitorId"] for batch in batches for row in batch] == ["m2"]
+
+
+class TestMetaplaneSourceResponse:
+ @parameterized.expand([(name,) for name in sorted(METAPLANE_ENDPOINTS)])
+ def test_source_response_matches_endpoint_settings(self, endpoint: str) -> None:
+ response = metaplane_source(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_make_manager(),
+ )
+ config = METAPLANE_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # Only the monitor fan-out defers the watermark to job end.
+ assert response.sort_mode == ("desc" if endpoint == "monitor_evaluations" else "asc")
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/tests/test_metaplane_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/tests/test_metaplane_source.py
new file mode 100644
index 000000000000..ce12689c413c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metaplane/tests/test_metaplane_source.py
@@ -0,0 +1,128 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+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 MetaplaneSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.metaplane import MetaplaneResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.source import MetaplaneSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> mock.MagicMock:
+ inputs = mock.MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "monitor_evaluations")
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)
+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)
+ return inputs
+
+
+class TestMetaplaneSource:
+ def setup_method(self) -> None:
+ self.source = MetaplaneSource()
+ self.team_id = 123
+ self.config = MetaplaneSourceConfig(api_key="mp-test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.METAPLANE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Metaplane"
+ assert config.label == "Metaplane by Datadog"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is not True
+ assert len(config.fields) == 1
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+
+ def test_get_schemas_matches_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))
+ def test_get_schemas_incremental_flags(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ expected_incremental = endpoint == "monitor_evaluations"
+ assert schema.supports_incremental is expected_incremental
+ # Merge-only everywhere: the evaluation cursor may re-pull the watermark row,
+ # which append mode would materialize as a duplicate.
+ assert schema.supports_append is False
+ if expected_incremental:
+ assert [f["field"] for f in schema.incremental_fields] == ["createdAt"]
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["monitors"])
+ assert [s.name for s in schemas] == ["monitors"]
+
+ @pytest.mark.parametrize("expected_key_prefix", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key_prefix: str) -> None:
+ errors = self.source.get_non_retryable_errors()
+ assert any(key.startswith(expected_key_prefix) for key in errors)
+
+ @pytest.mark.parametrize(
+ "is_valid, expected_valid, expected_has_message",
+ [
+ (True, True, False),
+ (False, False, True),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.source.validate_metaplane_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ is_valid: bool,
+ expected_valid: bool,
+ expected_has_message: bool,
+ ) -> None:
+ mock_validate.return_value = is_valid
+ valid, message = self.source.validate_credentials(self.config, self.team_id)
+ assert valid is expected_valid
+ assert (message is not None) is expected_has_message
+ mock_validate.assert_called_once_with(self.config.api_key)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MetaplaneResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.source.metaplane_source")
+ def test_source_for_pipeline_passes_arguments(self, mock_metaplane_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(
+ schema_name="monitor_evaluations",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_metaplane_source.call_args
+ assert kwargs["api_key"] == self.config.api_key
+ assert kwargs["endpoint"] == "monitor_evaluations"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.metaplane.source.metaplane_source")
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(
+ self, mock_metaplane_source: mock.MagicMock
+ ) -> None:
+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="ignored")
+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)
+
+ _, kwargs = mock_metaplane_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None