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): bulk approve and delete metrics (#83858)

Thiago Salvatore48756454555e
diff --git a/.gitignore b/.gitignore
index 8bd2298c21be..4f1300bde968 100644
--- a/.gitignore
+++ b/.gitignore
@@ -233,3 +233,4 @@ dump.rdb
# Log corpora captured for the pattern replay harness. These hold real log bodies —
# addresses, hostnames, request ids, user agents — and this repository is public.
corpora/
+.gstack/
diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.py
index c580595e723f..9d9d0464d772 100644
--- a/products/data_catalog/backend/facade/api.py
+++ b/products/data_catalog/backend/facade/api.py
@@ -16,8 +16,13 @@ from ..logic.certifications import (
from ..logic.drift import compute_drift
from ..logic.execution import run_metric
from ..logic.metrics import (
+ BULK_SKIP_NOT_FOUND,
+ METRIC_BULK_MAX,
+ MetricBulkSkip,
approve_metric,
approved_metric_names_for_team,
+ bulk_approve_metrics,
+ bulk_soft_delete_metrics,
metrics_for_team,
refresh_metric_from_insight,
soft_delete_metric,
@@ -26,16 +31,23 @@ from ..logic.metrics import (
)
from ..logic.relationships import accept_proposal, propose_relationship, reject_proposal, relationships_for_team
from ..logic.validation import MAX_DESCRIPTION_LENGTH, validate_metric_definition
+from ..models import METRIC_NAME_MAX_LENGTH
from .models import Metric, RelationshipProposal, TableCertification
__all__ = [
+ "BULK_SKIP_NOT_FOUND",
"MAX_DESCRIPTION_LENGTH",
+ "METRIC_BULK_MAX",
+ "METRIC_NAME_MAX_LENGTH",
"Metric",
+ "MetricBulkSkip",
"RelationshipProposal",
"TableCertification",
"accept_proposal",
"approve_metric",
"approved_metric_names_for_team",
+ "bulk_approve_metrics",
+ "bulk_soft_delete_metrics",
"certifications_for_team",
"certify",
"compute_drift",
diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.py
index 3aa0dd72eaf6..94dba9331e3a 100644
--- a/products/data_catalog/backend/logic/metrics.py
+++ b/products/data_catalog/backend/logic/metrics.py
@@ -9,7 +9,9 @@ measurement.
"""
import re
+from functools import partial
from typing import TYPE_CHECKING, Optional
+from uuid import UUID
from django.db import IntegrityError, transaction
from django.db.models import QuerySet
@@ -17,6 +19,7 @@ from django.utils import timezone
from rest_framework.exceptions import ValidationError
+from posthog.dataclasses import frozen
from posthog.models import Team, User
from posthog.models.scoping import team_scope
from posthog.rbac.user_access_control import UserAccessControl
@@ -61,6 +64,22 @@ _APPROVAL_FIELDS = frozenset({"status", "approved_by", "approved_at"})
# description), so moving an approved definition under a different name changes what the approval says.
_APPROVAL_RELEVANT_FIELDS = frozenset({"name", "description", "unit"})
+# One bulk request holds a row lock per metric for the length of a single transaction, so the batch
+# is capped. A team's catalog is tens of metrics, well inside this.
+METRIC_BULK_MAX = 100
+
+BULK_SKIP_NOT_FOUND = "Not found"
+BULK_SKIP_ALREADY_APPROVED = "Already approved"
+BULK_SKIP_DRIFTED = "Drifted from its source insight"
+
+
+@frozen
+class MetricBulkSkip:
+ """A metric a bulk operation did not act on, and why."""
+
+ name: str
+ reason: str
+
def _canonical_definition(
definition: Optional[dict], team: Team, user: Optional[User]
@@ -315,6 +334,13 @@ def update_metric(
return metric
+def _apply_approval(metric: Metric, user: Optional[User]) -> None:
+ metric.status = MetricStatus.APPROVED
+ metric.approved_by = user
+ metric.approved_at = timezone.now()
+ metric.save(update_fields=[*_APPROVAL_FIELDS, "updated_at"])
+
+
def approve_metric(metric: Metric, user: Optional[User], request: "Request | None" = None) -> Metric:
"""Bless a metric as canonical. Blocked (409) while drifted. Idempotent on an already-approved metric."""
with team_scope(metric.team_id), transaction.atomic():
@@ -331,10 +357,7 @@ def approve_metric(metric: Metric, user: Optional[User], request: "Request | Non
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"])
+ _apply_approval(metric, user)
capture_metric_event(METRIC_APPROVED_EVENT, metric, team=metric.team, user=user, request=request)
return metric
@@ -373,14 +396,128 @@ def refresh_metric_from_insight(metric: Metric, user: Optional[User], request: "
return metric
-def soft_delete_metric(metric: Metric, user: Optional[User] = None, request: "Request | None" = None) -> None:
+def _apply_soft_delete(metric: Metric) -> None:
metric.deleted = True
metric.deleted_at = timezone.now()
+ metric.save(update_fields=["deleted", "deleted_at", "updated_at"])
+
+
+def soft_delete_metric(metric: Metric, user: Optional[User] = None, request: "Request | None" = None) -> None:
with team_scope(metric.team_id):
- metric.save(update_fields=["deleted", "deleted_at", "updated_at"])
+ _apply_soft_delete(metric)
capture_metric_event(METRIC_DELETED_EVENT, metric, team=metric.team, user=user, request=request)
+def _batch_team(metrics: list[Metric]) -> Team:
+ """The single team a bulk batch belongs to, loaded once so event capture doesn't refetch per metric."""
+ team_ids = {metric.team_id for metric in metrics}
+ if len(team_ids) > 1:
+ raise ValueError("A bulk metric operation must stay within one team.")
+ return Team.objects.get(pk=team_ids.pop())
+
+
+def _lock_batch(team_id: int, metrics: list[Metric]) -> dict[UUID, Metric]:
+ """Re-read and row-lock the batch, keyed by id.
+
+ Locks in ``pk`` order so two concurrent bulk operations over overlapping rows queue behind each
+ other instead of deadlocking. A metric missing from the result was deleted between resolution and
+ the lock.
+ """
+ locked = (
+ Metric.objects.for_team(team_id)
+ .filter(pk__in=[metric.pk for metric in metrics], deleted=False)
+ # Cache owner and created_by so serializing the approve response reads them off the row
+ # instead of one posthog_user lookup per metric. Both FKs are nullable, so select_related
+ # is a LEFT OUTER JOIN; Postgres rejects FOR UPDATE on the nullable side of an outer join,
+ # so scope the lock to the Metric row with of=("self",) (which also keeps the lock off
+ # posthog_user).
+ .select_for_update(of=("self",))
+ .select_related("owner", "created_by")
+ .order_by("pk")
+ )
+ return {metric.id: metric for metric in locked}
+
+
+def _locked_match(locked: dict[UUID, Metric], requested: Metric) -> Optional[Metric]:
+ """The locked row that still holds the name the caller asked for, or None.
+
+ Callers address a metric by name, and a name is freed for reuse. A row renamed between name
+ resolution and the lock is no longer the metric that was requested, so the batch leaves it alone
+ rather than acting on it under a name nobody sent.
+ """
+ metric = locked.get(requested.id)
+ if metric is None or metric.name != requested.name:
+ return None
+ return metric
+
+
+def _capture_after_commit(
+ event: str, metrics: list[Metric], *, team: Team, user: Optional[User], request: "Request | None"
+) -> None:
+ for metric in metrics:
+ transaction.on_commit(partial(capture_metric_event, event, metric, team=team, user=user, request=request))
+
+
+def bulk_approve_metrics(
+ metrics: list[Metric], user: Optional[User], request: "Request | None" = None
+) -> tuple[list[Metric], list[MetricBulkSkip]]:
+ """Approve every approvable metric in one transaction, reporting the rest as skipped with a reason.
+
+ Drift is checked against the locked rows, so a metric that drifted or was approved between the
+ caller rendering it and this call is skipped rather than approved. Response order follows the
+ request.
+ """
+ if not metrics:
+ return [], []
+ team = _batch_team(metrics)
+ approved: list[Metric] = []
+ skipped: list[MetricBulkSkip] = []
+
+ with team_scope(team.id), transaction.atomic():
+ locked = _lock_batch(team.id, metrics)
+ drifted = compute_drift(locked.values())
+ for requested in metrics:
+ metric = _locked_match(locked, requested)
+ if metric is None:
+ skipped.append(MetricBulkSkip(name=requested.name, reason=BULK_SKIP_NOT_FOUND))
+ elif drifted[metric.id]:
+ skipped.append(MetricBulkSkip(name=metric.name, reason=BULK_SKIP_DRIFTED))
+ elif metric.status == MetricStatus.APPROVED:
+ skipped.append(MetricBulkSkip(name=metric.name, reason=BULK_SKIP_ALREADY_APPROVED))
+ else:
+ # Per-instance save, never a queryset UPDATE: the audit trail only fires in save().
+ _apply_approval(metric, user)
+ approved.append(metric)
+ _capture_after_commit(METRIC_APPROVED_EVENT, approved, team=team, user=user, request=request)
+
+ return approved, skipped
+
+
+def bulk_soft_delete_metrics(
+ metrics: list[Metric], user: Optional[User] = None, request: "Request | None" = None
+) -> tuple[list[Metric], list[MetricBulkSkip]]:
+ """Soft-delete a batch in one transaction, freeing their names for reuse."""
+ if not metrics:
+ return [], []
+ team = _batch_team(metrics)
+ deleted: list[Metric] = []
+ skipped: list[MetricBulkSkip] = []
+
+ with team_scope(team.id), transaction.atomic():
+ # Same pk lock order as bulk_approve_metrics, so a mixed approve/delete pair can't deadlock.
+ locked = _lock_batch(team.id, metrics)
+ for requested in metrics:
+ metric = _locked_match(locked, requested)
+ if metric is None:
+ skipped.append(MetricBulkSkip(name=requested.name, reason=BULK_SKIP_NOT_FOUND))
+ continue
+ _apply_soft_delete(metric)
+ deleted.append(metric)
+ _capture_after_commit(METRIC_DELETED_EVENT, deleted, team=team, user=user, request=request)
+
+ return deleted, skipped
+
+
def _reset_to_proposed(metric: Metric) -> None:
metric.status = MetricStatus.PROPOSED
metric.approved_by = None
diff --git a/products/data_catalog/backend/models/__init__.py b/products/data_catalog/backend/models/__init__.py
index 8d47b45a7a9b..c37ca7e407b5 100644
--- a/products/data_catalog/backend/models/__init__.py
+++ b/products/data_catalog/backend/models/__init__.py
@@ -1,5 +1,11 @@
from .certification import TableCertification
-from .metric import METRIC_NAME_REGEX, Metric
+from .metric import METRIC_NAME_MAX_LENGTH, METRIC_NAME_REGEX, Metric
from .relationship_proposal import RelationshipProposal
-__all__ = ["METRIC_NAME_REGEX", "Metric", "RelationshipProposal", "TableCertification"]
+__all__ = [
+ "METRIC_NAME_MAX_LENGTH",
+ "METRIC_NAME_REGEX",
+ "Metric",
+ "RelationshipProposal",
+ "TableCertification",
+]
diff --git a/products/data_catalog/backend/models/metric.py b/products/data_catalog/backend/models/metric.py
index 02637bdd523a..ba724e1a5ab4 100644
--- a/products/data_catalog/backend/models/metric.py
+++ b/products/data_catalog/backend/models/metric.py
@@ -11,6 +11,8 @@ from ..facade.enums import CreatedSource, MetricStatus
# `POST data_catalog/metrics/{name}/run`), so it must be a bare identifier.
METRIC_NAME_REGEX = r"^[A-Za-z][A-Za-z0-9_]*$"
+METRIC_NAME_MAX_LENGTH = 128
+
validate_metric_name = RegexValidator(
regex=METRIC_NAME_REGEX,
message="Name must start with a letter and contain only letters, numbers, and underscores.",
@@ -39,7 +41,7 @@ class Metric(
)
name = models.CharField(
- max_length=128,
+ max_length=METRIC_NAME_MAX_LENGTH,
validators=[validate_metric_name],
help_text="Identifier-safe run handle, unique among the team's live metrics. Renaming or "
"deleting a metric frees its name for reuse; references to the old name stop resolving.",
diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.py
index fa5b0031297d..b48f1f064f3c 100644
--- a/products/data_catalog/backend/presentation/serializers.py
+++ b/products/data_catalog/backend/presentation/serializers.py
@@ -13,7 +13,7 @@ from posthog.api.shared import UserBasicSerializer
from posthog.schema_enums import IntervalType
from ..facade import api
-from ..facade.api import MAX_DESCRIPTION_LENGTH
+from ..facade.api import MAX_DESCRIPTION_LENGTH, METRIC_NAME_MAX_LENGTH
from ..facade.enums import CreatedSource
from ..facade.models import Metric, RelationshipProposal, TableCertification
@@ -193,6 +193,49 @@ class MetricSerializer(serializers.ModelSerializer):
return api.compute_drift([obj])[obj.id]
+@extend_schema_serializer(component_name="DataCatalogMetricBulkNamesRequest")
+class MetricBulkNamesRequestSerializer(serializers.Serializer):
+ """Input for the bulk metric actions: the metric names to act on."""
+
+ names = serializers.ListField(
+ child=serializers.CharField(max_length=METRIC_NAME_MAX_LENGTH),
+ allow_empty=False,
+ # `allow_empty` alone doesn't reach the OpenAPI schema; `min_length` emits `minItems: 1`
+ # so generated MCP/Zod clients can't construct an empty batch the API would 400.
+ min_length=1,
+ max_length=api.METRIC_BULK_MAX,
+ help_text=f"Names of the metrics to act on, at most {api.METRIC_BULK_MAX}. Duplicates are collapsed.",
+ )
+
+
+@extend_schema_serializer(component_name="DataCatalogMetricBulkSkip")
+class MetricBulkSkipSerializer(serializers.Serializer):
+ """A metric the bulk action did not act on, and why."""
+
+ name = serializers.CharField(help_text="Name of the metric that was skipped.")
+ reason = serializers.CharField(
+ help_text="Why it was skipped, e.g. 'Not found', 'Already approved', 'Drifted from its source insight'."
+ )
+
+
+@extend_schema_serializer(component_name="DataCatalogMetricBulkApprove")
+class MetricBulkApproveResponseSerializer(serializers.Serializer):
+ """Outcome of a bulk approve: what changed, and what was left alone."""
+
+ approved = MetricSerializer(many=True, help_text="The metrics that are now approved, freshly serialized.")
+ skipped = MetricBulkSkipSerializer(many=True, help_text="Requested metrics that were not approved, with reasons.")
+
+
+@extend_schema_serializer(component_name="DataCatalogMetricBulkDelete")
+class MetricBulkDeleteResponseSerializer(serializers.Serializer):
+ """Outcome of a bulk delete: which names are gone, and what was left alone."""
+
+ deleted = serializers.ListField(
+ child=serializers.CharField(), help_text="Names of the metrics that were deleted, now free for reuse."
+ )
+ skipped = MetricBulkSkipSerializer(many=True, help_text="Requested metrics that were not deleted, with reasons.")
+
+
@extend_schema_serializer(component_name="DataCatalogCertification")
class CertificationSerializer(serializers.ModelSerializer):
status = serializers.CharField(
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index d5d2bb159eb3..2f014fe7b182 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -30,6 +30,9 @@ from ..facade.models import Metric, RelationshipProposal, TableCertification
from .serializers import (
CertificationCreateSerializer,
CertificationSerializer,
+ MetricBulkApproveResponseSerializer,
+ MetricBulkDeleteResponseSerializer,
+ MetricBulkNamesRequestSerializer,
MetricRunQuerySerializer,
MetricRunRequestSerializer,
MetricRunResponseSerializer,
@@ -43,6 +46,21 @@ from .serializers import (
_STRUCTURED_QUERY_KINDS = {*INSIGHT_DEFINITION_KINDS, *NODE_DEFINITION_KINDS}
+def _resolve_bulk_metrics(
+ queryset: QuerySet[Metric], names: list[str]
+) -> tuple[list[Metric], list[api.MetricBulkSkip]]:
+ """Resolve names against a team-scoped queryset, deduped, in request order.
+
+ Shared by both bulk metric actions, so a name that resolves for one resolves for the other.
+ """
+ requested = list(dict.fromkeys(names))
+ by_name = {metric.name: metric for metric in queryset.filter(name__in=requested)}
+ return (
+ [by_name[name] for name in requested if name in by_name],
+ [api.MetricBulkSkip(name=name, reason=api.BULK_SKIP_NOT_FOUND) for name in requested if name not in by_name],
+ )
+
+
class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/)."""
@@ -144,6 +162,45 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
metric = api.approve_metric(self.get_object(), cast(User, request.user), request=request)
return Response(self.get_serializer(metric).data)
+ # DRF routes detail=False actions before the {name} detail route, so these paths can't be
+ # shadowed by a metric literally named bulk_approve.
+ @action(
+ detail=False,
+ methods=["POST"],
+ required_scopes=["data_catalog_approval:write", "data_catalog:read"],
+ request=MetricBulkNamesRequestSerializer,
+ responses={200: MetricBulkApproveResponseSerializer},
+ )
+ @validated_request(request_serializer=MetricBulkNamesRequestSerializer)
+ def bulk_approve(self, request: ValidatedRequest, **kwargs) -> Response:
+ """Approve many metrics as canonical. Unknown, already-approved, and drifted metrics are skipped."""
+ metrics, unresolved = _resolve_bulk_metrics(self.get_queryset(), request.validated_data["names"])
+ approved, skipped = api.bulk_approve_metrics(metrics, cast(User, request.user), request=request)
+ # Approval is gated on a drift check over the same locked rows, so every metric in
+ # `approved` is in lockstep with its insight; recomputing would be a second bulk query.
+ context = {**self.get_serializer_context(), "drift_map": {metric.id: False for metric in approved}}
+ payload = MetricBulkApproveResponseSerializer(
+ {"approved": approved, "skipped": [*unresolved, *skipped]}, context=context
+ )
+ return Response(payload.data)
+
+ @action(
+ detail=False,
+ methods=["POST"],
+ required_scopes=["data_catalog:write"],
+ request=MetricBulkNamesRequestSerializer,
+ responses={200: MetricBulkDeleteResponseSerializer},
+ )
+ @validated_request(request_serializer=MetricBulkNamesRequestSerializer)
+ def bulk_delete(self, request: ValidatedRequest, **kwargs) -> Response:
+ """Delete many metrics, freeing their names for reuse. Unknown metrics are skipped."""
+ metrics, unresolved = _resolve_bulk_metrics(self.get_queryset(), request.validated_data["names"])
+ deleted, skipped = api.bulk_soft_delete_metrics(metrics, cast(User, request.user), request=request)
+ payload = MetricBulkDeleteResponseSerializer(
+ {"deleted": [metric.name for metric in deleted], "skipped": [*unresolved, *skipped]}
+ )
+ return Response(payload.data)
+
@action(
detail=True,
methods=["POST"],
diff --git a/products/data_catalog/backend/tests/test_analytics.py b/products/data_catalog/backend/tests/test_analytics.py
index eecc90b07aab..17c6a22ff038 100644
--- a/products/data_catalog/backend/tests/test_analytics.py
+++ b/products/data_catalog/backend/tests/test_analytics.py
@@ -105,3 +105,32 @@ class TestDataCatalogAnalyticsAttribution(APIBaseTest):
properties = created.kwargs["properties"]
assert properties["source"] == "web"
assert properties["is_system"] is False
+
+ @parameterized.expand(
+ [
+ ("bulk_approve", "data catalog metric approved"),
+ ("bulk_delete", "data catalog metric deleted"),
+ ]
+ )
+ @patch(_CAPTURE)
+ def test_bulk_action_emits_one_event_per_acted_metric_after_commit(
+ self, url_path: str, expected_event: str, capture: MagicMock
+ ) -> None:
+ url = f"/api/projects/{self.team.id}/data_catalog/metrics/"
+ upsert_metric(team=self.team, user=self.user, name="first", description="d", definition=_HOGQL)
+ upsert_metric(team=self.team, user=self.user, name="second", description="d", definition=_HOGQL)
+ capture.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=False) as callbacks:
+ response = self.client.post(
+ f"{url}{url_path}/", {"names": ["first", "second", "unheard_of"]}, format="json"
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert _catalog_calls(capture) == []
+
+ for callback in callbacks:
+ callback()
+ assert [(c.kwargs["event"], c.kwargs["properties"]["metric_name"]) for c in _catalog_calls(capture)] == [
+ (expected_event, "first"),
+ (expected_event, "second"),
+ ]
diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.py
index 44c9fe7789c8..d9b2069f62f4 100644
--- a/products/data_catalog/backend/tests/test_api.py
+++ b/products/data_catalog/backend/tests/test_api.py
@@ -10,6 +10,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
@@ -17,9 +18,18 @@ 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.logic.metrics import (
+ BULK_SKIP_ALREADY_APPROVED,
+ BULK_SKIP_DRIFTED,
+ BULK_SKIP_NOT_FOUND,
+ METRIC_BULK_MAX,
+ approve_metric,
+ soft_delete_metric,
+ upsert_metric,
+)
from products.data_catalog.backend.models import Metric
from products.data_catalog.backend.presentation.serializers import (
+ MetricBulkNamesRequestSerializer,
MetricRunQuerySerializer,
MetricRunRequestSerializer,
MetricSerializer,
@@ -341,6 +351,141 @@ class TestMetricLifecycleAPI(APIBaseTest):
response = self.client.post(f"{self.url}mrr/run/{query_string}", body, format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ def _drifted_metric(self, name: str) -> Metric:
+ insight = self._insight()
+ metric = upsert_metric(
+ team=self.team, user=self.user, name=name, description="d", source_insight_short_id=insight.short_id
+ )
+ Insight.objects.filter(pk=insight.pk).update(
+ query={"kind": "HogQLQuery", "query": "select count() from persons"}
+ )
+ return metric
+
+ def _other_team_metric(self, name: str) -> Metric:
+ other_team = Team.objects.create_with_data(
+ organization=self.organization, initiating_user=self.user, name="Other"
+ )
+ return Metric.objects.for_team(other_team.id).create(team=other_team, name=name, description="d")
+
+ def test_bulk_approve_partitions_the_batch_and_reasons_every_skip(self) -> None:
+ upsert_metric(team=self.team, user=self.user, name="first", description="d", definition=_HOGQL)
+ upsert_metric(team=self.team, user=self.user, name="second", description="d", definition=_HOGQL)
+ approve_metric(
+ upsert_metric(team=self.team, user=self.user, name="blessed", description="d", definition=_HOGQL), self.user
+ )
+ self._drifted_metric("stale")
+ soft_delete_metric(upsert_metric(team=self.team, user=self.user, name="gone", description="d"))
+ theirs = self._other_team_metric("theirs")
+
+ response = self.client.post(
+ f"{self.url}bulk_approve/",
+ {"names": ["first", "blessed", "stale", "gone", "theirs", "unheard_of", "second"]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert [metric["name"] for metric in body["approved"]] == ["first", "second"]
+ assert {skip["name"]: skip["reason"] for skip in body["skipped"]} == {
+ "blessed": BULK_SKIP_ALREADY_APPROVED,
+ "stale": BULK_SKIP_DRIFTED,
+ "gone": BULK_SKIP_NOT_FOUND,
+ "theirs": BULK_SKIP_NOT_FOUND,
+ "unheard_of": BULK_SKIP_NOT_FOUND,
+ }
+ assert Metric.objects.for_team(self.team.id).get(name="stale").status == MetricStatus.PROPOSED
+ theirs.refresh_from_db()
+ assert theirs.status == MetricStatus.PROPOSED
+
+ def test_bulk_approve_dedupes_repeated_names(self) -> None:
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ response = self.client.post(f"{self.url}bulk_approve/", {"names": ["mrr", "mrr"]}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert [metric["name"] for metric in response.json()["approved"]] == ["mrr"]
+
+ def test_bulk_approve_computes_drift_in_a_single_insight_query(self) -> None:
+ # Same N+1 guard as the list view: drift must not fan out into one insight lookup per metric.
+ names = []
+ for index in range(3):
+ insight = self._insight()
+ names.append(f"m{index}")
+ upsert_metric(
+ team=self.team,
+ user=self.user,
+ name=names[-1],
+ description="d",
+ source_insight_short_id=insight.short_id,
+ )
+ with CaptureQueriesContext(connection) as ctx:
+ response = self.client.post(f"{self.url}bulk_approve/", {"names": names}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ insight_queries = [q for q in ctx.captured_queries if "posthog_dashboarditem" in q["sql"]]
+ assert len(insight_queries) == 1, insight_queries
+
+ def test_bulk_approve_writes_the_audit_trail_per_metric(self) -> None:
+ # The approval must go through save(), not a queryset UPDATE, or the audit trail is silently lost.
+ upsert_metric(team=self.team, user=self.user, name="first", description="d", definition=_HOGQL)
+ upsert_metric(team=self.team, user=self.user, name="second", description="d", definition=_HOGQL)
+ ActivityLog.objects.all().delete()
+
+ response = self.client.post(f"{self.url}bulk_approve/", {"names": ["first", "second"]}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ logged = ActivityLog.objects.filter(team_id=self.team.id, scope="Metric", activity="updated")
+ assert {entry.detail["name"] for entry in logged if entry.detail} == {"first", "second"}
+
+ def test_bulk_delete_frees_the_names_and_skips_unknown_ones(self) -> None:
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d")
+ upsert_metric(team=self.team, user=self.user, name="arr", description="d")
+ theirs = self._other_team_metric("theirs")
+
+ response = self.client.post(
+ f"{self.url}bulk_delete/", {"names": ["mrr", "arr", "theirs", "unheard_of"]}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert body["deleted"] == ["mrr", "arr"]
+ assert {skip["name"] for skip in body["skipped"]} == {"theirs", "unheard_of"}
+ assert self.client.get(self.url).json()["results"] == []
+ theirs.refresh_from_db()
+ assert theirs.deleted is False
+
+ @parameterized.expand(
+ [
+ (
+ "approve_without_approval_scope",
+ "bulk_approve",
+ ["data_catalog:read", "data_catalog:write"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "approve_with_approval_scope",
+ "bulk_approve",
+ ["data_catalog:read", "data_catalog:write", "data_catalog_approval:write"],
+ status.HTTP_200_OK,
+ ),
+ ("delete_read_only", "bulk_delete", ["data_catalog:read"], status.HTTP_403_FORBIDDEN),
+ ("delete_with_write_scope", "bulk_delete", ["data_catalog:write"], status.HTTP_200_OK),
+ ]
+ )
+ def test_bulk_actions_enforce_token_scopes(
+ self, _name: str, url_path: str, scopes: list[str], expected: int
+ ) -> None:
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL)
+ self.client.logout()
+ response = self.client.post(f"{self.url}{url_path}/", {"names": ["mrr"]}, format="json", **self._bearer(scopes))
+ assert response.status_code == expected, response.json()
+
+ def test_bulk_approve_rejects_an_over_cap_batch(self) -> None:
+ # Wiring guard: the action validates through its request serializer. Bounds live in
+ # TestMetricBulkNamesValidation.
+ response = self.client.post(
+ f"{self.url}bulk_approve/", {"names": [f"m{index}" for index in range(METRIC_BULK_MAX + 1)]}, format="json"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "names"
+
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.
@@ -439,3 +584,19 @@ class TestMetricRunInputValidation(SimpleTestCase):
assert serializer.is_valid() is valid, serializer.errors
if not valid:
assert "confidence" in serializer.errors
+
+
+class TestMetricBulkNamesValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("empty", 0, False),
+ ("one", 1, True),
+ ("at_cap", METRIC_BULK_MAX, True),
+ ("over_cap", METRIC_BULK_MAX + 1, False),
+ ]
+ )
+ def test_batch_size_bounds(self, _name: str, count: int, valid: bool) -> None:
+ serializer = MetricBulkNamesRequestSerializer(data={"names": [f"m{index}" for index in range(count)]})
+ assert serializer.is_valid() is valid, serializer.errors
+ if not valid:
+ assert "names" in serializer.errors
diff --git a/products/data_catalog/backend/tests/test_logic.py b/products/data_catalog/backend/tests/test_logic.py
index c82114e618b8..7f29180829fe 100644
--- a/products/data_catalog/backend/tests/test_logic.py
+++ b/products/data_catalog/backend/tests/test_logic.py
@@ -326,6 +326,27 @@ class TestApproveMetric(BaseTest):
approve_metric(stale, self.user)
+class TestBulkRenameRace(BaseTest):
+ @parameterized.expand(
+ [
+ ("approve", metrics.bulk_approve_metrics, MetricStatus.PROPOSED),
+ ("delete", metrics.bulk_soft_delete_metrics, MetricStatus.PROPOSED),
+ ]
+ )
+ def test_bulk_skips_a_metric_renamed_since_resolution(self, _name: str, bulk_action, expected_status: str) -> None:
+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=_HOGQL_A)
+ # The caller resolved "mrr" to this row; another writer renames it before the batch locks it.
+ Metric.objects.for_team(self.team.id).filter(pk=metric.pk).update(name="arr")
+
+ acted, skipped = bulk_action([metric], self.user)
+
+ assert acted == []
+ assert [(skip.name, skip.reason) for skip in skipped] == [("mrr", metrics.BULK_SKIP_NOT_FOUND)]
+ current = Metric.objects.for_team(self.team.id).get(pk=metric.pk)
+ assert current.status == expected_status
+ assert current.deleted is False
+
+
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)
diff --git a/products/data_catalog/frontend/common.ts b/products/data_catalog/frontend/common.ts
index 4c298f5576e9..fc61eca85e4c 100644
--- a/products/data_catalog/frontend/common.ts
+++ b/products/data_catalog/frontend/common.ts
@@ -44,6 +44,13 @@ export const METRIC_DESCRIPTION_MAX_LENGTH = 1000
// Mirrors MAX_MARKDOWN_DEFINITION_LENGTH enforced in products/data_catalog/backend/logic/validation.py.
export const METRIC_MARKDOWN_MAX_LENGTH = 20000
+// Mirrors METRIC_BULK_MAX enforced in products/data_catalog/backend/logic/metrics.py.
+export const METRIC_BULK_MAX = 100
+
+export function metricCount(count: number): string {
+ return `${count} ${count === 1 ? 'metric' : 'metrics'}`
+}
+
export function validateMetricDescription(description: string): string | undefined {
if (description.length > METRIC_DESCRIPTION_MAX_LENGTH) {
return `Keep the description under ${METRIC_DESCRIPTION_MAX_LENGTH} characters. Say what the metric means in a few sentences.`
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index 1c0c9c6c5d6c..20ddd246f2a2 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -424,6 +424,49 @@ export interface DataCatalogMetricRunApi {
instructions: string | null
}
+/**
+ * Input for the bulk metric actions: the metric names to act on.
+ */
+export interface DataCatalogMetricBulkNamesRequestApi {
+ /**
+ * Names of the metrics to act on, at most 100. Duplicates are collapsed.
+ * @minItems 1
+ * @maxItems 100
+ * @items.maxLength 128
+ */
+ names: string[]
+}
+
+/**
+ * A metric the bulk action did not act on, and why.
+ */
+export interface DataCatalogMetricBulkSkipApi {
+ /** Name of the metric that was skipped. */
+ name: string
+ /** Why it was skipped, e.g. 'Not found', 'Already approved', 'Drifted from its source insight'. */
+ reason: string
+}
+
+/**
+ * Outcome of a bulk approve: what changed, and what was left alone.
+ */
+export interface DataCatalogMetricBulkApproveApi {
+ /** The metrics that are now approved, freshly serialized. */
+ approved: DataCatalogMetricApi[]
+ /** Requested metrics that were not approved, with reasons. */
+ skipped: DataCatalogMetricBulkSkipApi[]
+}
+
+/**
+ * Outcome of a bulk delete: which names are gone, and what was left alone.
+ */
+export interface DataCatalogMetricBulkDeleteApi {
+ /** Names of the metrics that were deleted, now free for reuse. */
+ deleted: string[]
+ /** Requested metrics that were not deleted, with reasons. */
+ skipped: DataCatalogMetricBulkSkipApi[]
+}
+
export interface DataCatalogRelationshipProposalApi {
readonly id: string
/**
diff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.ts
index 9a90531e8158..596062d184af 100644
--- a/products/data_catalog/frontend/generated/api.ts
+++ b/products/data_catalog/frontend/generated/api.ts
@@ -13,6 +13,9 @@ import type {
DataCatalogCertificationApi,
DataCatalogCertificationsListParams,
DataCatalogMetricApi,
+ DataCatalogMetricBulkApproveApi,
+ DataCatalogMetricBulkDeleteApi,
+ DataCatalogMetricBulkNamesRequestApi,
DataCatalogMetricRunApi,
DataCatalogMetricRunRequestApi,
DataCatalogMetricsListParams,
@@ -373,6 +376,46 @@ export const dataCatalogMetricsRunCreate = async (
})
}
+export const getDataCatalogMetricsBulkApproveCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_catalog/metrics/bulk_approve/`
+}
+
+/**
+ * Approve many metrics as canonical. Unknown, already-approved, and drifted metrics are skipped.
+ */
+export const dataCatalogMetricsBulkApproveCreate = async (
+ projectId: string,
+ dataCatalogMetricBulkNamesRequestApi: DataCatalogMetricBulkNamesRequestApi,
+ options?: RequestInit
+): Promise<DataCatalogMetricBulkApproveApi> => {
+ return apiMutator<DataCatalogMetricBulkApproveApi>(getDataCatalogMetricsBulkApproveCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataCatalogMetricBulkNamesRequestApi),
+ })
+}
+
+export const getDataCatalogMetricsBulkDeleteCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_catalog/metrics/bulk_delete/`
+}
+
+/**
+ * Delete many metrics, freeing their names for reuse. Unknown metrics are skipped.
+ */
+export const dataCatalogMetricsBulkDeleteCreate = async (
+ projectId: string,
+ dataCatalogMetricBulkNamesRequestApi: DataCatalogMetricBulkNamesRequestApi,
+ options?: RequestInit
+): Promise<DataCatalogMetricBulkDeleteApi> => {
+ return apiMutator<DataCatalogMetricBulkDeleteApi>(getDataCatalogMetricsBulkDeleteCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataCatalogMetricBulkNamesRequestApi),
+ })
+}
+
export const getDataCatalogRelationshipProposalsListUrl = (
projectId: string,
params?: DataCatalogRelationshipProposalsListParams
diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.ts
index bd700087a779..3ac2430ab756 100644
--- a/products/data_catalog/frontend/generated/api.zod.ts
+++ b/products/data_catalog/frontend/generated/api.zod.ts
@@ -283,6 +283,40 @@ export const DataCatalogMetricsRunCreateBody = /* @__PURE__ */ zod
})
.describe('Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name.')
+/**
+ * Approve many metrics as canonical. Unknown, already-approved, and drifted metrics are skipped.
+ */
+export const dataCatalogMetricsBulkApproveCreateBodyNamesItemMax = 128
+
+export const dataCatalogMetricsBulkApproveCreateBodyNamesMax = 100
+
+export const DataCatalogMetricsBulkApproveCreateBody = /* @__PURE__ */ zod
+ .object({
+ names: zod
+ .array(zod.string().max(dataCatalogMetricsBulkApproveCreateBodyNamesItemMax))
+ .min(1)
+ .max(dataCatalogMetricsBulkApproveCreateBodyNamesMax)
+ .describe('Names of the metrics to act on, at most 100. Duplicates are collapsed.'),
+ })
+ .describe('Input for the bulk metric actions: the metric names to act on.')
+
+/**
+ * Delete many metrics, freeing their names for reuse. Unknown metrics are skipped.
+ */
+export const dataCatalogMetricsBulkDeleteCreateBodyNamesItemMax = 128
+
+export const dataCatalogMetricsBulkDeleteCreateBodyNamesMax = 100
+
+export const DataCatalogMetricsBulkDeleteCreateBody = /* @__PURE__ */ zod
+ .object({
+ names: zod
+ .array(zod.string().max(dataCatalogMetricsBulkDeleteCreateBodyNamesItemMax))
+ .min(1)
+ .max(dataCatalogMetricsBulkDeleteCreateBodyNamesMax)
+ .describe('Names of the metrics to act on, at most 100. Duplicates are collapsed.'),
+ })
+ .describe('Input for the bulk metric actions: the metric names to act on.')
+
/**
* Reviewed join facts. Accepting one promotes it to a real DataWarehouseJoin; rejections persist.
*/
diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.ts
index 94633248cf93..194ba5e1d89d 100644
--- a/products/data_catalog/frontend/metricsLogic.test.ts
+++ b/products/data_catalog/frontend/metricsLogic.test.ts
@@ -9,6 +9,8 @@ import { expectLogic } from '~/test/keaTestUtils'
import {
dataCatalogMetricsApproveCreate,
+ dataCatalogMetricsBulkApproveCreate,
+ dataCatalogMetricsBulkDeleteCreate,
dataCatalogMetricsCreate,
dataCatalogMetricsDestroy,
dataCatalogMetricsList,
@@ -44,6 +46,8 @@ jest.mock('./generated/api', () => ({
dataCatalogMetricsApproveCreate: jest.fn(),
dataCatalogMetricsRefreshFromInsightCreate: jest.fn(),
dataCatalogMetricsDestroy: jest.fn(),
+ dataCatalogMetricsBulkApproveCreate: jest.fn(),
+ dataCatalogMetricsBulkDeleteCreate: jest.fn(),
}))
function buildMetric(overrides: Partial<DataCatalogMetricApi> = {}): DataCatalogMetricApi {
@@ -59,6 +63,11 @@ function buildMetric(overrides: Partial<DataCatalogMetricApi> = {}): DataCatalog
} as DataCatalogMetricApi
}
+const BULK_ACTIONS = [
+ ['approve', dataCatalogMetricsBulkApproveCreate, 'bulkApproveMetrics'],
+ ['delete', dataCatalogMetricsBulkDeleteCreate, 'bulkDeleteMetrics'],
+] as const
+
describe('metricsLogic', () => {
let logic: ReturnType<typeof metricsLogic.build>
@@ -193,6 +202,139 @@ describe('metricsLogic', () => {
expect(logic.values.allMetrics).toHaveLength(0)
})
+ it('loads every page of metrics', async () => {
+ ;(dataCatalogMetricsList as jest.Mock)
+ .mockResolvedValueOnce({
+ results: [buildMetric({ id: 'metric-1', name: 'first' })],
+ next: 'http://localhost/api/projects/1/data_catalog/metrics/?limit=100&offset=100',
+ })
+ .mockResolvedValueOnce({ results: [buildMetric({ id: 'metric-2', name: 'second' })], next: null })
+
+ logic.actions.loadMetrics()
+ await expectLogic(logic).toDispatchActions(['loadMetricsSuccess'])
+
+ expect(logic.values.allMetrics.map((metric) => metric.name)).toEqual(['first', 'second'])
+ expect((dataCatalogMetricsList as jest.Mock).mock.calls.map((call) => call[1].offset)).toEqual([0, 0, 100])
+ })
+
+ it('patches approved rows and reloads to reconcile skipped ones', async () => {
+ logic.actions.loadMetricsSuccess([
+ buildMetric({ id: 'metric-1', name: 'first' }),
+ buildMetric({ id: 'metric-2', name: 'second' }),
+ ])
+ ;(dataCatalogMetricsBulkApproveCreate as jest.Mock).mockResolvedValue({
+ approved: [buildMetric({ id: 'metric-1', name: 'first', status: 'approved' })],
+ skipped: [{ name: 'second', reason: 'Drifted from its source insight' }],
+ })
+ // The skip means the page's copy of 'second' is stale, so the reload returns the server's
+ // current state, where 'second' is now drifted.
+ ;(dataCatalogMetricsList as jest.Mock).mockResolvedValue({
+ results: [
+ buildMetric({ id: 'metric-1', name: 'first', status: 'approved' }),
+ buildMetric({ id: 'metric-2', name: 'second', is_drifted: true }),
+ ],
+ next: null,
+ })
+ const listCallsBefore = (dataCatalogMetricsList as jest.Mock).mock.calls.length
+ const onSuccess = jest.fn()
+
+ logic.actions.bulkApproveMetrics(['first', 'second'], onSuccess)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect((dataCatalogMetricsList as jest.Mock).mock.calls.length).toBeGreaterThan(listCallsBefore)
+ expect(logic.values.allMetrics.map((metric) => [metric.name, metric.is_drifted])).toEqual([
+ ['first', false],
+ ['second', true],
+ ])
+ expect(onSuccess).toHaveBeenCalled()
+ expect(lemonToast.warning).toHaveBeenCalledWith('Skipped 1 metric: Drifted from its source insight (1)')
+ expect(logic.values.bulkActionInFlight).toBeNull()
+ })
+
+ it('removes the deleted rows and clears the selection', async () => {
+ logic.actions.loadMetricsSuccess([
+ buildMetric({ id: 'metric-1', name: 'first' }),
+ buildMetric({ id: 'metric-2', name: 'second' }),
+ ])
+ ;(dataCatalogMetricsBulkDeleteCreate as jest.Mock).mockResolvedValue({ deleted: ['first'], skipped: [] })
+ const onSuccess = jest.fn()
+
+ logic.actions.bulkDeleteMetrics(['first'], onSuccess)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.allMetrics.map((metric) => metric.name)).toEqual(['second'])
+ expect(onSuccess).toHaveBeenCalled()
+ })
+
+ it('reloads to drop skipped rows after bulk delete', async () => {
+ logic.actions.loadMetricsSuccess([
+ buildMetric({ id: 'metric-1', name: 'first' }),
+ buildMetric({ id: 'metric-2', name: 'second' }),
+ ])
+ ;(dataCatalogMetricsBulkDeleteCreate as jest.Mock).mockResolvedValue({
+ deleted: ['first'],
+ skipped: [{ name: 'second', reason: 'Not found' }],
+ })
+ // 'second' was skipped as already gone, so the reload returns the server's current list
+ // without it and the stale row leaves the table.
+ ;(dataCatalogMetricsList as jest.Mock).mockResolvedValue({ results: [], next: null })
+ const onSuccess = jest.fn()
+
+ logic.actions.bulkDeleteMetrics(['first', 'second'], onSuccess)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.allMetrics).toHaveLength(0)
+ expect(onSuccess).toHaveBeenCalled()
+ expect(lemonToast.warning).toHaveBeenCalledWith('Skipped 1 metric: Not found (1)')
+ })
+
+ it.each(BULK_ACTIONS)('keeps the selection when bulk %s fails', async (_label, client, actionName) => {
+ ;(client as jest.Mock).mockRejectedValue(new ApiError('nope', 500))
+ const onSuccess = jest.fn()
+
+ logic.actions[actionName](['weekly_active_users'], onSuccess)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.allMetrics).toHaveLength(1)
+ expect(onSuccess).not.toHaveBeenCalled()
+ expect(lemonToast.error).toHaveBeenCalled()
+ expect(logic.values.bulkActionInFlight).toBeNull()
+ })
+
+ it.each(BULK_ACTIONS)('ignores a second bulk %s while one is in flight', async (_label, client, actionName) => {
+ let resolveRequest: (response: unknown) => void = () => {}
+ ;(client as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ resolveRequest = resolve
+ })
+ )
+
+ logic.actions[actionName](['weekly_active_users'])
+ logic.actions[actionName](['weekly_active_users'])
+ expect(client).toHaveBeenCalledTimes(1)
+
+ resolveRequest({ approved: [], deleted: [], skipped: [] })
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it('does not fire a bulk request while a row action on one of its metrics runs', async () => {
+ logic.actions.setActionInFlight('weekly_active_users', true)
+
+ logic.actions.bulkApproveMetrics(['weekly_active_users'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataCatalogMetricsBulkApproveCreate).not.toHaveBeenCalled()
+ })
+
+ it('does not fire a row action while a bulk action runs', async () => {
+ logic.actions.setBulkActionInFlight('approve')
+
+ logic.actions.approveMetric('weekly_active_users')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataCatalogMetricsApproveCreate).not.toHaveBeenCalled()
+ })
+
it('creates a metric from an insight with the short id and no definition', async () => {
;(dataCatalogMetricsCreate as jest.Mock).mockResolvedValue(
buildMetric({ id: 'metric-3', name: 'from_insight', source_insight_short_id: 'abc123' })
diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsx
index 536f1d185b5b..d9c278aa7c05 100644
--- a/products/data_catalog/frontend/metricsLogic.tsx
+++ b/products/data_catalog/frontend/metricsLogic.tsx
@@ -7,17 +7,24 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { createFuse } from 'lib/utils/fuseSearch'
import { urls } from 'scenes/urls'
+import { metricCount } from './common'
import {
dataCatalogMetricsApproveCreate,
+ dataCatalogMetricsBulkApproveCreate,
+ dataCatalogMetricsBulkDeleteCreate,
dataCatalogMetricsCreate,
dataCatalogMetricsDestroy,
dataCatalogMetricsList,
dataCatalogMetricsRefreshFromInsightCreate,
} from './generated/api'
-import type { DataCatalogMetricApi } from './generated/api.schemas'
+import type { DataCatalogMetricApi, DataCatalogMetricBulkSkipApi } from './generated/api.schemas'
export type MetricStatusFilter = 'all' | 'proposed' | 'approved'
+export type BulkMetricAction = 'approve' | 'delete'
+
+const METRICS_PAGE_SIZE = 100
+
export interface MetricsFilters {
search: string
status: MetricStatusFilter
@@ -68,11 +75,21 @@ function apiErrorDetail(error: unknown): string | null {
return error instanceof ApiError ? error.detail : null
}
+function skippedMessage(skipped: DataCatalogMetricBulkSkipApi[]): string {
+ const countByReason = new Map<string, number>()
+ for (const skip of skipped) {
+ countByReason.set(skip.reason, (countByReason.get(skip.reason) || 0) + 1)
+ }
+ const reasons = [...countByReason.entries()].map(([reason, count]) => `${reason} (${count})`).join(', ')
+ return `Skipped ${metricCount(skipped.length)}: ${reasons}`
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsLogicValues {
actionsInFlight: Record<string, boolean>
allMetrics: DataCatalogMetricApi[]
allMetricsLoading: boolean
+ bulkActionInFlight: BulkMetricAction | null
filters: MetricsFilters
insightSearch: string
isCreatingMetric: boolean
@@ -90,6 +107,20 @@ export interface metricsLogicActions {
approveMetric: (name: string) => {
name: string
}
+ bulkApproveMetrics: (
+ names: string[],
+ onSuccess?: () => void
+ ) => {
+ names: string[]
+ onSuccess: (() => void) | undefined
+ }
+ bulkDeleteMetrics: (
+ names: string[],
+ onSuccess?: () => void
+ ) => {
+ names: string[]
+ onSuccess: (() => void) | undefined
+ }
closeMetricFromInsightModal: () => {
value: true
}
@@ -166,6 +197,9 @@ export interface metricsLogicActions {
inFlight: boolean
name: string
}
+ setBulkActionInFlight: (bulkAction: BulkMetricAction | null) => {
+ bulkAction: BulkMetricAction | null
+ }
setCreatingMetric: (creating: boolean) => {
creating: boolean
}
@@ -211,6 +245,9 @@ export const metricsLogic = kea<metricsLogicType>([
refreshMetricFromInsight: (name: string) => ({ name }),
deleteMetric: (name: string) => ({ name }),
setActionInFlight: (name: string, inFlight: boolean) => ({ name, inFlight }),
+ bulkApproveMetrics: (names: string[], onSuccess?: () => void) => ({ names, onSuccess }),
+ bulkDeleteMetrics: (names: string[], onSuccess?: () => void) => ({ names, onSuccess }),
+ setBulkActionInFlight: (bulkAction: BulkMetricAction | null) => ({ bulkAction }),
openMetricFromInsightModal: true,
closeMetricFromInsightModal: true,
createMetricFromInsight: (request: MetricFromInsightRequest) => ({ request }),
@@ -219,9 +256,20 @@ export const metricsLogic = kea<metricsLogicType>([
allMetrics: [
[] as DataCatalogMetricApi[],
{
+ // Walk every page: the tab badge counts proposed metrics across the whole catalog,
+ // and selection spans pages, so a single server page would hide the rest.
loadMetrics: async () => {
- const response = await dataCatalogMetricsList(projectId())
- return response.results || []
+ const metrics: DataCatalogMetricApi[] = []
+ for (let offset = 0; ; offset += METRICS_PAGE_SIZE) {
+ const response = await dataCatalogMetricsList(projectId(), {
+ limit: METRICS_PAGE_SIZE,
+ offset,
+ })
+ metrics.push(...(response.results || []))
+ if (!response.next || !response.results?.length) {
+ return metrics
+ }
+ }
},
},
],
@@ -289,6 +337,12 @@ export const metricsLogic = kea<metricsLogicType>([
setActionInFlight: (state, { name, inFlight }) => ({ ...state, [name]: inFlight }),
},
],
+ bulkActionInFlight: [
+ null as BulkMetricAction | null,
+ {
+ setBulkActionInFlight: (_, { bulkAction }) => bulkAction,
+ },
+ ],
insightSearch: [
'',
{
@@ -395,7 +449,7 @@ export const metricsLogic = kea<metricsLogicType>([
}
},
approveMetric: async ({ name }) => {
- if (values.actionsInFlight[name]) {
+ if (values.bulkActionInFlight || values.actionsInFlight[name]) {
return
}
actions.setActionInFlight(name, true)
@@ -423,7 +477,7 @@ export const metricsLogic = kea<metricsLogicType>([
}
},
refreshMetricFromInsight: async ({ name }) => {
- if (values.actionsInFlight[name]) {
+ if (values.bulkActionInFlight || values.actionsInFlight[name]) {
return
}
actions.setActionInFlight(name, true)
@@ -442,7 +496,7 @@ export const metricsLogic = kea<metricsLogicType>([
}
},
deleteMetric: async ({ name }) => {
- if (values.actionsInFlight[name]) {
+ if (values.bulkActionInFlight || values.actionsInFlight[name]) {
return
}
actions.setActionInFlight(name, true)
@@ -456,6 +510,56 @@ export const metricsLogic = kea<metricsLogicType>([
actions.setActionInFlight(name, false)
}
},
+ bulkApproveMetrics: async ({ names, onSuccess }) => {
+ if (values.bulkActionInFlight || names.some((name) => values.actionsInFlight[name])) {
+ return
+ }
+ actions.setBulkActionInFlight('approve')
+ try {
+ const response = await dataCatalogMetricsBulkApproveCreate(projectId(), { names })
+ const approvedByName = new Map(response.approved.map((metric) => [metric.name, metric]))
+ actions.loadMetricsSuccess(values.allMetrics.map((metric) => approvedByName.get(metric.name) ?? metric))
+ if (response.approved.length) {
+ lemonToast.success(`Approved ${metricCount(response.approved.length)}`)
+ }
+ if (response.skipped.length) {
+ lemonToast.warning(skippedMessage(response.skipped))
+ // A skipped metric kept the state the page rendered (e.g. still proposed, or no
+ // drift tag). Reload so the table matches the server the batch reconciled against.
+ actions.loadMetrics()
+ }
+ onSuccess?.()
+ } catch (error) {
+ lemonToast.error(apiErrorDetail(error) || 'Could not approve the selected metrics. Try again.')
+ } finally {
+ actions.setBulkActionInFlight(null)
+ }
+ },
+ bulkDeleteMetrics: async ({ names, onSuccess }) => {
+ if (values.bulkActionInFlight || names.some((name) => values.actionsInFlight[name])) {
+ return
+ }
+ actions.setBulkActionInFlight('delete')
+ try {
+ const response = await dataCatalogMetricsBulkDeleteCreate(projectId(), { names })
+ const deleted = new Set(response.deleted)
+ actions.loadMetricsSuccess(values.allMetrics.filter((metric) => !deleted.has(metric.name)))
+ if (response.deleted.length) {
+ lemonToast.success(`Deleted ${metricCount(response.deleted.length)}`)
+ }
+ if (response.skipped.length) {
+ lemonToast.warning(skippedMessage(response.skipped))
+ // A skipped metric may already be gone server-side (e.g. "Not found") yet still
+ // shows in the table. Reload so the table matches the server.
+ actions.loadMetrics()
+ }
+ onSuccess?.()
+ } catch (error) {
+ lemonToast.error(apiErrorDetail(error) || 'Could not delete the selected metrics. Try again.')
+ } finally {
+ actions.setBulkActionInFlight(null)
+ }
+ },
})),
afterMount(({ actions }) => {
actions.loadMetrics()
diff --git a/products/data_catalog/frontend/tabs/MetricsTab.tsx b/products/data_catalog/frontend/tabs/MetricsTab.tsx
index cabf670273e5..854b36bfa72f 100644
--- a/products/data_catalog/frontend/tabs/MetricsTab.tsx
+++ b/products/data_catalog/frontend/tabs/MetricsTab.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { useState } from 'react'
import { IconRefresh } from '@posthog/icons'
import { LemonButton, LemonDialog } from '@posthog/lemon-ui'
@@ -17,9 +18,9 @@ import { urls } from 'scenes/urls'
import { ProductKey } from '~/queries/schema/schema-general'
-import { humanizeDefinitionKind } from '../common'
+import { METRIC_BULK_MAX, humanizeDefinitionKind, metricCount } from '../common'
import type { DataCatalogMetricApi } from '../generated/api.schemas'
-import { MetricStatusFilter, metricsLogic } from '../metricsLogic'
+import { BulkMetricAction, MetricStatusFilter, metricsLogic } from '../metricsLogic'
const STATUS_FILTER_OPTIONS: { value: MetricStatusFilter; label: string }[] = [
{ value: 'all', label: 'All' },
@@ -27,6 +28,12 @@ const STATUS_FILTER_OPTIONS: { value: MetricStatusFilter; label: string }[] = [
{ value: 'approved', label: 'Approved' },
]
+const OVER_CAP_REASON = `Select at most ${METRIC_BULK_MAX} metrics at a time`
+
+function isApprovable(metric: DataCatalogMetricApi): boolean {
+ return metric.status !== 'approved' && !metric.is_drifted
+}
+
function StatusTag({ metric }: { metric: DataCatalogMetricApi }): JSX.Element {
return (
<div className="flex items-center gap-1">
@@ -57,9 +64,40 @@ function SourceTag({ metric }: { metric: DataCatalogMetricApi }): JSX.Element {
}
export function MetricsTab(): JSX.Element {
- const { metrics, allMetrics, allMetricsLoading, filters, actionsInFlight } = useValues(metricsLogic)
- const { setFilters, loadMetrics, approveMetric, refreshMetricFromInsight, deleteMetric, openNewMetricModal } =
- useActions(metricsLogic)
+ // State, not a ref, so the table re-renders once the slot mounts and the bar can portal into it.
+ // The bar portals below the table instead of above it, so selecting a row never shifts the rows.
+ const [bulkBarTarget, setBulkBarTarget] = useState<HTMLDivElement | null>(null)
+ const { metrics, allMetrics, allMetricsLoading, filters, actionsInFlight, bulkActionInFlight } =
+ useValues(metricsLogic)
+ const {
+ setFilters,
+ loadMetrics,
+ approveMetric,
+ refreshMetricFromInsight,
+ deleteMetric,
+ openNewMetricModal,
+ bulkApproveMetrics,
+ bulkDeleteMetrics,
+ } = useActions(metricsLogic)
+
+ const bulkBusyReason = bulkActionInFlight ? 'A bulk action is running' : undefined
+ // Reload replaces the whole list and takes no breakpoint, so a load that resolves after a
+ // mutation would repaint pre-mutation rows (e.g. bring back rows a bulk delete just removed).
+ // Block it while any mutation is in flight; the view is authoritative again on the next load.
+ const reloadDisabledReason =
+ bulkBusyReason ?? (Object.values(actionsInFlight).some(Boolean) ? 'A metric action is running' : undefined)
+ const otherBulkActionReason = (self: BulkMetricAction): string | undefined =>
+ bulkActionInFlight && bulkActionInFlight !== self ? 'Another bulk action is running' : undefined
+
+ const bulkApproveDisabledReason = (approvableCount: number): string | undefined => {
+ if (approvableCount === 0) {
+ return 'Every selected metric is already approved or has drifted. Refresh a drifted metric first.'
+ }
+ if (approvableCount > METRIC_BULK_MAX) {
+ return OVER_CAP_REASON
+ }
+ return otherBulkActionReason('approve')
+ }
const confirmDelete = (metric: DataCatalogMetricApi): void => {
LemonDialog.open({
@@ -80,6 +118,25 @@ export function MetricsTab(): JSX.Element {
})
}
+ const confirmBulkDelete = (names: string[], onDeleted: () => void): void => {
+ LemonDialog.open({
+ title: `Delete ${metricCount(names.length)}?`,
+ content: (
+ <div className="text-sm text-secondary">
+ This deletes the selected metrics and makes their names available for new metrics. Queries and links
+ that reference them will stop working.
+ </div>
+ ),
+ primaryButton: {
+ children: 'Delete',
+ type: 'primary',
+ status: 'danger',
+ onClick: () => bulkDeleteMetrics(names, onDeleted),
+ },
+ secondaryButton: { children: 'Cancel', type: 'tertiary' },
+ })
+ }
+
if (!allMetricsLoading && allMetrics.length === 0) {
return (
<ProductIntroduction
@@ -149,9 +206,10 @@ export function MetricsTab(): JSX.Element {
fullWidth
loading={inFlight}
disabledReason={
- metric.is_drifted
+ bulkBusyReason ??
+ (metric.is_drifted
? 'This metric has drifted from its source insight. Refresh it first.'
- : undefined
+ : undefined)
}
onClick={() => approveMetric(metric.name)}
>
@@ -162,6 +220,7 @@ export function MetricsTab(): JSX.Element {
<LemonButton
fullWidth
loading={inFlight}
+ disabledReason={bulkBusyReason}
onClick={() => refreshMetricFromInsight(metric.name)}
>
Refresh from insight
@@ -170,7 +229,7 @@ export function MetricsTab(): JSX.Element {
<LemonButton
fullWidth
status="danger"
- disabledReason={inFlight ? 'Working' : undefined}
+ disabledReason={bulkBusyReason ?? (inFlight ? 'Working' : undefined)}
onClick={() => confirmDelete(metric)}
>
Delete
@@ -204,6 +263,7 @@ export function MetricsTab(): JSX.Element {
icon={<IconRefresh />}
onClick={() => loadMetrics()}
loading={allMetricsLoading}
+ disabledReason={reloadDisabledReason}
size="small"
>
Reload
@@ -219,6 +279,60 @@ export function MetricsTab(): JSX.Element {
pagination={{ pageSize: 20 }}
emptyState="No metrics match your filters."
nouns={['metric', 'metrics']}
+ bulkSelection={{
+ // Key on the stable id, not the name: a name is freed for reuse when a metric is
+ // deleted or renamed, so a name-keyed selection could target a different metric
+ // that later takes the same name.
+ getKey: (metric: DataCatalogMetricApi) => metric.id,
+ noun: ['metric', 'metrics'],
+ rowAriaLabel: (metric: DataCatalogMetricApi) => `Select metric ${metric.name}`,
+ headerAriaLabel: 'Select all metrics on this page',
+ barPortalTarget: bulkBarTarget,
+ renderActions: (ctx) => {
+ // Selection spans pages, so resolve the keys against every metric rather
+ // than ctx.selectedRecords, which only covers the page on screen. Resolving
+ // by id also drops any selected metric that has since left the list.
+ const selected = new Set(ctx.selectedKeys)
+ const selectedMetrics = allMetrics.filter((metric) => selected.has(metric.id))
+ const approvableNames = selectedMetrics.filter(isApprovable).map((metric) => metric.name)
+ const selectedNames = selectedMetrics.map((metric) => metric.name)
+ return (
+ <>
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr="data-catalog-metrics-bulk-approve"
+ loading={bulkActionInFlight === 'approve'}
+ disabledReason={bulkApproveDisabledReason(approvableNames.length)}
+ onClick={() => bulkApproveMetrics(approvableNames, ctx.clearSelection)}
+ >
+ Approve ({approvableNames.length})
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ data-attr="data-catalog-metrics-bulk-delete"
+ loading={bulkActionInFlight === 'delete'}
+ disabledReason={
+ selectedNames.length === 0
+ ? 'The selected metrics are no longer available. Reload the list.'
+ : selectedNames.length > METRIC_BULK_MAX
+ ? OVER_CAP_REASON
+ : otherBulkActionReason('delete')
+ }
+ onClick={() => confirmBulkDelete(selectedNames, ctx.clearSelection)}
+ >
+ Delete
+ </LemonButton>
+ </>
+ )
+ },
+ }}
+ />
+ <div
+ ref={setBulkBarTarget}
+ className="sticky bottom-4 z-10 self-center w-fit rounded border border-primary bg-surface-primary px-2 py-1 shadow empty:hidden"
/>
</div>
)
diff --git a/products/data_catalog/mcp/tools.yaml b/products/data_catalog/mcp/tools.yaml
index 25d65a599a18..b05d8a7fce32 100644
--- a/products/data_catalog/mcp/tools.yaml
+++ b/products/data_catalog/mcp/tools.yaml
@@ -181,6 +181,12 @@ tools:
rename_params:
name: new_name
feature_flag: product-data-catalog
+ data-catalog-metrics-bulk-approve-create:
+ operation: data_catalog_metrics_bulk_approve_create
+ enabled: false
+ data-catalog-metrics-bulk-delete-create:
+ operation: data_catalog_metrics_bulk_delete_create
+ enabled: false
data-catalog-metrics-destroy:
operation: data_catalog_metrics_destroy
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dc3a6e5094c6..21ff49560ff9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20285,6 +20285,49 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ /**
+ * A metric the bulk action did not act on, and why.
+ */
+ export interface DataCatalogMetricBulkSkip {
+ /** Name of the metric that was skipped. */
+ name: string;
+ /** Why it was skipped, e.g. 'Not found', 'Already approved', 'Drifted from its source insight'. */
+ reason: string;
+ }
+
+ /**
+ * Outcome of a bulk approve: what changed, and what was left alone.
+ */
+ export interface DataCatalogMetricBulkApprove {
+ /** The metrics that are now approved, freshly serialized. */
+ approved: DataCatalogMetric[];
+ /** Requested metrics that were not approved, with reasons. */
+ skipped: DataCatalogMetricBulkSkip[];
+ }
+
+ /**
+ * Outcome of a bulk delete: which names are gone, and what was left alone.
+ */
+ export interface DataCatalogMetricBulkDelete {
+ /** Names of the metrics that were deleted, now free for reuse. */
+ deleted: string[];
+ /** Requested metrics that were not deleted, with reasons. */
+ skipped: DataCatalogMetricBulkSkip[];
+ }
+
+ /**
+ * Input for the bulk metric actions: the metric names to act on.
+ */
+ export interface DataCatalogMetricBulkNamesRequest {
+ /**
+ * Names of the metrics to act on, at most 100. Duplicates are collapsed.
+ * @minItems 1
+ * @maxItems 100
+ * @items.maxLength 128
+ */
+ names: string[];
+ }
+
/**
* Normalized envelope returned by the metric-run endpoint.
*/