: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): scaffold product with metric model and CRUD API (#69527)
Thiago Salvatore449a9ae871e5
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 8ab093dd0016..cc894a1a5ea6 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -191,6 +191,7 @@ rules:|MessageCategory|MessageRecipientPreference|MessageTemplate+ |Metric|MCPAnalyticsSubmission|MCPIntentClusterSnapshot|MCPIntentEmbeddingCache@@ -475,6 +476,7 @@ rules:|MessageCategory|MessageRecipientPreference|MessageTemplate+ |Metric|MCPIntentClusterSnapshot|MCPIntentEmbeddingCache|MCPSessiondiff --git a/frontend/package.json b/frontend/package.jsonindex deb8dd6da6f8..20c422b215ef 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -87,6 +87,7 @@"@posthog/products-conversations": "workspace:*","@posthog/products-customer-analytics": "workspace:*","@posthog/products-dashboards": "workspace:*",+ "@posthog/products-data-catalog": "workspace:*","@posthog/products-data-modeling": "workspace:*","@posthog/products-data-tools": "workspace:*","@posthog/products-data-warehouse": "workspace:*",diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex dce8b1771d20..f1ebaa9ea686 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -56,6 +56,14 @@ export const API_SCOPES: APIScope[] = [},{ key: 'customer_analytics', objectName: 'Customer analytics', objectPlural: 'customer analytics' },{ key: 'customer_journey', objectName: 'Customer journey', objectPlural: 'customer journeys' },+ { key: 'data_catalog', objectName: 'Data catalog', objectPlural: 'data catalog' },+ {+ key: 'data_catalog_approval',+ objectName: 'Data catalog approval',+ objectPlural: 'data catalog approvals',+ info: 'Grants the ability to promote catalog entries (approve a metric, certify a table, accept a relationship). This is the human-in-the-loop trust boundary: agents that can write to the catalog still cannot self-approve without this scope.',+ disabledActions: ['read'],+ },{ key: 'dashboard', objectName: 'Dashboard', objectPlural: 'dashboards' },{ key: 'dashboard_template', objectName: 'Dashboard template', objectPlural: 'dashboard templates' },{ key: 'dataset', objectName: 'Dataset', objectPlural: 'datasets' },diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex a8b21d0f13ae..8a3927325bd0 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5663,6 +5663,8 @@ export type APIScopeObject =| 'customer_analytics'| 'customer_journey'| 'customer_profile_config'+ | 'data_catalog'+ | 'data_catalog_approval'| 'dashboard'| 'dashboard_template'| 'dataset'diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 87bca6bde2d6..ff55359f98c1 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -659,6 +659,9 @@ importers:'@posthog/products-dashboards':specifier: workspace:*version: link:../products/dashboards+ '@posthog/products-data-catalog':+ specifier: workspace:*+ version: link:../products/data_catalog'@posthog/products-data-modeling':specifier: workspace:*version: link:../products/data_modeling@@ -3078,6 +3081,8 @@ importers:specifier: 'catalog:'version: 0.2.4([email protected]([email protected]))+ products/data_catalog: {}+products/data_modeling:dependencies:'@posthog/icons':diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex f9af9ca8fb93..3348e2efbd4b 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -93,6 +93,7 @@ ActivityScope = Literal["SignalReport","SignalScoutConfig","StreamlitApp",+ "Metric",]ChangeAction = Literal["changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out", "copied"@@ -396,6 +397,12 @@ activity_visibility_restrictions: list[dict[str, Any]] = []field_exclusions: dict[AuditableScope, list[str]] = {+ "Metric": [+ # Derived/throttled fields, not user-meaningful change diffs.+ "last_run_at",+ "source_insight_query_hash",+ "referenced_table_names",+ ],"OrganizationDomain": ["organization","scim_provisioned_users",diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 5671a8112a14..2de9db046b7f 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -34,6 +34,8 @@ APIScopeObject = Literal["customer_analytics","customer_journey","customer_profile_config",+ "data_catalog",+ "data_catalog_approval","dashboard","event_filter","dashboard_template",diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 1c626a357ad0..8e4d5ad880ad 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -95,6 +95,7 @@ PRODUCTS_APPS = ["products.growth.backend.apps.GrowthConfig","products.reminders.backend.apps.RemindersConfig","products.approvals.backend.apps.ApprovalsConfig",+ "products.data_catalog.backend.apps.DataCatalogConfig",]INSTALLED_APPS = [diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex ba2a1cfc5bcd..a749139e346c 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -26,6 +26,7 @@ model_activity:products.batch_exports.backend.activity_logging.handle_batch_expomodel_activity:products.business_knowledge.backend.signals.handle_knowledge_source_changemodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_changemodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_widget_change+model_activity:products.data_catalog.backend.activity_logging.handle_metric_activitymodel_activity:products.data_warehouse.backend.activity_logging.handle_external_data_schema_changemodel_activity:products.data_warehouse.backend.activity_logging.handle_external_data_source_changemodel_activity:products.experiments.backend.activity_logging.handle_experiment_changediff --git a/products/data_catalog/__init__.py b/products/data_catalog/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/data_catalog/backend/activity_logging.py b/products/data_catalog/backend/activity_logging.pynew file mode 100644index 000000000000..667c84ed7d9a--- /dev/null+++ b/products/data_catalog/backend/activity_logging.py@@ -0,0 +1,42 @@+"""Activity-log receiver for catalog metrics.++``ModelActivityMixin`` emits ``model_activity_signal`` on every metric save; this persists the audit+trail (create, approve, definition change, soft delete). Registered from ``apps.ready()``.+"""++from typing import Any, Optional, cast++from posthog.models import User+from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from .models import Metric+++@mutable_receiver(model_activity_signal, sender=Metric)+def handle_metric_activity(+ sender: type,+ scope: str,+ before_update: Optional[Metric],+ after_update: Optional[Metric],+ activity: str,+ user: Optional[User],+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance = after_update or before_update+ if instance is None:+ return+ log_activity(+ organization_id=None,+ team_id=instance.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(instance.id),+ scope=scope,+ activity=activity,+ detail=Detail(+ name=instance.name,+ changes=changes_between(cast(AuditableScope, scope), previous=before_update, current=after_update),+ ),+ )diff --git a/products/data_catalog/backend/apps.py b/products/data_catalog/backend/apps.pynew file mode 100644index 000000000000..e6824b076eda--- /dev/null+++ b/products/data_catalog/backend/apps.py@@ -0,0 +1,14 @@+"""Django app configuration for data_catalog."""++from django.apps import AppConfig+++class DataCatalogConfig(AppConfig):+ name = "products.data_catalog.backend"+ label = "data_catalog"+ verbose_name = "Data catalog"++ def ready(self) -> None:+ # noqa: PLC0415 — deferred to app-ready time so importing the signal receiver (which imports+ # models) doesn't run during django.setup().+ from . import activity_logging # noqa: F401, PLC0415diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.pynew file mode 100644index 000000000000..00ba583e291d--- /dev/null+++ b/products/data_catalog/backend/facade/api.py@@ -0,0 +1,20 @@+"""+Facade for data_catalog.++The only module this product's presentation layer (and external code) may import. It re-exports the+logic surface and model classes so the isolation boundary stays clean: presentation never reaches+into ``logic`` or ``models`` directly.+"""++from ..logic.metrics import metrics_for_team, soft_delete_metric, update_metric, upsert_metric+from ..logic.validation import validate_metric_definition+from .models import Metric++__all__ = [+ "Metric",+ "metrics_for_team",+ "soft_delete_metric",+ "update_metric",+ "upsert_metric",+ "validate_metric_definition",+]diff --git a/products/data_catalog/backend/facade/contracts.py b/products/data_catalog/backend/facade/contracts.pynew file mode 100644index 000000000000..32bc518ce77e--- /dev/null+++ b/products/data_catalog/backend/facade/contracts.py@@ -0,0 +1,9 @@+"""+Contract types for data_catalog.++Frozen dataclasses that define what this product exposes to other products. No Django imports.++v1 has no in-process cross-product consumers: information_schema loaders read the ORM classes via+``facade.models`` and everything else goes over HTTP. Contracts will land here when a Python caller+in another product needs metric/certification data.+"""diff --git a/products/data_catalog/backend/facade/enums.py b/products/data_catalog/backend/facade/enums.pynew file mode 100644index 000000000000..a3c64ad2716d--- /dev/null+++ b/products/data_catalog/backend/facade/enums.py@@ -0,0 +1,27 @@+"""+Exported enums for data_catalog.++These are the pure, Django-free types other layers (presentation, information_schema+loaders, MCP tooling) share. Internal-only constants stay in the implementation.+"""++from enum import StrEnum++# The definition kind for an agent-calculated, markdown-step metric (as opposed to an executable+# query definition). Not a posthog.schema query kind — the query runner never executes it; an agent+# follows the steps. JSX object references inside the markdown are a future expansion.+MARKDOWN_DEFINITION_KIND = "MarkdownDefinition"+++class MetricStatus(StrEnum):+ """Persisted lifecycle state of a metric. ``drifted`` is computed at read time, never stored."""++ PROPOSED = "proposed"+ APPROVED = "approved"+++class CreatedSource(StrEnum):+ """Who authored a catalog entry, for review context."""++ USER = "user"+ AI_GENERATED = "ai_generated"diff --git a/products/data_catalog/backend/facade/models.py b/products/data_catalog/backend/facade/models.pynew file mode 100644index 000000000000..36600bd1dce0--- /dev/null+++ b/products/data_catalog/backend/facade/models.py@@ -0,0 +1,10 @@+"""Model-class re-exports.++The one place external code (information_schema loaders, admin, fixtures) and this product's+own presentation layer are allowed to reach the ORM classes, keeping direct model imports off+the isolation boundary.+"""++from ..models import Metric++__all__ = ["Metric"]diff --git a/products/data_catalog/backend/logic/__init__.py b/products/data_catalog/backend/logic/__init__.pynew file mode 100644index 000000000000..417c9d9efd76--- /dev/null+++ b/products/data_catalog/backend/logic/__init__.py@@ -0,0 +1 @@+"""Business logic for data_catalog. Import the specific module you need (metrics, validation)."""diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.pynew file mode 100644index 000000000000..be2a7ee0f7cd--- /dev/null+++ b/products/data_catalog/backend/logic/metrics.py@@ -0,0 +1,152 @@+"""Metric write path — upsert with reserved-name semantics, partial update, soft delete.++Names are reserved forever per team: creating with an existing name refines that metric, and+creating with a soft-deleted name resurrects the row as ``proposed`` rather than minting a new+identity. Concurrent same-name creates collapse to one row via the unique constraint + retry.+"""++import re+from typing import Optional++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.models import Team, User+from posthog.models.scoping import team_scope++from ..facade.enums import CreatedSource, MetricStatus+from ..models import METRIC_NAME_REGEX, Metric+from .validation import validate_metric_definition+++class _Unset:+ """Sentinel for upsert fields the caller did not supply: kept as-is on refine, defaulted on create.++ A plain ``None`` default cannot express this because ``None`` is a legitimate value for+ ``definition``/``confidence``/``owner`` (an explicit clear), distinct from "not provided".+ """+++_UNSET = _Unset()+++def _canonical_definition(+ definition: Optional[dict], team: Team, user: Optional[User]+) -> tuple[Optional[dict], list[str]]:+ if definition is None:+ return None, []+ return validate_metric_definition(definition, team, user)+++def _resurrect_or_refine(metric: Metric, fields: dict) -> None:+ if metric.deleted:+ metric.deleted = False+ metric.deleted_at = None+ metric.status = MetricStatus.PROPOSED+ metric.approved_by = None+ metric.approved_at = None+ for key, value in fields.items():+ setattr(metric, key, value)+ metric.save()+++def upsert_metric(+ *,+ team: Team,+ user: Optional[User],+ name: str,+ description: str,+ display_name: str | _Unset = _UNSET,+ unit: str | _Unset = _UNSET,+ owner: User | None | _Unset = _UNSET,+ definition: dict | None | _Unset = _UNSET,+ created_source: CreatedSource | _Unset = _UNSET,+ ai_model: str | _Unset = _UNSET,+ confidence: float | None | _Unset = _UNSET,+ reasoning: str | _Unset = _UNSET,+) -> Metric:+ """Create a metric, or refine/resurrect the one already holding ``name`` for this team.++ Refine is a partial merge: only the fields the caller supplies are written, so a refine that+ omits a field leaves that field (a stored ``definition``, provenance, ...) untouched rather than+ resetting it. On create, omitted fields fall back to the model defaults (``owner`` to ``user``).+ """+ if not re.match(METRIC_NAME_REGEX, name or ""):+ raise ValidationError(+ {"name": "Name must start with a letter and contain only letters, numbers, and underscores."}+ )++ fields: dict[str, object] = {"description": description}+ for key, value in (+ ("display_name", display_name),+ ("unit", unit),+ ("owner", owner),+ ("created_source", created_source),+ ("ai_model", ai_model),+ ("confidence", confidence),+ ("reasoning", reasoning),+ ):+ if not isinstance(value, _Unset):+ fields[key] = value++ if not isinstance(definition, _Unset):+ canonical_def, referenced = _canonical_definition(definition, team, user)+ fields["definition"] = canonical_def+ fields["referenced_table_names"] = referenced++ # team_scope so the ModelActivityMixin's before-update lookup (via the fail-closed manager)+ # works regardless of caller context (viewset, Celery, MCP, tests).+ with team_scope(team.id):+ try:+ with transaction.atomic():+ existing = Metric.objects.for_team(team.id).filter(name=name).select_for_update().first()+ if existing is not None:+ _resurrect_or_refine(existing, fields)+ return existing+ return Metric.objects.for_team(team.id).create(+ team=team,+ name=name,+ created_by=user,+ status=MetricStatus.PROPOSED,+ **{"owner": user, **fields},+ )+ 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()+ if existing is None:+ raise+ _resurrect_or_refine(existing, fields)+ return existing+++def update_metric(metric: Metric, *, team: Team, user: Optional[User], **fields) -> Metric:+ """Partially update a metric. Name is write-once. Definition changes are re-validated."""+ if "name" in fields:+ raise ValidationError({"name": "Metric name is write-once and cannot be changed."})++ if "definition" in fields:+ canonical_def, referenced = _canonical_definition(fields["definition"], team, user)+ fields["definition"] = canonical_def+ fields["referenced_table_names"] = referenced++ for key, value in fields.items():+ setattr(metric, key, value)+ with team_scope(team.id):+ metric.save()+ return metric+++def soft_delete_metric(metric: Metric) -> None:+ metric.deleted = True+ metric.deleted_at = timezone.now()+ with team_scope(metric.team_id):+ metric.save()+++def metrics_for_team(team: Team) -> QuerySet[Metric]:+ """Live (non-deleted) metrics for a team, newest first."""+ return Metric.objects.for_team(team.id).filter(deleted=False).order_by("-created_at")diff --git a/products/data_catalog/backend/logic/validation.py b/products/data_catalog/backend/logic/validation.pynew file mode 100644index 000000000000..a520d7c3482a--- /dev/null+++ b/products/data_catalog/backend/logic/validation.py@@ -0,0 +1,184 @@+"""Metric definition validation — the single choke point for serializers and internal writers.++Every write of a ``definition`` goes through :func:`validate_metric_definition`, which returns the+upgrade-canonical definition (so schema migrations never read as drift later) plus the tables it+directly references (cached on the row for the catalog's denied-table filter).+"""++from typing import NoReturn, Optional++from pydantic import BaseModel+from rest_framework.exceptions import ValidationError++from posthog.schema import ActionsNode, DataWarehouseNode, EventsNode, FunnelsQuery, HogQLQuery, TrendsQuery++from posthog.hogql import ast+from posthog.hogql.context import HogQLContext+from posthog.hogql.errors import ExposedHogQLError, ResolutionError+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import prepare_ast_for_printing+from posthog.hogql.visitor import TraversingVisitor++from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User+from posthog.schema_migrations.upgrade import upgrade++from ..facade.enums import MARKDOWN_DEFINITION_KIND++# Query kinds a metric definition may take. Node kinds are the RFC's "event with filters"+# single series; insight kinds are the classic viz shapes. Kept small on purpose.+_NODE_MODELS: dict[str, type[BaseModel]] = {+ "EventsNode": EventsNode,+ "ActionsNode": ActionsNode,+ "DataWarehouseNode": DataWarehouseNode,+}+_INSIGHT_MODELS: dict[str, type[BaseModel]] = {"TrendsQuery": TrendsQuery, "FunnelsQuery": FunnelsQuery}+_SUPPORTED_KINDS = {"HogQLQuery", *_NODE_MODELS, *_INSIGHT_MODELS}++# A markdown definition is a bounded blob; keep it small so it stays a definition, not a document.+MAX_MARKDOWN_DEFINITION_LENGTH = 20_000++# HogQLQuery carries fields that would let a caller bypass team query controls (a raw ClickHouse+# passthrough, an arbitrary DB connection). A metric definition may only set these.+_HOGQL_ALLOWED_KEYS = {"kind", "query", "values"}+++class _TableReferenceCollector(TraversingVisitor):+ """Collects the identifiers used directly as FROM/JOIN targets in a parsed HogQL query."""++ def __init__(self) -> None:+ self.tables: set[str] = set()++ def visit_join_expr(self, node: ast.JoinExpr) -> None:+ if isinstance(node.table, ast.Field):+ self.tables.add(".".join(str(part) for part in node.table.chain))+ super().visit_join_expr(node)+++def _fail(error: str, hint: str) -> NoReturn:+ raise ValidationError({"field": "definition", "error": error, "hint": hint})+++def validate_metric_definition(definition: dict, team: Team, user: Optional[User] = None) -> tuple[dict, list[str]]:+ """Validate a metric definition and return ``(canonical_definition, referenced_table_names)``.++ Raises :class:`ValidationError` with a structured ``{field, error, hint}`` body on any problem.+ """+ if not isinstance(definition, dict) or not definition.get("kind"):+ _fail("A definition must be a query object with a 'kind'.", "Provide a HogQLQuery, TrendsQuery, or event node.")++ kind = definition["kind"]+ if kind == MARKDOWN_DEFINITION_KIND:+ # Agent-calculated definition: prose steps, not a query. Never upgrade()/schema-validate it.+ return _validate_markdown(definition)++ if kind == "InsightVizNode":+ source = definition.get("source")+ if not isinstance(source, dict):+ _fail("InsightVizNode has no source query.", "Use the insight's inner query as the definition.")+ return validate_metric_definition(source, team, user)++ # Reject unsupported kinds before upgrade() — upgrade runs kind-specific migrations that assume a+ # well-formed query of that kind and would crash on anything else.+ if kind not in _SUPPORTED_KINDS:+ supported = ", ".join(sorted(_SUPPORTED_KINDS))+ _fail(f"Unsupported definition kind '{kind}'.", f"Supported kinds: {supported}.")++ try:+ canonical = upgrade(definition)+ except Exception as e:+ _fail(f"Malformed {kind} definition: {e}", "Check the query shape against its schema.")++ kind = canonical.get("kind", kind)+ if kind == "HogQLQuery":+ return _validate_hogql(canonical, team, user)+ if kind in _NODE_MODELS:+ return _validate_schema_model(canonical, _NODE_MODELS[kind])+ return _validate_schema_model(canonical, _INSIGHT_MODELS[kind])+++def _validate_markdown(definition: dict) -> tuple[dict, list[str]]:+ extra_keys = set(definition.keys()) - {"kind", "markdown"}+ if extra_keys:+ _fail(+ f"A markdown definition may only set 'markdown': unexpected {sorted(extra_keys)}.",+ "Put the calculation steps in 'markdown' and remove the other keys.",+ )+ markdown = definition.get("markdown")+ if not isinstance(markdown, str) or not markdown.strip():+ _fail(+ "A markdown definition needs non-empty 'markdown' text.",+ "Describe the steps an agent should follow to calculate the metric.",+ )+ if len(markdown) > MAX_MARKDOWN_DEFINITION_LENGTH:+ _fail(+ "Markdown definition is too long.",+ f"Keep it under {MAX_MARKDOWN_DEFINITION_LENGTH} characters.",+ )+ return definition, []+++def _validate_hogql(definition: dict, team: Team, user: Optional[User]) -> tuple[dict, list[str]]:+ extra_keys = set(definition.keys()) - _HOGQL_ALLOWED_KEYS+ if extra_keys:+ _fail(+ f"HogQLQuery fields not allowed in a metric definition: {sorted(extra_keys)}.",+ "A metric definition may only set 'query' (and 'values'). Fields like connectionId or "+ "sendRawQuery are rejected.",+ )++ _ensure_valid_schema(definition, HogQLQuery)++ try:+ ast_node = parse_select(definition["query"])+ except ExposedHogQLError as e:+ _fail(f"Invalid HogQL query: {e}", "Fix the SQL syntax.")+ except ResolutionError as e:+ capture_exception(e)+ _fail("Could not resolve a table or field in the query.", "Check table and column names.")+ except Exception as e:+ capture_exception(e)+ _fail("Could not parse the query.", "Check the SQL syntax.")++ context = HogQLContext(team_id=team.pk, user=user, enable_select_queries=True)+ try:+ prepare_ast_for_printing(node=ast_node, context=context, dialect="clickhouse")+ except ExposedHogQLError as e:+ _fail(f"Invalid HogQL query: {e}", "Check that every referenced table and column exists and is accessible.")+ except Exception as e:+ capture_exception(e)+ _fail("Unexpected error resolving the query.", "Simplify the query and try again.")++ collector = _TableReferenceCollector()+ collector.visit(ast_node)+ return definition, sorted(collector.tables)+++def _validate_schema_model(definition: dict, model_class: type[BaseModel]) -> tuple[dict, list[str]]:+ _ensure_valid_schema(definition, model_class)+ return definition, _extract_warehouse_tables(definition)+++def _ensure_valid_schema(definition: dict, model_class: type[BaseModel]) -> None:+ try:+ model_class.model_validate(definition)+ except Exception as e:+ _fail(f"Definition does not match {model_class.__name__}: {e}", "Fix the query shape.")+++def _extract_warehouse_tables(definition: dict) -> list[str]:+ """Walk a node/insight query dict for DataWarehouseNode table references (direct references only)."""+ tables: set[str] = set()++ def walk(value: object) -> None:+ if isinstance(value, dict):+ if value.get("kind") == "DataWarehouseNode" and value.get("table_name"):+ tables.add(str(value["table_name"]))+ for child in value.values():+ walk(child)+ elif isinstance(value, list):+ for child in value:+ walk(child)++ walk(definition)+ return sorted(tables)diff --git a/products/data_catalog/backend/migrations/0001_initial.py b/products/data_catalog/backend/migrations/0001_initial.pynew file mode 100644index 000000000000..0ad2ac6afd28--- /dev/null+++ b/products/data_catalog/backend/migrations/0001_initial.py@@ -0,0 +1,209 @@+# Generated by Django 5.2.14 on 2026-07-08 22:29++import django.core.validators+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):+ initial = True++ dependencies = [+ ("posthog", "1247_oauthaccesstoken_token_idx"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="Metric",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ ("deleted", models.BooleanField(blank=True, default=False, null=True)),+ ("deleted_at", models.DateTimeField(blank=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "name",+ models.CharField(+ help_text="Identifier-safe run handle, unique per team and reserved forever. Write-once.",+ 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_]*$",+ )+ ],+ ),+ ),+ (+ "display_name",+ models.CharField(+ blank=True,+ help_text="Human-friendly label. Mutable, unlike name.",+ max_length=255,+ ),+ ),+ (+ "description",+ models.TextField(help_text="What the metric means and how to interpret it. The load-bearing text."),+ ),+ (+ "unit",+ models.CharField(+ blank=True,+ help_text="Unit of the result, e.g. usd, percent, cents.",+ max_length=64,+ ),+ ),+ (+ "definition",+ models.JSONField(+ blank=True,+ help_text="Machine-readable query (stored upgrade-canonical). Null means a name+description-only stub.",+ null=True,+ ),+ ),+ (+ "referenced_table_names",+ models.JSONField(+ blank=True,+ default=list,+ help_text="Tables the definition directly references, extracted at write time for the catalog's denied-table filter.",+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[("proposed", "proposed"), ("approved", "approved")],+ default=products.data_catalog.backend.facade.enums.MetricStatus["PROPOSED"],+ help_text="Persisted lifecycle state. drifted is computed at read time, not stored here.",+ max_length=32,+ ),+ ),+ ("approved_at", models.DateTimeField(blank=True, null=True)),+ (+ "source_insight_short_id",+ models.CharField(+ blank=True,+ help_text="Short ID of the insight this metric was created from, for drift detection.",+ max_length=12,+ null=True,+ ),+ ),+ (+ "source_insight_query_hash",+ models.CharField(+ blank=True,+ help_text="Canonical hash of the insight query snapshot at create/refresh time.",+ max_length=64,+ null=True,+ ),+ ),+ (+ "last_run_at",+ models.DateTimeField(+ blank=True,+ help_text="When the metric was last run (30-minute throttle).",+ null=True,+ ),+ ),+ (+ "created_source",+ models.CharField(+ choices=[("user", "user"), ("ai_generated", "ai_generated")],+ default=products.data_catalog.backend.facade.enums.CreatedSource["USER"],+ help_text="Whether a human or an agent authored this metric.",+ max_length=32,+ ),+ ),+ (+ "ai_model",+ models.CharField(+ blank=True,+ help_text="Model that generated the metric, if AI-authored.",+ max_length=128,+ ),+ ),+ (+ "confidence",+ models.FloatField(+ blank=True,+ help_text="AI author's confidence in the proposal, 0-1.",+ null=True,+ ),+ ),+ (+ "reasoning",+ models.TextField(+ blank=True,+ help_text="AI author's reasoning, surfaced as review context.",+ ),+ ),+ (+ "approved_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,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "owner",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ help_text="The human accountable for this metric. AI generates, a human owns.",+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "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_7d270a_idx"),+ models.Index(+ fields=["team", "source_insight_short_id"],+ name="data_catalo_team_id_f2da25_idx",+ ),+ ],+ "constraints": [models.UniqueConstraint(fields=("team", "name"), name="unique_metric_name_per_team")],+ },+ ),+ ]diff --git a/products/data_catalog/backend/migrations/__init__.py b/products/data_catalog/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/data_catalog/backend/migrations/max_migration.txt b/products/data_catalog/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..cbab66dde92a--- /dev/null+++ b/products/data_catalog/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initialdiff --git a/products/data_catalog/backend/models/__init__.py b/products/data_catalog/backend/models/__init__.pynew file mode 100644index 000000000000..68a587d6acdb--- /dev/null+++ b/products/data_catalog/backend/models/__init__.py@@ -0,0 +1,3 @@+from .metric import METRIC_NAME_REGEX, Metric++__all__ = ["METRIC_NAME_REGEX", "Metric"]diff --git a/products/data_catalog/backend/models/metric.py b/products/data_catalog/backend/models/metric.pynew file mode 100644index 000000000000..a42142105d6b--- /dev/null+++ b/products/data_catalog/backend/models/metric.py@@ -0,0 +1,129 @@+from django.core.validators import RegexValidator+from django.db import models++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import CreatedMetaFields, DeletedMetaFields, UpdatedMetaFields, UUIDModel++from ..facade.enums import CreatedSource, MetricStatus++# A metric name is the SQL/API run handle (`information_schema.metrics.name`,+# `POST data_catalog/metrics/{name}/run`), so it must be a bare identifier.+METRIC_NAME_REGEX = r"^[A-Za-z][A-Za-z0-9_]*$"++validate_metric_name = RegexValidator(+ regex=METRIC_NAME_REGEX,+ message="Name must start with a letter and contain only letters, numbers, and underscores.",+)+++class Metric(+ ModelActivityMixin, TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, DeletedMetaFields, UUIDModel+):+ """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.+ """++ # db_constraint=False on FKs to hot tables (posthog_team, posthog_user): a real FK constraint+ # takes SHARE ROW EXCLUSIVE on the parent, stalling writes under traffic. Scoping/integrity is+ # enforced at the app layer.+ 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, related_name="+"+ )++ name = models.CharField(+ max_length=128,+ validators=[validate_metric_name],+ help_text="Identifier-safe run handle, unique per team and reserved forever. Write-once.",+ )+ display_name = models.CharField(max_length=255, blank=True, help_text="Human-friendly label. Mutable, unlike name.")+ description = models.TextField(help_text="What the metric means and how to interpret it. The load-bearing text.")+ unit = models.CharField(max_length=64, blank=True, help_text="Unit of the result, e.g. usd, percent, cents.")+ owner = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ related_name="+",+ help_text="The human accountable for this metric. AI generates, a human owns.",+ )++ definition = models.JSONField(+ null=True,+ blank=True,+ help_text="Machine-readable query (stored upgrade-canonical). Null means a name+description-only stub.",+ )+ referenced_table_names = models.JSONField(+ default=list,+ blank=True,+ help_text="Tables the definition directly references, extracted at write time for the catalog's denied-table filter.",+ )++ status = models.CharField(+ max_length=32,+ choices=[(s.value, s.value) for s in MetricStatus],+ default=MetricStatus.PROPOSED,+ help_text="Persisted lifecycle state. drifted is computed at read time, not stored here.",+ )+ approved_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ related_name="+",+ )+ approved_at = models.DateTimeField(null=True, blank=True)++ source_insight_short_id = models.CharField(+ max_length=12,+ null=True,+ blank=True,+ help_text="Short ID of the insight this metric was created from, for drift detection.",+ )+ source_insight_query_hash = models.CharField(+ max_length=64,+ null=True,+ blank=True,+ help_text="Canonical hash of the insight query snapshot at create/refresh time.",+ )+ last_run_at = models.DateTimeField(+ null=True, blank=True, help_text="When the metric was last run (30-minute throttle)."+ )++ created_source = models.CharField(+ max_length=32,+ choices=[(s.value, s.value) for s in CreatedSource],+ default=CreatedSource.USER,+ help_text="Whether a human or an agent authored this metric.",+ )+ ai_model = models.CharField(+ max_length=128, blank=True, help_text="Model that generated the metric, if AI-authored."+ )+ confidence = models.FloatField(null=True, blank=True, help_text="AI author's confidence in the proposal, 0-1.")+ reasoning = models.TextField(blank=True, help_text="AI author's reasoning, surfaced as review context.")++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["team", "name"], name="unique_metric_name_per_team"),+ ]+ indexes = [+ models.Index(fields=["team", "status"]),+ models.Index(fields=["team", "source_insight_short_id"]),+ ]++ def __str__(self) -> str:+ return self.name++ @property+ def definition_kind(self) -> str | None:+ """The query kind (HogQLQuery, TrendsQuery, ...), derived from the stored definition."""+ if not self.definition:+ return None+ return self.definition.get("kind")diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.pynew file mode 100644index 000000000000..987b77663afb--- /dev/null+++ b/products/data_catalog/backend/presentation/serializers.py@@ -0,0 +1,96 @@+"""DRF serializers for data_catalog.++These are the source of truth for the generated frontend/MCP types, so every field carries+help_text. ``status`` is exposed as a plain read-only string (not a ChoiceField) to keep it out of+the drf-spectacular enum namespace, where a component named ``Status`` collides across the API.+"""++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import extend_schema_field, extend_schema_serializer+from rest_framework import serializers++from posthog.api.shared import UserBasicSerializer++from ..facade.enums import CreatedSource+from ..facade.models import Metric+++@extend_schema_field(OpenApiTypes.OBJECT)+class MetricDefinitionField(serializers.JSONField):+ """A machine-readable query (HogQLQuery, TrendsQuery, event node, ...). Typed as a free object."""+++@extend_schema_serializer(component_name="DataCatalogMetric")+class MetricSerializer(serializers.ModelSerializer):+ definition = MetricDefinitionField(+ required=False,+ allow_null=True,+ help_text="Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.",+ )+ definition_kind = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="Query kind of the definition (HogQLQuery, TrendsQuery, ...), or null for a stub.",+ )+ status = serializers.CharField(+ read_only=True,+ help_text="Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately.",+ )+ created_source = serializers.ChoiceField(+ choices=[(s.value, s.value) for s in CreatedSource],+ required=False,+ help_text="Whether a human ('user') or an agent ('ai_generated') authored this metric.",+ )+ owner = serializers.SerializerMethodField(+ help_text="Email of the human accountable for this metric, or null.",+ )+ created_by = UserBasicSerializer(read_only=True, help_text="User who first created this metric.")++ class Meta:+ model = Metric+ fields = [+ "id",+ "name",+ "display_name",+ "description",+ "unit",+ "owner",+ "definition",+ "definition_kind",+ "referenced_table_names",+ "status",+ "approved_at",+ "source_insight_short_id",+ "last_run_at",+ "created_source",+ "ai_model",+ "confidence",+ "reasoning",+ "created_by",+ "created_at",+ "updated_at",+ ]+ read_only_fields = [+ "id",+ "status",+ "approved_at",+ "referenced_table_names",+ "source_insight_short_id",+ "last_run_at",+ "created_by",+ "created_at",+ "updated_at",+ ]+ extra_kwargs = {+ "name": {"help_text": "Identifier-safe run handle, unique per team and reserved forever. Write-once."},+ "display_name": {"help_text": "Human-friendly label. Mutable, unlike name."},+ "description": {"help_text": "What the metric means and how to interpret it."},+ "unit": {"help_text": "Unit of the result, e.g. usd, percent, cents."},+ "ai_model": {"help_text": "Model that generated the metric, if AI-authored."},+ "confidence": {"help_text": "AI author's confidence in the proposal, 0-1."},+ "reasoning": {"help_text": "AI author's reasoning, surfaced as review context."},+ }++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_owner(self, obj: Metric) -> str | None:+ return obj.owner.email if obj.owner else Nonediff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.pynew file mode 100644index 000000000000..f083e42f466b--- /dev/null+++ b/products/data_catalog/backend/presentation/views.py@@ -0,0 +1,70 @@+"""DRF views for data_catalog.++Thin: validate via the serializer, call the facade, serialize the result. Domain invariants+(name reservation, upsert, validation) live in the logic layer behind the facade.+"""++from typing import cast++from django.db.models import QuerySet++from drf_spectacular.utils import extend_schema+from rest_framework import status, viewsets+from rest_framework.exceptions import ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models import User++from ..facade import api+from ..facade.models import Metric+from .serializers import MetricSerializer+++class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+ """CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/)."""++ scope_object = "data_catalog"+ lookup_field = "name"+ serializer_class = MetricSerializer+ queryset = Metric.objects.unscoped()++ def safely_get_queryset(self, queryset: QuerySet[Metric]) -> QuerySet[Metric]:+ return queryset.filter(team_id=self.team_id, deleted=False).order_by("-created_at")++ @extend_schema(description="Create a metric, or refine the one already holding this name for the team.")+ def create(self, request: Request, *args, **kwargs) -> Response:+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ # Pass only the fields the client actually sent, so an upsert that refines an existing metric+ # leaves omitted fields (a stored definition, provenance, ...) untouched rather than resetting them.+ optional = {+ key: data[key]+ for key in ("display_name", "unit", "definition", "created_source", "ai_model", "confidence", "reasoning")+ if key in data+ }+ metric = api.upsert_metric(+ team=self.team,+ user=cast(User, request.user),+ name=data["name"],+ description=data["description"],+ **optional,+ )+ return Response(self.get_serializer(metric).data, status=status.HTTP_201_CREATED)++ def update(self, request: Request, *args, **kwargs) -> Response:+ partial = kwargs.pop("partial", False)+ metric = self.get_object()+ 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), **fields)+ return Response(self.get_serializer(metric).data)++ def perform_destroy(self, instance: Metric) -> None:+ api.soft_delete_metric(instance)diff --git a/products/data_catalog/backend/routes.py b/products/data_catalog/backend/routes.pynew file mode 100644index 000000000000..424ea64c4dfc--- /dev/null+++ b/products/data_catalog/backend/routes.py@@ -0,0 +1,7 @@+from posthog.api.routing import RouterRegistry++from products.data_catalog.backend.presentation.views import MetricViewSet+++def register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(r"data_catalog/metrics", MetricViewSet, "environment_data_catalog_metrics", ["team_id"])diff --git a/products/data_catalog/backend/tasks/schedules.py b/products/data_catalog/backend/tasks/schedules.pynew file mode 100644index 000000000000..681c699798b9--- /dev/null+++ b/products/data_catalog/backend/tasks/schedules.py@@ -0,0 +1,2 @@+"""Celery beat schedules for data_catalog."""+# Define periodic task schedules herediff --git a/products/data_catalog/backend/tasks/tasks.py b/products/data_catalog/backend/tasks/tasks.pynew file mode 100644index 000000000000..f395f84f8179--- /dev/null+++ b/products/data_catalog/backend/tasks/tasks.py@@ -0,0 +1,8 @@+"""+Celery tasks for data_catalog.++Async entrypoints that call the facade (facade/api.py).+Keep task functions thin - only call facade methods.+"""+# from celery import shared_task+# from ..facade import apidiff --git a/products/data_catalog/backend/tests/__init__.py b/products/data_catalog/backend/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/data_catalog/backend/tests/conftest.py b/products/data_catalog/backend/tests/conftest.pynew file mode 100644index 000000000000..a750567d3250--- /dev/null+++ b/products/data_catalog/backend/tests/conftest.py@@ -0,0 +1,15 @@+import pytest++from posthog.models.scoping import team_scope++[email protected](autouse=True)+def _set_team_scope(request):+ # Only pytest-function-style tests that request the `team` fixture need auto-scoping.+ # unittest-style tests (APIBaseTest/BaseTest) set their own context, so skip them.+ if request.node.get_closest_marker("django_db") is None or "team" not in request.fixturenames:+ yield+ return+ team = request.getfixturevalue("team")+ with team_scope(team.id):+ yielddiff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.pynew file mode 100644index 000000000000..272c2ed052c6--- /dev/null+++ b/products/data_catalog/backend/tests/test_api.py@@ -0,0 +1,96 @@+from posthog.test.base import APIBaseTest++from rest_framework import status++from posthog.models.team import Team++from products.data_catalog.backend.facade.enums import MetricStatus+from products.data_catalog.backend.models import Metric+++class TestMetricAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.url = f"/api/projects/{self.team.id}/data_catalog/metrics/"++ def test_create_lands_proposed(self) -> None:+ response = self.client.post(self.url, {"name": "mrr", "description": "Monthly revenue"}, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = response.json()+ assert body["name"] == "mrr"+ assert body["status"] == MetricStatus.PROPOSED++ def test_status_and_approval_are_not_writable(self) -> None:+ response = self.client.post(+ self.url,+ {"name": "mrr", "description": "d", "status": "approved", "approved_at": "2020-01-01T00:00:00Z"},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["status"] == MetricStatus.PROPOSED+ assert response.json()["approved_at"] is None++ def test_create_is_upsert_on_name(self) -> None:+ self.client.post(self.url, {"name": "mrr", "description": "v1"}, format="json")+ response = self.client.post(self.url, {"name": "mrr", "description": "v2"}, format="json")+ assert response.status_code == status.HTTP_201_CREATED+ assert Metric.objects.for_team(self.team.id).count() == 1+ assert self.client.get(f"{self.url}mrr/").json()["description"] == "v2"++ def test_refine_via_post_preserves_omitted_definition(self) -> None:+ definition = {"kind": "HogQLQuery", "query": "select count() from events"}+ self.client.post(self.url, {"name": "mrr", "description": "v1", "definition": definition}, format="json")+ response = self.client.post(self.url, {"name": "mrr", "description": "v2"}, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ body = self.client.get(f"{self.url}mrr/").json()+ assert body["description"] == "v2"+ assert body["definition"]["kind"] == "HogQLQuery"+ assert body["referenced_table_names"] == ["events"]++ def test_name_addressed_detail_routes(self) -> None:+ self.client.post(self.url, {"name": "mrr", "description": "v1"}, format="json")++ assert self.client.get(f"{self.url}mrr/").status_code == status.HTTP_200_OK++ patched = self.client.patch(f"{self.url}mrr/", {"display_name": "MRR"}, format="json")+ assert patched.status_code == status.HTTP_200_OK+ assert patched.json()["display_name"] == "MRR"++ assert self.client.delete(f"{self.url}mrr/").status_code == status.HTTP_204_NO_CONTENT+ assert self.client.get(f"{self.url}mrr/").status_code == status.HTTP_404_NOT_FOUND++ def test_patch_cannot_change_name(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++ def test_invalid_definition_rejected(self) -> None:+ response = self.client.post(+ self.url,+ {"name": "mrr", "description": "d", "definition": {"kind": "RetentionQuery"}},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_markdown_definition_accepted(self) -> None:+ response = self.client.post(+ self.url,+ {+ "name": "activation",+ "description": "Activated users",+ "definition": {"kind": "MarkdownDefinition", "markdown": "1. User did A then B within 7 days."},+ },+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["definition_kind"] == "MarkdownDefinition"++ def test_list_is_team_scoped(self) -> None:+ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ self.client.post(self.url, {"name": "mine", "description": "d"}, format="json")+ Metric.objects.for_team(other_team.id).create(team=other_team, name="theirs", description="d")++ names = [row["name"] for row in self.client.get(self.url).json()["results"]]+ assert names == ["mine"]diff --git a/products/data_catalog/backend/tests/test_logic.py b/products/data_catalog/backend/tests/test_logic.pynew file mode 100644index 000000000000..060e2d351e71--- /dev/null+++ b/products/data_catalog/backend/tests/test_logic.py@@ -0,0 +1,141 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.db import IntegrityError++from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from products.data_catalog.backend.facade.enums import CreatedSource, MetricStatus+from products.data_catalog.backend.logic import metrics+from products.data_catalog.backend.logic.metrics import soft_delete_metric, update_metric, upsert_metric+from products.data_catalog.backend.logic.validation import validate_metric_definition+from products.data_catalog.backend.models import Metric+++class TestMetricUpsert(BaseTest):+ def _upsert(self, name: str, description: str = "desc", **kwargs) -> Metric:+ return upsert_metric(team=self.team, user=self.user, name=name, description=description, **kwargs)++ def test_creates_proposed_metric(self) -> None:+ metric = self._upsert("mrr", created_source=CreatedSource.AI_GENERATED)+ assert metric.status == MetricStatus.PROPOSED+ assert metric.created_source == CreatedSource.AI_GENERATED+ assert metric.owner_id == self.user.id++ def test_same_name_refines_not_duplicates(self) -> None:+ first = self._upsert("mrr", description="v1")+ second = self._upsert("mrr", description="v2")+ assert first.id == second.id+ assert Metric.objects.for_team(self.team.id).count() == 1+ assert Metric.objects.for_team(self.team.id).get().description == "v2"++ def test_refine_leaves_unspecified_fields_untouched(self) -> None:+ self._upsert(+ "mrr",+ created_source=CreatedSource.AI_GENERATED,+ ai_model="claude",+ definition={"kind": "HogQLQuery", "query": "select count() from events"},+ )+ refined = self._upsert("mrr", description="v2")+ assert refined.description == "v2"+ assert refined.definition is not None+ assert refined.definition["kind"] == "HogQLQuery"+ assert refined.referenced_table_names == ["events"]+ assert refined.created_source == CreatedSource.AI_GENERATED+ assert 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()+ 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"++ @parameterized.expand([("bad name",), ("1leading_digit",), ("has-dash",), ("",)])+ def test_rejects_invalid_names(self, name: str) -> None:+ with self.assertRaises(ValidationError):+ self._upsert(name)++ def test_concurrent_create_retries_to_single_row(self) -> None:+ # Simulate the race: the pre-check misses, create hits the unique constraint (IntegrityError),+ # and the retry finds and refines the row the other writer created. Guards the except branch.+ winner = self._upsert("mrr", description="winner")++ mock_qs = MagicMock()+ mock_qs.filter.return_value.select_for_update.return_value.first.side_effect = [None, winner]+ mock_qs.create.side_effect = IntegrityError("duplicate key")++ with patch.object(metrics.Metric.objects, "for_team", return_value=mock_qs):+ result = self._upsert("mrr", description="racer")++ assert result.id == winner.id+ assert Metric.objects.for_team(self.team.id).count() == 1+++class TestMetricUpdate(BaseTest):+ def test_update_changes_fields(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="v1")+ updated = update_metric(metric, team=self.team, user=self.user, description="v2", unit="usd")+ assert updated.description == "v2"+ assert updated.unit == "usd"++ def test_update_rejects_name_change(self) -> 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="arr")++ def test_update_definition_reextracts_tables(self) -> None:+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="v1")+ updated = update_metric(+ metric,+ team=self.team,+ user=self.user,+ definition={"kind": "HogQLQuery", "query": "select count() from events"},+ )+ assert updated.referenced_table_names == ["events"]+++class TestValidateMetricDefinition(BaseTest):+ def test_valid_hogql_extracts_referenced_tables(self) -> None:+ _, tables = validate_metric_definition(+ {"kind": "HogQLQuery", "query": "select count() from events"}, self.team, self.user+ )+ assert tables == ["events"]++ def test_insight_viz_node_is_unwrapped(self) -> None:+ canonical, _ = validate_metric_definition(+ {"kind": "InsightVizNode", "source": {"kind": "HogQLQuery", "query": "select 1"}},+ self.team,+ self.user,+ )+ assert canonical["kind"] == "HogQLQuery"++ def test_markdown_definition_accepted(self) -> None:+ canonical, tables = validate_metric_definition(+ {"kind": "MarkdownDefinition", "markdown": "1. Sum the paid subscriptions over the month."},+ self.team,+ self.user,+ )+ assert canonical["kind"] == "MarkdownDefinition"+ assert tables == []++ @parameterized.expand(+ [+ ("unsupported_kind", {"kind": "RetentionQuery"}),+ ("raw_connection", {"kind": "HogQLQuery", "query": "select 1", "connectionId": "abc"}),+ ("raw_query", {"kind": "HogQLQuery", "query": "select 1", "sendRawQuery": True}),+ ("bad_sql", {"kind": "HogQLQuery", "query": "not valid sql !!!"}),+ ("no_kind", {"query": "select 1"}),+ ("markdown_empty", {"kind": "MarkdownDefinition", "markdown": " "}),+ ("markdown_smuggled_query", {"kind": "MarkdownDefinition", "markdown": "x", "query": "select 1"}),+ ]+ )+ def test_rejects_invalid_definitions(self, _name: str, definition: dict) -> None:+ with self.assertRaises(ValidationError):+ validate_metric_definition(definition, self.team, self.user)diff --git a/products/data_catalog/backend/tests/test_models.py b/products/data_catalog/backend/tests/test_models.pynew file mode 100644index 000000000000..a99cd0d291c7--- /dev/null+++ b/products/data_catalog/backend/tests/test_models.py@@ -0,0 +1,36 @@+from posthog.test.base import BaseTest++from django.db import IntegrityError, transaction++from products.data_catalog.backend.facade.enums import MetricStatus+from products.data_catalog.backend.models import Metric+++class TestMetricModel(BaseTest):+ def _create(self, name: str, **kwargs) -> Metric:+ return Metric.objects.for_team(self.team.id).create(team=self.team, name=name, description="desc", **kwargs)++ def test_name_is_unique_per_team(self) -> None:+ self._create("mrr")+ 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_definition_kind_derived_from_definition(self) -> None:+ stub = self._create("stub")+ assert stub.definition_kind is None+ defined = self._create("defined", definition={"kind": "HogQLQuery", "query": "select 1"})+ assert defined.definition_kind == "HogQLQuery"++ def test_defaults(self) -> None:+ metric = self._create("mrr")+ assert metric.status == MetricStatus.PROPOSED+ assert metric.referenced_table_names == []+ assert metric.deleted is Falsediff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..351796a331d1--- /dev/null+++ b/products/data_catalog/frontend/generated/api.schemas.ts@@ -0,0 +1,256 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+/**+ * * `user` - user+ * * `ai_generated` - ai_generated+ */+export type CreatedSourceEnumApi = (typeof CreatedSourceEnumApi)[keyof typeof CreatedSourceEnumApi]++export const CreatedSourceEnumApi = {+ User: 'user',+ AiGenerated: 'ai_generated',+} as const++/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Other: 'other',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}++/**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+export type DataCatalogMetricApiDefinition = { [key: string]: unknown } | null++export interface DataCatalogMetricApi {+ readonly id: string+ /**+ * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name: string+ /**+ * Human-friendly label. Mutable, unlike name.+ * @maxLength 255+ */+ display_name?: string+ /** What the metric means and how to interpret it. */+ description: string+ /**+ * Unit of the result, e.g. usd, percent, cents.+ * @maxLength 64+ */+ unit?: string+ /**+ * Email of the human accountable for this metric, or null.+ * @nullable+ */+ readonly owner: string | null+ /**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+ definition?: DataCatalogMetricApiDefinition+ /**+ * Query kind of the definition (HogQLQuery, TrendsQuery, ...), or null for a stub.+ * @nullable+ */+ readonly definition_kind: string | null+ /** Tables the definition directly references, extracted at write time for the catalog's denied-table filter. */+ readonly referenced_table_names: unknown+ /** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */+ readonly status: string+ /** @nullable */+ readonly approved_at: string | null+ /**+ * Short ID of the insight this metric was created from, for drift detection.+ * @nullable+ */+ readonly source_insight_short_id: string | null+ /**+ * When the metric was last run (30-minute throttle).+ * @nullable+ */+ readonly last_run_at: string | null+ /** Whether a human ('user') or an agent ('ai_generated') authored this metric.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnumApi+ /**+ * Model that generated the metric, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string+ /**+ * AI author's confidence in the proposal, 0-1.+ * @nullable+ */+ confidence?: number | null+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string+ /** User who first created this metric. */+ readonly created_by: UserBasicApi+ readonly created_at: string+ /** @nullable */+ readonly updated_at: string | null+}++export interface PaginatedDataCatalogMetricListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: DataCatalogMetricApi[]+}++/**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+export type PatchedDataCatalogMetricApiDefinition = { [key: string]: unknown } | null++export interface PatchedDataCatalogMetricApi {+ readonly id?: string+ /**+ * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name?: string+ /**+ * Human-friendly label. Mutable, unlike name.+ * @maxLength 255+ */+ display_name?: string+ /** What the metric means and how to interpret it. */+ description?: string+ /**+ * Unit of the result, e.g. usd, percent, cents.+ * @maxLength 64+ */+ unit?: string+ /**+ * Email of the human accountable for this metric, or null.+ * @nullable+ */+ readonly owner?: string | null+ /**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+ definition?: PatchedDataCatalogMetricApiDefinition+ /**+ * Query kind of the definition (HogQLQuery, TrendsQuery, ...), or null for a stub.+ * @nullable+ */+ readonly definition_kind?: string | null+ /** Tables the definition directly references, extracted at write time for the catalog's denied-table filter. */+ readonly referenced_table_names?: unknown+ /** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */+ readonly status?: string+ /** @nullable */+ readonly approved_at?: string | null+ /**+ * Short ID of the insight this metric was created from, for drift detection.+ * @nullable+ */+ readonly source_insight_short_id?: string | null+ /**+ * When the metric was last run (30-minute throttle).+ * @nullable+ */+ readonly last_run_at?: string | null+ /** Whether a human ('user') or an agent ('ai_generated') authored this metric.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnumApi+ /**+ * Model that generated the metric, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string+ /**+ * AI author's confidence in the proposal, 0-1.+ * @nullable+ */+ confidence?: number | null+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string+ /** User who first created this metric. */+ readonly created_by?: UserBasicApi+ readonly created_at?: string+ /** @nullable */+ readonly updated_at?: string | null+}++export type DataCatalogMetricsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/data_catalog/frontend/generated/api.ts b/products/data_catalog/frontend/generated/api.tsnew file mode 100644index 000000000000..c1cc8d7fcb61--- /dev/null+++ b/products/data_catalog/frontend/generated/api.ts@@ -0,0 +1,161 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ DataCatalogMetricApi,+ DataCatalogMetricsListParams,+ PaginatedDataCatalogMetricListApi,+ PatchedDataCatalogMetricApi,+} from './api.schemas'++// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>++export const getDataCatalogMetricsListUrl = (projectId: string, params?: DataCatalogMetricsListParams) => {+ 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/metrics/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_catalog/metrics/`+}++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const dataCatalogMetricsList = async (+ projectId: string,+ params?: DataCatalogMetricsListParams,+ options?: RequestInit+): Promise<PaginatedDataCatalogMetricListApi> => {+ return apiMutator<PaginatedDataCatalogMetricListApi>(getDataCatalogMetricsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getDataCatalogMetricsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/`+}++/**+ * Create a metric, or refine the one already holding this name for the team.+ */+export const dataCatalogMetricsCreate = async (+ projectId: string,+ dataCatalogMetricApi: NonReadonly<DataCatalogMetricApi>,+ options?: RequestInit+): Promise<DataCatalogMetricApi> => {+ return apiMutator<DataCatalogMetricApi>(getDataCatalogMetricsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataCatalogMetricApi),+ })+}++export const getDataCatalogMetricsRetrieveUrl = (projectId: string, name: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${name}/`+}++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const dataCatalogMetricsRetrieve = async (+ projectId: string,+ name: string,+ options?: RequestInit+): Promise<DataCatalogMetricApi> => {+ return apiMutator<DataCatalogMetricApi>(getDataCatalogMetricsRetrieveUrl(projectId, name), {+ ...options,+ method: 'GET',+ })+}++export const getDataCatalogMetricsUpdateUrl = (projectId: string, name: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${name}/`+}++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const dataCatalogMetricsUpdate = async (+ projectId: string,+ name: string,+ dataCatalogMetricApi: NonReadonly<DataCatalogMetricApi>,+ options?: RequestInit+): Promise<DataCatalogMetricApi> => {+ return apiMutator<DataCatalogMetricApi>(getDataCatalogMetricsUpdateUrl(projectId, name), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataCatalogMetricApi),+ })+}++export const getDataCatalogMetricsPartialUpdateUrl = (projectId: string, name: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${name}/`+}++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const dataCatalogMetricsPartialUpdate = async (+ projectId: string,+ name: string,+ patchedDataCatalogMetricApi?: NonReadonly<PatchedDataCatalogMetricApi>,+ options?: RequestInit+): Promise<DataCatalogMetricApi> => {+ return apiMutator<DataCatalogMetricApi>(getDataCatalogMetricsPartialUpdateUrl(projectId, name), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedDataCatalogMetricApi),+ })+}++export const getDataCatalogMetricsDestroyUrl = (projectId: string, name: string) => {+ return `/api/projects/${projectId}/data_catalog/metrics/${name}/`+}++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const dataCatalogMetricsDestroy = async (+ projectId: string,+ name: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getDataCatalogMetricsDestroyUrl(projectId, name), {+ ...options,+ method: 'DELETE',+ })+}diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..c78fe322bfa0--- /dev/null+++ b/products/data_catalog/frontend/generated/api.zod.ts@@ -0,0 +1,158 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Create a metric, or refine the one already holding this name for the team.+ */+export const dataCatalogMetricsCreateBodyNameMax = 128++export const dataCatalogMetricsCreateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataCatalogMetricsCreateBodyDisplayNameMax = 255++export const dataCatalogMetricsCreateBodyUnitMax = 64++export const dataCatalogMetricsCreateBodyAiModelMax = 128++export const DataCatalogMetricsCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(dataCatalogMetricsCreateBodyNameMax)+ .regex(dataCatalogMetricsCreateBodyNameRegExp)+ .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ display_name: zod+ .string()+ .max(dataCatalogMetricsCreateBodyDisplayNameMax)+ .optional()+ .describe('Human-friendly label. Mutable, unlike name.'),+ description: zod.string().describe('What the metric means and how to interpret it.'),+ unit: zod+ .string()+ .max(dataCatalogMetricsCreateBodyUnitMax)+ .optional()+ .describe('Unit of the result, e.g. usd, percent, cents.'),+ definition: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ created_source: zod+ .enum(['user', 'ai_generated'])+ .describe('\* `user` - user\n\* `ai_generated` - ai_generated')+ .optional()+ .describe(+ "Whether a human ('user') or an agent ('ai_generated') authored this metric.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"+ ),+ ai_model: zod+ .string()+ .max(dataCatalogMetricsCreateBodyAiModelMax)+ .optional()+ .describe('Model that generated the metric, if AI-authored.'),+ confidence: zod.number().nullish().describe("AI author's confidence in the proposal, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+})++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const dataCatalogMetricsUpdateBodyNameMax = 128++export const dataCatalogMetricsUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataCatalogMetricsUpdateBodyDisplayNameMax = 255++export const dataCatalogMetricsUpdateBodyUnitMax = 64++export const dataCatalogMetricsUpdateBodyAiModelMax = 128++export const DataCatalogMetricsUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(dataCatalogMetricsUpdateBodyNameMax)+ .regex(dataCatalogMetricsUpdateBodyNameRegExp)+ .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ display_name: zod+ .string()+ .max(dataCatalogMetricsUpdateBodyDisplayNameMax)+ .optional()+ .describe('Human-friendly label. Mutable, unlike name.'),+ description: zod.string().describe('What the metric means and how to interpret it.'),+ unit: zod+ .string()+ .max(dataCatalogMetricsUpdateBodyUnitMax)+ .optional()+ .describe('Unit of the result, e.g. usd, percent, cents.'),+ definition: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ created_source: zod+ .enum(['user', 'ai_generated'])+ .describe('\* `user` - user\n\* `ai_generated` - ai_generated')+ .optional()+ .describe(+ "Whether a human ('user') or an agent ('ai_generated') authored this metric.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"+ ),+ ai_model: zod+ .string()+ .max(dataCatalogMetricsUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the metric, if AI-authored.'),+ confidence: zod.number().nullish().describe("AI author's confidence in the proposal, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+})++/**+ * CRUD for catalog metrics, addressed by their reserved ``name`` (e.g. /metrics/mrr/).+ */+export const dataCatalogMetricsPartialUpdateBodyNameMax = 128++export const dataCatalogMetricsPartialUpdateBodyNameRegExp = new RegExp('^[A-Za-z][A-Za-z0-9_]\*$')+export const dataCatalogMetricsPartialUpdateBodyDisplayNameMax = 255++export const dataCatalogMetricsPartialUpdateBodyUnitMax = 64++export const dataCatalogMetricsPartialUpdateBodyAiModelMax = 128++export const DataCatalogMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyNameMax)+ .regex(dataCatalogMetricsPartialUpdateBodyNameRegExp)+ .optional()+ .describe('Identifier-safe run handle, unique per team and reserved forever. Write-once.'),+ display_name: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyDisplayNameMax)+ .optional()+ .describe('Human-friendly label. Mutable, unlike name.'),+ description: zod.string().optional().describe('What the metric means and how to interpret it.'),+ unit: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyUnitMax)+ .optional()+ .describe('Unit of the result, e.g. usd, percent, cents.'),+ definition: zod+ .record(zod.string(), zod.unknown())+ .nullish()+ .describe('Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.'),+ created_source: zod+ .enum(['user', 'ai_generated'])+ .describe('\* `user` - user\n\* `ai_generated` - ai_generated')+ .optional()+ .describe(+ "Whether a human ('user') or an agent ('ai_generated') authored this metric.\n\n\* `user` - user\n\* `ai_generated` - ai_generated"+ ),+ ai_model: zod+ .string()+ .max(dataCatalogMetricsPartialUpdateBodyAiModelMax)+ .optional()+ .describe('Model that generated the metric, if AI-authored.'),+ confidence: zod.number().nullish().describe("AI author's confidence in the proposal, 0-1."),+ reasoning: zod.string().optional().describe("AI author's reasoning, surfaced as review context."),+})diff --git a/products/data_catalog/manifest.tsx b/products/data_catalog/manifest.tsxnew file mode 100644index 000000000000..14a2e6a06350--- /dev/null+++ b/products/data_catalog/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for data_catalog.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'DataCatalog',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/data_catalog/package.json b/products/data_catalog/package.jsonnew file mode 100644index 000000000000..e735d088a970--- /dev/null+++ b/products/data_catalog/package.json@@ -0,0 +1,6 @@+{+ "name": "@posthog/products-data-catalog",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"+ }+}diff --git a/products/data_catalog/product.yaml b/products/data_catalog/product.yamlnew file mode 100644index 000000000000..61ee6b85dbe9--- /dev/null+++ b/products/data_catalog/product.yaml@@ -0,0 +1,3 @@+name: Data catalog+owners:+ - team-data-modelingdiff --git a/products/data_catalog/tsconfig.json b/products/data_catalog/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/data_catalog/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex b9028bc1876b..ca4b0ef076dc 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -995,6 +995,7 @@ export type ActivityLogListParams = {* * `SignalReport` - SignalReport* * `SignalScoutConfig` - SignalScoutConfig* * `StreamlitApp` - StreamlitApp+ * * `Metric` - Metric* @minLength 1*/scope?: ActivityLogListScope@@ -1078,6 +1079,7 @@ export const ActivityLogListScope = {SignalReport: 'SignalReport',SignalScoutConfig: 'SignalScoutConfig',StreamlitApp: 'StreamlitApp',+ Metric: 'Metric',} as const/**@@ -1148,6 +1150,7 @@ export const ActivityLogListScope = {* * `SignalReport` - SignalReport* * `SignalScoutConfig` - SignalScoutConfig* * `StreamlitApp` - StreamlitApp+ * * `Metric` - Metric*/export type ActivityLogListScopesItem = (typeof ActivityLogListScopesItem)[keyof typeof ActivityLogListScopesItem]@@ -1219,6 +1222,7 @@ export const ActivityLogListScopesItem = {SignalReport: 'SignalReport',SignalScoutConfig: 'SignalScoutConfig',StreamlitApp: 'StreamlitApp',+ Metric: 'Metric',} as constexport type AdvancedActivityLogsListParams = {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 640a608416a1..6afa13c2c38c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14674,6 +14674,18 @@ export namespace Schemas {color?: string | null;}+ /**+ * * `user` - user+ * * `ai_generated` - ai_generated+ */+ export type CreatedSourceEnum = typeof CreatedSourceEnum[keyof typeof CreatedSourceEnum];+++ export const CreatedSourceEnum = {+ User: 'user',+ AiGenerated: 'ai_generated',+ } as const;+/*** * `web` - web* * `api` - api@@ -15518,6 +15530,87 @@ export namespace Schemas {error: string | null;}+ /**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+ export type DataCatalogMetricDefinition = { [key: string]: unknown } | null;++ export interface DataCatalogMetric {+ readonly id: string;+ /**+ * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name: string;+ /**+ * Human-friendly label. Mutable, unlike name.+ * @maxLength 255+ */+ display_name?: string;+ /** What the metric means and how to interpret it. */+ description: string;+ /**+ * Unit of the result, e.g. usd, percent, cents.+ * @maxLength 64+ */+ unit?: string;+ /**+ * Email of the human accountable for this metric, or null.+ * @nullable+ */+ readonly owner: string | null;+ /**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+ definition?: DataCatalogMetricDefinition;+ /**+ * Query kind of the definition (HogQLQuery, TrendsQuery, ...), or null for a stub.+ * @nullable+ */+ readonly definition_kind: string | null;+ /** Tables the definition directly references, extracted at write time for the catalog's denied-table filter. */+ readonly referenced_table_names: unknown;+ /** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */+ readonly status: string;+ /** @nullable */+ readonly approved_at: string | null;+ /**+ * Short ID of the insight this metric was created from, for drift detection.+ * @nullable+ */+ readonly source_insight_short_id: string | null;+ /**+ * When the metric was last run (30-minute throttle).+ * @nullable+ */+ readonly last_run_at: string | null;+ /** Whether a human ('user') or an agent ('ai_generated') authored this metric.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnum;+ /**+ * Model that generated the metric, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string;+ /**+ * AI author's confidence in the proposal, 0-1.+ * @nullable+ */+ confidence?: number | null;+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string;+ /** User who first created this metric. */+ readonly created_by: UserBasic;+ readonly created_at: string;+ /** @nullable */+ readonly updated_at: string | null;+ }+export interface DataColorTheme {readonly id: number;/** @maxLength 100 */@@ -33954,6 +34047,15 @@ export namespace Schemas {results: DashboardTemplate[];}+ export interface PaginatedDataCatalogMetricList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: DataCatalogMetric[];+ }+export interface PaginatedDataColorThemeList {count: number;/** @nullable */@@ -39365,6 +39467,87 @@ export namespace Schemas {readonly non_portable_references?: NonPortableReferences;}+ /**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+ export type PatchedDataCatalogMetricDefinition = { [key: string]: unknown } | null;++ export interface PatchedDataCatalogMetric {+ readonly id?: string;+ /**+ * Identifier-safe run handle, unique per team and reserved forever. Write-once.+ * @maxLength 128+ * @pattern ^[A-Za-z][A-Za-z0-9_]*$+ */+ name?: string;+ /**+ * Human-friendly label. Mutable, unlike name.+ * @maxLength 255+ */+ display_name?: string;+ /** What the metric means and how to interpret it. */+ description?: string;+ /**+ * Unit of the result, e.g. usd, percent, cents.+ * @maxLength 64+ */+ unit?: string;+ /**+ * Email of the human accountable for this metric, or null.+ * @nullable+ */+ readonly owner?: string | null;+ /**+ * Machine-readable query. Omit for a name+description-only stub. Stored upgrade-canonical.+ * @nullable+ */+ definition?: PatchedDataCatalogMetricDefinition;+ /**+ * Query kind of the definition (HogQLQuery, TrendsQuery, ...), or null for a stub.+ * @nullable+ */+ readonly definition_kind?: string | null;+ /** Tables the definition directly references, extracted at write time for the catalog's denied-table filter. */+ readonly referenced_table_names?: unknown;+ /** Persisted lifecycle state: 'proposed' or 'approved'. Drift is reported separately. */+ readonly status?: string;+ /** @nullable */+ readonly approved_at?: string | null;+ /**+ * Short ID of the insight this metric was created from, for drift detection.+ * @nullable+ */+ readonly source_insight_short_id?: string | null;+ /**+ * When the metric was last run (30-minute throttle).+ * @nullable+ */+ readonly last_run_at?: string | null;+ /** Whether a human ('user') or an agent ('ai_generated') authored this metric.+ *+ * * `user` - user+ * * `ai_generated` - ai_generated */+ created_source?: CreatedSourceEnum;+ /**+ * Model that generated the metric, if AI-authored.+ * @maxLength 128+ */+ ai_model?: string;+ /**+ * AI author's confidence in the proposal, 0-1.+ * @nullable+ */+ confidence?: number | null;+ /** AI author's reasoning, surfaced as review context. */+ reasoning?: string;+ /** User who first created this metric. */+ readonly created_by?: UserBasic;+ readonly created_at?: string;+ /** @nullable */+ readonly updated_at?: string | null;+ }+export interface PatchedDataColorTheme {readonly id?: number;/** @maxLength 100 */@@ -65417,6 +65600,7 @@ export namespace Schemas {* * `SignalReport` - SignalReport* * `SignalScoutConfig` - SignalScoutConfig* * `StreamlitApp` - StreamlitApp+ * * `Metric` - Metric* @minLength 1*/scope?: ActivityLogListScope;@@ -65501,6 +65685,7 @@ export namespace Schemas {SignalReport: 'SignalReport',SignalScoutConfig: 'SignalScoutConfig',StreamlitApp: 'StreamlitApp',+ Metric: 'Metric',} as const;/**@@ -65571,6 +65756,7 @@ export namespace Schemas {* * `SignalReport` - SignalReport* * `SignalScoutConfig` - SignalScoutConfig* * `StreamlitApp` - StreamlitApp+ * * `Metric` - Metric*/export type ActivityLogListScopesItem = typeof ActivityLogListScopesItem[keyof typeof ActivityLogListScopesItem];@@ -65643,6 +65829,7 @@ export namespace Schemas {SignalReport: 'SignalReport',SignalScoutConfig: 'SignalScoutConfig',StreamlitApp: 'StreamlitApp',+ Metric: 'Metric',} as const;export type AdvancedActivityLogsListParams = {@@ -66891,6 +67078,17 @@ export namespace Schemas {Txt: 'txt',} as const;+ export type DataCatalogMetricsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type DataColorThemesListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex dfbc203ac48d..b6fc32ea27af 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -47,6 +47,10 @@ export const OAUTH_SCOPES_SUPPORTED = ['customer_journey:write','customer_profile_config:read','customer_profile_config:write',+ 'data_catalog:read',+ 'data_catalog:write',+ 'data_catalog_approval:read',+ 'data_catalog_approval:write','dashboard:read','dashboard:write','event_filter:read',diff --git a/tach.toml b/tach.tomlindex c83cb7bfc47c..c96df45ba0b7 100644--- a/tach.toml+++ b/tach.toml@@ -1027,3 +1027,23 @@ layer = "modules"path = "products.field_notes"depends_on = ["posthog"]layer = "modules"++[[modules]]+path = "products.data_catalog"+depends_on = [+ "posthog",+ "products.data_tools",+ "products.product_analytics",+ "products.warehouse_sources",+ "products.data_modeling",+]+layer = "modules"++[[interfaces]]+expose = [+ "backend\\.facade.*",+ "backend\\.presentation\\.views.*",+]+from = [+ "products.data_catalog",+]