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): table certification model and certify/deprecate flow (#69531)

Thiago Salvatore15c837e0ed18
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index f100ae08e8be..435a8e06604a 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -254,6 +254,7 @@ rules:
|SubscriptionDelivery
|Survey
|SurveyResponseArchive
+ |TableCertification
|Tag
|Tagger
|Task
@@ -542,6 +543,7 @@ rules:
|SubscriptionDelivery
|Survey
|SurveyResponseArchive
+ |TableCertification
|Tag
|Tagger
|Task
diff --git a/common/storybook/test-sequencer.js b/common/storybook/test-sequencer.js
index a91cb34e6bf7..c83e1609a986 100644
--- a/common/storybook/test-sequencer.js
+++ b/common/storybook/test-sequencer.js
@@ -100,6 +100,7 @@ function binPackShard(tests, shardCount, shardIndex, timings, browser) {
}
class BalancedSequencer extends Sequencer {
+ /** @returns {import('@jest/test-result').Test[]} */
shard(tests, options) {
const timings = loadTimings()
if (!timings) {
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index d5c2297cb652..cdad75f41996 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -95,6 +95,7 @@ ActivityScope = Literal[
"SignalScoutConfig",
"StreamlitApp",
"Metric",
+ "TableCertification",
]
ChangeAction = Literal[
"changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out", "copied"
diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.py
index 9f7b56ba7afe..9807d9ed94cc 100644
--- a/products/data_catalog/backend/facade/api.py
+++ b/products/data_catalog/backend/facade/api.py
@@ -6,6 +6,13 @@ logic surface and model classes so the isolation boundary stays clean: presentat
into ``logic`` or ``models`` directly.
"""
+from ..logic.certifications import (
+ certifications_for_team,
+ certify,
+ deprecate,
+ propose_certification,
+ revoke_certification,
+)
from ..logic.drift import compute_drift
from ..logic.execution import run_metric
from ..logic.metrics import (
@@ -17,14 +24,20 @@ from ..logic.metrics import (
upsert_metric,
)
from ..logic.validation import validate_metric_definition
-from .models import Metric
+from .models import Metric, TableCertification
__all__ = [
"Metric",
+ "TableCertification",
"approve_metric",
+ "certifications_for_team",
+ "certify",
"compute_drift",
+ "deprecate",
"metrics_for_team",
+ "propose_certification",
"refresh_metric_from_insight",
+ "revoke_certification",
"run_metric",
"soft_delete_metric",
"update_metric",
diff --git a/products/data_catalog/backend/facade/enums.py b/products/data_catalog/backend/facade/enums.py
index 2954602f0096..8db29736062d 100644
--- a/products/data_catalog/backend/facade/enums.py
+++ b/products/data_catalog/backend/facade/enums.py
@@ -32,3 +32,11 @@ class CreatedSource(StrEnum):
USER = "user"
AI_GENERATED = "ai_generated"
+
+
+class CertificationStatus(StrEnum):
+ """Human-vouched trust mark on a warehouse table or view."""
+
+ PROPOSED = "proposed"
+ CERTIFIED = "certified"
+ DEPRECATED = "deprecated"
diff --git a/products/data_catalog/backend/facade/models.py b/products/data_catalog/backend/facade/models.py
index 36600bd1dce0..c2fc05730787 100644
--- a/products/data_catalog/backend/facade/models.py
+++ b/products/data_catalog/backend/facade/models.py
@@ -5,6 +5,6 @@ own presentation layer are allowed to reach the ORM classes, keeping direct mode
the isolation boundary.
"""
-from ..models import Metric
+from ..models import Metric, TableCertification
-__all__ = ["Metric"]
+__all__ = ["Metric", "TableCertification"]
diff --git a/products/data_catalog/backend/logic/certifications.py b/products/data_catalog/backend/logic/certifications.py
new file mode 100644
index 000000000000..18f8a03d3ac9
--- /dev/null
+++ b/products/data_catalog/backend/logic/certifications.py
@@ -0,0 +1,197 @@
+"""Table/view certification lifecycle.
+
+A certification is a human-vouched trust mark on a warehouse table or view. Targets can be addressed
+by id or (for convenience) by name; because ``DataWarehouseTable.name`` is not team-unique (resyncs
+leave newest-wins duplicates), an ambiguous name returns a 409 listing the candidates so the caller
+picks explicitly. Revocation is a hard delete; both are activity-logged.
+"""
+
+from typing import Optional
+from uuid import UUID
+
+from django.db import IntegrityError, transaction
+from django.db.models import QuerySet
+from django.utils import timezone
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.event_usage import report_user_action
+from posthog.models import Team, User
+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+
+from ..facade.enums import CertificationStatus
+from ..models import TableCertification
+from .exceptions import CatalogConflict
+
+_SCOPE = "TableCertification"
+
+
+def _target_name(cert: TableCertification) -> str:
+ if cert.table_id:
+ return cert.table.name if cert.table else ""
+ return cert.saved_query.name if cert.saved_query else ""
+
+
+def _log(user: Optional[User], cert: TableCertification, activity: str, changes: Optional[list[Change]] = None) -> None:
+ log_activity(
+ organization_id=None,
+ team_id=cert.team_id,
+ user=user,
+ was_impersonated=False,
+ item_id=str(cert.id),
+ scope=_SCOPE,
+ activity=activity,
+ detail=Detail(name=_target_name(cert), changes=changes),
+ )
+
+
+def _capture(user: Optional[User], team: Team, event: str, cert: TableCertification) -> None:
+ if user is None:
+ return
+ report_user_action(
+ user=user,
+ event=event,
+ team=team,
+ properties={"certification_id": str(cert.id), "status": cert.status, "target": _target_name(cert)},
+ )
+
+
+def _duplicate_target_conflict(certification: TableCertification) -> CatalogConflict:
+ return CatalogConflict(detail={"error": f"This target is already marked '{certification.status}'."})
+
+
+def _resolve_table(team: Team, table_id: str | UUID | None, table_name: str | None) -> DataWarehouseTable:
+ # queryable() drops soft-deleted tables and those orphaned by a soft-deleted source.
+ live = DataWarehouseTable.objects.queryable().filter(team_id=team.id)
+ if table_id:
+ table = live.filter(id=table_id).first()
+ if table is None:
+ raise ValidationError({"table_id": "Table not found."})
+ return table
+ matches = list(live.filter(name=table_name))
+ if not matches:
+ raise ValidationError({"table_name": f"No table named '{table_name}'."})
+ if len(matches) > 1:
+ raise CatalogConflict(
+ detail={
+ "error": f"Multiple tables named '{table_name}'. Pass table_id to disambiguate.",
+ "candidates": [{"id": str(t.id), "created_at": t.created_at.isoformat()} for t in matches],
+ }
+ )
+ return matches[0]
+
+
+def _resolve_saved_query(
+ team: Team, saved_query_id: str | UUID | None, view_name: str | None
+) -> DataWarehouseSavedQuery:
+ live = DataWarehouseSavedQuery.objects.filter(team_id=team.id, deleted=False)
+ if saved_query_id:
+ saved_query = live.filter(id=saved_query_id).first()
+ if saved_query is None:
+ raise ValidationError({"saved_query_id": "View not found."})
+ return saved_query
+ matches = list(live.filter(name=view_name))
+ if not matches:
+ raise ValidationError({"view_name": f"No view named '{view_name}'."})
+ if len(matches) > 1:
+ raise CatalogConflict(
+ detail={
+ "error": f"Multiple views named '{view_name}'. Pass saved_query_id to disambiguate.",
+ "candidates": [{"id": str(v.id), "created_at": v.created_at.isoformat()} for v in matches],
+ }
+ )
+ return matches[0]
+
+
+def propose_certification(
+ *,
+ team: Team,
+ user: Optional[User],
+ table_id: str | UUID | None = None,
+ saved_query_id: str | UUID | None = None,
+ table_name: str | None = None,
+ view_name: str | None = None,
+ notes: str = "",
+) -> TableCertification:
+ selectors = {
+ "table_id": table_id,
+ "saved_query_id": saved_query_id,
+ "table_name": table_name,
+ "view_name": view_name,
+ }
+ if sum(value is not None for value in selectors.values()) != 1:
+ raise ValidationError({"target": "Provide exactly one of table_id, saved_query_id, table_name, or view_name."})
+
+ target_table = target_saved_query = None
+ if table_id is not None or table_name is not None:
+ target_table = _resolve_table(team, table_id, table_name)
+ else:
+ target_saved_query = _resolve_saved_query(team, saved_query_id, view_name)
+
+ certifications = TableCertification.objects.for_team(team.id, canonical=True)
+ existing = certifications.filter(table=target_table, saved_query=target_saved_query).first()
+ if existing is not None:
+ raise _duplicate_target_conflict(existing)
+
+ try:
+ with transaction.atomic():
+ cert = certifications.create(
+ team=team,
+ table=target_table,
+ saved_query=target_saved_query,
+ notes=notes,
+ created_by=user,
+ )
+ except IntegrityError:
+ existing = certifications.filter(table=target_table, saved_query=target_saved_query).first()
+ if existing is None:
+ raise
+ raise _duplicate_target_conflict(existing)
+
+ _log(user, cert, "created")
+ _capture(user, team, "data catalog certification proposed", cert)
+ return cert
+
+
+def certify(cert: TableCertification, user: Optional[User]) -> TableCertification:
+ return _set_status(cert, user, CertificationStatus.CERTIFIED, "data catalog certification certified")
+
+
+def deprecate(cert: TableCertification, user: Optional[User]) -> TableCertification:
+ return _set_status(cert, user, CertificationStatus.DEPRECATED, "data catalog certification deprecated")
+
+
+def _set_status(
+ cert: TableCertification, user: Optional[User], status: CertificationStatus, event: str
+) -> TableCertification:
+ if cert.status == status:
+ return cert
+ previous = cert.status
+ cert.status = status
+ cert.certified_by = user
+ cert.certified_at = timezone.now()
+ cert.save()
+ _log(user, cert, "updated", [Change(type=_SCOPE, field="status", before=previous, after=status, action="changed")])
+ _capture(user, cert.team, event, cert)
+ return cert
+
+
+def revoke_certification(cert: TableCertification, user: Optional[User]) -> None:
+ _log(user, cert, "deleted")
+ _capture(user, cert.team, "data catalog certification revoked", cert)
+ cert.delete()
+
+
+def certifications_for_team(team: Team) -> QuerySet[TableCertification]:
+ """Certifications whose target is not soft-deleted, newest first."""
+ return (
+ TableCertification.objects.for_team(team.id, canonical=True)
+ .exclude(table__deleted=True)
+ .exclude(table__external_data_source__deleted=True)
+ .exclude(saved_query__deleted=True)
+ .select_related("table", "saved_query", "certified_by")
+ .order_by("-created_at")
+ )
diff --git a/products/data_catalog/backend/logic/exceptions.py b/products/data_catalog/backend/logic/exceptions.py
index 21d83e180754..c1ded9c761e2 100644
--- a/products/data_catalog/backend/logic/exceptions.py
+++ b/products/data_catalog/backend/logic/exceptions.py
@@ -27,3 +27,11 @@ class MetricHasNoDefinition(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = "This metric has no definition to run. It is name and description only."
default_code = "metric_has_no_definition"
+
+
+class CatalogConflict(APIException):
+ """A 409 for catalog conflicts (duplicate certification, ambiguous table name, existing proposal)."""
+
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = "This catalog entry conflicts with an existing one."
+ default_code = "catalog_conflict"
diff --git a/products/data_catalog/backend/migrations/0002_tablecertification.py b/products/data_catalog/backend/migrations/0002_tablecertification.py
new file mode 100644
index 000000000000..f63c7b87792a
--- /dev/null
+++ b/products/data_catalog/backend/migrations/0002_tablecertification.py
@@ -0,0 +1,125 @@
+# Generated by Django 5.2.14 on 2026-07-13 19:21
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+import products.data_catalog.backend.facade.enums
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_catalog", "0001_initial"),
+ ("data_modeling", "0028_alter_datawarehousemanagedviewset_kind"),
+ ("posthog", "1252_datadeletionrequest_property_removal_marker"),
+ ("warehouse_sources", "0068_backfill_direct_query_enabled_false"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TableCertification",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[("proposed", "proposed"), ("certified", "certified"), ("deprecated", "deprecated")],
+ default=products.data_catalog.backend.facade.enums.CertificationStatus["PROPOSED"],
+ help_text="proposed, certified (prefer this source), or deprecated (avoid this source).",
+ max_length=32,
+ ),
+ ),
+ (
+ "notes",
+ models.TextField(
+ blank=True, help_text="Why this mark exists, e.g. 'canonical MRR source, refreshed daily'."
+ ),
+ ),
+ ("certified_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "certified_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "saved_query",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ help_text="The warehouse view this mark applies to (XOR table).",
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="data_modeling.datawarehousesavedquery",
+ ),
+ ),
+ (
+ "table",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ help_text="The warehouse table this mark applies to (XOR saved_query).",
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="warehouse_sources.datawarehousetable",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"
+ ),
+ ),
+ ],
+ options={
+ "indexes": [models.Index(fields=["team", "status"], name="data_catalo_team_id_3f966c_idx")],
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(
+ models.Q(("saved_query__isnull", True), ("table__isnull", False)),
+ models.Q(("saved_query__isnull", False), ("table__isnull", True)),
+ _connector="OR",
+ ),
+ name="certification_exactly_one_target",
+ ),
+ models.UniqueConstraint(
+ condition=models.Q(("table__isnull", False)),
+ fields=("team", "table"),
+ name="unique_certification_per_table",
+ ),
+ models.UniqueConstraint(
+ condition=models.Q(("saved_query__isnull", False)),
+ fields=("team", "saved_query"),
+ name="unique_certification_per_saved_query",
+ ),
+ ],
+ },
+ ),
+ ]
diff --git a/products/data_catalog/backend/migrations/max_migration.txt b/products/data_catalog/backend/migrations/max_migration.txt
index cbab66dde92a..d8565958bfee 100644
--- a/products/data_catalog/backend/migrations/max_migration.txt
+++ b/products/data_catalog/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0002_tablecertification
diff --git a/products/data_catalog/backend/models/__init__.py b/products/data_catalog/backend/models/__init__.py
index 68a587d6acdb..2d794843d447 100644
--- a/products/data_catalog/backend/models/__init__.py
+++ b/products/data_catalog/backend/models/__init__.py
@@ -1,3 +1,4 @@
+from .certification import TableCertification
from .metric import METRIC_NAME_REGEX, Metric
-__all__ = ["METRIC_NAME_REGEX", "Metric"]
+__all__ = ["METRIC_NAME_REGEX", "Metric", "TableCertification"]
diff --git a/products/data_catalog/backend/models/certification.py b/products/data_catalog/backend/models/certification.py
new file mode 100644
index 000000000000..ed22e5114151
--- /dev/null
+++ b/products/data_catalog/backend/models/certification.py
@@ -0,0 +1,88 @@
+from django.db import models
+
+from posthog.models.scoping.manager import TeamScopedManager
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+
+from ..facade.enums import CertificationStatus
+
+
+class TableCertification(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
+ """A human-vouched trust mark on a warehouse table or view.
+
+ Exactly one target (table XOR saved_query). Revocation is a hard delete (activity-logged in the
+ logic layer), so there is no soft-delete here; when the target itself soft-deletes, the loader and
+ API reads exclude the row rather than cascading.
+ """
+
+ objects = TeamScopedManager()
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ )
+ table = models.ForeignKey(
+ "warehouse_sources.DataWarehouseTable",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ help_text="The warehouse table this mark applies to (XOR saved_query).",
+ )
+ saved_query = models.ForeignKey(
+ "data_modeling.DataWarehouseSavedQuery",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ help_text="The warehouse view this mark applies to (XOR table).",
+ )
+
+ status = models.CharField(
+ max_length=32,
+ choices=[(s.value, s.value) for s in CertificationStatus],
+ default=CertificationStatus.PROPOSED,
+ help_text="proposed, certified (prefer this source), or deprecated (avoid this source).",
+ )
+ notes = models.TextField(
+ blank=True, help_text="Why this mark exists, e.g. 'canonical MRR source, refreshed daily'."
+ )
+ certified_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ )
+ certified_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta:
+ constraints = [
+ models.CheckConstraint(
+ check=(
+ models.Q(table__isnull=False, saved_query__isnull=True)
+ | models.Q(table__isnull=True, saved_query__isnull=False)
+ ),
+ name="certification_exactly_one_target",
+ ),
+ models.UniqueConstraint(
+ fields=["team", "table"],
+ condition=models.Q(table__isnull=False),
+ name="unique_certification_per_table",
+ ),
+ models.UniqueConstraint(
+ fields=["team", "saved_query"],
+ condition=models.Q(saved_query__isnull=False),
+ name="unique_certification_per_saved_query",
+ ),
+ ]
+ indexes = [models.Index(fields=["team", "status"])]
+
+ def __str__(self) -> str:
+ return f"{self.status} certification"
diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.py
index db1b59ef7e6b..4b15be07f9c0 100644
--- a/products/data_catalog/backend/presentation/serializers.py
+++ b/products/data_catalog/backend/presentation/serializers.py
@@ -14,7 +14,7 @@ from posthog.schema_enums import IntervalType
from ..facade import api
from ..facade.enums import CreatedSource
-from ..facade.models import Metric
+from ..facade.models import Metric, TableCertification
@extend_schema_field(OpenApiTypes.OBJECT)
@@ -177,3 +177,62 @@ class MetricSerializer(serializers.ModelSerializer):
if drift_map is not None and obj.id in drift_map:
return drift_map[obj.id]
return api.compute_drift([obj])[obj.id]
+
+
+@extend_schema_serializer(component_name="DataCatalogCertification")
+class CertificationSerializer(serializers.ModelSerializer):
+ status = serializers.CharField(
+ read_only=True, help_text="proposed, certified (prefer this source), or deprecated (avoid this source)."
+ )
+ target_type = serializers.SerializerMethodField(help_text="Whether the marked target is a 'table' or a 'view'.")
+ target_name = serializers.SerializerMethodField(help_text="Name of the marked table or view.")
+ certified_by = UserBasicSerializer(
+ read_only=True, allow_null=True, help_text="User who last set certified/deprecated, or null."
+ )
+
+ class Meta:
+ model = TableCertification
+ fields = [
+ "id",
+ "table",
+ "saved_query",
+ "target_type",
+ "target_name",
+ "status",
+ "notes",
+ "certified_by",
+ "certified_at",
+ "created_by",
+ "created_at",
+ ]
+ read_only_fields = [
+ "id",
+ "table",
+ "saved_query",
+ "status",
+ "certified_by",
+ "certified_at",
+ "created_by",
+ "created_at",
+ ]
+ extra_kwargs = {"notes": {"help_text": "Why this mark exists, e.g. 'canonical MRR source'."}}
+
+ @extend_schema_field(OpenApiTypes.STR)
+ def get_target_type(self, obj: TableCertification) -> str:
+ return "table" if obj.table_id else "view"
+
+ @extend_schema_field(OpenApiTypes.STR)
+ def get_target_name(self, obj: TableCertification) -> str:
+ if obj.table_id:
+ return obj.table.name if obj.table else ""
+ return obj.saved_query.name if obj.saved_query else ""
+
+
+class CertificationCreateSerializer(serializers.Serializer):
+ """Input for proposing a certification: address the target by id or (convenience) by name."""
+
+ table_id = serializers.UUIDField(required=False, help_text="Warehouse table id to certify (XOR the other targets).")
+ saved_query_id = serializers.UUIDField(required=False, help_text="Warehouse view (saved query) id to certify.")
+ table_name = serializers.CharField(required=False, help_text="Table name; 409 with candidates if ambiguous.")
+ view_name = serializers.CharField(required=False, help_text="View name; 409 with candidates if ambiguous.")
+ notes = serializers.CharField(required=False, allow_blank=True, help_text="Why this mark exists.")
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index 64015bf0192f..82fca7c2be88 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -9,7 +9,7 @@ from typing import cast
from django.db.models import QuerySet
from drf_spectacular.utils import OpenApiResponse, extend_schema
-from rest_framework import status, viewsets
+from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action as drf_action
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.request import Request
@@ -25,8 +25,10 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedR
from ..facade import api
from ..facade.enums import HOGQL_DEFINITION_KIND, INSIGHT_DEFINITION_KINDS, NODE_DEFINITION_KINDS
-from ..facade.models import Metric
+from ..facade.models import Metric, TableCertification
from .serializers import (
+ CertificationCreateSerializer,
+ CertificationSerializer,
MetricRunQuerySerializer,
MetricRunRequestSerializer,
MetricRunResponseSerializer,
@@ -196,3 +198,60 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
query_id=overrides.get("query_id"),
)
return Response(envelope)
+
+
+class CertificationViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.CreateModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.DestroyModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Trust marks on warehouse tables and views. Reads exclude soft-deleted targets."""
+
+ scope_object = "data_catalog"
+ serializer_class = CertificationSerializer
+ queryset = TableCertification.objects.unscoped()
+
+ def safely_get_queryset(self, queryset: QuerySet[TableCertification]) -> QuerySet[TableCertification]:
+ return api.certifications_for_team(self.team)
+
+ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:
+ if getattr(view, "action", None) == "destroy":
+ return ["data_catalog_approval:write", "data_catalog:read"]
+ return None
+
+ @extend_schema(request=CertificationCreateSerializer, responses={201: CertificationSerializer})
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ serializer = CertificationCreateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ cert = api.propose_certification(team=self.team, user=cast(User, request.user), **serializer.validated_data)
+ return Response(CertificationSerializer(cert).data, status=status.HTTP_201_CREATED)
+
+ def perform_destroy(self, instance: TableCertification) -> None:
+ api.revoke_certification(instance, cast(User, self.request.user))
+
+ @action(
+ detail=True,
+ methods=["POST"],
+ required_scopes=["data_catalog_approval:write", "data_catalog:read"],
+ request=None,
+ responses={200: CertificationSerializer},
+ )
+ def certify(self, request: Request, **kwargs) -> Response:
+ """Mark the target as certified (prefer this source)."""
+ cert = api.certify(self.get_object(), cast(User, request.user))
+ return Response(CertificationSerializer(cert).data)
+
+ @action(
+ detail=True,
+ methods=["POST"],
+ required_scopes=["data_catalog_approval:write", "data_catalog:read"],
+ request=None,
+ responses={200: CertificationSerializer},
+ )
+ def deprecate(self, request: Request, **kwargs) -> Response:
+ """Mark the target as deprecated (avoid this source)."""
+ cert = api.deprecate(self.get_object(), cast(User, request.user))
+ return Response(CertificationSerializer(cert).data)
diff --git a/products/data_catalog/backend/routes.py b/products/data_catalog/backend/routes.py
index 424ea64c4dfc..0025b81dd413 100644
--- a/products/data_catalog/backend/routes.py
+++ b/products/data_catalog/backend/routes.py
@@ -1,7 +1,13 @@
from posthog.api.routing import RouterRegistry
-from products.data_catalog.backend.presentation.views import MetricViewSet
+from products.data_catalog.backend.presentation.views import CertificationViewSet, MetricViewSet
def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(r"data_catalog/metrics", MetricViewSet, "environment_data_catalog_metrics", ["team_id"])
+ routers.projects.register(
+ r"data_catalog/certifications",
+ CertificationViewSet,
+ "environment_data_catalog_certifications",
+ ["team_id"],
+ )
diff --git a/products/data_catalog/backend/tests/test_certifications.py b/products/data_catalog/backend/tests/test_certifications.py
new file mode 100644
index 000000000000..b5e772be9009
--- /dev/null
+++ b/products/data_catalog/backend/tests/test_certifications.py
@@ -0,0 +1,317 @@
+from posthog.test.base import APIBaseTest, BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.db import IntegrityError, transaction
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.exceptions import ValidationError
+
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team import Team
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.data_catalog.backend.facade.enums import CertificationStatus
+from products.data_catalog.backend.logic.certifications import (
+ certifications_for_team,
+ certify,
+ deprecate,
+ propose_certification,
+ revoke_certification,
+)
+from products.data_catalog.backend.logic.exceptions import CatalogConflict
+from products.data_catalog.backend.models import TableCertification
+from products.data_catalog.backend.presentation.serializers import (
+ CertificationCreateSerializer,
+ CertificationSerializer,
+)
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
+
+
+def _table(
+ team: Team,
+ name: str = "stripe_customers",
+ external_data_source: ExternalDataSource | None = None,
+) -> DataWarehouseTable:
+ return DataWarehouseTable.objects.create(
+ name=name,
+ format="Parquet",
+ team=team,
+ url_pattern="s3://bucket/x",
+ external_data_source=external_data_source,
+ )
+
+
+def _view(team: Team, name: str = "revenue_view") -> DataWarehouseSavedQuery:
+ return DataWarehouseSavedQuery.objects.create(team=team, name=name, query={"kind": "HogQLQuery"})
+
+
+class TestTableCertificationModel(BaseTest):
+ def test_requires_exactly_one_target(self) -> None:
+ table = _table(self.team)
+ view = DataWarehouseSavedQuery.objects.create(team=self.team, name="v", query={"kind": "HogQLQuery"})
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ TableCertification.objects.for_team(self.team.id).create(team=self.team, table=table, saved_query=view)
+
+ def test_requires_at_least_one_target(self) -> None:
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ TableCertification.objects.for_team(self.team.id).create(team=self.team)
+
+ @parameterized.expand([("table",), ("view",)])
+ def test_one_certification_per_target(self, target_type: str) -> None:
+ target = _table(self.team) if target_type == "table" else _view(self.team)
+ target_fields = {"table": target} if target_type == "table" else {"saved_query": target}
+ TableCertification.objects.for_team(self.team.id).create(team=self.team, **target_fields)
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ TableCertification.objects.for_team(self.team.id).create(team=self.team, **target_fields)
+
+
+class TestCertificationLogic(BaseTest):
+ @parameterized.expand(
+ [("table_id", "table"), ("table_name", "table"), ("saved_query_id", "view"), ("view_name", "view")]
+ )
+ def test_propose_by_selector(self, selector: str, target_type: str) -> None:
+ target = _table(self.team) if target_type == "table" else _view(self.team)
+ selector_value = str(target.id) if selector.endswith("_id") else target.name
+
+ certification = propose_certification(team=self.team, user=self.user, **{selector: selector_value})
+
+ assert certification.status == CertificationStatus.PROPOSED
+ assert certification.created_by_id == self.user.id
+ assert certification.table_id == (target.id if target_type == "table" else None)
+ assert certification.saved_query_id == (target.id if target_type == "view" else None)
+
+ def test_ambiguous_table_name_returns_candidates(self) -> None:
+ _table(self.team, name="dupe")
+ _table(self.team, name="dupe")
+ with self.assertRaises(CatalogConflict):
+ propose_certification(team=self.team, user=self.user, table_name="dupe")
+
+ @parameterized.expand([("table_id", "table"), ("saved_query_id", "view")])
+ def test_duplicate_target_conflicts(self, selector: str, target_type: str) -> None:
+ target = _table(self.team) if target_type == "table" else _view(self.team)
+ target_selector = {selector: str(target.id)}
+ propose_certification(team=self.team, user=self.user, **target_selector)
+ with self.assertRaises(CatalogConflict):
+ propose_certification(team=self.team, user=self.user, **target_selector)
+
+ @parameterized.expand(
+ [
+ ("table_id", "saved_query_id"),
+ ("table_id", "table_name"),
+ ("table_id", "view_name"),
+ ("saved_query_id", "table_name"),
+ ("saved_query_id", "view_name"),
+ ("table_name", "view_name"),
+ ]
+ )
+ def test_rejects_mixed_selectors(self, first_selector: str, second_selector: str) -> None:
+ table = _table(self.team)
+ view = _view(self.team)
+ selector_values = {
+ "table_id": str(table.id),
+ "saved_query_id": str(view.id),
+ "table_name": table.name,
+ "view_name": view.name,
+ }
+
+ with self.assertRaisesMessage(ValidationError, "exactly one"):
+ propose_certification(
+ team=self.team,
+ user=self.user,
+ **{first_selector: selector_values[first_selector], second_selector: selector_values[second_selector]},
+ )
+
+ def test_concurrent_duplicate_conflicts(self) -> None:
+ table = _table(self.team)
+ winning_certification = TableCertification(team=self.team, table=table)
+ certification_queryset = MagicMock()
+ certification_queryset.filter.return_value.first.side_effect = [None, winning_certification]
+ certification_queryset.create.side_effect = IntegrityError
+
+ with (
+ patch.object(TableCertification.objects, "for_team", return_value=certification_queryset),
+ self.assertRaises(CatalogConflict),
+ ):
+ propose_certification(team=self.team, user=self.user, table_id=str(table.id))
+
+ def test_certify_and_deprecate_set_status_and_are_idempotent(self) -> None:
+ table = _table(self.team)
+ cert = propose_certification(team=self.team, user=self.user, table_id=str(table.id))
+
+ certified = certify(cert, self.user)
+ assert certified.status == CertificationStatus.CERTIFIED
+ assert certified.certified_by_id == self.user.id
+ assert certify(cert, self.user).status == CertificationStatus.CERTIFIED
+
+ assert deprecate(cert, self.user).status == CertificationStatus.DEPRECATED
+
+ def test_revoke_hard_deletes(self) -> None:
+ table = _table(self.team)
+ cert = propose_certification(team=self.team, user=self.user, table_id=str(table.id))
+ revoke_certification(cert, self.user)
+ assert not TableCertification.objects.for_team(self.team.id).filter(pk=cert.pk).exists()
+
+ @parameterized.expand([("table",), ("view",), ("external_source",)])
+ def test_soft_deleted_target_excluded(self, target_type: str) -> None:
+ source = None
+ if target_type == "external_source":
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="stripe",
+ connection_id="stripe",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type="Stripe",
+ )
+ target = _view(self.team) if target_type == "view" else _table(self.team, external_data_source=source)
+ selector = "saved_query_id" if target_type == "view" else "table_id"
+ propose_certification(team=self.team, user=self.user, **{selector: str(target.id)})
+ assert certifications_for_team(self.team).count() == 1
+
+ deleted_object = source or target
+ deleted_object.deleted = True
+ deleted_object.save()
+
+ assert certifications_for_team(self.team).count() == 0
+
+ def test_serializes_mixed_certifications_in_one_query(self) -> None:
+ table_certification = propose_certification(team=self.team, user=self.user, table_id=str(_table(self.team).id))
+ certify(table_certification, self.user)
+ propose_certification(team=self.team, user=self.user, saved_query_id=str(_view(self.team).id))
+
+ with self.assertNumQueries(1):
+ serialized = CertificationSerializer(certifications_for_team(self.team), many=True).data
+
+ assert {certification["target_type"] for certification in serialized} == {"table", "view"}
+ assert any(certification["certified_by"] is None for certification in serialized)
+
+ def test_proposal_stays_in_the_requested_environment(self) -> None:
+ child_team = Team.objects.create(
+ organization=self.organization,
+ project=self.project,
+ parent_team=self.team,
+ name="Child environment",
+ )
+ table = _table(child_team)
+
+ certification = propose_certification(team=child_team, user=self.user, table_id=str(table.id))
+
+ assert certification.team_id == child_team.id
+ assert certifications_for_team(child_team).get() == certification
+ assert not certifications_for_team(self.team).exists()
+
+ def test_certifications_are_isolated_between_project_environments(self) -> None:
+ child_team = Team.objects.create(
+ organization=self.organization,
+ project=self.project,
+ parent_team=self.team,
+ name="Child environment",
+ )
+ parent_certification = propose_certification(
+ team=self.team,
+ user=self.user,
+ table_id=str(_table(self.team, name="parent_table").id),
+ )
+ child_certification = propose_certification(
+ team=child_team,
+ user=self.user,
+ table_id=str(_table(child_team, name="child_table").id),
+ )
+
+ assert list(certifications_for_team(self.team)) == [parent_certification]
+ assert list(certifications_for_team(child_team)) == [child_certification]
+
+
+class TestCertificationAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.url = f"/api/projects/{self.team.id}/data_catalog/certifications/"
+
+ def test_create_and_certify(self) -> None:
+ table = _table(self.team)
+ created = self.client.post(self.url, {"table_id": str(table.id)}, format="json")
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ cert_id = created.json()["id"]
+
+ certified = self.client.post(f"{self.url}{cert_id}/certify/")
+ assert certified.status_code == status.HTTP_200_OK
+ assert certified.json()["status"] == CertificationStatus.CERTIFIED
+
+ def test_certify_requires_approval_scope(self) -> None:
+ table = _table(self.team)
+ cert = propose_certification(team=self.team, user=self.user, table_id=str(table.id))
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="k",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=["data_catalog:read", "data_catalog:write"],
+ )
+ self.client.logout()
+ response = self.client.post(f"{self.url}{cert.id}/certify/", HTTP_AUTHORIZATION=f"Bearer {raw}")
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_revoke_requires_approval_scope(self) -> None:
+ table = _table(self.team)
+ cert = propose_certification(team=self.team, user=self.user, table_id=str(table.id))
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="k",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=["data_catalog:read", "data_catalog:write"],
+ )
+ self.client.logout()
+
+ response = self.client.delete(f"{self.url}{cert.id}/", HTTP_AUTHORIZATION=f"Bearer {raw}")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert TableCertification.objects.for_team(self.team.id).filter(id=cert.id).exists()
+
+ @parameterized.expand([("certify",), ("deprecate",), ("destroy",)])
+ def test_approval_actions_require_base_catalog_scope(self, act: str) -> None:
+ # data_catalog_approval:write alone must not grant access without base catalog read —
+ # required_scopes replaces the viewset default, so the base scope has to be listed too.
+ table = _table(self.team)
+ cert = propose_certification(team=self.team, user=self.user, table_id=str(table.id))
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="k",
+ user=self.user,
+ secure_value=hash_key_value(raw),
+ scopes=["data_catalog_approval:write"],
+ )
+ self.client.logout()
+
+ if act == "destroy":
+ response = self.client.delete(f"{self.url}{cert.id}/", HTTP_AUTHORIZATION=f"Bearer {raw}")
+ else:
+ response = self.client.post(f"{self.url}{cert.id}/{act}/", HTTP_AUTHORIZATION=f"Bearer {raw}")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ @parameterized.expand([("put",), ("patch",)])
+ def test_update_methods_not_allowed(self, method: str) -> None:
+ table = _table(self.team)
+ cert = propose_certification(team=self.team, user=self.user, table_id=str(table.id), notes="original")
+
+ response = getattr(self.client, method)(f"{self.url}{cert.id}/", {"notes": "changed"}, format="json")
+
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+ cert.refresh_from_db()
+ assert cert.notes == "original"
+
+ def test_rejects_malformed_uuid(self) -> None:
+ response = self.client.post(self.url, {"table_id": "not-a-uuid"}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "table_id"
+
+
+class TestCertificationInputValidation(SimpleTestCase):
+ @parameterized.expand([("table_id",), ("saved_query_id",)])
+ def test_rejects_malformed_uuid(self, field: str) -> None:
+ serializer = CertificationCreateSerializer(data={field: "not-a-uuid"})
+ assert not serializer.is_valid()
+ assert field in serializer.errors
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index d7c02e418106..983d9fff4eb8 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -62,6 +62,60 @@ export interface UserBasicApi {
role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
}
+export interface DataCatalogCertificationApi {
+ readonly id: string
+ /**
+ * The warehouse table this mark applies to (XOR saved_query).
+ * @nullable
+ */
+ readonly table: string | null
+ /**
+ * The warehouse view this mark applies to (XOR table).
+ * @nullable
+ */
+ readonly saved_query: string | null
+ /** Whether the marked target is a 'table' or a 'view'. */
+ readonly target_type: string
+ /** Name of the marked table or view. */
+ readonly target_name: string
+ /** proposed, certified (prefer this source), or deprecated (avoid this source). */
+ readonly status: string
+ /** Why this mark exists, e.g. 'canonical MRR source'. */
+ notes?: string
+ /** User who last set certified/deprecated, or null. */
+ readonly certified_by: UserBasicApi | null
+ /** @nullable */
+ readonly certified_at: string | null
+ /** @nullable */
+ readonly created_by: number | null
+ readonly created_at: string
+}
+
+export interface PaginatedDataCatalogCertificationListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: DataCatalogCertificationApi[]
+}
+
+/**
+ * Input for proposing a certification: address the target by id or (convenience) by name.
+ */
+export interface CertificationCreateApi {
+ /** Warehouse table id to certify (XOR the other targets). */
+ table_id?: string
+ /** Warehouse view (saved query) id to certify. */
+ saved_query_id?: string
+ /** Table name; 409 with candidates if ambiguous. */
+ table_name?: string
+ /** View name; 409 with candidates if ambiguous. */
+ view_name?: string
+ /** Why this mark exists. */
+ notes?: string
+}
+
/**
* * `user` - user
* * `ai_generated` - ai_generated
@@ -340,6 +394,17 @@ export interface DataCatalogMetricRunApi {
instructions: string | null
}
+export type DataCatalogCertificationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type DataCatalogMetricsListParams = {
/**
* Number of results to return per page.
diff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.ts
index 35b20eeb96c3..99cdb97c3e79 100644
--- a/products/data_catalog/frontend/generated/api.ts
+++ b/products/data_catalog/frontend/generated/api.ts
@@ -9,11 +9,15 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ CertificationCreateApi,
+ DataCatalogCertificationApi,
+ DataCatalogCertificationsListParams,
DataCatalogMetricApi,
DataCatalogMetricRunApi,
DataCatalogMetricRunRequestApi,
DataCatalogMetricsListParams,
DataCatalogMetricsRunCreateParams,
+ PaginatedDataCatalogCertificationListApi,
PaginatedDataCatalogMetricListApi,
PatchedDataCatalogMetricApi,
} from './api.schemas'
@@ -35,6 +39,134 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getDataCatalogCertificationsListUrl = (
+ projectId: string,
+ params?: DataCatalogCertificationsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/data_catalog/certifications/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_catalog/certifications/`
+}
+
+/**
+ * Trust marks on warehouse tables and views. Reads exclude soft-deleted targets.
+ */
+export const dataCatalogCertificationsList = async (
+ projectId: string,
+ params?: DataCatalogCertificationsListParams,
+ options?: RequestInit
+): Promise<PaginatedDataCatalogCertificationListApi> => {
+ return apiMutator<PaginatedDataCatalogCertificationListApi>(
+ getDataCatalogCertificationsListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDataCatalogCertificationsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_catalog/certifications/`
+}
+
+/**
+ * Trust marks on warehouse tables and views. Reads exclude soft-deleted targets.
+ */
+export const dataCatalogCertificationsCreate = async (
+ projectId: string,
+ certificationCreateApi?: CertificationCreateApi,
+ options?: RequestInit
+): Promise<DataCatalogCertificationApi> => {
+ return apiMutator<DataCatalogCertificationApi>(getDataCatalogCertificationsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(certificationCreateApi),
+ })
+}
+
+export const getDataCatalogCertificationsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_catalog/certifications/${id}/`
+}
+
+/**
+ * Trust marks on warehouse tables and views. Reads exclude soft-deleted targets.
+ */
+export const dataCatalogCertificationsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DataCatalogCertificationApi> => {
+ return apiMutator<DataCatalogCertificationApi>(getDataCatalogCertificationsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getDataCatalogCertificationsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_catalog/certifications/${id}/`
+}
+
+/**
+ * Trust marks on warehouse tables and views. Reads exclude soft-deleted targets.
+ */
+export const dataCatalogCertificationsDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getDataCatalogCertificationsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getDataCatalogCertificationsCertifyCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_catalog/certifications/${id}/certify/`
+}
+
+/**
+ * Mark the target as certified (prefer this source).
+ */
+export const dataCatalogCertificationsCertifyCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DataCatalogCertificationApi> => {
+ return apiMutator<DataCatalogCertificationApi>(getDataCatalogCertificationsCertifyCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getDataCatalogCertificationsDeprecateCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/data_catalog/certifications/${id}/deprecate/`
+}
+
+/**
+ * Mark the target as deprecated (avoid this source).
+ */
+export const dataCatalogCertificationsDeprecateCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DataCatalogCertificationApi> => {
+ return apiMutator<DataCatalogCertificationApi>(getDataCatalogCertificationsDeprecateCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getDataCatalogMetricsListUrl = (projectId: string, params?: DataCatalogMetricsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.ts
index 819028071943..38b1b8222f84 100644
--- a/products/data_catalog/frontend/generated/api.zod.ts
+++ b/products/data_catalog/frontend/generated/api.zod.ts
@@ -9,6 +9,19 @@
*/
import * as zod from 'zod'
+/**
+ * Trust marks on warehouse tables and views. Reads exclude soft-deleted targets.
+ */
+export const DataCatalogCertificationsCreateBody = /* @__PURE__ */ zod
+ .object({
+ table_id: zod.uuid().optional().describe('Warehouse table id to certify (XOR the other targets).'),
+ saved_query_id: zod.uuid().optional().describe('Warehouse view (saved query) id to certify.'),
+ table_name: zod.string().optional().describe('Table name; 409 with candidates if ambiguous.'),
+ view_name: zod.string().optional().describe('View name; 409 with candidates if ambiguous.'),
+ notes: zod.string().optional().describe('Why this mark exists.'),
+ })
+ .describe('Input for proposing a certification: address the target by id or (convenience) by name.')
+
/**
* Create a metric, or refine the one already holding this name for the team.
*/
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index d6e0ceabb6dd..824ce8cb8e26 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -997,6 +997,7 @@ export type ActivityLogListParams = {
* * `SignalScoutConfig` - SignalScoutConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
+ * * `TableCertification` - TableCertification
* @minLength 1
*/
scope?: ActivityLogListScope
@@ -1082,6 +1083,7 @@ export const ActivityLogListScope = {
SignalScoutConfig: 'SignalScoutConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
+ TableCertification: 'TableCertification',
} as const
/**
@@ -1154,6 +1156,7 @@ export const ActivityLogListScope = {
* * `SignalScoutConfig` - SignalScoutConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
+ * * `TableCertification` - TableCertification
*/
export type ActivityLogListScopesItem = (typeof ActivityLogListScopesItem)[keyof typeof ActivityLogListScopesItem]
@@ -1227,6 +1230,7 @@ export const ActivityLogListScopesItem = {
SignalScoutConfig: 'SignalScoutConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
+ TableCertification: 'TableCertification',
} as const
export type AdvancedActivityLogsListParams = {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 24c834ae71b3..72c591b5c64c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12836,6 +12836,22 @@ export namespace Schemas {
Both: 'both',
} as const;
+ /**
+ * Input for proposing a certification: address the target by id or (convenience) by name.
+ */
+ export interface CertificationCreate {
+ /** Warehouse table id to certify (XOR the other targets). */
+ table_id?: string;
+ /** Warehouse view (saved query) id to certify. */
+ saved_query_id?: string;
+ /** Table name; 409 with candidates if ambiguous. */
+ table_name?: string;
+ /** View name; 409 with candidates if ambiguous. */
+ view_name?: string;
+ /** Why this mark exists. */
+ notes?: string;
+ }
+
export type ChangeRequestApprovalsItem = { [key: string]: unknown };
/**
@@ -15550,6 +15566,35 @@ export namespace Schemas {
error: string | null;
}
+ export interface DataCatalogCertification {
+ readonly id: string;
+ /**
+ * The warehouse table this mark applies to (XOR saved_query).
+ * @nullable
+ */
+ readonly table: string | null;
+ /**
+ * The warehouse view this mark applies to (XOR table).
+ * @nullable
+ */
+ readonly saved_query: string | null;
+ /** Whether the marked target is a 'table' or a 'view'. */
+ readonly target_type: string;
+ /** Name of the marked table or view. */
+ readonly target_name: string;
+ /** proposed, certified (prefer this source), or deprecated (avoid this source). */
+ readonly status: string;
+ /** Why this mark exists, e.g. 'canonical MRR source'. */
+ notes?: string;
+ /** User who last set certified/deprecated, or null. */
+ readonly certified_by: UserBasic | null;
+ /** @nullable */
+ readonly certified_at: string | null;
+ /** @nullable */
+ readonly created_by: number | null;
+ readonly created_at: string;
+ }
+
/**
* Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.
* @nullable
@@ -35000,6 +35045,15 @@ export namespace Schemas {
results: DashboardTemplate[];
}
+ export interface PaginatedDataCatalogCertificationList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: DataCatalogCertification[];
+ }
+
export interface PaginatedDataCatalogMetricList {
count: number;
/** @nullable */
@@ -67079,6 +67133,7 @@ export namespace Schemas {
* * `SignalScoutConfig` - SignalScoutConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
+ * * `TableCertification` - TableCertification
* @minLength 1
*/
scope?: ActivityLogListScope;
@@ -67165,6 +67220,7 @@ export namespace Schemas {
SignalScoutConfig: 'SignalScoutConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
+ TableCertification: 'TableCertification',
} as const;
/**
@@ -67237,6 +67293,7 @@ export namespace Schemas {
* * `SignalScoutConfig` - SignalScoutConfig
* * `StreamlitApp` - StreamlitApp
* * `Metric` - Metric
+ * * `TableCertification` - TableCertification
*/
export type ActivityLogListScopesItem = typeof ActivityLogListScopesItem[keyof typeof ActivityLogListScopesItem];
@@ -67311,6 +67368,7 @@ export namespace Schemas {
SignalScoutConfig: 'SignalScoutConfig',
StreamlitApp: 'StreamlitApp',
Metric: 'Metric',
+ TableCertification: 'TableCertification',
} as const;
export type AdvancedActivityLogsListParams = {
@@ -68559,6 +68617,17 @@ export namespace Schemas {
Txt: 'txt',
} as const;
+ export type DataCatalogCertificationsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type DataCatalogMetricsListParams = {
/**
* Number of results to return per page.