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-catalog): metric-run endpoint over the query runner (#69530)

Thiago Salvatore2643a99b6779
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 8d5558dde57c..d48476db78ee 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -52,6 +52,7 @@ class Product(StrEnum):
COHORTS = "cohorts"
CONVERSATIONS = "conversations"
CUSTOMER_ANALYTICS = "customer_analytics"
+ DATA_CATALOG = "data_catalog"
ENDPOINTS = "endpoints"
ENGINEERING_ANALYTICS = "engineering_analytics"
ERROR_TRACKING = "error_tracking"
diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.py
index a4fd09302913..9f7b56ba7afe 100644
--- a/products/data_catalog/backend/facade/api.py
+++ b/products/data_catalog/backend/facade/api.py
@@ -7,6 +7,7 @@ into ``logic`` or ``models`` directly.
"""
from ..logic.drift import compute_drift
+from ..logic.execution import run_metric
from ..logic.metrics import (
approve_metric,
metrics_for_team,
@@ -24,6 +25,7 @@ __all__ = [
"compute_drift",
"metrics_for_team",
"refresh_metric_from_insight",
+ "run_metric",
"soft_delete_metric",
"update_metric",
"upsert_metric",
diff --git a/products/data_catalog/backend/facade/enums.py b/products/data_catalog/backend/facade/enums.py
index a3c64ad2716d..2954602f0096 100644
--- a/products/data_catalog/backend/facade/enums.py
+++ b/products/data_catalog/backend/facade/enums.py
@@ -12,6 +12,13 @@ from enum import StrEnum
# follows the steps. JSX object references inside the markdown are a future expansion.
MARKDOWN_DEFINITION_KIND = "MarkdownDefinition"
+# Query kinds an executable metric definition may take, split by how they run. Validation maps each
+# kind to its posthog.schema model; execution wraps node kinds in a single-series TrendsQuery (they
+# have no query runner of their own); the API picks query throttles from the same split.
+HOGQL_DEFINITION_KIND = "HogQLQuery"
+NODE_DEFINITION_KINDS = ("EventsNode", "ActionsNode", "DataWarehouseNode")
+INSIGHT_DEFINITION_KINDS = ("TrendsQuery", "FunnelsQuery")
+
class MetricStatus(StrEnum):
"""Persisted lifecycle state of a metric. ``drifted`` is computed at read time, never stored."""
diff --git a/products/data_catalog/backend/logic/execution.py b/products/data_catalog/backend/logic/execution.py
new file mode 100644
index 000000000000..0587c34e0cf2
--- /dev/null
+++ b/products/data_catalog/backend/logic/execution.py
@@ -0,0 +1,228 @@
+"""Metric execution — run a metric's definition through the standard HogQL query runner.
+
+The definition is executed through the same engine as insights and the SQL editor, so results are
+identical. Bare series nodes (EventsNode, ActionsNode, DataWarehouseNode) aren't runnable on their
+own, so they execute as a single-series trends query; the envelope keeps the stored kind. Date
+params map into the prepared query's dateRange for insight/node kinds and are rejected on HogQLQuery
+kinds, whose window is fixed in the SQL. The deep link encodes the prepared query — overrides
+included — so opening it reproduces exactly what ran.
+"""
+
+import json
+from copy import deepcopy
+from datetime import timedelta
+from typing import Optional
+from urllib.parse import quote
+
+from django.utils import timezone
+
+from pydantic import BaseModel
+from rest_framework.exceptions import Throttled, ValidationError
+
+from posthog.hogql.errors import ExposedHogQLError
+
+from posthog.api.services.query import process_query_dict
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
+from posthog.clickhouse.query_tagging import (
+ Feature,
+ Product,
+ get_query_tag_value,
+ is_api_key_access_method,
+ tags_context,
+)
+from posthog.errors import ExposedCHQueryError
+from posthog.event_usage import report_user_action
+from posthog.exceptions_capture import capture_exception
+from posthog.hogql_queries.query_runner import ExecutionMode, execution_mode_from_refresh
+from posthog.models import Team, User
+from posthog.utils import absolute_uri
+
+from ..facade.enums import HOGQL_DEFINITION_KIND, MARKDOWN_DEFINITION_KIND, NODE_DEFINITION_KINDS
+from ..models import Metric
+from .drift import compute_drift
+from .exceptions import MetricHasNoDefinition
+
+_LAST_RUN_THROTTLE = timedelta(minutes=30)
+
+# Same wording as /query/'s concurrency response, so agents see one message for one condition.
+_CONCURRENCY_LIMIT_MESSAGE = "Too many queries are running right now — please try again in a moment."
+
+
+def run_metric(
+ *,
+ team: Team,
+ metric: Metric,
+ user: Optional[User],
+ refresh: bool | str | None = None,
+ date_from: Optional[str] = None,
+ date_to: Optional[str] = None,
+ interval: Optional[str] = None,
+ query_id: Optional[str] = None,
+) -> dict:
+ if not metric.definition:
+ raise MetricHasNoDefinition()
+
+ is_drifted = compute_drift([metric])[metric.id]
+
+ if metric.definition_kind == MARKDOWN_DEFINITION_KIND:
+ # Agent-calculated: return the steps to follow instead of executing a query. Still recorded
+ # as a run for attribution.
+ _touch_last_run(team, metric)
+ _capture_run(user, team, metric, is_drifted)
+ return _markdown_envelope(metric, is_drifted)
+
+ query = prepare_execution_query(metric.definition, date_from=date_from, date_to=date_to, interval=interval)
+
+ execution_mode = (
+ execution_mode_from_refresh(refresh) if refresh else ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ )
+ try:
+ with tags_context(product=Product.DATA_CATALOG, feature=Feature.QUERY):
+ raw = process_query_dict(
+ team,
+ query,
+ execution_mode=execution_mode,
+ user=user,
+ query_id=query_id,
+ # Mirror /query and endpoint execution: API-key runs are subject to the same query
+ # safeguards (rejected constructs, API-team concurrency limiter) as those paths.
+ is_query_service=is_api_key_access_method(get_query_tag_value("access_method")),
+ )
+ except (ExposedHogQLError, ExposedCHQueryError) as e:
+ raise ValidationError(
+ {
+ "field": "definition",
+ "error": f"This metric could not run: {e}",
+ "hint": "A table or column it references may no longer exist. Check system.information_schema.tables.",
+ }
+ )
+ except ConcurrencyLimitExceeded:
+ raise Throttled(detail=_CONCURRENCY_LIMIT_MESSAGE)
+ except ValidationError:
+ raise
+ except Exception as e:
+ capture_exception(e)
+ raise
+
+ payload = raw.model_dump(mode="json") if isinstance(raw, BaseModel) else raw
+ payload = payload if isinstance(payload, dict) else {}
+ if payload.get("error"):
+ # The engine reports schema-validation failures as an error payload instead of raising; a
+ # run that produced no results must not read as a success.
+ raise ValidationError(
+ {
+ "field": "definition",
+ "error": f"This metric could not run: {payload['error']}",
+ "hint": "The definition (or a date/interval override) does not form a valid query.",
+ }
+ )
+
+ _touch_last_run(team, metric)
+ _capture_run(user, team, metric, is_drifted)
+ return _envelope(metric, payload, team, query, is_drifted)
+
+
+def prepare_execution_query(
+ definition: dict,
+ *,
+ date_from: Optional[str] = None,
+ date_to: Optional[str] = None,
+ interval: Optional[str] = None,
+) -> dict:
+ """The exact query handed to the engine: the stored definition, node kinds wrapped runnable,
+ date/interval overrides applied."""
+ query = deepcopy(definition)
+ if query.get("kind") in NODE_DEFINITION_KINDS:
+ # A bare series node has no query runner of its own; run it as a single-series trends query.
+ query = {"kind": "TrendsQuery", "series": [query]}
+ _apply_date_params(query, date_from, date_to, interval)
+ return query
+
+
+def _apply_date_params(query: dict, date_from: Optional[str], date_to: Optional[str], interval: Optional[str]) -> None:
+ if date_from is None and date_to is None and interval is None:
+ return
+ if query.get("kind") == HOGQL_DEFINITION_KIND:
+ field = "date_from" if date_from is not None else ("date_to" if date_to is not None else "interval")
+ raise ValidationError(
+ {
+ "field": field,
+ "error": "This metric's dates are fixed in its SQL and cannot be overridden at run time.",
+ "hint": "Report the definition's own window, or ask for a parameterized metric.",
+ }
+ )
+ date_range = dict(query.get("dateRange") or {})
+ if date_from is not None:
+ date_range["date_from"] = date_from
+ if date_to is not None:
+ date_range["date_to"] = date_to
+ if date_range:
+ query["dateRange"] = date_range
+ if interval is not None:
+ query["interval"] = interval
+
+
+def _envelope(metric: Metric, payload: dict, team: Team, prepared_query: dict, is_drifted: bool) -> dict:
+ return {
+ "status": metric.status,
+ "is_drifted": is_drifted,
+ "unit": metric.unit or None,
+ "kind": metric.definition_kind,
+ "results": payload.get("results"),
+ "compiled_query": payload.get("hogql"),
+ "query_status": payload.get("query_status"),
+ "posthog_url": _deep_link(team, prepared_query),
+ "instructions": None,
+ }
+
+
+def _markdown_envelope(metric: Metric, is_drifted: bool) -> dict:
+ return {
+ "status": metric.status,
+ "is_drifted": is_drifted,
+ "unit": metric.unit or None,
+ "kind": metric.definition_kind,
+ "results": None,
+ "compiled_query": None,
+ "query_status": None,
+ "posthog_url": None,
+ "instructions": (metric.definition or {}).get("markdown"),
+ }
+
+
+def _deep_link(team: Team, prepared_query: dict) -> str:
+ if prepared_query.get("kind") == HOGQL_DEFINITION_KIND:
+ # A JSON node in open_query prefills the SQL editor with the full query, values included;
+ # a bare SQL string would drop the values.
+ node = {"kind": "DataVisualizationNode", "source": prepared_query}
+ path = f"/project/{team.id}/sql?open_query={quote(json.dumps(node))}"
+ else:
+ # The insight scene expects the InsightVizNode wrapper insights themselves store in #q=.
+ node = {"kind": "InsightVizNode", "source": prepared_query}
+ path = f"/project/{team.id}/insights/new#q={quote(json.dumps(node))}"
+ return absolute_uri(path)
+
+
+def _touch_last_run(team: Team, metric: Metric) -> None:
+ now = timezone.now()
+ if metric.last_run_at is None or (now - metric.last_run_at) > _LAST_RUN_THROTTLE:
+ # Bypass save() (and the activity mixin) — a run is not an audit-worthy change.
+ Metric.objects.for_team(team.id).filter(pk=metric.pk).update(last_run_at=now)
+ metric.last_run_at = now
+
+
+def _capture_run(user: Optional[User], team: Team, metric: Metric, is_drifted: bool) -> None:
+ if user is None:
+ return
+ report_user_action(
+ user=user,
+ event="data catalog metric run",
+ team=team,
+ properties={
+ "metric_id": str(metric.id),
+ "metric_name": metric.name,
+ "definition_kind": metric.definition_kind,
+ "status": metric.status,
+ "is_drifted": is_drifted,
+ },
+ )
diff --git a/products/data_catalog/backend/logic/validation.py b/products/data_catalog/backend/logic/validation.py
index a520d7c3482a..63a26cf550b2 100644
--- a/products/data_catalog/backend/logic/validation.py
+++ b/products/data_catalog/backend/logic/validation.py
@@ -23,17 +23,18 @@ from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
from posthog.schema_migrations.upgrade import upgrade
-from ..facade.enums import MARKDOWN_DEFINITION_KIND
+from ..facade.enums import HOGQL_DEFINITION_KIND, MARKDOWN_DEFINITION_KIND
-# Query kinds a metric definition may take. Node kinds are the RFC's "event with filters"
-# single series; insight kinds are the classic viz shapes. Kept small on purpose.
+# Query kinds a metric definition may take (the facade enums are the public split). Node kinds are
+# the RFC's "event with filters" single series; insight kinds are the classic viz shapes. Kept
+# small on purpose.
_NODE_MODELS: dict[str, type[BaseModel]] = {
"EventsNode": EventsNode,
"ActionsNode": ActionsNode,
"DataWarehouseNode": DataWarehouseNode,
}
_INSIGHT_MODELS: dict[str, type[BaseModel]] = {"TrendsQuery": TrendsQuery, "FunnelsQuery": FunnelsQuery}
-_SUPPORTED_KINDS = {"HogQLQuery", *_NODE_MODELS, *_INSIGHT_MODELS}
+_SUPPORTED_KINDS = {HOGQL_DEFINITION_KIND, *_NODE_MODELS, *_INSIGHT_MODELS}
# A markdown definition is a bounded blob; keep it small so it stays a definition, not a document.
MAX_MARKDOWN_DEFINITION_LENGTH = 20_000
diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.py
index 68547c536797..db1b59ef7e6b 100644
--- a/products/data_catalog/backend/presentation/serializers.py
+++ b/products/data_catalog/backend/presentation/serializers.py
@@ -10,6 +10,7 @@ from drf_spectacular.utils import extend_schema_field, extend_schema_serializer
from rest_framework import serializers
from posthog.api.shared import UserBasicSerializer
+from posthog.schema_enums import IntervalType
from ..facade import api
from ..facade.enums import CreatedSource
@@ -21,6 +22,65 @@ class MetricDefinitionField(serializers.JSONField):
"""A machine-readable query (HogQLQuery, TrendsQuery, event node, ...). Typed as a free object."""
+@extend_schema_field(OpenApiTypes.ANY)
+class _FreeJSONField(serializers.JSONField):
+ """A free-form JSON value (query results / query status shapes)."""
+
+
+@extend_schema_serializer(component_name="DataCatalogMetricRun")
+class MetricRunResponseSerializer(serializers.Serializer):
+ """Normalized envelope returned by the metric-run endpoint."""
+
+ status = serializers.CharField(help_text="Lifecycle state of the metric that produced these results.")
+ is_drifted = serializers.BooleanField(
+ help_text="True when the definition has drifted from its linked source insight (or the insight is gone). "
+ "Only status 'approved' with is_drifted false is canonical."
+ )
+ unit = serializers.CharField(allow_null=True, help_text="Unit of the result, e.g. usd, percent.")
+ kind = serializers.CharField(allow_null=True, help_text="Query kind that was executed.")
+ results = _FreeJSONField(
+ allow_null=True, help_text="The query results, for an executable metric. Null for a markdown metric."
+ )
+ compiled_query = serializers.CharField(allow_null=True, help_text="The compiled HogQL, when available.")
+ query_status = _FreeJSONField(allow_null=True, help_text="Async query status, when the run is not blocking.")
+ posthog_url = serializers.CharField(
+ allow_null=True, help_text="Deep link to open the query in the app (SQL editor or insight)."
+ )
+ instructions = serializers.CharField(
+ allow_null=True,
+ help_text="For a markdown (agent-calculated) metric, the steps to follow to compute it. Null for an executable metric.",
+ )
+
+
+@extend_schema_serializer(component_name="DataCatalogMetricRunRequest")
+class MetricRunRequestSerializer(serializers.Serializer):
+ """Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name."""
+
+ date_from = serializers.CharField(
+ required=False,
+ help_text="Override the start of the query window (e.g. '-7d'). Rejected for HogQLQuery metrics, whose window is fixed in SQL.",
+ )
+ date_to = serializers.CharField(required=False, help_text="Override the end of the query window.")
+ interval = serializers.ChoiceField(
+ choices=[t.value for t in IntervalType],
+ required=False,
+ help_text="Override the bucket interval. Rejected for HogQLQuery metrics.",
+ )
+ query_id = serializers.CharField(required=False, help_text="Client-supplied id to correlate or cancel the run.")
+
+
+@extend_schema_serializer(component_name="DataCatalogMetricRunQuery")
+class MetricRunQuerySerializer(serializers.Serializer):
+ """Query params for the metric-run endpoint."""
+
+ refresh = serializers.ChoiceField(
+ choices=["blocking", "async", "lazy_async", "force_blocking", "force_async", "force_cache"],
+ required=False,
+ help_text="Cache/execution behavior, same semantics as /query/. Omit to serve a fresh cache "
+ "hit and calculate blocking when stale.",
+ )
+
+
@extend_schema_serializer(component_name="DataCatalogMetric")
class MetricSerializer(serializers.ModelSerializer):
definition = MetricDefinitionField(
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index cc0ccc88ccf3..64015bf0192f 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -8,20 +8,34 @@ from typing import cast
from django.db.models import QuerySet
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import status, viewsets
-from rest_framework.exceptions import ValidationError
+from rest_framework.decorators import action as drf_action
+from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.models import User
+from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle, HogQLQueryThrottle
from ..facade import api
+from ..facade.enums import HOGQL_DEFINITION_KIND, INSIGHT_DEFINITION_KINDS, NODE_DEFINITION_KINDS
from ..facade.models import Metric
-from .serializers import MetricSerializer
+from .serializers import (
+ MetricRunQuerySerializer,
+ MetricRunRequestSerializer,
+ MetricRunResponseSerializer,
+ MetricSerializer,
+)
+
+# Kinds that execute a ClickHouse query through the trends/funnels pipeline (node kinds run as a
+# wrapped single-series trends query).
+_STRUCTURED_QUERY_KINDS = {*INSIGHT_DEFINITION_KINDS, *NODE_DEFINITION_KINDS}
class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
@@ -42,6 +56,22 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return ["data_catalog:write", "insight:read"]
return None
+ def get_throttles(self) -> list[BaseThrottle]:
+ # Running a metric executes a query, so it must carry the same query throttles as /query/;
+ # markdown and definition-less metrics never reach ClickHouse and keep the API defaults.
+ if getattr(self, "action", None) == "run":
+ kind = (
+ Metric.objects.for_team(self.team_id)
+ .filter(name=self.kwargs.get("name"), deleted=False)
+ .values_list("definition__kind", flat=True)
+ .first()
+ )
+ if kind == HOGQL_DEFINITION_KIND:
+ return [HogQLQueryThrottle()]
+ if kind in _STRUCTURED_QUERY_KINDS:
+ return [ClickHouseBurstRateThrottle(), ClickHouseSustainedRateThrottle()]
+ return super().get_throttles()
+
def list(self, request: Request, *args, **kwargs) -> Response:
# Precompute drift for the whole page in one bulk query, so is_drifted doesn't fan out
# into a per-metric insight lookup (an N+1 over the catalog list).
@@ -123,3 +153,46 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""Re-snapshot the linked insight's current query into the definition."""
metric = api.refresh_metric_from_insight(self.get_object(), cast(User, request.user))
return Response(self.get_serializer(metric).data)
+
+ # @extend_schema must sit OUTSIDE @action: DRF's @action resets func.kwargs, wiping any schema
+ # annotation applied earlier — including @validated_request's — from the generated OpenAPI.
+ @extend_schema(
+ request=MetricRunRequestSerializer,
+ parameters=[MetricRunQuerySerializer],
+ responses={
+ 200: OpenApiResponse(response=MetricRunResponseSerializer, description="The normalized run envelope."),
+ 400: OpenApiResponse(
+ description="The metric has no runnable definition, an override is invalid for its kind, or the query failed."
+ ),
+ 429: OpenApiResponse(description="Query rate limit or concurrency limit exceeded."),
+ 500: OpenApiResponse(description="Unexpected error while executing the query."),
+ },
+ )
+ @drf_action(
+ detail=True,
+ methods=["POST"],
+ required_scopes=["data_catalog:read", "query:read"],
+ )
+ @validated_request(
+ request_serializer=MetricRunRequestSerializer,
+ query_serializer=MetricRunQuerySerializer,
+ )
+ def run(self, request: ValidatedRequest, **kwargs) -> Response:
+ """Execute the metric's definition and return the normalized result envelope."""
+ # required_scopes gates tokens on query:read, but session users carry no scopes and
+ # AccessControlPermission only checks the data_catalog resource. Enforce query RBAC
+ # explicitly so a member with query access denied can't read data through a metric run.
+ if not self.user_access_control.check_access_level_for_resource("query", "viewer"):
+ raise PermissionDenied("You need query access to run a metric.")
+ overrides = request.validated_data
+ envelope = api.run_metric(
+ team=self.team,
+ metric=self.get_object(),
+ user=cast(User, request.user),
+ refresh=request.validated_query_data.get("refresh"),
+ date_from=overrides.get("date_from"),
+ date_to=overrides.get("date_to"),
+ interval=overrides.get("interval"),
+ query_id=overrides.get("query_id"),
+ )
+ return Response(envelope)
diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.py
index 2a2c28eba6e4..bcdba9897922 100644
--- a/products/data_catalog/backend/tests/test_api.py
+++ b/products/data_catalog/backend/tests/test_api.py
@@ -1,21 +1,31 @@
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+from django.core.cache import cache
from django.db import connection
+from django.test import SimpleTestCase
from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
+from posthog.models.organization import OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.rate_limit import ClickHouseBurstRateThrottle, HogQLQueryThrottle
from products.data_catalog.backend.facade.enums import MetricStatus
from products.data_catalog.backend.logic.metrics import upsert_metric
from products.data_catalog.backend.models import Metric
+from products.data_catalog.backend.presentation.serializers import MetricRunQuerySerializer, MetricRunRequestSerializer
from products.product_analytics.backend.models.insight import Insight
+from ee.models.rbac.access_control import AccessControl
+
_HOGQL = {"kind": "HogQLQuery", "query": "select count() from events"}
+_PROCESS_QUERY = "products.data_catalog.backend.logic.execution.process_query_dict"
class TestMetricAPI(APIBaseTest):
@@ -232,3 +242,162 @@ class TestMetricLifecycleAPI(APIBaseTest):
self.url, {"name": "mrr", "description": "d"}, format="json", **self._bearer(["data_catalog:write"])
)
assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ def test_run_without_definition_returns_400(self) -> None:
+ self.client.post(self.url, {"name": "mrr", "description": "stub only"}, format="json")
+ response = self.client.post(f"{self.url}mrr/run/")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_run_rejects_date_params_on_hogql_metric(self) -> None:
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ response = self.client.post(f"{self.url}mrr/run/", {"date_from": "-7d"}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_run_requires_query_read_scope(self) -> None:
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ self.client.logout()
+ # data_catalog:read alone is not enough — run also touches the query engine.
+ response = self.client.post(f"{self.url}mrr/run/", **self._bearer(["data_catalog:read"]))
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_run_denied_for_session_user_without_query_access(self) -> None:
+ # Session users carry no API scopes, so required_scopes can't gate them and
+ # AccessControlPermission only checks the data_catalog resource. A member with query
+ # access explicitly set to "none" must still be blocked from reading data through a run.
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save(update_fields=["level"])
+ AccessControl.objects.create(
+ team=self.team,
+ resource="query",
+ resource_id=None,
+ organization_member=self.organization_membership,
+ access_level="none",
+ )
+ cache.clear()
+ response = self.client.post(f"{self.url}mrr/run/")
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+
+ def test_run_markdown_metric_returns_instructions(self) -> None:
+ upsert_metric(
+ team=self.team,
+ user=self.user,
+ name="activation",
+ description="d",
+ definition={"kind": "MarkdownDefinition", "markdown": "1. User did A then B within 7 days."},
+ )
+ response = self.client.post(f"{self.url}activation/run/")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["kind"] == "MarkdownDefinition"
+ assert body["results"] is None
+ assert "A then B" in body["instructions"]
+
+ @parameterized.expand(
+ [
+ ("invalid_interval_in_body", {"interval": "fortnight"}, ""),
+ ("invalid_refresh_query_param", {}, "?refresh=nope"),
+ ]
+ )
+ def test_run_rejects_malformed_input(self, _name: str, body: dict, query_string: str) -> None:
+ # Wiring guard: the run action must validate through its serializers, so malformed input
+ # never reaches the query engine. The value matrix lives in TestMetricRunInputValidation.
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ response = self.client.post(f"{self.url}mrr/run/{query_string}", body, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_run_reports_drift_on_approved_metric(self) -> None:
+ # An approved metric whose source insight has moved on must say so in the run envelope —
+ # an agent decides trust from this response alone.
+ insight = Insight.objects.create(team=self.team, created_by=self.user, query=_HOGQL)
+ self.client.post(
+ self.url, {"name": "mrr", "description": "d", "source_insight_short_id": insight.short_id}, format="json"
+ )
+ assert self.client.post(f"{self.url}mrr/approve/").status_code == status.HTTP_200_OK
+ Insight.objects.filter(pk=insight.pk).update(
+ query={"kind": "HogQLQuery", "query": "select count() from persons"}
+ )
+
+ with patch(_PROCESS_QUERY, return_value={"results": [[1]], "hogql": "SELECT 1"}):
+ response = self.client.post(f"{self.url}mrr/run/")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["status"] == MetricStatus.APPROVED
+ assert body["is_drifted"] is True
+
+
+class TestMetricRunThrottles(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.url = f"/api/projects/{self.team.id}/data_catalog/metrics/"
+
+ def _denied(self, throttle_class: type) -> tuple:
+ return (
+ patch.object(throttle_class, "allow_request", return_value=False),
+ patch.object(throttle_class, "wait", return_value=None),
+ )
+
+ def test_hogql_metric_uses_hogql_query_throttle(self) -> None:
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ deny, wait = self._denied(HogQLQueryThrottle)
+ with deny, wait:
+ response = self.client.post(f"{self.url}mrr/run/")
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+
+ def test_structured_metric_uses_clickhouse_throttles(self) -> None:
+ upsert_metric(
+ team=self.team,
+ user=self.user,
+ name="purchases",
+ description="d",
+ definition={"kind": "EventsNode", "event": "purchase"},
+ )
+ deny, wait = self._denied(ClickHouseBurstRateThrottle)
+ with deny, wait:
+ response = self.client.post(f"{self.url}purchases/run/")
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+
+ def test_markdown_metric_keeps_default_throttles(self) -> None:
+ upsert_metric(
+ team=self.team,
+ user=self.user,
+ name="activation",
+ description="d",
+ definition={"kind": "MarkdownDefinition", "markdown": "1. Count."},
+ )
+ hogql_deny, hogql_wait = self._denied(HogQLQueryThrottle)
+ ch_deny, ch_wait = self._denied(ClickHouseBurstRateThrottle)
+ with hogql_deny, hogql_wait, ch_deny, ch_wait:
+ response = self.client.post(f"{self.url}activation/run/")
+ assert response.status_code == status.HTTP_200_OK
+
+
+class TestMetricRunInputValidation(SimpleTestCase):
+ @parameterized.expand([("day", True), ("month", True), ("fortnight", False), ("5m", False)])
+ def test_interval_choices(self, value: str, valid: bool) -> None:
+ serializer = MetricRunRequestSerializer(data={"interval": value})
+ assert serializer.is_valid() is valid
+ if not valid:
+ assert "interval" in serializer.errors
+
+ @parameterized.expand(
+ [
+ ("blocking", True),
+ ("async", True),
+ ("lazy_async", True),
+ ("force_blocking", True),
+ ("force_async", True),
+ ("force_cache", True),
+ ("true", False),
+ ("nope", False),
+ ]
+ )
+ def test_refresh_choices(self, value: str, valid: bool) -> None:
+ serializer = MetricRunQuerySerializer(data={"refresh": value})
+ assert serializer.is_valid() is valid
+ if not valid:
+ assert "refresh" in serializer.errors
diff --git a/products/data_catalog/backend/tests/test_execution.py b/products/data_catalog/backend/tests/test_execution.py
new file mode 100644
index 000000000000..ac34b4d1bd61
--- /dev/null
+++ b/products/data_catalog/backend/tests/test_execution.py
@@ -0,0 +1,243 @@
+import json
+from typing import cast
+from urllib.parse import parse_qs, unquote, urlparse
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.exceptions import Throttled, ValidationError
+
+from posthog.hogql.errors import ExposedHogQLError
+
+from posthog.api.services.query import process_query_dict
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_context
+from posthog.errors import ExposedCHQueryError
+from posthog.hogql_queries.query_runner import ExecutionMode
+
+from products.data_catalog.backend.logic.execution import prepare_execution_query, run_metric
+from products.data_catalog.backend.logic.metrics import upsert_metric
+from products.data_catalog.backend.models import Metric
+
+_HOGQL = {"kind": "HogQLQuery", "query": "select count() as c from events"}
+_EVENTS_NODE = {"kind": "EventsNode", "event": "purchase"}
+_PROCESS_QUERY = "products.data_catalog.backend.logic.execution.process_query_dict"
+_OK_PAYLOAD = {"results": [[1]], "hogql": "SELECT 1"}
+
+
+def _decoded_insight_link(url: str) -> dict:
+ fragment = urlparse(url).fragment
+ assert fragment.startswith("q="), url
+ return json.loads(unquote(fragment[2:]))
+
+
+def _decoded_sql_editor_link(url: str) -> dict:
+ return json.loads(parse_qs(urlparse(url).query)["open_query"][0])
+
+
+class TestMetricRunExecution(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.run_url = f"/api/projects/{self.team.id}/data_catalog/metrics/mrr/run/"
+ for i in range(3):
+ _create_event(team=self.team, event="purchase", distinct_id=f"user_{i}")
+ flush_persons_and_events()
+
+ def test_run_envelope_matches_direct_execution(self) -> None:
+ # The RFC's same-engine guarantee: metric-run must return exactly what running the definition
+ # directly returns, wrapped in the envelope.
+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ response = self.client.post(self.run_url)
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ body = response.json()
+ assert set(body) >= {"status", "is_drifted", "unit", "kind", "results", "compiled_query", "query_status"}
+ assert body["kind"] == "HogQLQuery"
+ assert body["is_drifted"] is False
+ assert "/sql?open_query=" in body["posthog_url"]
+
+ assert metric.definition is not None
+ direct = process_query_dict(
+ self.team, metric.definition, execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, user=self.user
+ )
+ direct_json = direct.model_dump(mode="json") if hasattr(direct, "model_dump") else direct
+ assert body["results"] == direct_json["results"]
+ assert body["results"] == [[3]]
+
+ def test_run_events_node_executes_as_trends(self) -> None:
+ # A bare EventsNode has no query runner; the run must still return the number by executing
+ # it as a single-series trends query, while the envelope keeps the stored kind.
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_EVENTS_NODE)
+ response = self.client.post(self.run_url)
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ body = response.json()
+ assert body["kind"] == "EventsNode"
+ assert body["results"][0]["count"] == 3
+
+
+class TestMetricRunPreparation(APIBaseTest):
+ def _run(self, definition: dict, **overrides: str) -> tuple[dict, dict]:
+ """Run a metric with the engine mocked; returns (query handed to the engine, envelope)."""
+ metric = upsert_metric(team=self.team, user=self.user, name="prep", description="d", definition=definition)
+ captured: dict = {}
+
+ def capture(team: object, query: dict, **kwargs: object) -> dict:
+ captured.update(query)
+ return dict(_OK_PAYLOAD)
+
+ with patch(_PROCESS_QUERY, side_effect=capture):
+ envelope = run_metric(team=self.team, metric=metric, user=self.user, **overrides)
+ return captured, envelope
+
+ @parameterized.expand(
+ [
+ ("events", {"kind": "EventsNode", "event": "purchase"}),
+ ("actions", {"kind": "ActionsNode", "id": 1}),
+ (
+ "data_warehouse",
+ {
+ "kind": "DataWarehouseNode",
+ "id": "orders",
+ "table_name": "orders",
+ "id_field": "id",
+ "distinct_id_field": "user_id",
+ "timestamp_field": "created_at",
+ },
+ ),
+ ]
+ )
+ def test_node_definitions_execute_as_single_series_trends(self, _name: str, node: dict) -> None:
+ executed, envelope = self._run(node)
+ assert executed["kind"] == "TrendsQuery"
+ assert executed["series"] == [node]
+ assert envelope["kind"] == node["kind"]
+
+ def test_date_overrides_reach_executed_query_and_deep_link(self) -> None:
+ definition = {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "purchase"}]}
+ executed, envelope = self._run(definition, date_from="-30d", date_to="-1d", interval="week")
+ assert executed["dateRange"] == {"date_from": "-30d", "date_to": "-1d"}
+ assert executed["interval"] == "week"
+
+ linked = _decoded_insight_link(envelope["posthog_url"])
+ assert linked["kind"] == "InsightVizNode"
+ assert linked["source"] == executed
+
+ def test_hogql_values_round_trip_through_deep_link(self) -> None:
+ definition = {"kind": "HogQLQuery", "query": "select count() from events", "values": {"threshold": 10}}
+ _, envelope = self._run(definition)
+ linked = _decoded_sql_editor_link(envelope["posthog_url"])
+ assert linked["kind"] == "DataVisualizationNode"
+ assert linked["source"] == definition
+
+ def test_error_payload_is_a_failed_run(self) -> None:
+ # The engine reports schema-validation failures as {"error": ...} without raising; that must
+ # surface as a 400, not a successful run with null results.
+ metric = upsert_metric(team=self.team, user=self.user, name="prep", description="d", definition=_HOGQL)
+ with patch(_PROCESS_QUERY, return_value={"results": None, "error": "1 validation error"}):
+ with self.assertRaises(ValidationError):
+ run_metric(team=self.team, metric=metric, user=self.user)
+ metric.refresh_from_db()
+ assert metric.last_run_at is None
+
+ @parameterized.expand(
+ [
+ ("exposed_hogql", ExposedHogQLError("no such table"), ValidationError),
+ ("exposed_clickhouse", ExposedCHQueryError("memory limit"), ValidationError),
+ ("concurrency", ConcurrencyLimitExceeded("too many"), Throttled),
+ ("unexpected", RuntimeError("engine bug"), RuntimeError),
+ ]
+ )
+ def test_engine_exceptions_keep_their_http_semantics(
+ self, _name: str, engine_error: Exception, expected: type[Exception]
+ ) -> None:
+ metric = upsert_metric(team=self.team, user=self.user, name="prep", description="d", definition=_HOGQL)
+ with patch(_PROCESS_QUERY, side_effect=engine_error):
+ with self.assertRaises(expected):
+ run_metric(team=self.team, metric=metric, user=self.user)
+ metric.refresh_from_db()
+ assert metric.last_run_at is None
+
+ @parameterized.expand(
+ [
+ ("date_from", {"date_from": "-7d"}, "date_from"),
+ ("date_to", {"date_to": "-1d"}, "date_to"),
+ ("interval", {"interval": "week"}, "interval"),
+ ]
+ )
+ def test_hogql_date_override_names_the_provided_field(self, _name: str, params: dict, expected_field: str) -> None:
+ # The rejection must point at whichever date param the caller actually sent, not always date_from.
+ with self.assertRaises(ValidationError) as ctx:
+ prepare_execution_query(_HOGQL, **params)
+ detail = cast(dict, ctx.exception.detail)
+ assert str(detail["field"]) == expected_field
+
+
+class TestMetricRunAttribution(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The markdown path exercises the same attribution code without a ClickHouse query.
+ upsert_metric(
+ team=self.team,
+ user=self.user,
+ name="activation",
+ description="d",
+ definition={"kind": "MarkdownDefinition", "markdown": "1. Count activated users."},
+ )
+ self.run_url = f"/api/projects/{self.team.id}/data_catalog/metrics/activation/run/"
+
+ def test_last_run_at_set_and_throttled(self) -> None:
+ self.client.post(self.run_url)
+ metric = Metric.objects.for_team(self.team.id).get(name="activation")
+ first_run = metric.last_run_at
+ assert first_run is not None
+
+ self.client.post(self.run_url)
+ metric.refresh_from_db()
+ assert metric.last_run_at == first_run # within the 30-minute throttle window
+
+
+class TestMetricRunTagging(APIBaseTest):
+ def test_run_tags_clickhouse_query_with_data_catalog_product(self) -> None:
+ # run_metric executes queries via process_query_dict directly, so it must set the query tags
+ # itself. Untagged, ClickHouse queries warn in prod and hard-fail in local dev; TEST disables
+ # tag enforcement, so only this explicit assertion guards against dropping the tags.
+ metric = upsert_metric(team=self.team, user=self.user, name="tagged", description="d", definition=_HOGQL)
+ captured: dict[str, object] = {}
+
+ def capture(*args: object, **kwargs: object) -> dict:
+ tags = get_query_tags()
+ captured["product"], captured["feature"] = tags.product, tags.feature
+ return dict(_OK_PAYLOAD)
+
+ with patch(_PROCESS_QUERY, side_effect=capture):
+ run_metric(team=self.team, metric=metric, user=self.user)
+
+ assert (captured["product"], captured["feature"]) == (Product.DATA_CATALOG, Feature.QUERY)
+
+ @parameterized.expand(
+ [
+ ("personal_api_key", "personal_api_key", True),
+ ("project_secret_api_key", "project_secret_api_key", True),
+ ("oauth", "oauth", False),
+ ("no_access_method", None, False),
+ ]
+ )
+ def test_run_propagates_is_query_service_from_access_method(
+ self, _name: str, access_method: str | None, expected: bool
+ ) -> None:
+ # API-key runs must hit /query's safeguards (rejected constructs, API-team concurrency limit);
+ # dropping the propagation lets a stored query bypass them, so lock the mapping in.
+ metric = upsert_metric(team=self.team, user=self.user, name="svc", description="d", definition=_HOGQL)
+ captured: dict[str, object] = {}
+
+ def capture(*args: object, **kwargs: object) -> dict:
+ captured["is_query_service"] = kwargs.get("is_query_service")
+ return dict(_OK_PAYLOAD)
+
+ with patch(_PROCESS_QUERY, side_effect=capture), tags_context(access_method=access_method):
+ run_metric(team=self.team, metric=metric, user=self.user)
+
+ assert captured["is_query_service"] is expected
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index b5d6cd6a6b5b..d7c02e418106 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -254,6 +254,92 @@ export interface PatchedDataCatalogMetricApi {
readonly updated_at?: string | null
}
+/**
+ * * `second` - second
+ * * `minute` - minute
+ * * `hour` - hour
+ * * `day` - day
+ * * `week` - week
+ * * `month` - month
+ * * `quarter` - quarter
+ * * `year` - year
+ */
+export type DataCatalogMetricRunRequestIntervalEnumApi =
+ (typeof DataCatalogMetricRunRequestIntervalEnumApi)[keyof typeof DataCatalogMetricRunRequestIntervalEnumApi]
+
+export const DataCatalogMetricRunRequestIntervalEnumApi = {
+ Second: 'second',
+ Minute: 'minute',
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+ Quarter: 'quarter',
+ Year: 'year',
+} as const
+
+/**
+ * Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name.
+ */
+export interface DataCatalogMetricRunRequestApi {
+ /** Override the start of the query window (e.g. '-7d'). Rejected for HogQLQuery metrics, whose window is fixed in SQL. */
+ date_from?: string
+ /** Override the end of the query window. */
+ date_to?: string
+ /** Override the bucket interval. Rejected for HogQLQuery metrics.
+ *
+ * * `second` - second
+ * * `minute` - minute
+ * * `hour` - hour
+ * * `day` - day
+ * * `week` - week
+ * * `month` - month
+ * * `quarter` - quarter
+ * * `year` - year */
+ interval?: DataCatalogMetricRunRequestIntervalEnumApi
+ /** Client-supplied id to correlate or cancel the run. */
+ query_id?: string
+}
+
+/**
+ * Normalized envelope returned by the metric-run endpoint.
+ */
+export interface DataCatalogMetricRunApi {
+ /** Lifecycle state of the metric that produced these results. */
+ status: string
+ /** True when the definition has drifted from its linked source insight (or the insight is gone). Only status 'approved' with is_drifted false is canonical. */
+ is_drifted: boolean
+ /**
+ * Unit of the result, e.g. usd, percent.
+ * @nullable
+ */
+ unit: string | null
+ /**
+ * Query kind that was executed.
+ * @nullable
+ */
+ kind: string | null
+ /** The query results, for an executable metric. Null for a markdown metric. */
+ results: unknown
+ /**
+ * The compiled HogQL, when available.
+ * @nullable
+ */
+ compiled_query: string | null
+ /** Async query status, when the run is not blocking. */
+ query_status: unknown
+ /**
+ * Deep link to open the query in the app (SQL editor or insight).
+ * @nullable
+ */
+ posthog_url: string | null
+ /**
+ * For a markdown (agent-calculated) metric, the steps to follow to compute it. Null for an executable metric.
+ * @nullable
+ */
+ instructions: string | null
+}
+
export type DataCatalogMetricsListParams = {
/**
* Number of results to return per page.
@@ -264,3 +350,30 @@ export type DataCatalogMetricsListParams = {
*/
offset?: number
}
+
+export type DataCatalogMetricsRunCreateParams = {
+ /**
+ * Cache/execution behavior, same semantics as /query/. Omit to serve a fresh cache hit and calculate blocking when stale.
+ *
+ * * `blocking` - blocking
+ * * `async` - async
+ * * `lazy_async` - lazy_async
+ * * `force_blocking` - force_blocking
+ * * `force_async` - force_async
+ * * `force_cache` - force_cache
+ * @minLength 1
+ */
+ refresh?: DataCatalogMetricsRunCreateRefresh
+}
+
+export type DataCatalogMetricsRunCreateRefresh =
+ (typeof DataCatalogMetricsRunCreateRefresh)[keyof typeof DataCatalogMetricsRunCreateRefresh]
+
+export const DataCatalogMetricsRunCreateRefresh = {
+ Blocking: 'blocking',
+ Async: 'async',
+ LazyAsync: 'lazy_async',
+ ForceBlocking: 'force_blocking',
+ ForceAsync: 'force_async',
+ ForceCache: 'force_cache',
+} as const
diff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.ts
index fc43d0703806..35b20eeb96c3 100644
--- a/products/data_catalog/frontend/generated/api.ts
+++ b/products/data_catalog/frontend/generated/api.ts
@@ -10,7 +10,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
DataCatalogMetricApi,
+ DataCatalogMetricRunApi,
+ DataCatalogMetricRunRequestApi,
DataCatalogMetricsListParams,
+ DataCatalogMetricsRunCreateParams,
PaginatedDataCatalogMetricListApi,
PatchedDataCatalogMetricApi,
} from './api.schemas'
@@ -195,3 +198,41 @@ export const dataCatalogMetricsRefreshFromInsightCreate = async (
method: 'POST',
})
}
+
+export const getDataCatalogMetricsRunCreateUrl = (
+ projectId: string,
+ name: string,
+ params?: DataCatalogMetricsRunCreateParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/data_catalog/metrics/${name}/run/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_catalog/metrics/${name}/run/`
+}
+
+/**
+ * Execute the metric's definition and return the normalized result envelope.
+ */
+export const dataCatalogMetricsRunCreate = async (
+ projectId: string,
+ name: string,
+ dataCatalogMetricRunRequestApi?: DataCatalogMetricRunRequestApi,
+ params?: DataCatalogMetricsRunCreateParams,
+ options?: RequestInit
+): Promise<DataCatalogMetricRunApi> => {
+ return apiMutator<DataCatalogMetricRunApi>(getDataCatalogMetricsRunCreateUrl(projectId, name, params), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataCatalogMetricRunRequestApi),
+ })
+}
diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.ts
index 7a9586e940b7..819028071943 100644
--- a/products/data_catalog/frontend/generated/api.zod.ts
+++ b/products/data_catalog/frontend/generated/api.zod.ts
@@ -183,3 +183,28 @@ export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({
confidence: zod.number().nullish().describe("AI author's confidence in the proposal, 0-1."),
reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),
})
+
+/**
+ * Execute the metric's definition and return the normalized result envelope.
+ */
+export const DataCatalogMetricsRunCreateBody = /* @__PURE__ */ zod
+ .object({
+ date_from: zod
+ .string()
+ .optional()
+ .describe(
+ "Override the start of the query window (e.g. '-7d'). Rejected for HogQLQuery metrics, whose window is fixed in SQL."
+ ),
+ date_to: zod.string().optional().describe('Override the end of the query window.'),
+ interval: zod
+ .enum(['second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'])
+ .describe(
+ '\* `second` - second\n\* `minute` - minute\n\* `hour` - hour\n\* `day` - day\n\* `week` - week\n\* `month` - month\n\* `quarter` - quarter\n\* `year` - year'
+ )
+ .optional()
+ .describe(
+ 'Override the bucket interval. Rejected for HogQLQuery metrics.\n\n\* `second` - second\n\* `minute` - minute\n\* `hour` - hour\n\* `day` - day\n\* `week` - week\n\* `month` - month\n\* `quarter` - quarter\n\* `year` - year'
+ ),
+ query_id: zod.string().optional().describe('Client-supplied id to correlate or cancel the run.'),
+ })
+ .describe('Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name.')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 50df797a19a4..f05fb77a1943 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15602,6 +15602,92 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ /**
+ * Normalized envelope returned by the metric-run endpoint.
+ */
+ export interface DataCatalogMetricRun {
+ /** Lifecycle state of the metric that produced these results. */
+ status: string;
+ /** True when the definition has drifted from its linked source insight (or the insight is gone). Only status 'approved' with is_drifted false is canonical. */
+ is_drifted: boolean;
+ /**
+ * Unit of the result, e.g. usd, percent.
+ * @nullable
+ */
+ unit: string | null;
+ /**
+ * Query kind that was executed.
+ * @nullable
+ */
+ kind: string | null;
+ /** The query results, for an executable metric. Null for a markdown metric. */
+ results: unknown;
+ /**
+ * The compiled HogQL, when available.
+ * @nullable
+ */
+ compiled_query: string | null;
+ /** Async query status, when the run is not blocking. */
+ query_status: unknown;
+ /**
+ * Deep link to open the query in the app (SQL editor or insight).
+ * @nullable
+ */
+ posthog_url: string | null;
+ /**
+ * For a markdown (agent-calculated) metric, the steps to follow to compute it. Null for an executable metric.
+ * @nullable
+ */
+ instructions: string | null;
+ }
+
+ /**
+ * * `second` - second
+ * * `minute` - minute
+ * * `hour` - hour
+ * * `day` - day
+ * * `week` - week
+ * * `month` - month
+ * * `quarter` - quarter
+ * * `year` - year
+ */
+ export type DataCatalogMetricRunRequestIntervalEnum = typeof DataCatalogMetricRunRequestIntervalEnum[keyof typeof DataCatalogMetricRunRequestIntervalEnum];
+
+
+ export const DataCatalogMetricRunRequestIntervalEnum = {
+ Second: 'second',
+ Minute: 'minute',
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+ Month: 'month',
+ Quarter: 'quarter',
+ Year: 'year',
+ } as const;
+
+ /**
+ * Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name.
+ */
+ export interface DataCatalogMetricRunRequest {
+ /** Override the start of the query window (e.g. '-7d'). Rejected for HogQLQuery metrics, whose window is fixed in SQL. */
+ date_from?: string;
+ /** Override the end of the query window. */
+ date_to?: string;
+ /** Override the bucket interval. Rejected for HogQLQuery metrics.
+ *
+ * * `second` - second
+ * * `minute` - minute
+ * * `hour` - hour
+ * * `day` - day
+ * * `week` - week
+ * * `month` - month
+ * * `quarter` - quarter
+ * * `year` - year */
+ interval?: DataCatalogMetricRunRequestIntervalEnum;
+ /** Client-supplied id to correlate or cancel the run. */
+ query_id?: string;
+ }
+
export interface DataColorTheme {
readonly id: number;
/** @maxLength 100 */
@@ -67923,6 +68009,33 @@ export namespace Schemas {
offset?: number;
};
+ export type DataCatalogMetricsRunCreateParams = {
+ /**
+ * Cache/execution behavior, same semantics as /query/. Omit to serve a fresh cache hit and calculate blocking when stale.
+ *
+ * * `blocking` - blocking
+ * * `async` - async
+ * * `lazy_async` - lazy_async
+ * * `force_blocking` - force_blocking
+ * * `force_async` - force_async
+ * * `force_cache` - force_cache
+ * @minLength 1
+ */
+ refresh?: DataCatalogMetricsRunCreateRefresh;
+ };
+
+ export type DataCatalogMetricsRunCreateRefresh = typeof DataCatalogMetricsRunCreateRefresh[keyof typeof DataCatalogMetricsRunCreateRefresh];
+
+
+ export const DataCatalogMetricsRunCreateRefresh = {
+ Blocking: 'blocking',
+ Async: 'async',
+ LazyAsync: 'lazy_async',
+ ForceBlocking: 'force_blocking',
+ ForceAsync: 'force_async',
+ ForceCache: 'force_cache',
+ } as const;
+
export type DataColorThemesListParams = {
/**
* Number of results to return per page.