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): change the owner of many metrics at once (#123557)

Thiago Salvatore3161488e7228
diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.py
index d0601d3581a9..2e97385c6ad1 100644
--- a/products/data_catalog/backend/facade/api.py
+++ b/products/data_catalog/backend/facade/api.py
@@ -33,6 +33,7 @@ from ..logic.metrics import (
approve_metric,
approved_metric_names_for_team,
bulk_approve_metrics,
+ bulk_change_metric_owner,
bulk_soft_delete_metrics,
metrics_for_team,
metrics_visible_to_user,
@@ -70,6 +71,7 @@ __all__ = [
"approve_metric",
"approved_metric_names_for_team",
"bulk_approve_metrics",
+ "bulk_change_metric_owner",
"bulk_soft_delete_metrics",
"certification_target_name",
"certifications_for_team",
diff --git a/products/data_catalog/backend/facade/contracts.py b/products/data_catalog/backend/facade/contracts.py
index 3de25d667b34..14cfa0e93c20 100644
--- a/products/data_catalog/backend/facade/contracts.py
+++ b/products/data_catalog/backend/facade/contracts.py
@@ -24,3 +24,9 @@ class HogQLMetricDefinition:
class MetricRead:
summary: MetricSummary
hogql_definition: HogQLMetricDefinition | None
+
+
+@dataclass(frozen=True)
+class MetricBulkOwnerChange:
+ updated_ids: list[UUID]
+ skipped_ids: list[UUID]
diff --git a/products/data_catalog/backend/logic/analytics.py b/products/data_catalog/backend/logic/analytics.py
index 79be5fe4f18a..8c1ef03c9d9f 100644
--- a/products/data_catalog/backend/logic/analytics.py
+++ b/products/data_catalog/backend/logic/analytics.py
@@ -11,7 +11,12 @@ from typing import TYPE_CHECKING, Any, Optional
from posthog.hogql.database.database import get_data_warehouse_table_name
-from posthog.event_usage import get_request_analytics_properties, report_user_action, report_user_or_team_action
+from posthog.event_usage import (
+ AnalyticsProps,
+ get_request_analytics_properties,
+ report_user_action,
+ report_user_or_team_action,
+)
from posthog.models import Team, User
if TYPE_CHECKING:
@@ -50,6 +55,7 @@ def capture_metric_event(
user: Optional[User],
request: "Request | None" = None,
extra: Optional[dict[str, Any]] = None,
+ analytics_props: Optional[AnalyticsProps] = None,
) -> None:
_report(
event,
@@ -68,6 +74,7 @@ def capture_metric_event(
team=team,
user=user,
request=request,
+ analytics_props=analytics_props,
)
@@ -127,10 +134,12 @@ def _report(
team: Team,
user: Optional[User],
request: "Request | None",
+ analytics_props: Optional[AnalyticsProps] = None,
) -> None:
properties["is_system"] = user is None
if user is not None:
- report_user_action(user, event, properties, team=team, request=request)
+ report_user_action(user, event, properties, team=team, request=request, analytics_props=analytics_props)
return
- analytics_props = get_request_analytics_properties(request) if request is not None else None
+ if request is not None:
+ analytics_props = get_request_analytics_properties(request)
report_user_or_team_action(event, properties, user=None, team=team, analytics_props=analytics_props)
diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.py
index e0b43eef3bb0..f253efb9cbfa 100644
--- a/products/data_catalog/backend/logic/metrics.py
+++ b/products/data_catalog/backend/logic/metrics.py
@@ -24,12 +24,14 @@ from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.information_schema import references_denied_table
from posthog.dataclasses import frozen
+from posthog.event_usage import AnalyticsProps
from posthog.models import Team, User
from posthog.models.scoping import team_scope
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.product_analytics.backend.facade.models import Insight
+from ..facade.contracts import MetricBulkOwnerChange
from ..facade.enums import CreatedSource, MetricStatus
from ..models import METRIC_NAME_REGEX, Metric
from ..tasks.tasks import sync_metric_lineage_task
@@ -519,7 +521,7 @@ def _batch_team(metrics: list[Metric]) -> Team:
return Team.objects.get(pk=team_ids.pop())
-def _lock_batch(team_id: int, metrics: list[Metric]) -> dict[UUID, Metric]:
+def _lock_batch(team_id: int, metric_ids: list[UUID]) -> 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
@@ -528,7 +530,7 @@ def _lock_batch(team_id: int, metrics: list[Metric]) -> dict[UUID, Metric]:
"""
locked = (
Metric.objects.for_team(team_id)
- .filter(pk__in=[metric.pk for metric in metrics], deleted=False)
+ .filter(pk__in=metric_ids, 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,
@@ -555,10 +557,28 @@ def _locked_match(locked: dict[UUID, Metric], requested: Metric) -> Optional[Met
def _capture_after_commit(
- event: str, metrics: list[Metric], *, team: Team, user: Optional[User], request: "Request | None"
+ event: str,
+ metrics: list[Metric],
+ *,
+ team: Team,
+ user: Optional[User],
+ request: "Request | None",
+ extra: Optional[dict[str, object]] = None,
+ analytics_props: Optional[AnalyticsProps] = None,
) -> None:
for metric in metrics:
- transaction.on_commit(partial(capture_metric_event, event, metric, team=team, user=user, request=request))
+ transaction.on_commit(
+ partial(
+ capture_metric_event,
+ event,
+ metric,
+ team=team,
+ user=user,
+ request=request,
+ extra=extra,
+ analytics_props=analytics_props,
+ )
+ )
def bulk_approve_metrics(
@@ -577,7 +597,7 @@ def bulk_approve_metrics(
skipped: list[MetricBulkSkip] = []
with team_scope(team.id), transaction.atomic():
- locked = _lock_batch(team.id, metrics)
+ locked = _lock_batch(team.id, [metric.pk for metric in metrics])
drifted = compute_drift(locked.values())
for requested in metrics:
metric = _locked_match(locked, requested)
@@ -608,7 +628,7 @@ def bulk_soft_delete_metrics(
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)
+ locked = _lock_batch(team.id, [metric.pk for metric in metrics])
for requested in metrics:
metric = _locked_match(locked, requested)
if metric is None:
@@ -624,6 +644,47 @@ def bulk_soft_delete_metrics(
return deleted, skipped
+def bulk_change_metric_owner(
+ *,
+ team_id: int,
+ names_by_id: dict[UUID, str],
+ owner_id: Optional[int],
+ user_id: int,
+ analytics_props: Optional[AnalyticsProps] = None,
+) -> MetricBulkOwnerChange:
+ """Set one owner on a batch of metrics in one transaction."""
+ if not names_by_id:
+ return MetricBulkOwnerChange(updated_ids=[], skipped_ids=[])
+ team = Team.objects.get(id=team_id)
+ user = User.objects.get(id=user_id)
+ owner = User.objects.get(id=owner_id) if owner_id is not None else None
+ updated: list[Metric] = []
+
+ with team_scope(team_id), transaction.atomic():
+ locked = _lock_batch(team_id, list(names_by_id))
+ for metric_id, name in names_by_id.items():
+ metric = locked.get(metric_id)
+ if metric is None or metric.name != name:
+ continue
+ metric.owner = owner
+ metric.save(update_fields=["owner", "updated_at"])
+ updated.append(metric)
+ _capture_after_commit(
+ METRIC_UPDATED_EVENT,
+ updated,
+ team=team,
+ user=user,
+ request=None,
+ extra={"updated_fields": ["owner"]},
+ analytics_props=analytics_props,
+ )
+
+ updated_ids = [metric.id for metric in updated]
+ return MetricBulkOwnerChange(
+ updated_ids=updated_ids, skipped_ids=[metric_id for metric_id in names_by_id if metric_id not in updated_ids]
+ )
+
+
def _reset_to_proposed(metric: Metric) -> None:
metric.status = MetricStatus.PROPOSED
metric.approved_by = None
diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.py
index 267b67793d48..28faad6daa99 100644
--- a/products/data_catalog/backend/presentation/serializers.py
+++ b/products/data_catalog/backend/presentation/serializers.py
@@ -37,7 +37,7 @@ class MetricOwnerField(serializers.EmailField):
email = super().run_validation(data)
if email is None:
return None
- team = self.context["get_team"]()
+ team = self.context["view"].team
owner = User.objects.filter(
email__iexact=email, organization_membership__organization_id=team.organization_id
).first()
@@ -308,6 +308,17 @@ class MetricBulkNamesRequestSerializer(serializers.Serializer):
)
+@extend_schema_serializer(component_name="DataCatalogMetricBulkChangeOwnerRequest")
+class MetricBulkChangeOwnerRequestSerializer(MetricBulkNamesRequestSerializer):
+ """Input for giving many metrics one owner."""
+
+ owner = MetricOwnerField(
+ allow_null=True,
+ help_text="Email of the member of this organization who becomes the owner of every named metric, or null "
+ "to clear the owner. Changing the owner keeps each metric's approval.",
+ )
+
+
@extend_schema_serializer(component_name="DataCatalogMetricBulkSkip")
class MetricBulkSkipSerializer(serializers.Serializer):
"""A metric the bulk action did not act on, and why."""
@@ -326,6 +337,16 @@ class MetricBulkApproveResponseSerializer(serializers.Serializer):
skipped = MetricBulkSkipSerializer(many=True, help_text="Requested metrics that were not approved, with reasons.")
+@extend_schema_serializer(component_name="DataCatalogMetricBulkChangeOwner")
+class MetricBulkChangeOwnerResponseSerializer(serializers.Serializer):
+ """Outcome of a bulk owner change: what changed, and what was left alone."""
+
+ updated = MetricSerializer(many=True, help_text="The metrics that now have the new owner, freshly serialized.")
+ skipped = MetricBulkSkipSerializer(
+ many=True, help_text="Requested metrics whose owner did not change, 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."""
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index 4a750b976551..6fbaaaac7bc5 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -27,6 +27,7 @@ from rest_framework.views import APIView
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
+from posthog.event_usage import get_request_analytics_properties
from posthog.helpers.full_text_search import build_search_vector
from posthog.models import User
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle, HogQLQueryThrottle
@@ -39,6 +40,8 @@ from .serializers import (
CertificationSerializer,
MetricApproveRequestSerializer,
MetricBulkApproveResponseSerializer,
+ MetricBulkChangeOwnerRequestSerializer,
+ MetricBulkChangeOwnerResponseSerializer,
MetricBulkDeleteResponseSerializer,
MetricBulkNamesRequestSerializer,
MetricCreateSerializer,
@@ -292,6 +295,42 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
)
return Response(payload.data)
+ @action(
+ detail=False,
+ methods=["POST"],
+ url_path="bulk/change_owner",
+ required_scopes=["data_catalog:write"],
+ request=MetricBulkChangeOwnerRequestSerializer,
+ responses={200: MetricBulkChangeOwnerResponseSerializer},
+ )
+ @validated_request(request_serializer=MetricBulkChangeOwnerRequestSerializer, include_serializer_context=True)
+ def bulk_change_owner(self, request: ValidatedRequest, **kwargs) -> Response:
+ """Give many metrics one owner, keeping their approvals. Unknown metrics are skipped."""
+ metrics, unresolved = _resolve_bulk_metrics(self.get_queryset(), request.validated_data["names"])
+ owner = request.validated_data["owner"]
+ names_by_id = {metric.id: metric.name for metric in metrics}
+ change = api.bulk_change_metric_owner(
+ team_id=self.team.id,
+ names_by_id=names_by_id,
+ owner_id=owner.id if owner else None,
+ user_id=cast(User, request.user).id,
+ analytics_props=get_request_analytics_properties(request),
+ )
+ position = {metric_id: index for index, metric_id in enumerate(change.updated_ids)}
+ updated = sorted(
+ self.get_queryset().filter(id__in=change.updated_ids).select_related("owner", "created_by", "approved_by"),
+ key=lambda metric: position[metric.id],
+ )
+ skipped = [
+ api.MetricBulkSkip(name=names_by_id[metric_id], reason=api.BULK_SKIP_NOT_FOUND)
+ for metric_id in change.skipped_ids
+ ]
+ context = {**self.get_serializer_context(), "drift_map": api.compute_drift(updated)}
+ payload = MetricBulkChangeOwnerResponseSerializer(
+ {"updated": updated, "skipped": [*unresolved, *skipped]}, context=context
+ )
+ return Response(payload.data)
+
@action(
detail=True,
methods=["POST"],
diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.py
index c2db907221de..0a76ee3914fd 100644
--- a/products/data_catalog/backend/tests/test_api.py
+++ b/products/data_catalog/backend/tests/test_api.py
@@ -27,6 +27,7 @@ from products.data_catalog.backend.logic.metrics import (
BULK_SKIP_NOT_FOUND,
METRIC_BULK_MAX,
approve_metric,
+ bulk_change_metric_owner,
soft_delete_metric,
upsert_metric,
)
@@ -526,7 +527,15 @@ class TestMetricLifecycleAPI(APIBaseTest):
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:
+ @parameterized.expand(
+ [
+ ("bulk_approve", "bulk_approve", {}),
+ ("bulk_change_owner", "bulk/change_owner", {"owner": None}),
+ ]
+ )
+ def test_bulk_action_computes_drift_in_a_single_insight_query(
+ self, _name: str, url_path: str, extra_payload: dict
+ ) -> 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):
@@ -540,7 +549,7 @@ class TestMetricLifecycleAPI(APIBaseTest):
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")
+ response = self.client.post(f"{self.url}{url_path}/", {"names": names, **extra_payload}, 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
@@ -574,6 +583,46 @@ class TestMetricLifecycleAPI(APIBaseTest):
theirs.refresh_from_db()
assert theirs.deleted is False
+ def test_bulk_change_owner_keeps_approval_and_skips_unknown_ones(self) -> None:
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+ approved = upsert_metric(team=self.team, user=self.user, name="mrr", description="d")
+ approve_metric(approved, self.user)
+ 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/change_owner/",
+ {"names": ["mrr", "arr", "theirs", "unheard_of"], "owner": "[email protected]"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ body = response.json()
+ assert [(metric["name"], metric["owner"], metric["status"]) for metric in body["updated"]] == [
+ ("mrr", "[email protected]", MetricStatus.APPROVED),
+ ("arr", "[email protected]", MetricStatus.PROPOSED),
+ ]
+ assert {skip["name"] for skip in body["skipped"]} == {"theirs", "unheard_of"}
+ theirs.refresh_from_db()
+ assert theirs.owner_id != User.objects.get(email="[email protected]").id
+
+ def test_bulk_change_owner_skips_a_metric_renamed_after_name_resolution(self) -> None:
+ renamed = upsert_metric(team=self.team, user=self.user, name="arr", description="d")
+
+ change = bulk_change_metric_owner(
+ team_id=self.team.id, names_by_id={renamed.id: "mrr"}, owner_id=None, user_id=self.user.id
+ )
+
+ assert change.updated_ids == []
+ assert change.skipped_ids == [renamed.id]
+ renamed.refresh_from_db()
+ assert renamed.owner_id == self.user.id
+
+ def test_bulk_change_owner_path_leaves_a_metric_of_that_name_reachable(self) -> None:
+ upsert_metric(team=self.team, user=self.user, name="bulk_change_owner", description="d")
+
+ assert self.client.get(f"{self.url}bulk_change_owner/").status_code == status.HTTP_200_OK
+
@parameterized.expand(
[
(
@@ -590,6 +639,8 @@ class TestMetricLifecycleAPI(APIBaseTest):
),
("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),
+ ("change_owner_read_only", "bulk/change_owner", ["data_catalog:read"], status.HTTP_403_FORBIDDEN),
+ ("change_owner_with_write_scope", "bulk/change_owner", ["data_catalog:write"], status.HTTP_200_OK),
]
)
def test_bulk_actions_enforce_token_scopes(
@@ -597,7 +648,9 @@ class TestMetricLifecycleAPI(APIBaseTest):
) -> 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))
+ response = self.client.post(
+ f"{self.url}{url_path}/", {"names": ["mrr"], "owner": None}, format="json", **self._bearer(scopes)
+ )
assert response.status_code == expected, response.json()
def test_bulk_approve_rejects_an_over_cap_batch(self) -> None:
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index 8efa448a7c1f..dd14f8e0fef7 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -575,9 +575,9 @@ export interface DataCatalogMetricRunApi {
}
/**
- * Input for the bulk metric actions: the metric names to act on.
+ * Input for giving many metrics one owner.
*/
-export interface DataCatalogMetricBulkNamesRequestApi {
+export interface DataCatalogMetricBulkChangeOwnerRequestApi {
/**
* Names of the metrics to act on, at most 100. Duplicates are collapsed.
* @minItems 1
@@ -585,6 +585,11 @@ export interface DataCatalogMetricBulkNamesRequestApi {
* @items.maxLength 128
*/
names: string[]
+ /**
+ * Email of the member of this organization who becomes the owner of every named metric, or null to clear the owner. Changing the owner keeps each metric's approval.
+ * @nullable
+ */
+ owner: string | null
}
/**
@@ -597,6 +602,29 @@ export interface DataCatalogMetricBulkSkipApi {
reason: string
}
+/**
+ * Outcome of a bulk owner change: what changed, and what was left alone.
+ */
+export interface DataCatalogMetricBulkChangeOwnerApi {
+ /** The metrics that now have the new owner, freshly serialized. */
+ updated: DataCatalogMetricApi[]
+ /** Requested metrics whose owner did not change, with reasons. */
+ skipped: DataCatalogMetricBulkSkipApi[]
+}
+
+/**
+ * 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[]
+}
+
/**
* Outcome of a bulk approve: what changed, and what was left alone.
*/
diff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.ts
index 19b4adb48d5c..87d41da7e85e 100644
--- a/products/data_catalog/frontend/generated/api.ts
+++ b/products/data_catalog/frontend/generated/api.ts
@@ -15,6 +15,8 @@ import type {
DataCatalogMetricApi,
DataCatalogMetricApproveRequestApi,
DataCatalogMetricBulkApproveApi,
+ DataCatalogMetricBulkChangeOwnerApi,
+ DataCatalogMetricBulkChangeOwnerRequestApi,
DataCatalogMetricBulkDeleteApi,
DataCatalogMetricBulkNamesRequestApi,
DataCatalogMetricCreateApi,
@@ -381,6 +383,26 @@ export const dataCatalogMetricsRunCreate = async (
})
}
+export const getDataCatalogMetricsBulkChangeOwnerCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_catalog/metrics/bulk/change_owner/`
+}
+
+/**
+ * Give many metrics one owner, keeping their approvals. Unknown metrics are skipped.
+ */
+export const dataCatalogMetricsBulkChangeOwnerCreate = async (
+ projectId: string,
+ dataCatalogMetricBulkChangeOwnerRequestApi: DataCatalogMetricBulkChangeOwnerRequestApi,
+ options?: RequestInit
+): Promise<DataCatalogMetricBulkChangeOwnerApi> => {
+ return apiMutator<DataCatalogMetricBulkChangeOwnerApi>(getDataCatalogMetricsBulkChangeOwnerCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(dataCatalogMetricBulkChangeOwnerRequestApi),
+ })
+}
+
export const getDataCatalogMetricsBulkApproveCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/data_catalog/metrics/bulk_approve/`
}
diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.ts
index 62f893ddc720..9d4b91dfc9c3 100644
--- a/products/data_catalog/frontend/generated/api.zod.ts
+++ b/products/data_catalog/frontend/generated/api.zod.ts
@@ -342,6 +342,29 @@ export const DataCatalogMetricsRunCreateBody = /* @__PURE__ */ zod
})
.describe('Optional run-time overrides. The whole body may be omitted; a metric runs by its URL name.')
+/**
+ * Give many metrics one owner, keeping their approvals. Unknown metrics are skipped.
+ */
+export const dataCatalogMetricsBulkChangeOwnerCreateBodyNamesItemMax = 128
+
+export const dataCatalogMetricsBulkChangeOwnerCreateBodyNamesMax = 100
+
+export const DataCatalogMetricsBulkChangeOwnerCreateBody = /* @__PURE__ */ zod
+ .object({
+ names: zod
+ .array(zod.string().max(dataCatalogMetricsBulkChangeOwnerCreateBodyNamesItemMax))
+ .min(1)
+ .max(dataCatalogMetricsBulkChangeOwnerCreateBodyNamesMax)
+ .describe('Names of the metrics to act on, at most 100. Duplicates are collapsed.'),
+ owner: zod
+ .email()
+ .nullable()
+ .describe(
+ "Email of the member of this organization who becomes the owner of every named metric, or null to clear the owner. Changing the owner keeps each metric's approval."
+ ),
+ })
+ .describe('Input for giving many metrics one owner.')
+
/**
* Approve many metrics as canonical. Unknown, already-approved, and drifted metrics are skipped.
*/
diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.ts
index 1609fa5cb57b..f57c88d1f126 100644
--- a/products/data_catalog/frontend/metricsLogic.test.ts
+++ b/products/data_catalog/frontend/metricsLogic.test.ts
@@ -10,6 +10,7 @@ import { expectLogic } from '~/test/keaTestUtils'
import {
dataCatalogMetricsApproveCreate,
dataCatalogMetricsBulkApproveCreate,
+ dataCatalogMetricsBulkChangeOwnerCreate,
dataCatalogMetricsBulkDeleteCreate,
dataCatalogMetricsCreate,
dataCatalogMetricsDestroy,
@@ -61,6 +62,7 @@ jest.mock('./generated/api', () => ({
dataCatalogMetricsDestroy: jest.fn(),
dataCatalogMetricsBulkApproveCreate: jest.fn(),
dataCatalogMetricsBulkDeleteCreate: jest.fn(),
+ dataCatalogMetricsBulkChangeOwnerCreate: jest.fn(),
dataCatalogMetricsPartialUpdate: jest.fn(),
}))
@@ -196,38 +198,62 @@ describe('metricsLogic', () => {
expect((dataCatalogMetricsList as jest.Mock).mock.calls.map((call) => call[1].offset)).toEqual([0, 0, 100])
})
- it('filters by creator and reports the filter change once typing settles', async () => {
- const me = userLogic.values.user?.uuid as string
- const mine = buildMetric({
- id: 'metric-1',
- name: 'mine',
- created_by: { id: 1, uuid: me, email: '[email protected]', hedgehog_config: null },
- })
- const theirs = buildMetric({
- id: 'metric-2',
- name: 'theirs',
- created_by: { id: 2, uuid: 'someone-else', email: '[email protected]', hedgehog_config: null },
- })
- logic.actions.loadMetricsSuccess([mine, theirs])
- const capture = jest.spyOn(posthog, 'capture').mockImplementation()
- jest.useFakeTimers({ doNotFake: ['queueMicrotask', 'nextTick'] })
- try {
- logic.actions.setFilters({ createdBy: me })
- expect(logic.values.metrics).toEqual([mine])
- expect(capture).not.toHaveBeenCalled()
-
- await jest.advanceTimersByTimeAsync(500)
- expect(capture).toHaveBeenCalledWith(
- 'data catalog metrics filtered',
- expect.objectContaining({ changed_filters: ['createdBy'], created_by: 'me', result_count: 1 })
- )
-
- logic.actions.setFilters({ createdBy: null })
- expect(logic.values.metrics).toEqual([mine, theirs])
- } finally {
- jest.useRealTimers()
- capture.mockRestore()
+ it.each([
+ ['creator', 'createdBy', 'created_by'],
+ ['owner', 'owner', 'owner'],
+ ] as const)(
+ 'filters by %s and reports the filter change once typing settles',
+ async (_label, filterKey, property) => {
+ const me = userLogic.values.user?.uuid as string
+ const myEmail = userLogic.values.user?.email as string
+ const filterValue = filterKey === 'createdBy' ? me : myEmail
+ const mine = buildMetric({
+ id: 'metric-1',
+ name: 'mine',
+ created_by: { id: 1, uuid: me, email: myEmail, hedgehog_config: null },
+ owner: myEmail,
+ })
+ const theirs = buildMetric({
+ id: 'metric-2',
+ name: 'theirs',
+ created_by: { id: 2, uuid: 'someone-else', email: '[email protected]', hedgehog_config: null },
+ owner: '[email protected]',
+ })
+ logic.actions.loadMetricsSuccess([mine, theirs])
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ jest.useFakeTimers({ doNotFake: ['queueMicrotask', 'nextTick'] })
+ try {
+ logic.actions.setFilters({ [filterKey]: filterValue })
+ expect(logic.values.metrics).toEqual([mine])
+ expect(capture).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(500)
+ expect(capture).toHaveBeenCalledWith(
+ 'data catalog metrics filtered',
+ expect.objectContaining({ changed_filters: [filterKey], [property]: 'me', result_count: 1 })
+ )
+
+ logic.actions.setFilters({ [filterKey]: null })
+ expect(logic.values.metrics).toEqual([mine, theirs])
+ } finally {
+ jest.useRealTimers()
+ capture.mockRestore()
+ }
}
+ )
+
+ it('offers the owners of the metrics as owner filter options, so a former member stays listed', async () => {
+ logic.actions.loadMetricsSuccess([
+ buildMetric({ id: 'metric-1', name: 'a', owner: '[email protected]' }),
+ buildMetric({ id: 'metric-2', name: 'b', owner: '[email protected]' }),
+ buildMetric({ id: 'metric-3', name: 'c', owner: null }),
+ buildMetric({ id: 'metric-4', name: 'd', owner: '[email protected]' }),
+ ])
+
+ expect(logic.values.ownerFilterOptions).toEqual(['[email protected]', '[email protected]'])
+
+ logic.actions.setFilters({ owner: '[email protected]' })
+ expect(logic.values.metrics.map((metric) => metric.name)).toEqual(['b'])
})
it('patches approved rows and reloads to reconcile skipped ones', async () => {
@@ -264,6 +290,31 @@ describe('metricsLogic', () => {
expect(logic.values.bulkActionInFlight).toBeNull()
})
+ it('gives the selected rows their new owner and clears the selection', async () => {
+ logic.actions.loadMetricsSuccess([
+ buildMetric({ id: 'metric-1', name: 'first' }),
+ buildMetric({ id: 'metric-2', name: 'second' }),
+ ])
+ ;(dataCatalogMetricsBulkChangeOwnerCreate as jest.Mock).mockResolvedValue({
+ updated: [buildMetric({ id: 'metric-1', name: 'first', owner: '[email protected]' })],
+ skipped: [],
+ })
+ const onSuccess = jest.fn()
+
+ logic.actions.bulkChangeMetricOwner(['first'], '[email protected]', onSuccess)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(dataCatalogMetricsBulkChangeOwnerCreate).toHaveBeenCalledWith('1', {
+ names: ['first'],
+ owner: '[email protected]',
+ })
+ expect(logic.values.allMetrics.map((metric) => [metric.name, metric.owner])).toEqual([
+ ['first', '[email protected]'],
+ ['second', null],
+ ])
+ expect(onSuccess).toHaveBeenCalled()
+ })
+
it('removes the deleted rows and clears the selection', async () => {
logic.actions.loadMetricsSuccess([
buildMetric({ id: 'metric-1', name: 'first' }),
diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsx
index e6c497b1126b..b79b9bad120e 100644
--- a/products/data_catalog/frontend/metricsLogic.tsx
+++ b/products/data_catalog/frontend/metricsLogic.tsx
@@ -16,6 +16,7 @@ import { createMetricAsUser, MetricSaveAction, toastCreatedMetric } from './crea
import {
dataCatalogMetricsApproveCreate,
dataCatalogMetricsBulkApproveCreate,
+ dataCatalogMetricsBulkChangeOwnerCreate,
dataCatalogMetricsBulkDeleteCreate,
dataCatalogMetricsDestroy,
dataCatalogMetricsList,
@@ -27,7 +28,7 @@ import { openOverwriteMetricDialog } from './openOverwriteMetricDialog'
export type MetricStatusFilter = 'all' | 'proposed' | 'approved'
-export type BulkMetricAction = 'approve' | 'delete'
+export type BulkMetricAction = 'approve' | 'delete' | 'change_owner'
const METRICS_PAGE_SIZE = 100
@@ -35,12 +36,14 @@ export interface MetricsFilters {
search: string
status: MetricStatusFilter
createdBy: string | null
+ owner: string | null
}
export const DEFAULT_METRICS_FILTERS: MetricsFilters = {
search: '',
status: 'all',
createdBy: null,
+ owner: null,
}
export interface MetricFromInsightRequest {
@@ -84,6 +87,7 @@ export interface metricsLogicValues {
filters: MetricsFilters
metricFromInsightModalOpen: boolean
metrics: DataCatalogMetricApi[]
+ ownerFilterOptions: string[]
proposedCount: number
}
@@ -99,6 +103,15 @@ export interface metricsLogicActions {
names: string[]
onSuccess: (() => void) | undefined
}
+ bulkChangeMetricOwner: (
+ names: string[],
+ owner: string | null,
+ onSuccess?: () => void
+ ) => {
+ names: string[]
+ onSuccess: (() => void) | undefined
+ owner: string | null
+ }
bulkDeleteMetrics: (
names: string[],
onSuccess?: () => void
@@ -171,6 +184,7 @@ export interface metricsLogicActions {
export interface metricsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
metrics: (allMetrics: DataCatalogMetricApi[], filters: MetricsFilters) => DataCatalogMetricApi[]
+ ownerFilterOptions: (allMetrics: DataCatalogMetricApi[]) => string[]
proposedCount: (allMetrics: DataCatalogMetricApi[]) => number
}
}
@@ -197,6 +211,11 @@ export const metricsLogic = kea<metricsLogicType>([
setActionInFlight: (name: string, inFlight: boolean) => ({ name, inFlight }),
bulkApproveMetrics: (names: string[], onSuccess?: () => void) => ({ names, onSuccess }),
bulkDeleteMetrics: (names: string[], onSuccess?: () => void) => ({ names, onSuccess }),
+ bulkChangeMetricOwner: (names: string[], owner: string | null, onSuccess?: () => void) => ({
+ names,
+ owner,
+ onSuccess,
+ }),
setBulkActionInFlight: (bulkAction: BulkMetricAction | null) => ({ bulkAction }),
openMetricFromInsightModal: true,
closeMetricFromInsightModal: true,
@@ -274,6 +293,9 @@ export const metricsLogic = kea<metricsLogicType>([
// serializer type.
results = results.filter((metric) => metric.created_by?.uuid === filters.createdBy)
}
+ if (filters.owner) {
+ results = results.filter((metric) => metric.owner === filters.owner)
+ }
if (filters.search) {
const fuse = createFuse<DataCatalogMetricApi>(results, {
keys: ['name', 'display_name', 'description'],
@@ -284,6 +306,11 @@ export const metricsLogic = kea<metricsLogicType>([
return results
},
],
+ ownerFilterOptions: [
+ (s) => [s.allMetrics],
+ (allMetrics: DataCatalogMetricApi[]): string[] =>
+ [...new Set(allMetrics.flatMap((metric) => (metric.owner ? [metric.owner] : [])))].sort(),
+ ],
proposedCount: [
(s) => [s.allMetrics],
(allMetrics: DataCatalogMetricApi[]) => allMetrics.filter((metric) => metric.status === 'proposed').length,
@@ -293,11 +320,14 @@ export const metricsLogic = kea<metricsLogicType>([
setFilters: async ({ filters }, breakpoint) => {
// The search box dispatches on every keystroke, so wait for typing to settle before reporting.
await breakpoint(500)
- const { status, createdBy, search } = values.filters
+ const { status, createdBy, owner, search } = values.filters
+ const describeMember = (identifier: string | null, mine: string | undefined): string =>
+ identifier ? (identifier === mine ? 'me' : 'other') : 'any'
posthog.capture('data catalog metrics filtered', {
changed_filters: Object.keys(filters),
status,
- created_by: createdBy ? (createdBy === values.user?.uuid ? 'me' : 'other') : 'any',
+ created_by: describeMember(createdBy, values.user?.uuid),
+ owner: describeMember(owner, values.user?.email),
has_search: search.length > 0,
result_count: values.metrics.length,
})
@@ -433,6 +463,31 @@ export const metricsLogic = kea<metricsLogicType>([
actions.setBulkActionInFlight(null)
}
},
+ bulkChangeMetricOwner: async ({ names, owner, onSuccess }) => {
+ if (values.bulkActionInFlight || names.some((name) => values.actionsInFlight[name])) {
+ return
+ }
+ actions.setBulkActionInFlight('change_owner')
+ try {
+ const response = await dataCatalogMetricsBulkChangeOwnerCreate(projectId(), { names, owner })
+ const updatedByName = new Map(response.updated.map((metric) => [metric.name, metric]))
+ actions.loadMetricsSuccess(values.allMetrics.map((metric) => updatedByName.get(metric.name) ?? metric))
+ if (response.updated.length) {
+ lemonToast.success(`Changed the owner of ${metricCount(response.updated.length)}`)
+ }
+ if (response.skipped.length) {
+ lemonToast.warning(skippedMessage(response.skipped))
+ actions.loadMetrics()
+ }
+ onSuccess?.()
+ } catch (error) {
+ lemonToast.error(
+ apiErrorDetail(error) || 'Could not change the owner of the selected metrics. Try again.'
+ )
+ } finally {
+ actions.setBulkActionInFlight(null)
+ }
+ },
bulkDeleteMetrics: async ({ names, onSuccess }) => {
if (values.bulkActionInFlight || names.some((name) => values.actionsInFlight[name])) {
return
diff --git a/products/data_catalog/frontend/tabs/MetricsTab.tsx b/products/data_catalog/frontend/tabs/MetricsTab.tsx
index 543ad60fc6de..9acf76924dfc 100644
--- a/products/data_catalog/frontend/tabs/MetricsTab.tsx
+++ b/products/data_catalog/frontend/tabs/MetricsTab.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconRefresh } from '@posthog/icons'
-import { LemonButton, LemonDialog } from '@posthog/lemon-ui'
+import { LemonButton, LemonDialog, LemonSelect } from '@posthog/lemon-ui'
import { MemberSelect } from 'lib/components/MemberSelect'
import { More } from 'lib/lemon-ui/LemonButton/More'
@@ -66,7 +66,7 @@ export function MetricsTab(): JSX.Element {
// 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 } =
+ const { metrics, allMetrics, allMetricsLoading, filters, actionsInFlight, bulkActionInFlight, ownerFilterOptions } =
useValues(metricsLogic)
const {
setFilters,
@@ -77,6 +77,7 @@ export function MetricsTab(): JSX.Element {
setMetricOwner,
bulkApproveMetrics,
bulkDeleteMetrics,
+ bulkChangeMetricOwner,
} = useActions(metricsLogic)
const bulkBusyReason = bulkActionInFlight ? 'A bulk action is running' : undefined
@@ -98,6 +99,16 @@ export function MetricsTab(): JSX.Element {
return otherBulkActionReason('approve')
}
+ const bulkSelectionDisabledReason = (selectedCount: number, self: BulkMetricAction): string | undefined => {
+ if (selectedCount === 0) {
+ return 'The selected metrics are no longer available. Reload the list.'
+ }
+ if (selectedCount > METRIC_BULK_MAX) {
+ return OVER_CAP_REASON
+ }
+ return otherBulkActionReason(self)
+ }
+
const confirmDelete = (metric: DataCatalogMetricApi): void => {
LemonDialog.open({
title: 'Delete metric?',
@@ -257,6 +268,19 @@ export function MetricsTab(): JSX.Element {
onChange={(user) => setFilters({ createdBy: user?.uuid || null })}
/>
</div>
+ <div className="flex items-center gap-2">
+ <span>Owner:</span>
+ <LemonSelect
+ size="small"
+ value={filters.owner}
+ onChange={(owner) => setFilters({ owner })}
+ options={[
+ { value: null, label: 'Any user' },
+ ...ownerFilterOptions.map((owner) => ({ value: owner, label: owner })),
+ ]}
+ data-attr="data-catalog-metrics-owner-filter"
+ />
+ </div>
<LemonSegmentedButton
value={filters.status}
onChange={(status) => setFilters({ status })}
@@ -315,19 +339,35 @@ export function MetricsTab(): JSX.Element {
>
Approve ({approvableNames.length})
</LemonButton>
+ <MemberSelect
+ value={null}
+ defaultLabel="Unassigned"
+ onChange={(user) =>
+ bulkChangeMetricOwner(selectedNames, user?.email ?? null, ctx.clearSelection)
+ }
+ >
+ {() => (
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr="data-catalog-metrics-bulk-change-owner"
+ loading={bulkActionInFlight === 'change_owner'}
+ disabledReason={bulkSelectionDisabledReason(
+ selectedNames.length,
+ 'change_owner'
+ )}
+ >
+ Change owner
+ </LemonButton>
+ )}
+ </MemberSelect>
<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')
- }
+ disabledReason={bulkSelectionDisabledReason(selectedNames.length, 'delete')}
onClick={() => confirmBulkDelete(selectedNames, ctx.clearSelection)}
>
Delete
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5bafbf3868ba..46acb4b8adfc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29905,6 +29905,34 @@ export namespace Schemas {
skipped: DataCatalogMetricBulkSkip[];
}
+ /**
+ * Outcome of a bulk owner change: what changed, and what was left alone.
+ */
+ export interface DataCatalogMetricBulkChangeOwner {
+ /** The metrics that now have the new owner, freshly serialized. */
+ updated: DataCatalogMetric[];
+ /** Requested metrics whose owner did not change, with reasons. */
+ skipped: DataCatalogMetricBulkSkip[];
+ }
+
+ /**
+ * Input for giving many metrics one owner.
+ */
+ export interface DataCatalogMetricBulkChangeOwnerRequest {
+ /**
+ * Names of the metrics to act on, at most 100. Duplicates are collapsed.
+ * @minItems 1
+ * @maxItems 100
+ * @items.maxLength 128
+ */
+ names: string[];
+ /**
+ * Email of the member of this organization who becomes the owner of every named metric, or null to clear the owner. Changing the owner keeps each metric's approval.
+ * @nullable
+ */
+ owner: string | null;
+ }
+
/**
* Outcome of a bulk delete: which names are gone, and what was left alone.
*/