:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-catalog): metric approval lifecycle with insight snapshot and drift (#69528)
Thiago Salvatore9ce984754e54
diff --git a/posthog/api/utils.py b/posthog/api/utils.pyindex 3956abdf9fad..6fc7e640233b 100644--- a/posthog/api/utils.py+++ b/posthog/api/utils.py@@ -15,6 +15,7 @@ from django.db.models import QuerySetfrom django.http import HttpRequestimport structlog+from drf_spectacular.utils import emptyfrom posthoganalytics import capture_exceptionfrom prometheus_client import Counterfrom requests.adapters import HTTPAdapter@@ -527,7 +528,7 @@ def on_permitted_recording_domain(permitted_domains: list[str], request: HttpReq# By default, DRF spectacular uses the serializer of the view as the response format for actions. However, most actions don't return a version of the model, but something custom. This function removes the response from all actions in the documentation.-def action(methods=None, detail=None, url_path=None, url_name=None, responses=None, **kwargs):+def action(methods=None, detail=None, url_path=None, url_name=None, responses=None, request=empty, **kwargs):"""Mark a ViewSet method as a routable action.@@ -545,6 +546,8 @@ def action(methods=None, detail=None, url_path=None, url_name=None, responses=NoDefaults to the name of the method decorated with underscoresreplaced with dashes.:param responses: Serializer or pydantic model of the response for documentation+ :param request: Serializer/schema of the request body for documentation. Defaults to inferring+ from the viewset's ``serializer_class``; pass ``None`` for actions with no body.:param kwargs: Additional properties to set on the view. This can be usedto override viewset-level *_classes settings, equivalent tohow the `@renderer_classes` etc. decorators work for function-@@ -552,7 +555,7 @@ def action(methods=None, detail=None, url_path=None, url_name=None, responses=No"""def decorator(func):- @extend_schema(responses=responses)+ @extend_schema(request=request, responses=responses)@drf_action(methods=methods,detail=detail,diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.pyindex 00ba583e291d..a4fd09302913 100644--- a/products/data_catalog/backend/facade/api.py+++ b/products/data_catalog/backend/facade/api.py@@ -6,13 +6,24 @@ logic surface and model classes so the isolation boundary stays clean: presentatinto ``logic`` or ``models`` directly."""-from ..logic.metrics import metrics_for_team, soft_delete_metric, update_metric, upsert_metric+from ..logic.drift import compute_drift+from ..logic.metrics import (+ approve_metric,+ metrics_for_team,+ refresh_metric_from_insight,+ soft_delete_metric,+ update_metric,+ upsert_metric,+)from ..logic.validation import validate_metric_definitionfrom .models import Metric__all__ = ["Metric",+ "approve_metric",+ "compute_drift","metrics_for_team",+ "refresh_metric_from_insight","soft_delete_metric","update_metric","upsert_metric",diff --git a/products/data_catalog/backend/logic/drift.py b/products/data_catalog/backend/logic/drift.pynew file mode 100644index 000000000000..923e917ba4d3--- /dev/null+++ b/products/data_catalog/backend/logic/drift.py@@ -0,0 +1,67 @@+"""Insight snapshotting and drift detection.++A metric created from an insight snapshots the insight's query at create time. Drift is computed+lazily at read time: the current insight query, canonicalized the same way, is compared to the stored+snapshot hash. Canonicalization runs ``upgrade()`` first so a schema migration never reads as drift.+"""++import json+import hashlib+from collections.abc import Iterable+from copy import deepcopy+from typing import Optional+from uuid import UUID++from posthog.schema_migrations.upgrade import upgrade++from products.product_analytics.backend.models.insight import Insight++from ..models import Metric+++def canonical_query_hash(query: dict) -> str:+ """Stable hash of a query, invariant to key order and schema version."""+ return hashlib.sha256(json.dumps(upgrade(deepcopy(query)), sort_keys=True).encode()).hexdigest()+++def effective_insight_query(insight: Insight) -> Optional[dict]:+ """The insight's query, converting legacy ``filters``-only insights via query_from_filters."""+ return insight.query or insight.query_from_filters+++def fetch_insight(team_id: int, short_id: str, *, include_deleted: bool = False) -> Optional[Insight]:+ manager = Insight.objects_including_soft_deleted if include_deleted else Insight.objects+ return manager.filter(team_id=team_id, short_id=short_id).first()+++def compute_drift(metrics: Iterable[Metric]) -> dict[UUID, bool]:+ """Map each metric id to whether its definition has drifted from its source insight.++ A missing or deleted source insight counts as drifted: absence of evidence never passes as+ verified lockstep. One bulk query over the linked insights, shared by the API and the catalog.+ """+ metrics = list(metrics)+ result: dict[UUID, bool] = {metric.id: False for metric in metrics}+ linked = [metric for metric in metrics if metric.source_insight_short_id]+ if not linked:+ return result++ short_ids = {metric.source_insight_short_id for metric in linked}+ team_ids = {metric.team_id for metric in linked}+ insights = Insight.objects_including_soft_deleted.filter(team_id__in=team_ids, short_id__in=short_ids)+ by_key: dict[tuple[int, str | None], Insight] = {+ (insight.team_id, insight.short_id): insight for insight in insights+ }++ for metric in linked:+ insight = by_key.get((metric.team_id, metric.source_insight_short_id))+ if insight is None or insight.deleted:+ result[metric.id] = True+ continue+ current_query = effective_insight_query(insight)+ if not current_query:+ result[metric.id] = True+ continue+ result[metric.id] = canonical_query_hash(current_query) != metric.source_insight_query_hash++ return resultdiff --git a/products/data_catalog/backend/logic/exceptions.py b/products/data_catalog/backend/logic/exceptions.pynew file mode 100644index 000000000000..21d83e180754--- /dev/null+++ b/products/data_catalog/backend/logic/exceptions.py@@ -0,0 +1,29 @@+"""Domain exceptions for the metric lifecycle.++Subclassing DRF's APIException lets the viewset stay thin: raising these from the logic layer maps+to the right HTTP status automatically, no per-action try/except needed.+"""++from rest_framework import status+from rest_framework.exceptions import APIException+++class MetricDrifted(APIException):+ status_code = status.HTTP_409_CONFLICT+ default_detail = (+ "This metric's definition has drifted from its source insight. Refresh it from the insight "+ "or unlink the insight before approving."+ )+ default_code = "metric_drifted"+++class SourceInsightUnavailable(APIException):+ status_code = status.HTTP_400_BAD_REQUEST+ default_detail = "The source insight is no longer available. Edit the definition directly or unlink the insight."+ default_code = "source_insight_unavailable"+++class MetricHasNoDefinition(APIException):+ status_code = status.HTTP_400_BAD_REQUEST+ default_detail = "This metric has no definition to run. It is name and description only."+ default_code = "metric_has_no_definition"diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.pyindex be2a7ee0f7cd..235cb63d2453 100644--- a/products/data_catalog/backend/logic/metrics.py+++ b/products/data_catalog/backend/logic/metrics.py@@ -1,8 +1,10 @@-"""Metric write path — upsert with reserved-name semantics, partial update, soft delete.+"""Metric write path and approval lifecycle.-Names are reserved forever per team: creating with an existing name refines that metric, and-creating with a soft-deleted name resurrects the row as ``proposed`` rather than minting a new-identity. Concurrent same-name creates collapse to one row via the unique constraint + retry.+Names are reserved forever per team: creating with an existing name refines that metric, and creating+with a soft-deleted name resurrects the row as ``proposed``. A metric can be created from an insight+(its query is snapshotted server-side and drift is flagged for re-review). Promotion to ``approved``+is blocked while a metric is drifted. All transitions emit capture events for success-criteria+measurement."""import re@@ -14,11 +16,17 @@ from django.utils import timezonefrom rest_framework.exceptions import ValidationError+from posthog.event_usage import report_user_actionfrom posthog.models import Team, Userfrom posthog.models.scoping import team_scope+from posthog.rbac.user_access_control import UserAccessControl++from products.product_analytics.backend.models.insight import Insightfrom ..facade.enums import CreatedSource, MetricStatusfrom ..models import METRIC_NAME_REGEX, Metric+from .drift import canonical_query_hash, compute_drift, effective_insight_query, fetch_insight+from .exceptions import MetricDrifted, SourceInsightUnavailablefrom .validation import validate_metric_definition@@ -32,6 +40,31 @@ class _Unset:_UNSET = _Unset()+# The columns _reset_to_proposed touches, so a lifecycle reset can be scoped into update_fields.+_APPROVAL_FIELDS = frozenset({"status", "approved_by", "approved_at"})++# Fields that carry the metric's reviewed meaning: editing any of them invalidates a prior approval.+# The definition is compared by canonical hash separately; these are compared by value. display_name+# (a cosmetic label), owner, and provenance metadata are not part of what a reviewer blessed.+_APPROVAL_RELEVANT_FIELDS = frozenset({"description", "unit"})+++def _capture(user: Optional[User], team: Team, event: str, metric: Metric) -> None:+ if user is None:+ return+ report_user_action(+ user=user,+ event=event,+ team=team,+ properties={+ "metric_id": str(metric.id),+ "metric_name": metric.name,+ "definition_kind": metric.definition_kind,+ "status": metric.status,+ "created_source": metric.created_source,+ },+ )+def _canonical_definition(definition: Optional[dict], team: Team, user: Optional[User]@@ -41,13 +74,115 @@ def _canonical_definition(return validate_metric_definition(definition, team, user)+def _require_insight_viewer_access(insight: Insight, team: Team, user: Optional[User]) -> None:+ """Gate snapshotting an insight's query on per-object viewer access.++ Team scoping alone doesn't enforce object-level insight access controls, so a caller with+ catalog write access could otherwise read a restricted insight's query back out of the metric.+ System/agent callers (``user`` is None) are already trusted and bypass this.+ """+ if user is None:+ return+ if not UserAccessControl(user=user, team=team).check_access_level_for_object(insight, "viewer"):+ raise ValidationError({"source_insight_short_id": "You do not have access to this insight."})+++def _snapshot_from_insight(team: Team, short_id: str, user: Optional[User]) -> tuple[dict, str]:+ """Snapshot a live insight's query and its canonical hash for drift tracking."""+ insight = fetch_insight(team.id, short_id)+ if insight is None:+ raise ValidationError({"source_insight_short_id": "Insight not found."})+ _require_insight_viewer_access(insight, team, user)+ query = effective_insight_query(insight)+ if not query:+ raise ValidationError(+ {"source_insight_short_id": "Could not convert this insight's query. Define the metric manually."}+ )+ return query, canonical_query_hash(query)+++def _resolve_definition_fields(+ definition: dict | None | _Unset,+ source_insight_short_id: str | None | _Unset,+ team: Team,+ user: Optional[User],+) -> dict[str, object]:+ """Derive the definition / insight-link fields to write, honoring the definition-XOR-insight rule.++ Returns only the keys the caller actually engaged, so a refine that supplies neither writes+ nothing (leaving a stored definition and its insight link untouched). A supplied definition+ validates, extracts referenced tables, and unlinks any source insight; a non-empty insight id+ snapshots the query; a supplied-but-empty insight id clears the link and its snapshot hash.+ """+ insight_supplied = not isinstance(source_insight_short_id, _Unset)++ if not isinstance(source_insight_short_id, _Unset) and source_insight_short_id:+ if not isinstance(definition, _Unset) and definition is not None:+ raise ValidationError({"definition": "Provide a definition or a source insight, not both."})+ snapshot_def, snapshot_hash = _snapshot_from_insight(team, source_insight_short_id, user)+ canonical_def, referenced = _canonical_definition(snapshot_def, team, user)+ return {+ "definition": canonical_def,+ "referenced_table_names": referenced,+ "source_insight_short_id": source_insight_short_id,+ "source_insight_query_hash": snapshot_hash,+ }++ result: dict[str, object] = {}+ if not isinstance(definition, _Unset):+ canonical_def, referenced = _canonical_definition(definition, team, user)+ result["definition"] = canonical_def+ result["referenced_table_names"] = referenced+ result["source_insight_short_id"] = None+ result["source_insight_query_hash"] = None++ if insight_supplied:+ # Supplied but empty (the truthy case returned above): unlink and drop the snapshot hash.+ result["source_insight_short_id"] = None+ result["source_insight_query_hash"] = None++ return result+++def _definition_hash(definition: Optional[dict]) -> Optional[str]:+ return canonical_query_hash(definition) if definition else None+++def _invalidates_approval(metric: Metric, fields: dict) -> bool:+ """True if this write changes the metric's reviewed meaning (definition, description, or unit).++ Compares the incoming ``fields`` against ``metric``'s current (pre-mutation) values. For a+ definition-less metric the description is the entire meaningful definition, so a description or+ unit edit — reachable with catalog write access alone — must reset approval just as a definition+ edit does.++ Changing the source-insight link (unlink or relink) while the metric is drifted also+ invalidates: it would erase the drift signal that flags the approval as stale, laundering an+ outdated approval into "approved and current". Unlinking an in-sync metric keeps approval — the+ blessed definition is unchanged and was in lockstep when tracking stopped.+ """+ if "definition" in fields and _definition_hash(fields["definition"]) != _definition_hash(metric.definition):+ return True+ if (+ "source_insight_short_id" in fields+ and fields["source_insight_short_id"] != metric.source_insight_short_id+ and metric.status == MetricStatus.APPROVED+ and compute_drift([metric])[metric.id]+ ):+ return True+ return any(key in fields and fields[key] != getattr(metric, key) for key in _APPROVAL_RELEVANT_FIELDS)++def _resurrect_or_refine(metric: Metric, fields: dict) -> None:if metric.deleted:metric.deleted = Falsemetric.deleted_at = None- metric.status = MetricStatus.PROPOSED- metric.approved_by = None- metric.approved_at = None+ _reset_to_proposed(metric)+ elif _invalidates_approval(metric, fields):+ # Refining an approved metric's meaning (definition, description, or unit) changes what it+ # computes or how it reads; its review no longer holds, so drop back to proposed (matching+ # update_metric's PATCH behavior).+ _reset_to_proposed(metric)for key, value in fields.items():setattr(metric, key, value)metric.save()@@ -63,6 +198,7 @@ def upsert_metric(unit: str | _Unset = _UNSET,owner: User | None | _Unset = _UNSET,definition: dict | None | _Unset = _UNSET,+ source_insight_short_id: str | None | _Unset = _UNSET,created_source: CreatedSource | _Unset = _UNSET,ai_model: str | _Unset = _UNSET,confidence: float | None | _Unset = _UNSET,@@ -73,6 +209,9 @@ def upsert_metric(Refine is a partial merge: only the fields the caller supplies are written, so a refine thatomits a field leaves that field (a stored ``definition``, provenance, ...) untouched rather thanresetting it. On create, omitted fields fall back to the model defaults (``owner`` to ``user``).++ Accepts a ``definition`` XOR a ``source_insight_short_id`` (create-from-insight snapshots the+ insight's query server-side). Always lands ``proposed``."""if not re.match(METRIC_NAME_REGEX, name or ""):raise ValidationError(@@ -92,10 +231,7 @@ def upsert_metric(if not isinstance(value, _Unset):fields[key] = value- if not isinstance(definition, _Unset):- canonical_def, referenced = _canonical_definition(definition, team, user)- fields["definition"] = canonical_def- fields["referenced_table_names"] = referenced+ fields.update(_resolve_definition_fields(definition, source_insight_short_id, team, user))# team_scope so the ModelActivityMixin's before-update lookup (via the fail-closed manager)# works regardless of caller context (viewset, Celery, MCP, tests).@@ -103,16 +239,18 @@ def upsert_metric(try:with transaction.atomic():existing = Metric.objects.for_team(team.id).filter(name=name).select_for_update().first()+ created = existing is Noneif existing is not None:_resurrect_or_refine(existing, fields)- return existing- return Metric.objects.for_team(team.id).create(- team=team,- name=name,- created_by=user,- status=MetricStatus.PROPOSED,- **{"owner": user, **fields},- )+ metric = existing+ else:+ metric = Metric.objects.for_team(team.id).create(+ team=team,+ name=name,+ created_by=user,+ status=MetricStatus.PROPOSED,+ **{"owner": user, **fields},+ )except IntegrityError:# A concurrent writer created (team, name) first; refine that row instead of failing.with transaction.atomic():@@ -120,31 +258,103 @@ def upsert_metric(if existing is None:raise_resurrect_or_refine(existing, fields)- return existing+ metric, created = existing, False++ _capture(user, team, "data catalog metric created" if created else "data catalog metric updated", metric)+ return metricdef update_metric(metric: Metric, *, team: Team, user: Optional[User], **fields) -> Metric:- """Partially update a metric. Name is write-once. Definition changes are re-validated."""+ """Partially update a metric. Name is write-once; editing an approved definition resets approval."""if "name" in fields:raise ValidationError({"name": "Metric name is write-once and cannot be changed."})- if "definition" in fields:- canonical_def, referenced = _canonical_definition(fields["definition"], team, user)- fields["definition"] = canonical_def- fields["referenced_table_names"] = referenced+ # Route definition / insight-link through the same resolver as create, so a PATCH honors the+ # definition-XOR-insight rule, snapshots (and validates) on relink, and drops the hash on unlink.+ definition_arg = fields.pop("definition", _UNSET)+ source_insight_arg = fields.pop("source_insight_short_id", _UNSET)+ fields.update(_resolve_definition_fields(definition_arg, source_insight_arg, team, user))- for key, value in fields.items():- setattr(metric, key, value)- with team_scope(team.id):- metric.save()+ with team_scope(team.id), transaction.atomic():+ metric = Metric.objects.for_team(team.id).select_for_update().get(pk=metric.pk)+ approval_invalidated = _invalidates_approval(metric, fields)++ for key, value in fields.items():+ setattr(metric, key, value)++ changed_fields = set(fields.keys())+ if approval_invalidated and metric.status == MetricStatus.APPROVED:+ # The edit changed what the metric means, so its approval no longer holds.+ _reset_to_proposed(metric)+ changed_fields |= _APPROVAL_FIELDS++ metric.save(update_fields=[*changed_fields, "updated_at"])+ _capture(user, team, "data catalog metric updated", metric)+ return metric+++def approve_metric(metric: Metric, user: Optional[User]) -> Metric:+ """Bless a metric as canonical. Blocked (409) while drifted. Idempotent on an already-approved metric."""+ with team_scope(metric.team_id), transaction.atomic():+ metric = Metric.objects.for_team(metric.team_id).select_for_update().get(pk=metric.pk)+ if compute_drift([metric])[metric.id]:+ raise MetricDrifted()+ if metric.status == MetricStatus.APPROVED:+ return metric+ metric.status = MetricStatus.APPROVED+ metric.approved_by = user+ metric.approved_at = timezone.now()+ metric.save(update_fields=[*_APPROVAL_FIELDS, "updated_at"])+ _capture(user, metric.team, "data catalog metric approved", metric)+ return metric+++def refresh_metric_from_insight(metric: Metric, user: Optional[User]) -> Metric:+ """Re-snapshot the linked insight's current query; a changed definition resets approval."""+ with team_scope(metric.team_id), transaction.atomic():+ metric = Metric.objects.for_team(metric.team_id).select_for_update().get(pk=metric.pk)+ if not metric.source_insight_short_id:+ raise ValidationError({"source_insight_short_id": "This metric is not linked to an insight."})++ insight = fetch_insight(metric.team_id, metric.source_insight_short_id, include_deleted=True)+ if insight is None or insight.deleted:+ raise SourceInsightUnavailable()+ _require_insight_viewer_access(insight, metric.team, user)+ query = effective_insight_query(insight)+ if not query:+ raise SourceInsightUnavailable(+ "Could not convert the source insight's query. Edit the definition or unlink."+ )++ canonical_def, referenced = _canonical_definition(query, metric.team, user)+ new_hash = canonical_query_hash(query)+ changed = new_hash != metric.source_insight_query_hash++ metric.definition = canonical_def+ metric.referenced_table_names = referenced+ metric.source_insight_query_hash = new_hash+ changed_fields = {"definition", "referenced_table_names", "source_insight_query_hash"}+ if changed and metric.status == MetricStatus.APPROVED:+ _reset_to_proposed(metric)+ changed_fields |= _APPROVAL_FIELDS++ metric.save(update_fields=[*changed_fields, "updated_at"])+ _capture(user, metric.team, "data catalog metric updated", metric)return metric-def soft_delete_metric(metric: Metric) -> None:+def soft_delete_metric(metric: Metric, user: Optional[User] = None) -> None:metric.deleted = Truemetric.deleted_at = timezone.now()with team_scope(metric.team_id):- metric.save()+ metric.save(update_fields=["deleted", "deleted_at", "updated_at"])+ _capture(user, metric.team, "data catalog metric deleted", metric)+++def _reset_to_proposed(metric: Metric) -> None:+ metric.status = MetricStatus.PROPOSED+ metric.approved_by = None+ metric.approved_at = Nonedef metrics_for_team(team: Team) -> QuerySet[Metric]:diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.pyindex 987b77663afb..68547c536797 100644--- a/products/data_catalog/backend/presentation/serializers.py+++ b/products/data_catalog/backend/presentation/serializers.py@@ -11,6 +11,7 @@ from rest_framework import serializersfrom posthog.api.shared import UserBasicSerializer+from ..facade import apifrom ..facade.enums import CreatedSourcefrom ..facade.models import Metric@@ -36,6 +37,9 @@ class MetricSerializer(serializers.ModelSerializer):read_only=True,help_text="Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately.",)+ is_drifted = serializers.SerializerMethodField(+ help_text="True when the definition has drifted from its linked source insight (or the insight is gone).",+ )created_source = serializers.ChoiceField(choices=[(s.value, s.value) for s in CreatedSource],required=False,@@ -45,6 +49,9 @@ class MetricSerializer(serializers.ModelSerializer):help_text="Email of the human accountable for this metric, or null.",)created_by = UserBasicSerializer(read_only=True, help_text="User who first created this metric.")+ approved_by = UserBasicSerializer(+ read_only=True, allow_null=True, help_text="User who approved this metric as canonical, or null."+ )class Meta:model = Metric@@ -59,7 +66,9 @@ class MetricSerializer(serializers.ModelSerializer):"definition_kind","referenced_table_names","status",+ "is_drifted","approved_at",+ "approved_by","source_insight_short_id","last_run_at","created_source",@@ -74,8 +83,8 @@ class MetricSerializer(serializers.ModelSerializer):"id","status","approved_at",+ "approved_by","referenced_table_names",- "source_insight_short_id","last_run_at","created_by","created_at",@@ -83,6 +92,11 @@ class MetricSerializer(serializers.ModelSerializer):]extra_kwargs = {"name": {"help_text": "Identifier-safe run handle, unique per team and reserved forever. Write-once."},+ "source_insight_short_id": {+ "required": False,+ "help_text": "Create the metric from this insight's query (snapshotted server-side). "+ "Set to null to unlink. Mutually exclusive with definition.",+ },"display_name": {"help_text": "Human-friendly label. Mutable, unlike name."},"description": {"help_text": "What the metric means and how to interpret it."},"unit": {"help_text": "Unit of the result, e.g. usd, percent, cents."},@@ -94,3 +108,12 @@ class MetricSerializer(serializers.ModelSerializer):@extend_schema_field(serializers.CharField(allow_null=True))def get_owner(self, obj: Metric) -> str | None:return obj.owner.email if obj.owner else None++ @extend_schema_field(OpenApiTypes.BOOL)+ def get_is_drifted(self, obj: Metric) -> bool:+ # The list view precomputes drift for the whole page into ``drift_map`` (one bulk query);+ # single-object paths (retrieve, create, approve, ...) fall back to a bounded per-object query.+ drift_map = self.context.get("drift_map")+ if drift_map is not None and obj.id in drift_map:+ return drift_map[obj.id]+ return api.compute_drift([obj])[obj.id]diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.pyindex f083e42f466b..cc0ccc88ccf3 100644--- a/products/data_catalog/backend/presentation/views.py+++ b/products/data_catalog/backend/presentation/views.py@@ -1,7 +1,7 @@"""DRF views for data_catalog.Thin: validate via the serializer, call the facade, serialize the result. Domain invariants-(name reservation, upsert, validation) live in the logic layer behind the facade.+(name reservation, upsert, validation, drift, approval) live in the logic layer behind the facade."""from typing import cast@@ -13,8 +13,10 @@ from rest_framework import status, viewsetsfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.views import APIViewfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import actionfrom posthog.models import Userfrom ..facade import api@@ -33,6 +35,25 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def safely_get_queryset(self, queryset: QuerySet[Metric]) -> QuerySet[Metric]:return queryset.filter(team_id=self.team_id, deleted=False).order_by("-created_at")+ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:+ if getattr(view, "action", None) not in ("create", "update", "partial_update"):+ return None+ if isinstance(request.data, dict) and request.data.get("source_insight_short_id"):+ return ["data_catalog:write", "insight:read"]+ return None++ 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).+ queryset = self.filter_queryset(self.get_queryset())+ page = self.paginate_queryset(queryset)+ metrics = page if page is not None else list(queryset)+ context = {**self.get_serializer_context(), "drift_map": api.compute_drift(metrics)}+ serializer = self.get_serializer(metrics, many=True, context=context)+ if page is not None:+ return self.get_paginated_response(serializer.data)+ return Response(serializer.data)+@extend_schema(description="Create a metric, or refine the one already holding this name for the team.")def create(self, request: Request, *args, **kwargs) -> Response:serializer = self.get_serializer(data=request.data)@@ -42,7 +63,16 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# leaves omitted fields (a stored definition, provenance, ...) untouched rather than resetting them.optional = {key: data[key]- for key in ("display_name", "unit", "definition", "created_source", "ai_model", "confidence", "reasoning")+ for key in (+ "display_name",+ "unit",+ "definition",+ "source_insight_short_id",+ "created_source",+ "ai_model",+ "confidence",+ "reasoning",+ )if key in data}metric = api.upsert_metric(@@ -67,4 +97,29 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return Response(self.get_serializer(metric).data)def perform_destroy(self, instance: Metric) -> None:- api.soft_delete_metric(instance)+ api.soft_delete_metric(instance, cast(User, self.request.user))++ @action(+ detail=True,+ methods=["POST"],+ required_scopes=["data_catalog_approval:write", "data_catalog:read"],+ request=None,+ responses={200: MetricSerializer},+ )+ def approve(self, request: Request, **kwargs) -> Response:+ """Bless a metric as canonical. Returns 409 while the metric is drifted from its insight."""+ metric = api.approve_metric(self.get_object(), cast(User, request.user))+ return Response(self.get_serializer(metric).data)++ @action(+ detail=True,+ methods=["POST"],+ url_path="refresh_from_insight",+ required_scopes=["data_catalog:write", "insight:read"],+ request=None,+ responses={200: MetricSerializer},+ )+ def refresh_from_insight(self, request: Request, **kwargs) -> Response:+ """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)diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.pyindex 272c2ed052c6..2a2c28eba6e4 100644--- a/products/data_catalog/backend/tests/test_api.py+++ b/products/data_catalog/backend/tests/test_api.py@@ -1,11 +1,21 @@from posthog.test.base import APIBaseTest+from django.db import connection+from django.test.utils import CaptureQueriesContext++from parameterized import parameterizedfrom rest_framework import status+from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Team+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.data_catalog.backend.facade.enums import MetricStatus+from products.data_catalog.backend.logic.metrics import upsert_metricfrom products.data_catalog.backend.models import Metric+from products.product_analytics.backend.models.insight import Insight++_HOGQL = {"kind": "HogQLQuery", "query": "select count() from events"}class TestMetricAPI(APIBaseTest):@@ -94,3 +104,131 @@ class TestMetricAPI(APIBaseTest):names = [row["name"] for row in self.client.get(self.url).json()["results"]]assert names == ["mine"]+++class TestMetricLifecycleAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/data_catalog/metrics/"++ def _insight(self, query: dict | None = None) -> Insight:+ return Insight.objects.create(team=self.team, created_by=self.user, query=query or _HOGQL)++ def test_session_user_can_approve(self) -> None:+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)+ response = self.client.post(f"{self.url}mrr/approve/")+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["status"] == MetricStatus.APPROVED++ def test_create_from_insight_snapshots_definition(self) -> None:+ insight = self._insight()+ response = self.client.post(+ self.url, {"name": "mrr", "description": "d", "source_insight_short_id": insight.short_id}, format="json"+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["definition"]["kind"] == "HogQLQuery"+ assert body["is_drifted"] is False++ def test_list_computes_drift_in_a_single_insight_query(self) -> None:+ # is_drifted must not fan out into one insight lookup per metric: the list view precomputes+ # drift for the whole page in one bulk query. Three linked metrics => one insight query.+ for i in range(3):+ insight = self._insight()+ self.client.post(+ self.url,+ {"name": f"m{i}", "description": "d", "source_insight_short_id": insight.short_id},+ format="json",+ )+ with CaptureQueriesContext(connection) as ctx:+ response = self.client.get(self.url)+ assert response.status_code == status.HTTP_200_OK+ insight_queries = [q for q in ctx.captured_queries if "posthog_dashboarditem" in q["sql"]]+ assert len(insight_queries) == 1, insight_queries++ def test_approve_returns_409_while_drifted(self) -> None:+ insight = self._insight()+ self.client.post(+ self.url, {"name": "mrr", "description": "d", "source_insight_short_id": insight.short_id}, format="json"+ )+ Insight.objects.filter(pk=insight.pk).update(+ query={"kind": "HogQLQuery", "query": "select count() from persons"}+ )+ assert self.client.get(f"{self.url}mrr/").json()["is_drifted"] is True+ assert self.client.post(f"{self.url}mrr/approve/").status_code == status.HTTP_409_CONFLICT++ def test_refresh_then_approve_succeeds(self) -> None:+ insight = self._insight()+ self.client.post(+ self.url, {"name": "mrr", "description": "d", "source_insight_short_id": insight.short_id}, format="json"+ )+ Insight.objects.filter(pk=insight.pk).update(+ query={"kind": "HogQLQuery", "query": "select count() from persons"}+ )+ assert self.client.post(f"{self.url}mrr/refresh_from_insight/").status_code == status.HTTP_200_OK+ assert self.client.post(f"{self.url}mrr/approve/").status_code == status.HTTP_200_OK++ def _bearer(self, scopes: list[str]) -> dict:+ raw = generate_random_token_personal()+ PersonalAPIKey.objects.create(label="k", user=self.user, secure_value=hash_key_value(raw), scopes=scopes)+ return {"HTTP_AUTHORIZATION": f"Bearer {raw}"}++ @parameterized.expand(+ [+ ("without_approval_scope", ["data_catalog:read", "data_catalog:write"], status.HTTP_403_FORBIDDEN),+ ("approval_scope_only", ["data_catalog_approval:write"], status.HTTP_403_FORBIDDEN),+ (+ "with_approval_scope",+ ["data_catalog:read", "data_catalog:write", "data_catalog_approval:write"],+ status.HTTP_200_OK,+ ),+ ]+ )+ def test_token_needs_approval_scope_to_approve(self, _name: str, scopes: list[str], expected: int) -> None:+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)+ self.client.logout() # force the personal API key authenticator, not the session+ response = self.client.post(f"{self.url}mrr/approve/", **self._bearer(scopes))+ assert response.status_code == expected, response.json()++ @parameterized.expand(+ [+ ("without_insight_read", ["data_catalog:read", "data_catalog:write"], status.HTTP_403_FORBIDDEN),+ (+ "with_insight_read",+ ["data_catalog:read", "data_catalog:write", "insight:read"],+ status.HTTP_201_CREATED,+ ),+ ]+ )+ def test_create_from_insight_needs_insight_read_scope(self, _name: str, scopes: list[str], expected: int) -> None:+ insight = self._insight()+ self.client.logout()+ response = self.client.post(+ self.url,+ {"name": "mrr", "description": "d", "source_insight_short_id": insight.short_id},+ format="json",+ **self._bearer(scopes),+ )+ assert response.status_code == expected, response.json()++ @parameterized.expand(+ [+ ("without_insight_read", ["data_catalog:read", "data_catalog:write"], status.HTTP_403_FORBIDDEN),+ ("with_insight_read", ["data_catalog:read", "data_catalog:write", "insight:read"], status.HTTP_200_OK),+ ]+ )+ def test_refresh_from_insight_needs_insight_read_scope(self, _name: str, scopes: list[str], expected: int) -> None:+ insight = self._insight()+ upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ self.client.logout()+ response = self.client.post(f"{self.url}mrr/refresh_from_insight/", **self._bearer(scopes))+ assert response.status_code == expected, response.json()++ def test_plain_create_does_not_need_insight_scope(self) -> None:+ self.client.logout()+ response = self.client.post(+ self.url, {"name": "mrr", "description": "d"}, format="json", **self._bearer(["data_catalog:write"])+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()diff --git a/products/data_catalog/backend/tests/test_logic.py b/products/data_catalog/backend/tests/test_logic.pyindex 060e2d351e71..3dd71258a901 100644--- a/products/data_catalog/backend/tests/test_logic.py+++ b/products/data_catalog/backend/tests/test_logic.py@@ -8,9 +8,21 @@ from rest_framework.exceptions import ValidationErrorfrom products.data_catalog.backend.facade.enums import CreatedSource, MetricStatusfrom products.data_catalog.backend.logic import metrics-from products.data_catalog.backend.logic.metrics import soft_delete_metric, update_metric, upsert_metric+from products.data_catalog.backend.logic.drift import compute_drift+from products.data_catalog.backend.logic.exceptions import MetricDrifted, SourceInsightUnavailable+from products.data_catalog.backend.logic.metrics import (+ approve_metric,+ refresh_metric_from_insight,+ soft_delete_metric,+ update_metric,+ upsert_metric,+)from products.data_catalog.backend.logic.validation import validate_metric_definitionfrom products.data_catalog.backend.models import Metric+from products.product_analytics.backend.models.insight import Insight++_HOGQL_A = {"kind": "HogQLQuery", "query": "select count() from events"}+_HOGQL_B = {"kind": "HogQLQuery", "query": "select count() from persons"}class TestMetricUpsert(BaseTest):@@ -139,3 +151,293 @@ class TestValidateMetricDefinition(BaseTest):def test_rejects_invalid_definitions(self, _name: str, definition: dict) -> None:with self.assertRaises(ValidationError):validate_metric_definition(definition, self.team, self.user)+++class TestCreateFromInsight(BaseTest):+ def _insight(self, query: dict | None = None) -> Insight:+ return Insight.objects.create(team=self.team, created_by=self.user, query=query or _HOGQL_A)++ def test_snapshots_query_and_is_not_drifted(self) -> None:+ insight = self._insight()+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ assert metric.definition is not None+ assert metric.definition["kind"] == "HogQLQuery"+ assert metric.source_insight_short_id == insight.short_id+ assert metric.source_insight_query_hash+ assert compute_drift([metric])[metric.id] is False++ def test_definition_and_source_are_mutually_exclusive(self) -> None:+ insight = self._insight()+ with self.assertRaises(ValidationError):+ upsert_metric(+ team=self.team,+ user=self.user,+ name="mrr",+ description="d",+ definition=_HOGQL_A,+ source_insight_short_id=insight.short_id,+ )++ def test_missing_insight_rejected(self) -> None:+ with self.assertRaises(ValidationError):+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id="nope")++ def test_create_from_insight_requires_viewer_access(self) -> None:+ # Catalog write access must not let a user snapshot an insight they can't view — that would+ # exfiltrate a restricted insight's query into the metric definition.+ insight = self._insight()+ with patch(+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",+ side_effect=lambda obj=None, *a, **k: type(obj).__name__ != "Insight",+ ):+ with self.assertRaises(ValidationError):+ upsert_metric(+ team=self.team,+ user=self.user,+ name="mrr",+ description="d",+ source_insight_short_id=insight.short_id,+ )++ def test_reordered_insight_query_is_not_drift(self) -> None:+ insight = self._insight(query={"kind": "HogQLQuery", "query": "select 1"})+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ # Same query, keys reordered: canonicalization (sort_keys + upgrade) must not read as drift.+ Insight.objects.filter(pk=insight.pk).update(query={"query": "select 1", "kind": "HogQLQuery"})+ assert compute_drift([metric])[metric.id] is False+++class TestApproveMetric(BaseTest):+ def _insight(self, query: dict | None = None) -> Insight:+ return Insight.objects.create(team=self.team, created_by=self.user, query=query or _HOGQL_A)++ def test_approve_sets_status_and_approver(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ approved = approve_metric(metric, self.user)+ assert approved.status == MetricStatus.APPROVED+ assert approved.approved_by_id == self.user.id++ def test_approve_is_idempotent(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ approve_metric(metric, self.user)+ again = approve_metric(metric, self.user)+ assert again.status == MetricStatus.APPROVED++ def test_approve_blocked_while_drifted(self) -> None:+ insight = self._insight()+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ Insight.objects.filter(pk=insight.pk).update(query=_HOGQL_B)+ with self.assertRaises(MetricDrifted):+ approve_metric(metric, self.user)++ def test_reapprove_of_drifted_approved_metric_raises(self) -> None:+ insight = self._insight()+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ approve_metric(metric, self.user)+ Insight.objects.filter(pk=insight.pk).update(query=_HOGQL_B)+ with self.assertRaises(MetricDrifted):+ approve_metric(metric, self.user)++ def test_approve_checks_drift_on_the_current_row_not_the_loaded_instance(self) -> None:+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="mrr",+ description="d",+ source_insight_short_id=self._insight().short_id,+ )+ stale = Metric.objects.for_team(self.team.id).get(pk=metric.pk)+ insight_b = self._insight(query=_HOGQL_B)+ update_metric(metric, team=self.team, user=self.user, source_insight_short_id=insight_b.short_id)+ Insight.objects.filter(pk=insight_b.pk).update(query={"kind": "HogQLQuery", "query": "select 1"})++ with self.assertRaises(MetricDrifted):+ approve_metric(stale, self.user)+++class TestRefreshFromInsight(BaseTest):+ def _insight(self, query: dict | None = None) -> Insight:+ return Insight.objects.create(team=self.team, created_by=self.user, query=query or _HOGQL_A)++ def test_refresh_resnapshots_and_resets_approval(self) -> None:+ insight = self._insight()+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ approve_metric(metric, self.user)+ Insight.objects.filter(pk=insight.pk).update(query=_HOGQL_B)++ refreshed = refresh_metric_from_insight(metric, self.user)+ assert refreshed.status == MetricStatus.PROPOSED+ assert refreshed.definition is not None+ assert "persons" in refreshed.definition["query"]+ assert compute_drift([refreshed])[refreshed.id] is False++ def test_refresh_deleted_insight_errors(self) -> None:+ insight = self._insight()+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ Insight.objects.filter(pk=insight.pk).update(deleted=True)+ with self.assertRaises(SourceInsightUnavailable):+ refresh_metric_from_insight(metric, self.user)++ def test_refresh_requires_viewer_access(self) -> None:+ # Losing viewer access to the linked insight must block re-snapshotting it.+ insight = self._insight()+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ with patch(+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object",+ side_effect=lambda obj=None, *a, **k: type(obj).__name__ != "Insight",+ ):+ with self.assertRaises(ValidationError):+ refresh_metric_from_insight(metric, self.user)+++class TestUpdateResetsApproval(BaseTest):+ def test_editing_definition_resets_approval(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ approve_metric(metric, self.user)+ updated = update_metric(metric, team=self.team, user=self.user, definition=_HOGQL_B)+ assert updated.status == MetricStatus.PROPOSED+ assert updated.approved_by_id is None++ def test_cosmetic_edit_keeps_approval(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ approve_metric(metric, self.user)+ updated = update_metric(metric, team=self.team, user=self.user, display_name="MRR")+ assert updated.status == MetricStatus.APPROVED++ @parameterized.expand(+ [+ ("description", {"description": "a materially different meaning"}),+ ("unit", {"unit": "percent"}),+ ]+ )+ def test_semantic_edit_resets_approval(self, _name: str, edit: dict) -> None:+ # description and unit carry the metric's reviewed meaning (for a definition-less metric the+ # description *is* the definition), so editing them with catalog write access must re-open review.+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", unit="usd")+ approve_metric(metric, self.user)+ updated = update_metric(metric, team=self.team, user=self.user, **edit)+ assert updated.status == MetricStatus.PROPOSED+ assert updated.approved_by_id is None++ def test_refine_definition_resets_approval(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ approve_metric(metric, self.user)+ refined = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_B)+ assert refined.status == MetricStatus.PROPOSED+ assert refined.approved_by_id is None++ def test_refine_cosmetic_change_keeps_approval(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ approve_metric(metric, self.user)+ refined = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", display_name="MRR")+ assert refined.status == MetricStatus.APPROVED++ def test_refine_description_change_resets_approval(self) -> None:+ # A refine that omits the definition but rewrites the description changes what a+ # definition-less metric means, so its approval must not carry over.+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d")+ approve_metric(metric, self.user)+ refined = upsert_metric(team=self.team, user=self.user, name="mrr", description="a different meaning")+ assert refined.status == MetricStatus.PROPOSED+ assert refined.approved_by_id is None++ def test_stale_update_after_approve_still_resets_approval(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ stale = Metric.objects.for_team(self.team.id).get(pk=metric.pk)+ approve_metric(metric, self.user)++ update_metric(stale, team=self.team, user=self.user, definition=_HOGQL_B)++ metric.refresh_from_db()+ assert metric.status == MetricStatus.PROPOSED+ assert metric.approved_by_id is None+ assert metric.definition is not None+ assert "persons" in metric.definition["query"]+++class TestUpdateInsightLink(BaseTest):+ def _insight(self, query: dict | None = None) -> Insight:+ return Insight.objects.create(team=self.team, created_by=self.user, query=query or _HOGQL_A)++ @parameterized.expand(+ [+ ("drifted", True, MetricStatus.PROPOSED),+ ("in_sync", False, MetricStatus.APPROVED),+ ]+ )+ def test_unlink_resets_approval_only_while_drifted(self, _name: str, drifted: bool, expected: str) -> None:+ # Unlinking a drifted approved metric would erase the drift signal that flags the approval+ # as stale, so it must re-open review; unlinking an in-sync metric keeps the blessing.+ insight = self._insight()+ metric = upsert_metric(+ team=self.team, user=self.user, name="mrr", description="d", source_insight_short_id=insight.short_id+ )+ approve_metric(metric, self.user)+ if drifted:+ Insight.objects.filter(pk=insight.pk).update(query=_HOGQL_B)++ updated = update_metric(metric, team=self.team, user=self.user, source_insight_short_id=None)++ assert updated.source_insight_short_id is None+ assert updated.status == expected++ def test_relink_to_new_insight_snapshots_and_resets_approval(self) -> None:+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="mrr",+ description="d",+ source_insight_short_id=self._insight().short_id,+ )+ approve_metric(metric, self.user)+ insight_b = self._insight(query=_HOGQL_B)++ updated = update_metric(metric, team=self.team, user=self.user, source_insight_short_id=insight_b.short_id)++ assert updated.status == MetricStatus.PROPOSED+ assert updated.source_insight_short_id == insight_b.short_id+ assert updated.definition is not None+ assert "persons" in updated.definition["query"]+ assert compute_drift([updated])[updated.id] is False++ @parameterized.expand(["update", "refine"])+ def test_definition_edit_unlinks_source_insight(self, path: str) -> None:+ metric = upsert_metric(+ team=self.team,+ user=self.user,+ name="mrr",+ description="d",+ source_insight_short_id=self._insight().short_id,+ )+ if path == "update":+ edited = update_metric(metric, team=self.team, user=self.user, definition=_HOGQL_B)+ else:+ edited = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_B)++ assert edited.source_insight_short_id is None+ assert edited.source_insight_query_hash is None++ def test_definition_and_source_are_mutually_exclusive_on_update(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)+ with self.assertRaises(ValidationError):+ update_metric(+ metric,+ team=self.team,+ user=self.user,+ definition=_HOGQL_A,+ source_insight_short_id=self._insight().short_id,+ )diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.tsindex 351796a331d1..b5d6cd6a6b5b 100644--- a/products/data_catalog/frontend/generated/api.schemas.ts+++ b/products/data_catalog/frontend/generated/api.schemas.ts@@ -7,17 +7,6 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/-/**- * * `user` - user- * * `ai_generated` - ai_generated- */-export type CreatedSourceEnumApi = (typeof CreatedSourceEnumApi)[keyof typeof CreatedSourceEnumApi]--export const CreatedSourceEnumApi = {- User: 'user',- AiGenerated: 'ai_generated',-} as const-/*** * `engineering` - Engineering* * `data` - Data@@ -73,6 +62,17 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+/**+ * * `user` - user+ * * `ai_generated` - ai_generated+ */+export type CreatedSourceEnumApi = (typeof CreatedSourceEnumApi)[keyof typeof CreatedSourceEnumApi]++export const CreatedSourceEnumApi = {+ User: 'user',+ AiGenerated: 'ai_generated',+} as const+/*** Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.* @nullable@@ -118,13 +118,18 @@ export interface DataCatalogMetricApi {readonly referenced_table_names: unknown/** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */readonly status: string+ /** True when the definition has drifted from its linked source insight (or the insight is gone). */+ readonly is_drifted: boolean/** @nullable */readonly approved_at: string | null+ /** User who approved this metric as canonical, or null. */+ readonly approved_by: UserBasicApi | null/**- * Short ID of the insight this metric was created from, for drift detection.+ * Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition.+ * @maxLength 12* @nullable*/- readonly source_insight_short_id: string | null+ source_insight_short_id?: string | null/*** When the metric was last run (30-minute throttle).* @nullable@@ -208,13 +213,18 @@ export interface PatchedDataCatalogMetricApi {readonly referenced_table_names?: unknown/** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */readonly status?: string+ /** True when the definition has drifted from its linked source insight (or the insight is gone). */+ readonly is_drifted?: boolean/** @nullable */readonly approved_at?: string | null+ /** User who approved this metric as canonical, or null. */+ readonly approved_by?: UserBasicApi | null/**- * Short ID of the insight this metric was created from, for drift detection.+ * Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition.+ * @maxLength 12* @nullable*/- readonly source_insight_short_id?: string | null+ source_insight_short_id?: string | null/*** When the metric was last run (30-minute throttle).* @nullablediff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.tsindex c1cc8d7fcb61..fc43d0703806 100644--- a/products/data_catalog/frontend/generated/api.ts+++ b/products/data_catalog/frontend/generated/api.ts@@ -159,3 +159,39 @@ export const dataCatalogMetricsDestroy = async (method: 'DELETE',})}++export const getDataCatalogMetricsApproveCreateUrl = (projectId: string, name: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${name}/approve/`+}++/**+ * Bless a metric as canonical. Returns 409 while the metric is drifted from its insight.+ */+export const dataCatalogMetricsApproveCreate = async (+ projectId: string,+ name: string,+ options?: RequestInit+): Promise<DataCatalogMetricApi> => {+ return apiMutator<DataCatalogMetricApi>(getDataCatalogMetricsApproveCreateUrl(projectId, name), {+ ...options,+ method: 'POST',+ })+}++export const getDataCatalogMetricsRefreshFromInsightCreateUrl = (projectId: string, name: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${name}/refresh_from_insight/`+}++/**+ * Re-snapshot the linked insight's current query into the definition.+ */+export const dataCatalogMetricsRefreshFromInsightCreate = async (+ projectId: string,+ name: string,+ options?: RequestInit+): Promise<DataCatalogMetricApi> => {+ return apiMutator<DataCatalogMetricApi>(getDataCatalogMetricsRefreshFromInsightCreateUrl(projectId, name), {+ ...options,+ method: 'POST',+ })+}diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.tsindex c78fe322bfa0..7a9586e940b7 100644--- a/products/data_catalog/frontend/generated/api.zod.ts+++ b/products/data_catalog/frontend/generated/api.zod.ts@@ -19,6 +19,8 @@ export const dataCatalogMetricsCreateBodyDisplayNameMax = 255export const dataCatalogMetricsCreateBodyUnitMax = 64+export const dataCatalogMetricsCreateBodySourceInsightShortIdMax = 12+export const dataCatalogMetricsCreateBodyAiModelMax = 128export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({@@ -42,6 +44,13 @@ export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({.record(zod.string(), zod.unknown()).nullish().describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ source_insight_short_id: zod+ .string()+ .max(dataCatalogMetricsCreateBodySourceInsightShortIdMax)+ .nullish()+ .describe(+ "Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition."+ ),created_source: zod.enum(['user', 'ai_generated']).describe('\* `user` - user\n\* `ai_generated` - ai_generated')@@ -68,6 +77,8 @@ export const dataCatalogMetricsUpdateBodyDisplayNameMax = 255export const dataCatalogMetricsUpdateBodyUnitMax = 64+export const dataCatalogMetricsUpdateBodySourceInsightShortIdMax = 12+export const dataCatalogMetricsUpdateBodyAiModelMax = 128export const DataCatalogMetricsUpdateBody = /* @__PURE__ */ zod.object({@@ -91,6 +102,13 @@ export const DataCatalogMetricsUpdateBody = /* @__PURE__ */ zod.object({.record(zod.string(), zod.unknown()).nullish().describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ source_insight_short_id: zod+ .string()+ .max(dataCatalogMetricsUpdateBodySourceInsightShortIdMax)+ .nullish()+ .describe(+ "Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition."+ ),created_source: zod.enum(['user', 'ai_generated']).describe('\* `user` - user\n\* `ai_generated` - ai_generated')@@ -117,6 +135,8 @@ export const dataCatalogMetricsPartialUpdateBodyDisplayNameMax = 255export const dataCatalogMetricsPartialUpdateBodyUnitMax = 64+export const dataCatalogMetricsPartialUpdateBodySourceInsightShortIdMax = 12+export const dataCatalogMetricsPartialUpdateBodyAiModelMax = 128export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({@@ -141,6 +161,13 @@ export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({.record(zod.string(), zod.unknown()).nullish().describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ source_insight_short_id: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodySourceInsightShortIdMax)+ .nullish()+ .describe(+ "Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition."+ ),created_source: zod.enum(['user', 'ai_generated']).describe('\* `user` - user\n\* `ai_generated` - ai_generated')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9dfe9fca36e8..ac1bbb5bdc61 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -15561,13 +15561,18 @@ export namespace Schemas {readonly referenced_table_names: unknown;/** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */readonly status: string;+ /** True when the definition has drifted from its linked source insight (or the insight is gone). */+ readonly is_drifted: boolean;/** @nullable */readonly approved_at: string | null;+ /** User who approved this metric as canonical, or null. */+ readonly approved_by: UserBasic | null;/**- * Short ID of the insight this metric was created from, for drift detection.+ * Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition.+ * @maxLength 12* @nullable*/- readonly source_insight_short_id: string | null;+ source_insight_short_id?: string | null;/*** When the metric was last run (30-minute throttle).* @nullable@@ -39557,13 +39562,18 @@ export namespace Schemas {readonly referenced_table_names?: unknown;/** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */readonly status?: string;+ /** True when the definition has drifted from its linked source insight (or the insight is gone). */+ readonly is_drifted?: boolean;/** @nullable */readonly approved_at?: string | null;+ /** User who approved this metric as canonical, or null. */+ readonly approved_by?: UserBasic | null;/**- * Short ID of the insight this metric was created from, for drift detection.+ * Create the metric from this insight's query (snapshotted server-side). Set to null to unlink. Mutually exclusive with definition.+ * @maxLength 12* @nullable*/- readonly source_insight_short_id?: string | null;+ source_insight_short_id?: string | null;/*** When the metric was last run (30-minute throttle).* @nullable