:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-catalog): free metric names on delete and allow renaming (#81529)
Thiago Salvatore11149002d198
diff --git a/.oxfmtrc.json b/.oxfmtrc.jsonindex cdcf38d8d611..2720e2b8f322 100644--- a/.oxfmtrc.json+++ b/.oxfmtrc.json@@ -95,6 +95,7 @@"products/desktop/**/*.mdx","products/desktop/pnpm-lock.yaml","products/desktop/apps/code/snapshots.yml",+ "frontend/snapshots.yml","venv","env",".venv",diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a755b6b6392f..a59b1f5a9797 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4758,10 +4758,10 @@ snapshots:hash: v1.k794b7964.ea754a4783f7653247f127337c407a8cdd4a9c6bc3f1b908d8d00dd1a090b966.KQ3yKnRzi4l3ZeYVThZdmo4L6mAbxtNa2uQh7y-kGWAproducts-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues--tile-filters-read-only--light:hash: v1.k794b7964.b2ca2efc52a9ccf56953159c66d3c8766acd1d3a17379d5faec45a4715ae24a9.fK76p7ZVcgvFJNcKJ5Ixy3YnBm_BcBSFnoytLS2jZdU- products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--dark:- hash: v1.k794b7964.ee9bd78f705c05a89b8dffa7ce394b1af07b75a9597fd220c94d177b49def5bd.Ii4is9m845vi1gNJRW-Pdw93hMfdAEL_0UIj6lAOTvw- products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--light:- hash: v1.k794b7964.b71412d69902241f7ec02efa87c138362522d5c7227c36a71e7f0dc0627d2a38.xiUrsbrXCMYmKv85SCzax7k6HNDzZsfKE5ZBhZBFPsI+ ? products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--dark+ : hash: v1.k794b7964.ee9bd78f705c05a89b8dffa7ce394b1af07b75a9597fd220c94d177b49def5bd.Ii4is9m845vi1gNJRW-Pdw93hMfdAEL_0UIj6lAOTvw+ ? products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--light+ : hash: v1.k794b7964.b71412d69902241f7ec02efa87c138362522d5c7227c36a71e7f0dc0627d2a38.xiUrsbrXCMYmKv85SCzax7k6HNDzZsfKE5ZBhZBFPsIproducts-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--dark:hash: v1.k794b7964.b1e0f5f542426e34dec73826f3135902a392c0c13dade4fec14037c615186b13.kbxxijyDI1SdvgdKwkRnIRLLgmsine5AYvOcD79DYsYproducts-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--light:diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex 7c851c0d808e..97fdd1c9cdb7 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -1489,7 +1489,9 @@ class InformationSchemaMetricsTable(InformationSchemaTable):fields: dict[str, FieldOrTable] = {"id": _string_field("id", description="Stable UUID of the metric (cross-reference for the REST API)."),"name": _string_field(- "name", description="Identifier-safe handle uniquely naming this metric within the project."+ "name",+ description="Identifier-safe handle uniquely naming this metric among the project's live metrics. "+ "Not permanent: a metric can be renamed, and deleting one frees its name for reuse.",),"display_name": _string_field("display_name", nullable=True, description="Human-friendly label."),"description": _string_field("description", description="What the metric means and how to interpret it."),diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.pyindex c4e8a7472ef1..3aa0dd72eaf6 100644--- a/products/data_catalog/backend/logic/metrics.py+++ b/products/data_catalog/backend/logic/metrics.py@@ -1,7 +1,8 @@"""Metric write path and approval lifecycle.-Names are reserved forever per team: creating with an existing name refines that metric, and creating-with a soft-deleted name resurrects the row as ``proposed``. A metric can be created from an insight+Names are unique among a team's live metrics: creating with a live existing name refines that metric,+while creating with a deleted metric's name starts a fresh one (delete and rename free the name for+reuse). A metric can be created from an insight(its query is snapshotted server-side and drift is flagged for re-review). Promotion to ``approved``is blocked while a metric is drifted. All transitions emit capture events for success-criteriameasurement.@@ -56,7 +57,9 @@ _APPROVAL_FIELDS = frozenset({"status", "approved_by", "approved_at"})# Fields that carry the metric's reviewed meaning: editing any of them invalidates a prior approval.# The definition is compared by canonical hash separately; these are compared by value. display_name# (a cosmetic label), owner, and provenance metadata are not part of what a reviewer blessed.-_APPROVAL_RELEVANT_FIELDS = frozenset({"description", "unit"})+# name is in here because agents pick a metric by matching its name (see the information_schema.metrics+# description), so moving an approved definition under a different name changes what the approval says.+_APPROVAL_RELEVANT_FIELDS = frozenset({"name", "description", "unit"})def _canonical_definition(@@ -166,12 +169,8 @@ def _invalidates_approval(metric: Metric, fields: dict) -> bool:return any(key in fields and fields[key] != getattr(metric, key) for key in _APPROVAL_RELEVANT_FIELDS)-def _resurrect_or_refine(metric: Metric, fields: dict) -> None:- if metric.deleted:- metric.deleted = False- metric.deleted_at = None- _reset_to_proposed(metric)- elif _invalidates_approval(metric, fields):+def _refine(metric: Metric, fields: dict) -> None:+ if _invalidates_approval(metric, fields):# Refining an approved metric's meaning (definition, description, or unit) changes what it# computes or how it reads; its review no longer holds, so drop back to proposed (matching# update_metric's PATCH behavior).@@ -198,7 +197,7 @@ def upsert_metric(reasoning: str | _Unset = _UNSET,request: "Request | None" = None,) -> Metric:- """Create a metric, or refine/resurrect the one already holding ``name`` for this team.+ """Create a metric, or refine the live one already holding ``name`` for this team.Refine is a partial merge: only the fields the caller supplies are written, so a refine thatomits a field leaves that field (a stored ``definition``, provenance, ...) untouched rather than@@ -233,10 +232,10 @@ def upsert_metric(with team_scope(team.id):try:with transaction.atomic():- existing = Metric.objects.for_team(team.id).filter(name=name).select_for_update().first()+ existing = Metric.objects.for_team(team.id).filter(name=name, deleted=False).select_for_update().first()created = existing is Noneif existing is not None:- _resurrect_or_refine(existing, fields)+ _refine(existing, fields)metric = existingelse:metric = Metric.objects.for_team(team.id).create(@@ -249,10 +248,10 @@ def upsert_metric(except IntegrityError:# A concurrent writer created (team, name) first; refine that row instead of failing.with transaction.atomic():- existing = Metric.objects.for_team(team.id).filter(name=name).select_for_update().first()+ existing = Metric.objects.for_team(team.id).filter(name=name, deleted=False).select_for_update().first()if existing is None:raise- _resurrect_or_refine(existing, fields)+ _refine(existing, fields)metric, created = existing, Falsecapture_metric_event(@@ -264,9 +263,17 @@ def upsert_metric(def update_metric(metric: Metric, *, team: Team, user: Optional[User], request: "Request | None" = None, **fields) -> Metric:- """Partially update a metric. Name is write-once; editing an approved definition resets approval."""- if "name" in fields:- raise ValidationError({"name": "Metric name is write-once and cannot be changed."})+ """Partially update a metric. Renaming frees the old name; editing an approved definition resets approval."""+ if fields.get("name") == metric.name:+ fields.pop("name")+ renamed_from = metric.name if "name" in fields else None+ if renamed_from is not None:+ if not re.match(METRIC_NAME_REGEX, fields["name"] or ""):+ raise ValidationError(+ {"name": "Name must start with a letter and contain only letters, numbers, and underscores."}+ )+ if Metric.objects.for_team(team.id).filter(name=fields["name"], deleted=False).exclude(pk=metric.pk).exists():+ raise ValidationError({"name": "A metric with this name already exists."})if "description" in fields:validate_description(fields["description"])@@ -276,21 +283,35 @@ def update_metric(source_insight_arg = fields.pop("source_insight_short_id", _UNSET)fields.update(_resolve_definition_fields(definition_arg, source_insight_arg, team, user))- with team_scope(team.id), transaction.atomic():- metric = Metric.objects.for_team(team.id).select_for_update().get(pk=metric.pk)- approval_invalidated = _invalidates_approval(metric, fields)-- for key, value in fields.items():- setattr(metric, key, value)-- changed_fields = set(fields.keys())- if approval_invalidated and metric.status == MetricStatus.APPROVED:- # The edit changed what the metric means, so its approval no longer holds.- _reset_to_proposed(metric)- changed_fields |= _APPROVAL_FIELDS-- metric.save(update_fields=[*changed_fields, "updated_at"])- capture_metric_event(METRIC_UPDATED_EVENT, metric, team=team, user=user, request=request)+ try:+ with team_scope(team.id), transaction.atomic():+ metric = Metric.objects.for_team(team.id).select_for_update().get(pk=metric.pk)+ approval_invalidated = _invalidates_approval(metric, fields)++ for key, value in fields.items():+ setattr(metric, key, value)++ changed_fields = set(fields.keys())+ if approval_invalidated and metric.status == MetricStatus.APPROVED:+ # The edit changed what the metric means, so its approval no longer holds.+ _reset_to_proposed(metric)+ changed_fields |= _APPROVAL_FIELDS++ metric.save(update_fields=[*changed_fields, "updated_at"])+ except IntegrityError:+ # A concurrent writer claimed the target name between the pre-check and the save (the row+ # lock is on this metric, not on the name).+ if renamed_from is None:+ raise+ raise ValidationError({"name": "A metric with this name already exists."})+ capture_metric_event(+ METRIC_UPDATED_EVENT,+ metric,+ team=team,+ user=user,+ request=request,+ extra={"renamed_from": renamed_from} if renamed_from else None,+ )return metricdiff --git a/products/data_catalog/backend/migrations/0006_metric_name_partial_unique.py b/products/data_catalog/backend/migrations/0006_metric_name_partial_unique.pynew file mode 100644index 000000000000..0a20b41a4154--- /dev/null+++ b/products/data_catalog/backend/migrations/0006_metric_name_partial_unique.py@@ -0,0 +1,44 @@+# Generated by Django 5.2.17 on 2026-08-11 19:22++import django.core.validators+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("data_catalog", "0005_alter_metric_description"),+ ("posthog", "1298_user_stripped_alias_index"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AlterField(+ model_name="metric",+ name="name",+ field=models.CharField(+ 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.",+ max_length=128,+ validators=[+ django.core.validators.RegexValidator(+ message="Name must start with a letter and contain only letters, numbers, and underscores.",+ regex="^[A-Za-z][A-Za-z0-9_]*$",+ )+ ],+ ),+ ),+ # The partial index is a strict subset of the unconditional one, so adding it first cannot+ # fail on existing data and live-name uniqueness stays enforced with no gap.+ migrations.AddConstraint(+ model_name="metric",+ constraint=models.UniqueConstraint(+ condition=models.Q(("deleted", False)),+ fields=("team", "name"),+ name="unique_live_metric_name_per_team",+ ),+ ),+ migrations.RemoveConstraint(+ model_name="metric",+ name="unique_metric_name_per_team",+ ),+ ]diff --git a/products/data_catalog/backend/migrations/max_migration.txt b/products/data_catalog/backend/migrations/max_migration.txtindex d26a5011866b..fe00c70b45e0 100644--- a/products/data_catalog/backend/migrations/max_migration.txt+++ b/products/data_catalog/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_alter_metric_description+0006_metric_name_partial_uniquediff --git a/products/data_catalog/backend/models/metric.py b/products/data_catalog/backend/models/metric.pyindex 4599fcb5800e..02637bdd523a 100644--- a/products/data_catalog/backend/models/metric.py+++ b/products/data_catalog/backend/models/metric.py@@ -22,10 +22,12 @@ class Metric():"""A canonical business metric: name + description, optionally a machine-readable definition.- Names are reserved forever per team (the unique constraint is unconditional, soft-deleted rows- keep their name), so a stored reference never silently points at a different metric. The state- machine (proposed -> approved, drift) lives in ``logic/`` — ``status`` is never a writable- serializer field.+ Names are unique per team among live metrics only (the unique constraint is partial on+ ``deleted=False``). Renaming or deleting a metric frees its name, and a freed name may later be+ claimed by an unrelated metric — a stored reference (SQL over ``information_schema.metrics``,+ run URLs) is only guaranteed stable while the metric lives under that name. The state machine+ (proposed -> approved, drift) lives in ``logic/`` — ``status`` is never a writable serializer+ field."""# db_constraint=False on FKs to hot tables (posthog_team, posthog_user): a real FK constraint@@ -39,7 +41,8 @@ class Metric(name = models.CharField(max_length=128,validators=[validate_metric_name],- help_text="Identifier-safe run handle, unique per team and reserved forever. Write-once.",+ 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.",)display_name = models.CharField(max_length=255, blank=True, help_text="Human-friendly label. Mutable, unlike name.")description = models.TextField(@@ -114,7 +117,11 @@ class Metric(class Meta:constraints = [- models.UniqueConstraint(fields=["team", "name"], name="unique_metric_name_per_team"),+ models.UniqueConstraint(+ fields=["team", "name"],+ condition=models.Q(deleted=False),+ name="unique_live_metric_name_per_team",+ ),]indexes = [models.Index(fields=["team", "status"]),diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.pyindex 962cef61b2fc..d006e2961586 100644--- a/products/data_catalog/backend/presentation/serializers.py+++ b/products/data_catalog/backend/presentation/serializers.py@@ -152,7 +152,11 @@ class MetricSerializer(serializers.ModelSerializer):"updated_at",]extra_kwargs = {- "name": {"help_text": "Identifier-safe run handle, unique per team and reserved forever. Write-once."},+ "name": {+ "help_text": "Identifier-safe run handle, unique among the team's live metrics. Renaming or "+ "deleting a metric frees its name for reuse, and anything referencing the old name (SQL over "+ "information_schema.metrics, run URLs, links) stops resolving."+ },"source_insight_short_id": {"required": False,"help_text": "Create the metric from this insight's query (snapshotted server-side). "diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.pyindex cc0c7aa43480..d5d2bb159eb3 100644--- a/products/data_catalog/backend/presentation/views.py+++ b/products/data_catalog/backend/presentation/views.py@@ -1,7 +1,7 @@"""DRF views for data_catalog.Thin: validate via the serializer, call the facade, serialize the result. Domain invariants-(name reservation, upsert, validation, drift, approval) live in the logic layer behind the facade.+(name uniqueness, upsert, rename, validation, drift, approval) live in the logic layer behind the facade."""from typing import cast@@ -12,7 +12,7 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import mixins, status, viewsetsfrom rest_framework.decorators import action as drf_action-from rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.throttling import BaseThrottle@@ -44,7 +44,7 @@ _STRUCTURED_QUERY_KINDS = {*INSIGHT_DEFINITION_KINDS, *NODE_DEFINITION_KINDS}class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):- """CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/)."""+ """CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/)."""scope_object = "data_catalog"lookup_field = "name"@@ -126,9 +126,6 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer = self.get_serializer(metric, data=request.data, partial=partial)serializer.is_valid(raise_exception=True)fields = dict(serializer.validated_data)- if "name" in fields and fields["name"] != metric.name:- raise ValidationError({"name": "Metric name is write-once and cannot be changed."})- fields.pop("name", None)metric = api.update_metric(metric, team=self.team, user=cast(User, request.user), request=request, **fields)return Response(self.get_serializer(metric).data)diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.pyindex 3b93eb67f231..44c9fe7789c8 100644--- a/products/data_catalog/backend/tests/test_api.py+++ b/products/data_catalog/backend/tests/test_api.py@@ -88,10 +88,25 @@ class TestMetricAPI(APIBaseTest):assert self.client.delete(f"{self.url}mrr/").status_code == status.HTTP_204_NO_CONTENTassert self.client.get(f"{self.url}mrr/").status_code == status.HTTP_404_NOT_FOUND- def test_patch_cannot_change_name(self) -> None:+ def test_patch_renames_metric(self) -> None:self.client.post(self.url, {"name": "mrr", "description": "v1"}, format="json")response = self.client.patch(f"{self.url}mrr/", {"name": "arr"}, format="json")- assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["name"] == "arr"+ assert self.client.get(f"{self.url}mrr/").status_code == status.HTTP_404_NOT_FOUND+ assert self.client.get(f"{self.url}arr/").status_code == status.HTTP_200_OK++ def test_create_after_delete_starts_fresh(self) -> None:+ created = self.client.post(+ self.url, {"name": "mrr", "description": "v1", "definition": _HOGQL}, format="json"+ ).json()+ self.client.delete(f"{self.url}mrr/")++ response = self.client.post(self.url, {"name": "mrr", "description": "v2"}, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["id"] != created["id"]+ assert body["definition"] is Nonedef test_invalid_definition_rejected(self) -> None:response = self.client.post(diff --git a/products/data_catalog/backend/tests/test_logic.py b/products/data_catalog/backend/tests/test_logic.pyindex 1e5681d0fe3a..c82114e618b8 100644--- a/products/data_catalog/backend/tests/test_logic.py+++ b/products/data_catalog/backend/tests/test_logic.py@@ -62,17 +62,16 @@ class TestMetricUpsert(BaseTest):assert refined.created_source == CreatedSource.AI_GENERATEDassert refined.ai_model == "claude"- def test_upsert_resurrects_soft_deleted_as_proposed(self) -> None:- metric = self._upsert("mrr")- Metric.objects.for_team(self.team.id).filter(pk=metric.pk).update(status=MetricStatus.APPROVED)- metric.refresh_from_db()+ def test_upsert_after_delete_creates_fresh_metric(self) -> None:+ metric = self._upsert("mrr", definition=_HOGQL_A)soft_delete_metric(metric)- resurrected = self._upsert("mrr", description="back")- assert resurrected.id == metric.id- assert resurrected.deleted is False- assert resurrected.status == MetricStatus.PROPOSED- assert resurrected.description == "back"+ fresh = self._upsert("mrr", description="fresh")+ assert fresh.id != metric.id+ assert fresh.status == MetricStatus.PROPOSED+ assert fresh.definition is None+ metric.refresh_from_db()+ assert metric.deleted is True@parameterized.expand([("bad name",), ("1leading_digit",), ("has-dash",), ("",)])def test_rejects_invalid_names(self, name: str) -> None:@@ -108,10 +107,39 @@ class TestMetricUpdate(BaseTest):assert updated.description == "v2"assert updated.unit == "usd"- def test_update_rejects_name_change(self) -> None:+ def test_rename_resets_approval(self) -> None:+ # Agents pick a metric by matching its name, so moving an approved definition under a new+ # name needs a fresh review. Catalog write access alone must not rebind an approved handle.+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="v1")+ metric = approve_metric(metric, self.user)++ renamed = update_metric(metric, team=self.team, user=self.user, name="arr")+ assert renamed.name == "arr"+ assert renamed.status == MetricStatus.PROPOSED+ assert renamed.approved_by_id is None+ assert renamed.approved_at is None++ @parameterized.expand([("bad name",), ("1leading_digit",), ("has-dash",), ("",)])+ def test_rename_rejects_invalid_names(self, name: str) -> None:metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="v1")with self.assertRaises(ValidationError):+ update_metric(metric, team=self.team, user=self.user, name=name)++ def test_rename_rejects_live_taken_name(self) -> None:+ upsert_metric(team=self.team, user=self.user, name="arr", description="taken")+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="v1")+ with self.assertRaises(ValidationError) as ctx:update_metric(metric, team=self.team, user=self.user, name="arr")+ assert "name" in ctx.exception.detail++ def test_rename_to_soft_deleted_name_succeeds(self) -> None:+ tombstone = upsert_metric(team=self.team, user=self.user, name="arr", description="old")+ soft_delete_metric(tombstone)+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="v1")++ renamed = update_metric(metric, team=self.team, user=self.user, name="arr")+ assert renamed.name == "arr"+ assert renamed.id == metric.iddef test_update_rejects_overlong_description(self) -> None:metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="v1")diff --git a/products/data_catalog/backend/tests/test_models.py b/products/data_catalog/backend/tests/test_models.pyindex a99cd0d291c7..b2e08a4317be 100644--- a/products/data_catalog/backend/tests/test_models.py+++ b/products/data_catalog/backend/tests/test_models.py@@ -15,13 +15,16 @@ class TestMetricModel(BaseTest):with self.assertRaises(IntegrityError), transaction.atomic():self._create("mrr")- def test_name_reserved_even_when_soft_deleted(self) -> None:- # The unique constraint is unconditional, so a soft-deleted name still blocks reuse at the- # DB level. This is what stops a stored reference from ever pointing at a different metric.- metric = self._create("mrr")- Metric.objects.for_team(self.team.id).filter(pk=metric.pk).update(deleted=True)- with self.assertRaises(IntegrityError), transaction.atomic():- self._create("mrr")+ def test_soft_deleted_name_is_reusable(self) -> None:+ # The unique constraint is partial on deleted=False: deleting frees the name, and any number+ # of tombstones may share it.+ first = self._create("mrr")+ Metric.objects.for_team(self.team.id).filter(pk=first.pk).update(deleted=True)+ second = self._create("mrr")+ assert second.id != first.id+ Metric.objects.for_team(self.team.id).filter(pk=second.pk).update(deleted=True)+ self._create("mrr")+ assert Metric.objects.for_team(self.team.id).filter(name="mrr").count() == 3def test_definition_kind_derived_from_definition(self) -> None:stub = self._create("stub")diff --git a/products/data_catalog/frontend/DataCatalogMetricScene.tsx b/products/data_catalog/frontend/DataCatalogMetricScene.tsxindex 98042aac56c2..be938a22c85c 100644--- a/products/data_catalog/frontend/DataCatalogMetricScene.tsx+++ b/products/data_catalog/frontend/DataCatalogMetricScene.tsx@@ -43,7 +43,12 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ScenePanel, ScenePanelActionsSection, ScenePanelInfoSection } from '~/layout/scenes/SceneLayout'import { InsightShortId, SidePanelTab } from '~/types'-import { humanizeDefinitionKind, METRIC_DESCRIPTION_MAX_LENGTH, METRIC_MARKDOWN_MAX_LENGTH } from './common'+import {+ humanizeDefinitionKind,+ METRIC_DESCRIPTION_MAX_LENGTH,+ METRIC_MARKDOWN_MAX_LENGTH,+ validateMetricName,+} from './common'import { MetricMarkdownEditorField } from './components/MetricMarkdownEditorField'import { buildMetricRunPrompt, RunMetricWithAIButton } from './components/RunMetricWithAIButton'import {@@ -78,6 +83,7 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicPropapproveMetric,refreshMetricFromInsight,deleteMetric,+ renameMetric,updateMetric,loadRunResult,setEditingDefinition,@@ -130,12 +136,38 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicPropconst confirmDelete = (): void => {LemonDialog.open({title: 'Delete metric?',- content: <div className="text-sm text-secondary">Deleting {metric.name} cannot be undone.</div>,+ content: (+ <div className="text-sm text-secondary">+ This deletes {metric.name} and makes its name available for a new metric. Queries and links that+ reference it will stop working.+ </div>+ ),primaryButton: { children: 'Delete', status: 'danger', onClick: deleteMetric },secondaryButton: { children: 'Cancel' },})}+ const openRenameDialog = (): void => {+ LemonDialog.openForm({+ title: 'Rename metric',+ initialValues: { name: metric.name },+ content: (+ <div className="flex flex-col gap-2">+ <div className="text-sm text-secondary">+ Anything that references this metric by name, like saved SQL queries, API calls, or links, will+ stop working until it is updated. The old name becomes available for a new metric.+ {isApproved && ' Renaming also sets the metric back to proposed, so it needs approving again.'}+ </div>+ <LemonField name="name" label="Name">+ <LemonInput data-attr="data-catalog-metric-rename-input" autoFocus />+ </LemonField>+ </div>+ ),+ errors: { name: (value) => validateMetricName(value ?? '') },+ onSubmit: ({ name: newName }) => renameMetric(newName),+ })+ }+const actions: MetricAction[] = [...(isApproved? []@@ -180,6 +212,14 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProponClick: loadRunResult,disabledReason: metric.definition_kind ? undefined : 'This metric has no runnable definition yet',},+ {+ key: 'rename',+ label: 'Rename',+ icon: <IconPencil />,+ onClick: openRenameDialog,+ disabledReason: mutating ? 'Working' : undefined,+ opensFloatingUi: true,+ },...(definitionSql? [{diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.tsindex 7311bab4deca..15e1466c21ed 100644--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts@@ -174,6 +174,24 @@ describe('dataCatalogMetricSceneLogic', () => {stubLogic.unmount()})+ it('renaming issues the patch against the old name and navigates to the new URL', async () => {+ ;(dataCatalogMetricsPartialUpdate as jest.Mock).mockResolvedValue(buildMetric({ name: 'wau' }))++ logic.actions.renameMetric('wau')+ await expectLogic(logic).toFinishAllListeners()++ expect(dataCatalogMetricsPartialUpdate).toHaveBeenCalledWith('1', 'weekly_active_users', { name: 'wau' })+ expect(router.values.location.pathname).toContain('/wau')+ })++ it('renaming to an invalid name issues no request', async () => {+ logic.actions.renameMetric('has-dash')+ await expectLogic(logic).toFinishAllListeners()++ expect(dataCatalogMetricsPartialUpdate).not.toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalled()+ })+it('opens the markdown editor once loaded when arriving with ?edit=definition', async () => {jest.clearAllMocks();(dataCatalogMetricsRetrieve as jest.Mock).mockResolvedValue(@@ -203,6 +221,7 @@ describe('dataCatalogMetricSceneLogic', () => {traversalLogic.actions.approveMetric()traversalLogic.actions.refreshMetricFromInsight()traversalLogic.actions.updateMetric({ definition: { kind: 'HogQLQuery', query: 'SELECT 2' } })+ traversalLogic.actions.renameMetric('valid_name')traversalLogic.actions.deleteMetric()traversalLogic.actions.loadRunResult()await expectLogic(traversalLogic).toFinishAllListeners()diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsxindex 6d222c98bab4..ac9b3a02b056 100644--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx@@ -105,6 +105,9 @@ export interface dataCatalogMetricSceneLogicActions {refreshMetricFromInsight: () => {value: true}+ renameMetric: (name: string) => {+ name: string+ }setDraftMarkdown: (draftMarkdown: string) => {draftMarkdown: string}@@ -173,6 +176,7 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(approveMetric: true,refreshMetricFromInsight: true,deleteMetric: true,+ renameMetric: (name: string) => ({ name }),updateMetric: (patch: PatchedDataCatalogMetricApi) => ({ patch }),setMutating: (mutating: boolean) => ({ mutating }),setEditingDefinition: (editingDefinition: boolean) => ({ editingDefinition }),@@ -330,6 +334,26 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(actions.setMutating(false)}},+ renameMetric: async ({ name }) => {+ if (values.mutating || isInvalidMetricName(props.name) || name === props.name) {+ return+ }+ const validationError = validateMetricName(name)+ if (validationError) {+ lemonToast.error(validationError)+ return+ }+ actions.setMutating(true)+ try {+ await dataCatalogMetricsPartialUpdate(projectId(), props.name, { name })+ lemonToast.success('Metric renamed')+ // The logic is keyed by name, so navigating remounts a fresh instance at the new URL.+ router.actions.replace(urls.dataCatalogMetric(name))+ } catch (error) {+ lemonToast.error(apiErrorDetail(error) || 'Could not rename the metric. Try again.')+ actions.setMutating(false)+ }+ },deleteMetric: async () => {if (values.mutating || isInvalidMetricName(props.name)) {returndiff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.tsindex 1d11d6864e19..1c0c9c6c5d6c 100644--- a/products/data_catalog/frontend/generated/api.schemas.ts+++ b/products/data_catalog/frontend/generated/api.schemas.ts@@ -156,7 +156,7 @@ export type DataCatalogMetricApiDefinition = { [key: string]: unknown } | nullexport interface DataCatalogMetricApi {readonly id: string/**- * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving.* @maxLength 128* @pattern ^[A-Za-z][A-Za-z0-9_]*$*/@@ -256,7 +256,7 @@ export type PatchedDataCatalogMetricApiDefinition = { [key: string]: unknown } |export interface PatchedDataCatalogMetricApi {readonly id?: string/**- * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving.* @maxLength 128* @pattern ^[A-Za-z][A-Za-z0-9_]*$*/diff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.tsindex 8cc2e72984e0..9a90531e8158 100644--- a/products/data_catalog/frontend/generated/api.ts+++ b/products/data_catalog/frontend/generated/api.ts@@ -188,7 +188,7 @@ export const getDataCatalogMetricsListUrl = (projectId: string, params?: DataCat}/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const dataCatalogMetricsList = async (projectId: string,@@ -226,7 +226,7 @@ export const getDataCatalogMetricsRetrieveUrl = (projectId: string, name: string}/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const dataCatalogMetricsRetrieve = async (projectId: string,@@ -244,7 +244,7 @@ export const getDataCatalogMetricsUpdateUrl = (projectId: string, name: string)}/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const dataCatalogMetricsUpdate = async (projectId: string,@@ -265,7 +265,7 @@ export const getDataCatalogMetricsPartialUpdateUrl = (projectId: string, name: s}/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const dataCatalogMetricsPartialUpdate = async (projectId: string,@@ -286,7 +286,7 @@ export const getDataCatalogMetricsDestroyUrl = (projectId: string, name: string)}/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const dataCatalogMetricsDestroy = async (projectId: string,diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.tsindex 11531f216f35..bd700087a779 100644--- a/products/data_catalog/frontend/generated/api.zod.ts+++ b/products/data_catalog/frontend/generated/api.zod.ts@@ -55,7 +55,9 @@ export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({.string().max(dataCatalogMetricsCreateBodyNameMax).regex(dataCatalogMetricsCreateBodyNameRegExp)- .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ .describe(+ "Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving."+ ),display_name: zod.string().max(dataCatalogMetricsCreateBodyDisplayNameMax)@@ -105,7 +107,7 @@ export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({})/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const dataCatalogMetricsUpdateBodyNameMax = 128@@ -128,7 +130,9 @@ export const DataCatalogMetricsUpdateBody = /* @__PURE__ */ zod.object({.string().max(dataCatalogMetricsUpdateBodyNameMax).regex(dataCatalogMetricsUpdateBodyNameRegExp)- .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ .describe(+ "Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving."+ ),display_name: zod.string().max(dataCatalogMetricsUpdateBodyDisplayNameMax)@@ -178,7 +182,7 @@ export const DataCatalogMetricsUpdateBody = /* @__PURE__ */ zod.object({})/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const dataCatalogMetricsPartialUpdateBodyNameMax = 128@@ -202,7 +206,9 @@ export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({.max(dataCatalogMetricsPartialUpdateBodyNameMax).regex(dataCatalogMetricsPartialUpdateBodyNameRegExp).optional()- .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ .describe(+ "Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving."+ ),display_name: zod.string().max(dataCatalogMetricsPartialUpdateBodyDisplayNameMax)diff --git a/products/data_catalog/frontend/tabs/MetricsTab.tsx b/products/data_catalog/frontend/tabs/MetricsTab.tsxindex 6f55554f5130..cabf670273e5 100644--- a/products/data_catalog/frontend/tabs/MetricsTab.tsx+++ b/products/data_catalog/frontend/tabs/MetricsTab.tsx@@ -64,7 +64,12 @@ export function MetricsTab(): JSX.Element {const confirmDelete = (metric: DataCatalogMetricApi): void => {LemonDialog.open({title: 'Delete metric?',- content: <div className="text-sm text-secondary">Deleting {metric.name} cannot be undone.</div>,+ content: (+ <div className="text-sm text-secondary">+ This deletes {metric.name} and makes its name available for a new metric. Queries and links that+ reference it will stop working.+ </div>+ ),primaryButton: {children: 'Delete',type: 'primary',diff --git a/products/data_catalog/mcp/tools.yaml b/products/data_catalog/mcp/tools.yamlindex 7fedaafc0881..ee907cc931b4 100644--- a/products/data_catalog/mcp/tools.yaml+++ b/products/data_catalog/mcp/tools.yaml@@ -117,9 +117,10 @@ tools:idempotent: truetitle: Create or refine a catalog metricdescription: >- Create a canonical metric, or refine the one already holding this name (upsert on name; always lands- 'proposed'). The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event- node) that the query runner computes, OR an agent-calculated markdown definition - {"kind":+ Create a canonical metric, or refine the live one already holding this name (upsert on name; always lands+ 'proposed'). A deleted metric's name is available again - creating with it starts a fresh metric with no+ history carried over. The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery /+ an event node) that the query runner computes, OR an agent-calculated markdown definition - {"kind":"MarkdownDefinition", "markdown": "<numbered steps to calculate the metric>"} - which an agent follows toproduce the number. Prefer an executable definition when the metric is deterministic; use a markdowndefinition when the calculation needs judgment or multiple steps. Only propose a definition that was@@ -165,13 +166,17 @@ tools:idempotent: truetitle: Update a catalog metricdescription: >- Update a metric's fields. Editing an approved metric's definition, description, or unit resets it to- 'proposed' (it must be re-approved by a human). When editing 'description', keep it to 1-3 sentences of+ Update a metric's fields. 'name' picks the metric to update. Editing an approved metric's definition,+ description, unit, or name resets it to 'proposed' (it must be re-approved by a human). Pass 'new_name' to+ rename the metric: the old name is freed for reuse, and anything that referenced it (saved SQL, run URLs,+ later tool calls) must switch to the new name. When editing 'description', keep it to 1-3 sentences ofbusiness meaning, not a narration of the query; rationale for the definition belongs in 'reasoning'.exclude_params:- created_sourceinject_body:created_source: ai_generated+ rename_params:+ name: new_namefeature_flag: product-data-catalogdata-catalog-metrics-destroy:operation: data_catalog_metrics_destroydiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 696349a8bb66..142642688160 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2372,7 +2372,7 @@"feature_flag": "product-data-catalog"},"data-catalog-metric-create": {- "description": "Create a canonical metric, or refine the one already holding this name (upsert on name; always lands 'proposed'). The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.",+ "description": "Create a canonical metric, or refine the live one already holding this name (upsert on name; always lands 'proposed'). A deleted metric's name is available again - creating with it starts a fresh metric with no history carried over. The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.","category": "Data catalog","feature": "data_catalog","summary": "Create or refine a catalog metric",@@ -2402,7 +2402,7 @@"feature_flag": "product-data-catalog"},"data-catalog-metric-update": {- "description": "Update a metric's fields. Editing an approved metric's definition, description, or unit resets it to 'proposed' (it must be re-approved by a human). When editing 'description', keep it to 1-3 sentences of business meaning, not a narration of the query; rationale for the definition belongs in 'reasoning'.",+ "description": "Update a metric's fields. 'name' picks the metric to update. Editing an approved metric's definition, description, unit, or name resets it to 'proposed' (it must be re-approved by a human). Pass 'new_name' to rename the metric: the old name is freed for reuse, and anything that referenced it (saved SQL, run URLs, later tool calls) must switch to the new name. When editing 'description', keep it to 1-3 sentences of business meaning, not a narration of the query; rationale for the definition belongs in 'reasoning'.","category": "Data catalog","feature": "data_catalog","summary": "Update a catalog metric",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 597a753c40e1..37d99c603891 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2387,7 +2387,7 @@"feature_flag": "product-data-catalog"},"data-catalog-metric-create": {- "description": "Create a canonical metric, or refine the one already holding this name (upsert on name; always lands 'proposed'). The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.",+ "description": "Create a canonical metric, or refine the live one already holding this name (upsert on name; always lands 'proposed'). A deleted metric's name is available again - creating with it starts a fresh metric with no history carried over. The definition can be an executable query (HogQLQuery / TrendsQuery / FunnelsQuery / an event node) that the query runner computes, OR an agent-calculated markdown definition - {\"kind\": \"MarkdownDefinition\", \"markdown\": \"<numbered steps to calculate the metric>\"} - which an agent follows to produce the number. Prefer an executable definition when the metric is deterministic; use a markdown definition when the calculation needs judgment or multiple steps. Only propose a definition that was explicitly asked for or that you have seen reused at least twice - do not speculatively catalog one-off queries. If you derived a number and no metric exists for it, offer to save the derivation as a proposed metric. Keep 'description' to 1-3 sentences saying what the metric means and what it serves - never a walkthrough of the query or calculation steps (the definition carries those); put rationale for the chosen definition in 'reasoning'. There is no list tool: discover existing metrics with execute-sql over system.information_schema.metrics.","category": "Data catalog","feature": "data_catalog","summary": "Create or refine a catalog metric",@@ -2417,7 +2417,7 @@"feature_flag": "product-data-catalog"},"data-catalog-metric-update": {- "description": "Update a metric's fields. Editing an approved metric's definition, description, or unit resets it to 'proposed' (it must be re-approved by a human). When editing 'description', keep it to 1-3 sentences of business meaning, not a narration of the query; rationale for the definition belongs in 'reasoning'.",+ "description": "Update a metric's fields. 'name' picks the metric to update. Editing an approved metric's definition, description, unit, or name resets it to 'proposed' (it must be re-approved by a human). Pass 'new_name' to rename the metric: the old name is freed for reuse, and anything that referenced it (saved SQL, run URLs, later tool calls) must switch to the new name. When editing 'description', keep it to 1-3 sentences of business meaning, not a narration of the query; rationale for the definition belongs in 'reasoning'.","category": "Data catalog","feature": "data_catalog","summary": "Update a catalog metric",diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex 9d770ef5a067..cc8d3e8d6478 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -623,6 +623,13 @@ function composeToolSchema(// mapping is tracked in renamedFields for body-building.const alias = renameMap.get(name)const fieldKey = alias ?? name+ // A body field that shares a path param's name (e.g. PATCH /metrics/{name}/+ // with a writable `name`) collapses into one input, because the body part is+ // merged over the path part. Renaming it separates the two, but only if the+ // body copy is dropped here — otherwise it still overwrites the path param.+ if (alias && pathParamNames.includes(name)) {+ bodyOmitFields.add(name)+ }bodyFieldNames.push(fieldKey)if (bodyVariantSpecific.has(name)) {variantSpecificBodyFieldNames.add(fieldKey)@@ -776,7 +783,12 @@ function composeToolSchema(const bodyImport = `${pascal}Body`for (const [original, alias] of renameMap) {renamedFields[alias] = original- schemaExpr += `\n .omit({ '${original}': true })`+ // When the original is also a path param, the body copy was already dropped above+ // and the surviving key addresses the resource, so omitting it here would leave the+ // handler with no value for the URL.+ if (!pathParamNames.includes(original)) {+ schemaExpr += `\n .omit({ '${original}': true })`+ }schemaExpr += `\n .extend({ ${alias}: ${bodyImport}.shape['${original}'] })`}}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4cb0251e7301..26da79d49c35 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18766,7 +18766,7 @@ export namespace Schemas {export interface DataCatalogMetric {readonly id: string;/**- * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving.* @maxLength 128* @pattern ^[A-Za-z][A-Za-z0-9_]*$*/@@ -54155,7 +54155,7 @@ export namespace Schemas {export interface PatchedDataCatalogMetric {readonly id?: string;/**- * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving.* @maxLength 128* @pattern ^[A-Za-z][A-Za-z0-9_]*$*/diff --git a/services/mcp/src/generated/data_catalog/api.ts b/services/mcp/src/generated/data_catalog/api.tsindex f66744e7efac..fd79c656115a 100644--- a/services/mcp/src/generated/data_catalog/api.ts+++ b/services/mcp/src/generated/data_catalog/api.ts@@ -94,7 +94,9 @@ export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({.string().max(dataCatalogMetricsCreateBodyNameMax).regex(dataCatalogMetricsCreateBodyNameRegExp)- .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ .describe(+ "Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving."+ ),display_name: zod.string().max(dataCatalogMetricsCreateBodyDisplayNameMax)@@ -137,7 +139,7 @@ export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({})/**- * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ * CRUD for catalog metrics, addressed by their ``name`` (e.g. /metrics/mrr/).*/export const DataCatalogMetricsPartialUpdateParams = /* @__PURE__ */ zod.object({name: zod.string(),@@ -170,7 +172,9 @@ export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({.max(dataCatalogMetricsPartialUpdateBodyNameMax).regex(dataCatalogMetricsPartialUpdateBodyNameRegExp).optional()- .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ .describe(+ "Identifier-safe run handle, unique among the team's live metrics. Renaming or deleting a metric frees its name for reuse, and anything referencing the old name (SQL over information_schema.metrics, run URLs, links) stops resolving."+ ),display_name: zod.string().max(dataCatalogMetricsPartialUpdateBodyDisplayNameMax)diff --git a/services/mcp/src/tools/generated/data_catalog.ts b/services/mcp/src/tools/generated/data_catalog.tsindex 56177b3208fa..206ff65c6b83 100644--- a/services/mcp/src/tools/generated/data_catalog.ts+++ b/services/mcp/src/tools/generated/data_catalog.ts@@ -345,9 +345,9 @@ const dataCatalogMetricRun = (): ToolBase<typeof DataCatalogMetricRunSchema, Sch},})-const DataCatalogMetricUpdateSchema = DataCatalogMetricsPartialUpdateParams.omit({ project_id: true }).extend(- DataCatalogMetricsPartialUpdateBody.shape-)+const DataCatalogMetricUpdateSchema = DataCatalogMetricsPartialUpdateParams.omit({ project_id: true })+ .extend(DataCatalogMetricsPartialUpdateBody.omit({ name: true }).shape)+ .extend({ new_name: DataCatalogMetricsPartialUpdateBody.shape['name'] })const dataCatalogMetricUpdate = (): ToolBase<typeof DataCatalogMetricUpdateSchema, Schemas.DataCatalogMetric> => ({name: 'data-catalog-metric-update',@@ -355,8 +355,8 @@ const dataCatalogMetricUpdate = (): ToolBase<typeof DataCatalogMetricUpdateSchemhandler: async (context: Context, params: z.infer<typeof DataCatalogMetricUpdateSchema>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}- if (params.name !== undefined) {- body['name'] = params.name+ if (params.new_name !== undefined) {+ body['name'] = params.new_name}if (params.display_name !== undefined) {body['display_name'] = params.display_namediff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.tsindex 78d1a0c60875..21c345bc89ba 100644--- a/services/mcp/tests/unit/generate-tools.test.ts+++ b/services/mcp/tests/unit/generate-tools.test.ts@@ -1034,6 +1034,53 @@ describe('rename_params', () => {expect(result.code).toContain('body["$unset"] = params.property_key')expect(result.code).not.toContain('params.$unset')})++ it('keeps the path param when the renamed body field shares its name', () => {+ // The body part is merged over the path part, so a writable body field that shares a+ // path param's name collapses into one input: the URL and the new value become the same+ // string, and the resource can never be renamed. Renaming must drop only the body copy.+ const config: ToolConfig = {+ operation: 'things_partial_update',+ enabled: true,+ rename_params: { name: 'new_name' },+ }+ const resolved = makeResolved({+ method: 'PATCH',+ path: '/api/projects/{project_id}/things/{name}/',+ operation: {+ operationId: 'things_partial_update',+ parameters: [{ name: 'name', in: 'path', required: true, schema: { type: 'string' } }],+ requestBody: {+ content: {+ 'application/json': {+ schema: {+ properties: {+ name: { type: 'string' },+ },+ },+ },+ },+ },+ },+ })++ const composed = composeToolSchema(config, resolved, makeSpec(), stubGetQuerySchema)+ expect(composed.schemaExpr).toContain("ThingsPartialUpdateBody.omit({ 'name': true })")+ expect(composed.schemaExpr).not.toContain("ThingsPartialUpdateParams.omit({ 'name': true })")+ expect(composed.renamedFields).toEqual({ new_name: 'name' })++ const generated = generateToolCode(+ 'things-partial-update',+ config,+ resolved,+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )+ expect(generated.code).toContain('body["name"] = params.new_name')+ expect(generated.code).toContain('String(params.name)')+ })})describe('param_overrides aliases', () => {