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-modeling): add metric node type and metric_id column (#101591)

Thiago Salvatore3fb029c29efb
diff --git a/posthog/temporal/data_modeling/activities/get_dag_structure.py b/posthog/temporal/data_modeling/activities/get_dag_structure.py
index d833e95b2897..5afc655a9fd6 100644
--- a/posthog/temporal/data_modeling/activities/get_dag_structure.py
+++ b/posthog/temporal/data_modeling/activities/get_dag_structure.py
@@ -5,7 +5,13 @@ from temporalio import activity
from posthog.sync import database_sync_to_async_pool
from posthog.temporal.common.logger import get_logger
-from products.data_modeling.backend.facade.models import DataModelingJobEngine, Edge, Node, NodeType
+from products.data_modeling.backend.facade.models import (
+ SAVED_QUERY_NODE_TYPES,
+ DataModelingJobEngine,
+ Edge,
+ Node,
+ NodeType,
+)
from .utils import is_node_suspended
@@ -46,9 +52,7 @@ def _get_dag_structure_async(team_id: int, dag_id: str) -> DAG:
nodes = Node.objects.filter(team_id=team_id, dag_id=dag_id)
# a node outlives the query it points at, because deleting one is best-effort while soft-deleting
# the query is not. running it can only fail, so it must not reach the materialization activity.
- executable_nodes = nodes.filter(type__in=[NodeType.VIEW, NodeType.MAT_VIEW, NodeType.ENDPOINT]).exclude(
- saved_query__deleted=True
- )
+ executable_nodes = nodes.filter(type__in=SAVED_QUERY_NODE_TYPES).exclude(saved_query__deleted=True)
ephemeral_nodes = executable_nodes.filter(type=NodeType.VIEW)
edges = (
Edge.objects.prefetch_related("source", "target")
diff --git a/products/data_modeling/backend/facade/models.py b/products/data_modeling/backend/facade/models.py
index 4e47615bd385..6add25b290a2 100644
--- a/products/data_modeling/backend/facade/models.py
+++ b/products/data_modeling/backend/facade/models.py
@@ -36,13 +36,14 @@ from products.data_modeling.backend.models.datawarehouse_saved_query_column_anno
)
from products.data_modeling.backend.models.datawarehouse_saved_query_draft import DataWarehouseSavedQueryDraft
from products.data_modeling.backend.models.edge import Edge
-from products.data_modeling.backend.models.node import Node, NodeType
+from products.data_modeling.backend.models.node import SAVED_QUERY_NODE_TYPES, LineageIssueKind, Node, NodeType
__all__ = [
"DAG",
"DEFAULT_DAG_NAME",
"RESERVED_DAG_NAMES",
"REVENUE_ANALYTICS_DAG_NAME",
+ "SAVED_QUERY_NODE_TYPES",
"DataModelingJob",
"DataModelingJobEngine",
"DataModelingJobStatus",
@@ -52,6 +53,7 @@ __all__ = [
"DataWarehouseSavedQueryDraft",
"Edge",
"Graph",
+ "LineageIssueKind",
"Node",
"NodeType",
"aget_saved_query_by_id",
diff --git a/products/data_modeling/backend/graph.py b/products/data_modeling/backend/graph.py
index 41ae9251d94e..23350da3854f 100644
--- a/products/data_modeling/backend/graph.py
+++ b/products/data_modeling/backend/graph.py
@@ -25,6 +25,7 @@ class Graph:
dag_id: UUID | str | None = None,
exclude_table_sources: bool = True,
exclude_table_targets: bool = True,
+ hidden_types: frozenset[str] = frozenset(),
):
"""Load edges and build adjacency maps.
@@ -33,6 +34,8 @@ class Graph:
dag_id: if set, filter to a single DAG; otherwise load all DAGs
exclude_table_sources: skip edges whose source is a TABLE node (for upstream counts)
exclude_table_targets: skip edges whose target is a TABLE node (for downstream counts)
+ hidden_types: node types the reader may not see, dropped from both sides so a count
+ never reports a node the same reader's node list omits
"""
qs = Edge.objects.filter(team_id=team_id)
if dag_id:
@@ -49,6 +52,8 @@ class Graph:
self._downstream_adj: dict[str, set[str]] = defaultdict(set) # source -> targets
for source_id, target_id, source_type, target_type in edge_rows:
+ if source_type in hidden_types or target_type in hidden_types:
+ continue
s = str(source_id)
t = str(target_id)
if not exclude_table_sources or source_type != NodeType.TABLE:
diff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.py
index afc9f7789cfc..0b3da77b254c 100644
--- a/products/data_modeling/backend/logic/node_frequency.py
+++ b/products/data_modeling/backend/logic/node_frequency.py
@@ -26,7 +26,7 @@ from products.data_modeling.backend.logic.freshness import (
)
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.models.edge import Edge
-from products.data_modeling.backend.models.node import Node, NodeType
+from products.data_modeling.backend.models.node import SAVED_QUERY_NODE_TYPES, Node, NodeType
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema
# Declared target lives here, mirroring properties["system"]["suspended"] (circuit breaker).
@@ -224,7 +224,7 @@ def build_frequency_graph(dag: DAG) -> FrequencyGraph:
for source_id, target_id in Edge.objects.filter(dag=dag).values_list("source_id", "target_id")
]
- schedulable = {str(node.id) for node in nodes if node.type != NodeType.TABLE}
+ schedulable = {str(node.id) for node in nodes if node.type in SAVED_QUERY_NODE_TYPES}
declared_targets: dict[str, timedelta] = {}
declared_anchors: dict[str, int] = {}
for node in nodes:
@@ -308,7 +308,7 @@ def saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) ->
def schedulable_nodes(dag: DAG) -> QuerySet[Node]:
"""The DAG's schedulable nodes: everything that carries a live saved query (not a source
table, not a soft-deleted query). The one definition of "what gets a freshness target"."""
- return Node.objects.filter(dag=dag).exclude(type=NodeType.TABLE).exclude(saved_query__deleted=True)
+ return Node.objects.filter(dag=dag, type__in=SAVED_QUERY_NODE_TYPES).exclude(saved_query__deleted=True)
def persist_seed_targets(dag: DAG, default: timedelta | None = None) -> int:
diff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.py
index de24d4f8bbef..ae25715167cd 100644
--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py
+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, TypedDict
+from typing import TYPE_CHECKING
from django.db import IntegrityError, transaction
from django.db.models import Q, QuerySet
@@ -26,15 +26,6 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
-# properties["system"] marker set by consolidate_dags --adopt-unresolvable when a query's SQL
-# would not resolve and its node was created without edges. A successful sync clears it.
-DEGRADED_SYNC_KEY = "degraded_sync"
-
-
-class DegradedSyncMarker(TypedDict):
- error: str
- at: str
-
def materializes(saved_query: "DataWarehouseSavedQuery") -> bool:
"""Whether a saved query is asking to be materialized.
@@ -290,11 +281,7 @@ def sync_saved_query_to_dag(
raise
# resolution succeeded, so an edge-less adoption marker no longer describes this node
- system = (target.properties or {}).get("system")
- if isinstance(system, dict):
- system.pop(DEGRADED_SYNC_KEY, None)
- if not system:
- target.properties.pop("system", None)
+ target.clear_lineage_markers()
# name is included in update_fields because Node.save() auto-syncs it from saved_query
target.save(update_fields=["name", "type", "properties"])
diff --git a/products/data_modeling/backend/logic/tier_run_report.py b/products/data_modeling/backend/logic/tier_run_report.py
index b5b2a2244f18..47d4ba6e5b41 100644
--- a/products/data_modeling/backend/logic/tier_run_report.py
+++ b/products/data_modeling/backend/logic/tier_run_report.py
@@ -161,9 +161,11 @@ def _reportable_nodes(dag: DAG) -> list[Node]:
"""Every node a run could act on. Mirrors `schedulable_nodes`' exclusion of soft-deleted saved
queries — those keep their target but the scheduler never sees them, so reporting them would
manufacture permanent phantom rows. Source (TABLE) nodes are kept so the page can show them.
+ METRIC nodes are dropped: nothing ever runs them.
"""
return list(
Node.objects.filter(team_id=dag.team_id, dag=dag)
+ .exclude(type=NodeType.METRIC)
.exclude(saved_query__deleted=True)
.select_related("saved_query")
)
diff --git a/products/data_modeling/backend/management/commands/check_node_tier_schedule.py b/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
index 5d7449fc3d18..846e73db1954 100644
--- a/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
+++ b/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
@@ -31,7 +31,7 @@ from products.data_modeling.backend.logic.tier_membership import (
read_live_tiers,
)
from products.data_modeling.backend.models.dag import DAG
-from products.data_modeling.backend.models.node import Node, NodeType
+from products.data_modeling.backend.models.node import SAVED_QUERY_NODE_TYPES, Node
class Command(BaseCommand):
@@ -116,7 +116,7 @@ class Command(BaseCommand):
self._print_human(live_by_dag, dags_by_id, statuses)
def _resolve_nodes(self, team_id: int, options: dict[str, Any]) -> list[Node]:
- qs = Node.objects.filter(team_id=team_id).exclude(type=NodeType.TABLE)
+ qs = Node.objects.filter(team_id=team_id, type__in=SAVED_QUERY_NODE_TYPES)
if options["node_id"]:
qs = qs.filter(id=options["node_id"])
elif options["saved_query_id"]:
@@ -131,9 +131,9 @@ class Command(BaseCommand):
def _dag_nodes(self, team_id: int, dag_id: str) -> list[Node]:
return list(
- Node.objects.filter(team_id=team_id, dag_id=dag_id)
- .exclude(type=NodeType.TABLE)
- .select_related("dag", "saved_query")
+ Node.objects.filter(team_id=team_id, dag_id=dag_id, type__in=SAVED_QUERY_NODE_TYPES).select_related(
+ "dag", "saved_query"
+ )
)
@staticmethod
diff --git a/products/data_modeling/backend/management/commands/consolidate_dags.py b/products/data_modeling/backend/management/commands/consolidate_dags.py
index a7a600c027d3..d92a88f821d6 100644
--- a/products/data_modeling/backend/management/commands/consolidate_dags.py
+++ b/products/data_modeling/backend/management/commands/consolidate_dags.py
@@ -8,7 +8,6 @@ from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError, CommandParser
from django.db import transaction
-from django.utils import timezone
import structlog
from temporalio.client import Client
@@ -30,12 +29,7 @@ from products.data_modeling.backend.logic.node_frequency import (
schedulable_nodes,
set_declared_target,
)
-from products.data_modeling.backend.logic.saved_query_dag_sync import (
- DEGRADED_SYNC_KEY,
- DegradedSyncMarker,
- node_type_for,
- sync_saved_query_to_dag,
-)
+from products.data_modeling.backend.logic.saved_query_dag_sync import node_type_for, sync_saved_query_to_dag
from products.data_modeling.backend.logic.schedule_reconcile import (
delete_dag_schedules,
delete_v1_saved_query_schedules,
@@ -601,7 +595,6 @@ class Command(BaseCommand):
fleet-wide, and the next successful sync clears the marker and rebuilds real edges.
Returns None if even the bare node cannot be created, falling back to keeping the DAG.
"""
- marker: DegradedSyncMarker = {"error": str(error)[:500], "at": timezone.now().isoformat()}
try:
# Atomic so a failed marker save rolls the creation back too: a committed but
# unmarked node would make the re-run classify this query as DROP instead of
@@ -613,9 +606,8 @@ class Command(BaseCommand):
dag=target,
defaults={"name": saved_query.name, "type": node_type_for(saved_query)},
)
- properties = node.properties or {}
- properties.setdefault("system", {})[DEGRADED_SYNC_KEY] = marker
- node.properties = properties
+ node.properties = node.properties or {}
+ node.mark_lineage_sync_failed(str(error))
node.save(update_fields=["properties"])
return node
except Exception:
diff --git a/products/data_modeling/backend/migrations/0044_node_metric_type.py b/products/data_modeling/backend/migrations/0044_node_metric_type.py
new file mode 100644
index 000000000000..9e0c92ed9df3
--- /dev/null
+++ b/products/data_modeling/backend/migrations/0044_node_metric_type.py
@@ -0,0 +1,52 @@
+from django.db import migrations, models
+from django.db.models import Q
+
+from posthog.migration_helpers import AddConstraintNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_modeling", "0043_datawarehousesavedquery_query_revision"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="node",
+ name="metric_id",
+ field=models.UUIDField(blank=True, null=True),
+ ),
+ migrations.AlterField(
+ model_name="node",
+ name="type",
+ field=models.TextField(
+ choices=[
+ ("table", "Table"),
+ ("view", "View"),
+ ("matview", "Mat View"),
+ ("endpoint", "Endpoint"),
+ ("metric", "Metric"),
+ ],
+ default="table",
+ max_length=16,
+ ),
+ ),
+ migrations.RemoveConstraint(
+ model_name="node",
+ name="saved_query_required_on_non_table_node_type",
+ ),
+ AddConstraintNotValid(
+ model_name="node",
+ constraint=models.CheckConstraint(
+ name="node_backing_reference_matches_type",
+ condition=(
+ Q(type="table", metric_id__isnull=True)
+ | Q(
+ type__in=["endpoint", "matview", "view"],
+ saved_query__isnull=False,
+ metric_id__isnull=True,
+ )
+ | Q(type="metric", saved_query__isnull=True, metric_id__isnull=False)
+ ),
+ ),
+ ),
+ ]
diff --git a/products/data_modeling/backend/migrations/0045_node_metric_indexes.py b/products/data_modeling/backend/migrations/0045_node_metric_indexes.py
new file mode 100644
index 000000000000..591e5ab15f19
--- /dev/null
+++ b/products/data_modeling/backend/migrations/0045_node_metric_indexes.py
@@ -0,0 +1,65 @@
+from django.db import migrations, models
+from django.db.models import Q
+
+from posthog.migration_helpers import CreateIndexConcurrently, DropIndexConcurrently, ValidateConstraint
+
+NODE_TABLE = "posthog_datamodelingnode"
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("data_modeling", "0044_node_metric_type"),
+ ]
+
+ operations = [
+ ValidateConstraint(model_name="node", name="node_backing_reference_matches_type"),
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="metric_unique_within_team_dag",
+ table_name=NODE_TABLE,
+ columns="(team_id, dag_fk_id, metric_id)",
+ unique=True,
+ where="WHERE metric_id IS NOT NULL",
+ ),
+ CreateIndexConcurrently(
+ index_name="name_unique_within_team_dag_for_tables_v2",
+ table_name=NODE_TABLE,
+ columns="(team_id, dag_fk_id, name)",
+ unique=True,
+ where="WHERE saved_query_id IS NULL AND metric_id IS NULL",
+ ),
+ DropIndexConcurrently(
+ index_name="name_unique_within_team_dag_for_tables",
+ table_name=NODE_TABLE,
+ columns="(team_id, dag_fk_id, name)",
+ unique=True,
+ where="WHERE saved_query_id IS NULL",
+ ),
+ ],
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="node",
+ constraint=models.UniqueConstraint(
+ condition=Q(metric_id__isnull=False),
+ fields=["team", "dag", "metric_id"],
+ name="metric_unique_within_team_dag",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="node",
+ constraint=models.UniqueConstraint(
+ condition=Q(saved_query__isnull=True, metric_id__isnull=True),
+ fields=["team", "dag", "name"],
+ name="name_unique_within_team_dag_for_tables_v2",
+ ),
+ ),
+ migrations.RemoveConstraint(
+ model_name="node",
+ name="name_unique_within_team_dag_for_tables",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/data_modeling/backend/migrations/max_migration.txt b/products/data_modeling/backend/migrations/max_migration.txt
index e38f0fa24db5..c4864d3f066b 100644
--- a/products/data_modeling/backend/migrations/max_migration.txt
+++ b/products/data_modeling/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0043_datawarehousesavedquery_query_revision
+0045_node_metric_indexes
diff --git a/products/data_modeling/backend/models/node.py b/products/data_modeling/backend/models/node.py
index b739dfe89a14..da4a23983ba9 100644
--- a/products/data_modeling/backend/models/node.py
+++ b/products/data_modeling/backend/models/node.py
@@ -1,5 +1,9 @@
+from collections.abc import Sequence
+from typing import Any, TypedDict
+
from django.db import models
from django.db.models import Q
+from django.utils import timezone
from posthog.models import Team
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
@@ -14,6 +18,35 @@ class NodeType(models.TextChoices):
VIEW = "view"
MAT_VIEW = "matview"
ENDPOINT = "endpoint"
+ METRIC = "metric"
+
+
+SAVED_QUERY_NODE_TYPES = frozenset({NodeType.VIEW, NodeType.MAT_VIEW, NodeType.ENDPOINT})
+_SAVED_QUERY_NODE_TYPE_VALUES = sorted(node_type.value for node_type in SAVED_QUERY_NODE_TYPES)
+
+
+# properties["system"] marker set by consolidate_dags --adopt-unresolvable when a query's SQL
+# would not resolve and its node was created without edges. A successful sync clears it.
+DEGRADED_SYNC_KEY = "degraded_sync"
+
+UNRESOLVED_DEPENDENCIES_KEY = "unresolved"
+
+MAX_SYNC_ERROR_LENGTH = 500
+
+
+class DegradedSyncMarker(TypedDict):
+ error: str
+ at: str
+
+
+class UnresolvedDependenciesMarker(TypedDict):
+ names: list[str]
+ at: str
+
+
+class LineageIssueKind(models.TextChoices):
+ SYNC_FAILED = "sync_failed"
+ UNRESOLVED = "unresolved"
class Node(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
@@ -24,6 +57,8 @@ class Node(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
saved_query = models.ForeignKey(DataWarehouseSavedQuery, on_delete=models.PROTECT, null=True, blank=True)
saved_query_id: int | None
+ metric_id = models.UUIDField(null=True, blank=True)
+
dag = models.ForeignKey(DAG, on_delete=models.CASCADE, db_column="dag_fk_id")
dag_id: int
@@ -38,6 +73,45 @@ class Node(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
)
properties = models.JSONField(default=dict)
+ def mark_lineage_sync_failed(self, error: str) -> None:
+ marker: DegradedSyncMarker = {
+ "error": str(error)[:MAX_SYNC_ERROR_LENGTH],
+ "at": timezone.now().isoformat(),
+ }
+ self.properties.setdefault("system", {})[DEGRADED_SYNC_KEY] = marker
+
+ def mark_lineage_unresolved(self, names: Sequence[str]) -> None:
+ marker: UnresolvedDependenciesMarker = {"names": list(names), "at": timezone.now().isoformat()}
+ self.properties.setdefault("system", {})[UNRESOLVED_DEPENDENCIES_KEY] = marker
+
+ def clear_lineage_markers(self) -> None:
+ system = (self.properties or {}).get("system")
+ if not isinstance(system, dict):
+ return
+ system.pop(DEGRADED_SYNC_KEY, None)
+ system.pop(UNRESOLVED_DEPENDENCIES_KEY, None)
+ if not system:
+ self.properties.pop("system", None)
+
+ @property
+ def lineage_issue(self) -> dict[str, Any] | None:
+ system = (self.properties or {}).get("system") or {}
+ degraded = system.get(DEGRADED_SYNC_KEY)
+ if isinstance(degraded, dict):
+ return {
+ "kind": LineageIssueKind.SYNC_FAILED.value,
+ "detail": degraded.get("error") or "",
+ "at": degraded.get("at"),
+ }
+ unresolved = system.get(UNRESOLVED_DEPENDENCIES_KEY)
+ if not isinstance(unresolved, dict) or not unresolved.get("names"):
+ return None
+ return {
+ "kind": LineageIssueKind.UNRESOLVED.value,
+ "detail": ", ".join(unresolved["names"]),
+ "at": unresolved.get("at"),
+ }
+
def save(self, *args, **kwargs):
# always inherit name from saved_query when one exists
if self.saved_query is not None:
@@ -50,8 +124,16 @@ class Node(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
db_table = "posthog_datamodelingnode"
constraints = [
models.CheckConstraint(
- name="saved_query_required_on_non_table_node_type",
- condition=Q(type=NodeType.TABLE) | Q(saved_query__isnull=False),
+ name="node_backing_reference_matches_type",
+ condition=(
+ Q(type=NodeType.TABLE, metric_id__isnull=True)
+ | Q(
+ type__in=_SAVED_QUERY_NODE_TYPE_VALUES,
+ saved_query__isnull=False,
+ metric_id__isnull=True,
+ )
+ | Q(type=NodeType.METRIC, saved_query__isnull=True, metric_id__isnull=False)
+ ),
),
models.UniqueConstraint(
condition=models.Q(saved_query__isnull=False),
@@ -59,8 +141,13 @@ class Node(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
fields=["team", "dag", "saved_query"],
),
models.UniqueConstraint(
- condition=models.Q(saved_query__isnull=True),
- name="name_unique_within_team_dag_for_tables",
+ condition=models.Q(metric_id__isnull=False),
+ name="metric_unique_within_team_dag",
+ fields=["team", "dag", "metric_id"],
+ ),
+ models.UniqueConstraint(
+ condition=models.Q(saved_query__isnull=True, metric_id__isnull=True),
+ name="name_unique_within_team_dag_for_tables_v2",
fields=["team", "dag", "name"],
),
]
diff --git a/products/data_modeling/backend/presentation/views/edge.py b/products/data_modeling/backend/presentation/views/edge.py
index 2f82a922c59a..063ff6fff60d 100644
--- a/products/data_modeling/backend/presentation/views/edge.py
+++ b/products/data_modeling/backend/presentation/views/edge.py
@@ -6,7 +6,14 @@ from rest_framework.pagination import PageNumberPagination
from posthog.api.routing import TeamAndOrgViewSetMixin
-from products.data_modeling.backend.facade.models import Edge
+from products.data_modeling.backend.facade.models import Edge, NodeType
+from products.data_modeling.backend.presentation.views.metric_visibility import MetricNodeVisibilityMixin
+
+_METRIC_EDGE_REFUSAL = "Edges that connect a metric are maintained by the data catalog."
+
+
+def _connects_a_metric(edge: Edge) -> bool:
+ return NodeType.METRIC in (edge.source.type, edge.target.type)
class EdgeSerializer(serializers.ModelSerializer):
@@ -45,6 +52,8 @@ class EdgeSerializer(serializers.ModelSerializer):
target_dag = attrs.get("dag")
if target_dag is not None and target_dag.is_managed:
raise serializers.ValidationError("Edges cannot be created in or moved into a system-managed DAG.")
+ if self.instance is not None and _connects_a_metric(self.instance):
+ raise serializers.ValidationError(_METRIC_EDGE_REFUSAL)
return attrs
@@ -52,7 +61,7 @@ class EdgePagination(PageNumberPagination):
page_size = 5000
-class EdgeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+class EdgeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "INTERNAL"
queryset = Edge.objects.select_related("dag").all()
serializer_class = EdgeSerializer
@@ -67,10 +76,12 @@ class EdgeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def perform_destroy(self, instance: Edge) -> None:
if instance.dag.is_managed:
raise serializers.ValidationError("Edges belonging to a system-managed DAG cannot be deleted.")
+ if _connects_a_metric(instance):
+ raise serializers.ValidationError(_METRIC_EDGE_REFUSAL)
instance.delete()
def safely_get_queryset(self, queryset):
- qs = queryset.filter(team_id=self.team_id)
+ qs = self._exclude_hidden_edges(queryset.filter(team_id=self.team_id))
dag_id = self.request.query_params.get("dag")
if dag_id:
try:
diff --git a/products/data_modeling/backend/presentation/views/metric_visibility.py b/products/data_modeling/backend/presentation/views/metric_visibility.py
new file mode 100644
index 000000000000..d86fadabc671
--- /dev/null
+++ b/products/data_modeling/backend/presentation/views/metric_visibility.py
@@ -0,0 +1,28 @@
+from typing import TYPE_CHECKING
+
+from django.db.models import Q, QuerySet
+
+from products.data_modeling.backend.facade.models import NodeType
+
+if TYPE_CHECKING:
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+
+class MetricNodeVisibilityMixin:
+ user_access_control: "UserAccessControl"
+
+ def _metric_nodes_hidden(self) -> bool:
+ return not self.user_access_control.check_access_level_for_resource("data_catalog", required_level="viewer")
+
+ def _hidden_node_types(self) -> frozenset[str]:
+ return frozenset({NodeType.METRIC}) if self._metric_nodes_hidden() else frozenset()
+
+ def _exclude_hidden_nodes(self, queryset: QuerySet) -> QuerySet:
+ if self._metric_nodes_hidden():
+ return queryset.exclude(type=NodeType.METRIC)
+ return queryset
+
+ def _exclude_hidden_edges(self, queryset: QuerySet) -> QuerySet:
+ if self._metric_nodes_hidden():
+ return queryset.exclude(Q(source__type=NodeType.METRIC) | Q(target__type=NodeType.METRIC))
+ return queryset
diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.py
index 98bb212b064c..a7537c9cc1a8 100644
--- a/products/data_modeling/backend/presentation/views/node.py
+++ b/products/data_modeling/backend/presentation/views/node.py
@@ -34,13 +34,17 @@ from products.data_modeling.backend.facade.api import (
)
from products.data_modeling.backend.facade.models import (
DAG,
+ SAVED_QUERY_NODE_TYPES,
DataModelingJob,
DataModelingJobEngine,
DataWarehouseSavedQuery,
Edge,
+ LineageIssueKind,
Node,
NodeType,
)
+from products.data_modeling.backend.presentation.views.edge import EdgeSerializer
+from products.data_modeling.backend.presentation.views.metric_visibility import MetricNodeVisibilityMixin
from products.warehouse_sources.backend.facade.models import sync_frequency_interval_to_sync_frequency
@@ -59,6 +63,22 @@ class NodeEndpointSerializer(serializers.Serializer):
version = serializers.IntegerField(help_text="Endpoint version this node's materialization backs.")
+class LineageLookupError(Exception):
+ """Raised when the lineage request names no node, or names one with an unparseable id."""
+
+
+class LineageIssueSerializer(serializers.Serializer):
+ kind = serializers.ChoiceField(
+ choices=LineageIssueKind.choices,
+ help_text="sync_failed when the last attempt to rebuild this node's edges ended in an error. "
+ "unresolved when the rebuild finished but some of the names this node reads matched no node in the DAG.",
+ )
+ detail = serializers.CharField(
+ help_text="The error for sync_failed, or the comma-separated names that did not resolve for unresolved."
+ )
+ at = serializers.DateTimeField(allow_null=True, help_text="When the issue was recorded.")
+
+
class NodeSerializer(serializers.ModelSerializer):
suspended = serializers.SerializerMethodField(read_only=True)
endpoint = serializers.SerializerMethodField(read_only=True)
@@ -70,6 +90,7 @@ class NodeSerializer(serializers.ModelSerializer):
user_tag = serializers.SerializerMethodField(read_only=True)
sync_interval = serializers.SerializerMethodField(read_only=True)
dag_name = serializers.SerializerMethodField(read_only=True)
+ lineage_issue = serializers.SerializerMethodField(read_only=True)
dag = TeamScopedPrimaryKeyRelatedField(queryset=DAG.objects.all())
class Meta:
@@ -82,6 +103,8 @@ class NodeSerializer(serializers.ModelSerializer):
"dag_name",
"description",
"saved_query_id",
+ "metric_id",
+ "lineage_issue",
"created_at",
"updated_at",
"upstream_count",
@@ -105,6 +128,8 @@ class NodeSerializer(serializers.ModelSerializer):
"sync_interval",
"dag_name",
"saved_query_id",
+ "metric_id",
+ "lineage_issue",
]
@extend_schema_field(
@@ -131,13 +156,16 @@ class NodeSerializer(serializers.ModelSerializer):
counts = self.context.get("node_counts")
if counts and str(node.id) in counts:
return counts[str(node.id)][0]
- return len(_get_upstream_nodes(node))
+ return len(_get_upstream_nodes(node, hidden_types=self._hidden_types()))
def get_downstream_count(self, node: Node) -> int:
counts = self.context.get("node_counts")
if counts and str(node.id) in counts:
return counts[str(node.id)][1]
- return len(_get_downstream_nodes(node))
+ return len(_get_downstream_nodes(node, hidden_types=self._hidden_types()))
+
+ def _hidden_types(self) -> frozenset[str]:
+ return self.context.get("hidden_node_types") or frozenset()
def get_last_run_at(self, node: Node) -> str | None:
run_at = getattr(node, "_latest_job_run_at", None)
@@ -172,6 +200,10 @@ class NodeSerializer(serializers.ModelSerializer):
def get_dag_name(self, node: Node) -> str:
return node.dag.name
+ @extend_schema_field(LineageIssueSerializer(allow_null=True))
+ def get_lineage_issue(self, node: Node) -> dict[str, Any] | None:
+ return node.lineage_issue
+
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
# System-managed DAGs (e.g. Revenue Analytics) own their nodes; the internal sync path
# maintains them directly via the ORM and bypasses this serializer. Block users from
@@ -181,6 +213,17 @@ class NodeSerializer(serializers.ModelSerializer):
target_dag = attrs.get("dag")
if target_dag is not None and target_dag.is_managed:
raise serializers.ValidationError("Nodes cannot be created in or moved into a system-managed DAG.")
+ if self.instance is not None and self.instance.type == NodeType.METRIC:
+ raise serializers.ValidationError("Metric nodes are maintained by the data catalog.")
+ node_type = attrs.get("type")
+ if node_type is not None:
+ # A full PUT round-trips the node's own type, so a type equal to the current one is
+ # not a retype and must not be rejected.
+ if self.instance is None:
+ if node_type != NodeType.TABLE:
+ raise serializers.ValidationError("Only table nodes can be created through the API.")
+ elif node_type != self.instance.type:
+ raise serializers.ValidationError("A node's type cannot be changed through the API.")
return attrs
@@ -199,7 +242,9 @@ _READ_DENIED = "Reading data models requires data warehouse read access."
# the temporal workflow and lineage API should migrate to Graph
-def _get_upstream_nodes(node: Node, include_tables: bool = False) -> set[str]:
+def _get_upstream_nodes(
+ node: Node, include_tables: bool = False, hidden_types: frozenset[str] = frozenset()
+) -> set[str]:
"""Get all upstream (ancestor) node IDs recursively, optionally excluding TABLE nodes."""
nodes: set[str] = set()
current = [node.id]
@@ -211,25 +256,26 @@ def _get_upstream_nodes(node: Node, include_tables: bool = False) -> set[str]:
)
if not include_tables:
qs = qs.exclude(source__type=NodeType.TABLE)
+ if hidden_types:
+ qs = qs.exclude(source__type__in=hidden_types)
current = list(qs.values_list("source_id", flat=True))
nodes.update(str(i) for i in current)
return nodes
-def _get_downstream_nodes(node: Node) -> set[str]:
+def _get_downstream_nodes(node: Node, hidden_types: frozenset[str] = frozenset()) -> set[str]:
"""Get all downstream (descendant) node IDs recursively, excluding TABLE nodes."""
nodes: set[str] = set()
current = [node.id]
while current:
- current = list(
- Edge.objects.exclude(target__type=NodeType.TABLE)
- .filter(
- team_id=node.team_id,
- dag=node.dag,
- source_id__in=current,
- )
- .values_list("target_id", flat=True)
+ qs = Edge.objects.exclude(target__type=NodeType.TABLE).filter(
+ team_id=node.team_id,
+ dag=node.dag,
+ source_id__in=current,
)
+ if hidden_types:
+ qs = qs.exclude(target__type__in=hidden_types)
+ current = list(qs.values_list("target_id", flat=True))
nodes.update(str(i) for i in current)
return nodes
@@ -257,7 +303,12 @@ def _node_queryset_with_latest_job() -> models.QuerySet:
return _annotate_latest_job(Node.objects.select_related("saved_query", "dag").all())
-class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+class LineageResponseSerializer(serializers.Serializer):
+ nodes = NodeSerializer(many=True, help_text="Every node reachable from the requested one, plus the node itself.")
+ edges = EdgeSerializer(many=True, help_text="Every edge between two of those nodes.")
+
+
+class NodeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "INTERNAL"
queryset = Node.objects.select_related("saved_query", "dag").all()
serializer_class = NodeSerializer
@@ -267,11 +318,13 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
ordering = "name"
def get_serializer_context(self) -> dict[str, Any]:
- return super().get_serializer_context()
+ return {**super().get_serializer_context(), "hidden_node_types": self._hidden_node_types()}
def perform_destroy(self, instance: Node) -> None:
if instance.dag.is_managed:
raise serializers.ValidationError("Nodes belonging to a system-managed DAG cannot be deleted.")
+ if instance.type == NodeType.METRIC:
+ raise serializers.ValidationError("Metric nodes are deleted by deleting their metric.")
instance.delete()
def _require_warehouse_access(self, *, level: AccessControlLevel, message: str) -> None:
@@ -294,7 +347,7 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
nodes = page if page is not None else queryset
dag_id = self._get_dag_id_param()
- graph = Graph(team_id=self.team_id, dag_id=dag_id)
+ graph = Graph(team_id=self.team_id, dag_id=dag_id, hidden_types=self._hidden_node_types())
node_ids = [str(n.id) for n in nodes]
counts = graph.batch_counts(node_ids)
@@ -315,7 +368,7 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return dag_id
def safely_get_queryset(self, queryset):
- qs = _annotate_latest_job(queryset.filter(team_id=self.team_id))
+ qs = _annotate_latest_job(self._exclude_hidden_nodes(queryset.filter(team_id=self.team_id)))
dag_id = self._get_dag_id_param()
if dag_id:
qs = qs.filter(dag_id=dag_id)
@@ -340,9 +393,9 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=status.HTTP_400_BAD_REQUEST,
)
- if node.type == NodeType.TABLE:
+ if node.type not in SAVED_QUERY_NODE_TYPES:
return response.Response(
- {"error": "Cannot run a table node"},
+ {"error": f"Cannot run a {node.type} node"},
status=status.HTTP_400_BAD_REQUEST,
)
@@ -390,6 +443,21 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return response.Response({"node_ids": list(node_ids)}, status=status.HTTP_200_OK)
+ def _lineage_lookup(self, req: request.Request) -> dict[str, UUID]:
+ by_param = {
+ "id": req.query_params.get("node_id"),
+ "saved_query_id": req.query_params.get("saved_query_id"),
+ "metric_id": req.query_params.get("metric_id"),
+ }
+ given = {field: value for field, value in by_param.items() if value}
+ if not given:
+ raise LineageLookupError("node_id, saved_query_id or metric_id is required")
+ field, value = next(iter(given.items()))
+ try:
+ return {field: UUID(value)}
+ except ValueError:
+ raise LineageLookupError("Invalid UUID")
+
@extend_schema(
parameters=[
OpenApiParameter("node_id", OpenApiTypes.UUID, description="Node to build lineage for."),
@@ -398,54 +466,56 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
OpenApiTypes.UUID,
description="Saved query to build lineage for, resolved to its node. Alternative to node_id.",
),
- ]
+ OpenApiParameter(
+ "metric_id",
+ OpenApiTypes.UUID,
+ description="Data catalog metric to build lineage for, resolved to its node. Alternative to node_id.",
+ ),
+ ],
+ responses={200: LineageResponseSerializer},
)
@action(methods=["GET"], detail=False)
def lineage(self, req: request.Request, *args, **kwargs) -> response.Response:
"""Return the subgraph of nodes and edges reachable from a node (upstream + downstream).
- Accepts either node_id or saved_query_id, so a caller holding only a saved query (the SQL
- editor) doesn't need to resolve the node itself.
+ Accepts node_id, saved_query_id or metric_id, so a caller holding only the backing resource
+ (the SQL editor, the metric page) doesn't need to resolve the node itself.
"""
- from products.data_modeling.backend.presentation.views.edge import EdgeSerializer
-
# Lineage exposes the same metadata the deleted `warehouse_view`-scoped upstream endpoint
# gated on.
self._require_warehouse_access(level="viewer", message="Reading lineage requires data warehouse read access.")
- node_id = req.query_params.get("node_id")
- saved_query_id = req.query_params.get("saved_query_id")
- if not node_id and not saved_query_id:
- return response.Response(
- {"error": "node_id or saved_query_id is required"}, status=status.HTTP_400_BAD_REQUEST
- )
- # Parse UUIDs up front: unlike the detail route, query params aren't validated by URL
- # routing, so an invalid string would surface as a 500 from the ORM instead of a 400.
try:
- lookup = {"id": UUID(node_id)} if node_id else {"saved_query_id": UUID(cast(str, saved_query_id))}
- except ValueError:
- return response.Response({"error": "Invalid UUID"}, status=status.HTTP_400_BAD_REQUEST)
+ lookup = self._lineage_lookup(req)
+ except LineageLookupError as error:
+ return response.Response({"error": str(error)}, status=status.HTTP_400_BAD_REQUEST)
# saved_query is a non-unique FK: a saved query synced into multiple DAGs has multiple nodes.
# Order for a deterministic pick (the graphs are equivalent for lineage purposes).
- node = Node.objects.filter(team_id=self.team_id, **lookup).order_by("created_at").first()
+ node = (
+ self._exclude_hidden_nodes(Node.objects.filter(team_id=self.team_id, **lookup))
+ .order_by("created_at")
+ .first()
+ )
if node is None:
return response.Response({"error": "Node not found"}, status=status.HTTP_404_NOT_FOUND)
- upstream_ids = _get_upstream_nodes(node, include_tables=True)
- downstream_ids = _get_downstream_nodes(node)
+ hidden_types = self._hidden_node_types()
+ upstream_ids = _get_upstream_nodes(node, include_tables=True, hidden_types=hidden_types)
+ downstream_ids = _get_downstream_nodes(node, hidden_types=hidden_types)
all_ids = upstream_ids | downstream_ids | {str(node.id)}
- nodes = _node_queryset_with_latest_job().filter(id__in=all_ids, team_id=self.team_id)
- edges = Edge.objects.select_related("source", "target", "dag").filter(
- team_id=self.team_id, source_id__in=all_ids, target_id__in=all_ids
+ nodes = self._exclude_hidden_nodes(
+ _node_queryset_with_latest_job().filter(id__in=all_ids, team_id=self.team_id)
+ )
+ edges = self._exclude_hidden_edges(
+ Edge.objects.select_related("source", "target", "dag").filter(
+ team_id=self.team_id, source_id__in=all_ids, target_id__in=all_ids
+ )
)
return response.Response(
- {
- "nodes": NodeSerializer(nodes, many=True, context=self.get_serializer_context()).data,
- "edges": EdgeSerializer(edges, many=True).data,
- }
+ LineageResponseSerializer({"nodes": nodes, "edges": edges}, context=self.get_serializer_context()).data
)
@action(methods=["POST"], detail=True)
@@ -455,9 +525,9 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
node = self.get_object()
- if node.type == NodeType.TABLE:
+ if node.type not in SAVED_QUERY_NODE_TYPES:
return response.Response(
- {"error": "Cannot materialize a table node"},
+ {"error": f"Cannot materialize a {node.type} node"},
status=status.HTTP_400_BAD_REQUEST,
)
diff --git a/products/data_modeling/backend/test/helpers.py b/products/data_modeling/backend/test/helpers.py
index 3f285e8a5396..1e1d5ad12e12 100644
--- a/products/data_modeling/backend/test/helpers.py
+++ b/products/data_modeling/backend/test/helpers.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from uuid import uuid4
from unittest import mock
@@ -15,6 +16,10 @@ def table_node(team, dag: DAG, name: str, properties: dict) -> Node:
return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)
+def metric_node(team, dag: DAG, name: str) -> Node:
+ return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.METRIC, metric_id=uuid4())
+
+
def saved_query_node(team, dag: DAG, name: str, node_type: str) -> Node:
saved_query = DataWarehouseSavedQuery.objects.create(
name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}
diff --git a/products/data_modeling/backend/test/test_check_node_tier_schedule.py b/products/data_modeling/backend/test/test_check_node_tier_schedule.py
index 201bd3a4beb5..9b3c206186cc 100644
--- a/products/data_modeling/backend/test/test_check_node_tier_schedule.py
+++ b/products/data_modeling/backend/test/test_check_node_tier_schedule.py
@@ -17,6 +17,7 @@ from products.data_modeling.backend.logic.tier_membership import EPHEMERAL_SKIPP
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.data_modeling.backend.models.node import Node, NodeType
+from products.data_modeling.backend.test.helpers import metric_node
TEMPORAL_READ = "products.data_modeling.backend.management.commands.check_node_tier_schedule.Command._read_live_tiers"
@@ -81,11 +82,21 @@ class TestCheckNodeTierScheduleGuards(BaseTest):
read_live.assert_not_called()
- def test_selector_matching_nothing_errors_instead_of_dumping_the_dag(self):
- # A typo'd --name used to fall through to "no selector given" and dump every node in the DAG,
- # which reads as a clean bill of health for a node that was never actually inspected.
+ @parameterized.expand(
+ [
+ # A typo'd --name used to fall through to "no selector given" and dump every node in the
+ # DAG, which reads as a clean bill of health for a node that was never actually inspected.
+ ("name_matching_nothing", "typo_view", False),
+ ("name_of_a_metric", "weekly_active_accounts", True),
+ ]
+ )
+ def test_selector_matching_no_schedulable_node_errors_instead_of_dumping_the_dag(
+ self, _name, selector, create_metric
+ ):
dag = DAG.objects.create(team=self.team, name="Default")
self._node(dag, "real_view")
+ if create_metric:
+ metric_node(self.team, dag, selector)
with patch(TEMPORAL_READ) as read_live:
with pytest.raises(CommandError, match="matches that selector"):
@@ -94,7 +105,7 @@ class TestCheckNodeTierScheduleGuards(BaseTest):
"--team-id",
str(self.team.pk),
"--name",
- "typo_view",
+ selector,
"--dag-id",
str(dag.id),
)
diff --git a/products/data_modeling/backend/test/test_node.py b/products/data_modeling/backend/test/test_node.py
index 98ddafccc474..fbb1efd98fae 100644
--- a/products/data_modeling/backend/test/test_node.py
+++ b/products/data_modeling/backend/test/test_node.py
@@ -1,8 +1,12 @@
+import uuid
+
import pytest
from posthog.test.base import BaseTest
from django.db import IntegrityError
+from parameterized import parameterized
+
from products.data_modeling.backend.models import DAG
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.data_modeling.backend.models.node import Node, NodeType
@@ -157,3 +161,73 @@ class TestNodeNameSync(BaseTest):
saved_query=saved_query,
type=NodeType.VIEW,
)
+
+
+class TestMetricNode(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.dag = DAG.objects.create(team=self.team, name="test")
+
+ def test_metric_node_carries_its_metric_id(self):
+ metric_id = uuid.uuid4()
+
+ node = Node.objects.create(
+ team=self.team,
+ dag=self.dag,
+ name="weekly_active_accounts",
+ type=NodeType.METRIC,
+ metric_id=metric_id,
+ )
+
+ node.refresh_from_db()
+ self.assertEqual(node.metric_id, metric_id)
+
+ @parameterized.expand(
+ [
+ ("metric_without_metric_id", NodeType.METRIC, False, False),
+ ("metric_with_saved_query", NodeType.METRIC, True, False),
+ ("metric_with_saved_query_and_metric_id", NodeType.METRIC, True, True),
+ ("table_with_metric_id", NodeType.TABLE, False, True),
+ ("view_with_metric_id", NodeType.VIEW, True, True),
+ ("view_without_saved_query", NodeType.VIEW, False, False),
+ ]
+ )
+ def test_backing_reference_must_match_type(self, _name, node_type, with_saved_query, with_metric_id):
+ saved_query = (
+ DataWarehouseSavedQuery.objects.create(
+ name="a_view",
+ team=self.team,
+ query={"query": "SELECT 1", "kind": "HogQLQuery"},
+ )
+ if with_saved_query
+ else None
+ )
+
+ with pytest.raises(IntegrityError):
+ Node.objects.create(
+ team=self.team,
+ dag=self.dag,
+ name="a_name",
+ type=node_type,
+ saved_query=saved_query,
+ metric_id=uuid.uuid4() if with_metric_id else None,
+ )
+
+ def test_one_node_per_metric_in_a_dag(self):
+ metric_id = uuid.uuid4()
+ Node.objects.create(team=self.team, dag=self.dag, name="revenue", type=NodeType.METRIC, metric_id=metric_id)
+
+ with pytest.raises(IntegrityError):
+ Node.objects.create(
+ team=self.team, dag=self.dag, name="revenue_renamed", type=NodeType.METRIC, metric_id=metric_id
+ )
+
+ def test_a_metric_may_share_a_name_with_a_table(self):
+ Node.objects.create(team=self.team, dag=self.dag, name="events", type=NodeType.TABLE)
+
+ metric = Node.objects.create(
+ team=self.team, dag=self.dag, name="events", type=NodeType.METRIC, metric_id=uuid.uuid4()
+ )
+
+ self.assertEqual(metric.name, "events")
diff --git a/products/data_modeling/backend/test/test_node_frequency.py b/products/data_modeling/backend/test/test_node_frequency.py
index fcbe545013cf..92a003f0be63 100644
--- a/products/data_modeling/backend/test/test_node_frequency.py
+++ b/products/data_modeling/backend/test/test_node_frequency.py
@@ -27,6 +27,7 @@ from products.data_modeling.backend.models.datawarehouse_saved_query import Data
from products.data_modeling.backend.models.edge import Edge
from products.data_modeling.backend.models.node import Node, NodeType
from products.data_modeling.backend.test.helpers import (
+ metric_node as _metric_node,
saved_query_node as _saved_query_node,
table_node as _table_node,
warehouse_source_node as _warehouse_source_node,
@@ -186,10 +187,17 @@ class TestSeedTargets(BaseTest):
seeds = seed_targets(dag)
self.assertEqual(seeds, {} if expected is None else {str(node.id): expected})
- def test_source_tables_are_never_seeded(self):
- dag = DAG.objects.create(team=self.team, name="seed-demo-src", sync_frequency_interval=H1)
- _table_node(self.team, dag, "events", {"origin": "posthog"})
+ @parameterized.expand(
+ [
+ ("source_table", lambda team, dag: _table_node(team, dag, "events", {"origin": "posthog"})),
+ ("metric", lambda team, dag: _metric_node(team, dag, "weekly_active_accounts")),
+ ]
+ )
+ def test_nodes_that_never_run_are_never_seeded(self, _name, make_node):
+ dag = DAG.objects.create(team=self.team, name=f"seed-demo-{_name}", sync_frequency_interval=H1)
+ make_node(self.team, dag)
self.assertEqual(seed_targets(dag), {})
+ self.assertEqual(persist_seed_targets(dag), 0)
@pytest.mark.django_db
diff --git a/products/data_modeling/backend/test/test_tier_run_report.py b/products/data_modeling/backend/test/test_tier_run_report.py
index fe2db7ba1b93..76b4038f8cb5 100644
--- a/products/data_modeling/backend/test/test_tier_run_report.py
+++ b/products/data_modeling/backend/test/test_tier_run_report.py
@@ -26,7 +26,7 @@ from products.data_modeling.backend.models.data_modeling_job import (
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.data_modeling.backend.models.edge import Edge
from products.data_modeling.backend.models.node import Node, NodeType
-from products.data_modeling.backend.test.helpers import saved_query_node, table_node
+from products.data_modeling.backend.test.helpers import metric_node, saved_query_node, table_node
DAILY = timedelta(days=1)
HOURLY = timedelta(hours=1)
@@ -193,6 +193,7 @@ class TestTierRunReport(BaseTest):
table_node(self.team, self.dag, "source_table", {})
self._node("targeted", DAILY)
stray = self._node("no_target", None)
+ metric_node(self.team, self.dag, "weekly_active_accounts")
(tier,) = build_tier_runs(self.dag)
diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.py
index 14b44292c65f..64bd17f78a7c 100644
--- a/products/data_modeling/backend/tests/api/test_node_api.py
+++ b/products/data_modeling/backend/tests/api/test_node_api.py
@@ -493,7 +493,7 @@ class TestNodeViewSet(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- @parameterized.expand(["node_id", "saved_query_id"])
+ @parameterized.expand(["node_id", "saved_query_id", "metric_id"])
def test_lineage_invalid_uuid_returns_400(self, lookup_param):
response = self.client.get(
f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?{lookup_param}=not-a-uuid"
@@ -501,7 +501,7 @@ class TestNodeViewSet(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- @parameterized.expand(["node_id", "saved_query_id"])
+ @parameterized.expand(["node_id", "saved_query_id", "metric_id"])
def test_lineage_does_not_leak_other_teams_nodes(self, lookup_param):
other_team = Team.objects.create(organization=self.organization)
other_dag = DAG.objects.create(team=other_team, name=f"posthog_{other_team.id}")
@@ -511,8 +511,19 @@ class TestNodeViewSet(APIBaseTest):
other_node = Node.objects.create(
team=other_team, dag=other_dag, saved_query=other_saved_query, type=NodeType.VIEW
)
+ other_metric_node = Node.objects.create(
+ team=other_team,
+ dag=other_dag,
+ name="other_metric",
+ type=NodeType.METRIC,
+ metric_id=uuid4(),
+ )
- lookup_value = other_node.id if lookup_param == "node_id" else other_saved_query.id
+ lookup_value = {
+ "node_id": other_node.id,
+ "saved_query_id": other_saved_query.id,
+ "metric_id": other_metric_node.metric_id,
+ }[lookup_param]
response = self.client.get(
f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?{lookup_param}={lookup_value}"
)
@@ -650,9 +661,9 @@ class TestNodeViewSet(APIBaseTest):
original_saved_query_id = self.view_node.saved_query_id
url = f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/"
if method == "patch":
- self.client.patch(url, data={"saved_query_id": str(foreign_sq.id)}, format="json")
+ response = self.client.patch(url, data={"saved_query_id": str(foreign_sq.id)}, format="json")
else:
- self.client.put(
+ response = self.client.put(
url,
data={
"name": "test_view",
@@ -663,6 +674,7 @@ class TestNodeViewSet(APIBaseTest):
format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
self.view_node.refresh_from_db()
self.assertEqual(self.view_node.saved_query_id, original_saved_query_id)
self.assertNotEqual(self.view_node.name, foreign_sq.name)
@@ -721,6 +733,217 @@ class TestNodeViewSet(APIBaseTest):
self.assertEqual(self.view_node.dag_id, self.dag.id)
+class TestMetricNodeAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.dag = DAG.objects.create(team=self.team, name=f"posthog_{self.team.id}")
+ self.table_node = Node.objects.create(team=self.team, dag=self.dag, name="events", type=NodeType.TABLE)
+ self.saved_query = DataWarehouseSavedQuery.objects.create(
+ name="accounts", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}
+ )
+ self.view_node = Node.objects.create(
+ team=self.team, dag=self.dag, saved_query=self.saved_query, type=NodeType.VIEW
+ )
+ self.metric_node = Node.objects.create(
+ team=self.team,
+ dag=self.dag,
+ name="weekly_active_accounts",
+ type=NodeType.METRIC,
+ metric_id=uuid4(),
+ )
+ Edge.objects.create(team=self.team, dag=self.dag, source=self.table_node, target=self.view_node)
+ Edge.objects.create(team=self.team, dag=self.dag, source=self.view_node, target=self.metric_node)
+ self.url = f"/api/environments/{self.team.id}/data_modeling_nodes/"
+
+ def test_list_serializes_the_metric_reference(self):
+ response = self.client.get(self.url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ serialized = next(node for node in response.json()["results"] if node["id"] == str(self.metric_node.id))
+ self.assertEqual(serialized["type"], NodeType.METRIC)
+ self.assertEqual(serialized["metric_id"], str(self.metric_node.metric_id))
+ self.assertIsNone(serialized["lineage_issue"])
+
+ @parameterized.expand(
+ [
+ ("sync_failed", {"degraded_sync": {"error": "boom", "at": "2026-09-15T00:00:00Z"}}, "boom"),
+ ("unresolved", {"unresolved": {"names": ["gone", "also_gone"], "at": None}}, "gone, also_gone"),
+ ]
+ )
+ def test_list_reports_a_lineage_issue(self, kind, system, expected_detail):
+ self.metric_node.properties = {"system": system}
+ self.metric_node.save()
+
+ response = self.client.get(self.url)
+
+ serialized = next(node for node in response.json()["results"] if node["id"] == str(self.metric_node.id))
+ self.assertEqual(serialized["lineage_issue"]["kind"], kind)
+ self.assertEqual(serialized["lineage_issue"]["detail"], expected_detail)
+
+ def test_lineage_by_metric_id_returns_the_upstream_view_and_table(self):
+ response = self.client.get(f"{self.url}lineage/?metric_id={self.metric_node.metric_id}")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ node_ids = {node["id"] for node in response.json()["nodes"]}
+ self.assertEqual(node_ids, {str(self.metric_node.id), str(self.view_node.id), str(self.table_node.id)})
+
+ @parameterized.expand(["run", "materialize"])
+ def test_a_metric_node_cannot_be_executed(self, action):
+ response = self.client.post(f"{self.url}{self.metric_node.id}/{action}/", {"direction": "upstream"})
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("metric", response.json()["error"].lower())
+
+ def test_a_metric_node_cannot_be_deleted_through_the_api(self):
+ response = self.client.delete(f"{self.url}{self.metric_node.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertTrue(Node.objects.filter(id=self.metric_node.id).exists())
+
+ def test_a_metric_node_cannot_be_retyped_to_table(self):
+ # metric_id is read-only, so a retype to table would leave it set and reach
+ # node_backing_reference_matches_type as an uncaught IntegrityError.
+ response = self.client.patch(f"{self.url}{self.metric_node.id}/", data={"type": NodeType.TABLE}, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.metric_node.refresh_from_db()
+ self.assertEqual(self.metric_node.type, NodeType.METRIC)
+
+ @parameterized.expand(["name", "description", "dag_id"])
+ def test_a_metric_node_cannot_be_updated_through_the_api(self, field):
+ payload = (
+ {"dag": str(DAG.objects.create(team=self.team, name="other").id)}
+ if field == "dag_id"
+ else {field: "changed"}
+ )
+ before = getattr(self.metric_node, field)
+
+ response = self.client.patch(f"{self.url}{self.metric_node.id}/", data=payload, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.metric_node.refresh_from_db()
+ self.assertEqual(getattr(self.metric_node, field), before)
+
+ def test_an_edge_into_a_metric_node_cannot_be_deleted_through_the_api(self):
+ edge = Edge.objects.get(target=self.metric_node)
+
+ response = self.client.delete(f"/api/environments/{self.team.id}/data_modeling_edges/{edge.id}/")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertTrue(Edge.objects.filter(id=edge.id).exists())
+
+ @parameterized.expand(["post", "patch"])
+ def test_only_table_nodes_can_be_written_through_the_api(self, method):
+ if method == "post":
+ response = self.client.post(
+ self.url,
+ data={"name": "sneaky", "type": NodeType.METRIC, "dag": str(self.dag.id)},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertFalse(Node.objects.filter(name="sneaky").exists())
+ return
+
+ response = self.client.patch(f"{self.url}{self.table_node.id}/", data={"type": NodeType.VIEW}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.table_node.refresh_from_db()
+ self.assertEqual(self.table_node.type, NodeType.TABLE)
+
+
+class TestMetricNodeVisibility(WarehouseAccessControlTestMixin):
+ resource = "warehouse_objects"
+
+ def setUp(self):
+ super().setUp()
+ self.dag = DAG.objects.create(team=self.team, name=f"posthog_{self.team.id}")
+ self.view_node = Node.objects.create(
+ team=self.team,
+ dag=self.dag,
+ saved_query=DataWarehouseSavedQuery.objects.create(
+ name="accounts", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}
+ ),
+ type=NodeType.VIEW,
+ )
+ self.metric_node = Node.objects.create(
+ team=self.team,
+ dag=self.dag,
+ name="weekly_active_accounts",
+ type=NodeType.METRIC,
+ metric_id=uuid4(),
+ )
+ self.edge = Edge.objects.create(team=self.team, dag=self.dag, source=self.view_node, target=self.metric_node)
+ self._create_access_control(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+
+ def _catalog_access(self, access_level: str) -> None:
+ if access_level == "none":
+ self._create_project_default(resource="data_catalog", access_level="none")
+ else:
+ self._create_access_control(self.viewer_user, resource="data_catalog", access_level=access_level)
+
+ @parameterized.expand(
+ [
+ ("nodes_hidden", "none", False),
+ ("nodes_visible", "viewer", True),
+ ]
+ )
+ def test_nodes_are_visible_only_with_catalog_access(self, _name, catalog_access, expected_visible):
+ self._catalog_access(catalog_access)
+
+ response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/")
+
+ node_ids = {node["id"] for node in response.json()["results"]}
+ self.assertEqual(str(self.metric_node.id) in node_ids, expected_visible)
+ self.assertIn(str(self.view_node.id), node_ids)
+
+ @parameterized.expand(
+ [
+ ("edges_hidden", "none", False),
+ ("edges_visible", "viewer", True),
+ ]
+ )
+ def test_edges_are_visible_only_with_catalog_access(self, _name, catalog_access, expected_visible):
+ self._catalog_access(catalog_access)
+
+ response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_edges/")
+
+ edge_ids = {edge["id"] for edge in response.json()["results"]}
+ self.assertEqual(str(self.edge.id) in edge_ids, expected_visible)
+
+ @parameterized.expand(
+ [
+ ("counts_hidden", "none", 0),
+ ("counts_visible", "viewer", 1),
+ ]
+ )
+ def test_downstream_count_never_reports_a_metric_the_reader_cannot_see(self, _name, catalog_access, expected):
+ self._catalog_access(catalog_access)
+
+ response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/")
+
+ view = next(node for node in response.json()["results"] if node["id"] == str(self.view_node.id))
+ self.assertEqual(view["downstream_count"], expected)
+
+ @parameterized.expand(
+ [
+ ("lineage_hidden", "none", False),
+ ("lineage_visible", "viewer", True),
+ ]
+ )
+ def test_lineage_shows_metric_nodes_only_with_catalog_access(self, _name, catalog_access, expected_visible):
+ self._catalog_access(catalog_access)
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?node_id={self.view_node.id}"
+ )
+
+ payload = response.json()
+ node_ids = {node["id"] for node in payload["nodes"]}
+ self.assertEqual(str(self.metric_node.id) in node_ids, expected_visible)
+ self.assertEqual(len(payload["edges"]) == 1, expected_visible)
+
+
@pytest.mark.ee
class TestNodeAccessControl(WarehouseAccessControlTestMixin):
# NodeViewSet is scope_object = "INTERNAL", so AccessControlPermission does not gate it on any
diff --git a/products/data_modeling/frontend/generated/api.schemas.ts b/products/data_modeling/frontend/generated/api.schemas.ts
index 23b009351491..68f8a37a0b60 100644
--- a/products/data_modeling/frontend/generated/api.schemas.ts
+++ b/products/data_modeling/frontend/generated/api.schemas.ts
@@ -94,6 +94,7 @@ export interface PatchedEdgeApi {
* * `view` - View
* * `matview` - Mat View
* * `endpoint` - Endpoint
+ * * `metric` - Metric
*/
export type NodeTypeEnumApi = (typeof NodeTypeEnumApi)[keyof typeof NodeTypeEnumApi]
@@ -102,8 +103,35 @@ export const NodeTypeEnumApi = {
View: 'view',
Matview: 'matview',
Endpoint: 'endpoint',
+ Metric: 'metric',
} as const
+/**
+ * * `sync_failed` - Sync Failed
+ * * `unresolved` - Unresolved
+ */
+export type LineageIssueKindEnumApi = (typeof LineageIssueKindEnumApi)[keyof typeof LineageIssueKindEnumApi]
+
+export const LineageIssueKindEnumApi = {
+ SyncFailed: 'sync_failed',
+ Unresolved: 'unresolved',
+} as const
+
+export interface LineageIssueApi {
+ /** sync_failed when the last attempt to rebuild this node's edges ended in an error. unresolved when the rebuild finished but some of the names this node reads matched no node in the DAG.
+ *
+ * * `sync_failed` - Sync Failed
+ * * `unresolved` - Unresolved */
+ kind: LineageIssueKindEnumApi
+ /** The error for sync_failed, or the comma-separated names that did not resolve for unresolved. */
+ detail: string
+ /**
+ * When the issue was recorded.
+ * @nullable
+ */
+ at: string | null
+}
+
export interface NodeSuspensionApi {
/** When the node was suspended. */
at: string
@@ -136,6 +164,9 @@ export interface NodeApi {
description?: string
/** @nullable */
readonly saved_query_id: string | null
+ /** @nullable */
+ readonly metric_id: string | null
+ readonly lineage_issue: LineageIssueApi | null
readonly created_at: string
/** @nullable */
readonly updated_at: string | null
@@ -189,6 +220,9 @@ export interface PatchedNodeApi {
description?: string
/** @nullable */
readonly saved_query_id?: string | null
+ /** @nullable */
+ readonly metric_id?: string | null
+ readonly lineage_issue?: LineageIssueApi | null
readonly created_at?: string
/** @nullable */
readonly updated_at?: string | null
@@ -222,6 +256,13 @@ export interface NodeResumeApi {
resumed: boolean
}
+export interface LineageResponseApi {
+ /** Every node reachable from the requested one, plus the node itself. */
+ nodes: NodeApi[]
+ /** Every edge between two of those nodes. */
+ edges: EdgeApi[]
+}
+
export type DataModelingDagsListParams = {
/**
* Number of results to return per page.
@@ -256,6 +297,10 @@ export type DataModelingNodesListParams = {
}
export type DataModelingNodesLineageRetrieveParams = {
+ /**
+ * Data catalog metric to build lineage for, resolved to its node. Alternative to node_id.
+ */
+ metric_id?: string
/**
* Node to build lineage for.
*/
diff --git a/products/data_modeling/frontend/generated/api.ts b/products/data_modeling/frontend/generated/api.ts
index f6e4b5a07ddd..a372748e5806 100644
--- a/products/data_modeling/frontend/generated/api.ts
+++ b/products/data_modeling/frontend/generated/api.ts
@@ -15,6 +15,7 @@ import type {
DataModelingNodesLineageRetrieveParams,
DataModelingNodesListParams,
EdgeApi,
+ LineageResponseApi,
NodeApi,
NodeResumeApi,
PaginatedDAGListApi,
@@ -433,15 +434,15 @@ export const getDataModelingNodesLineageRetrieveUrl = (
/**
* Return the subgraph of nodes and edges reachable from a node (upstream + downstream).
*
- * Accepts either node_id or saved_query_id, so a caller holding only a saved query (the SQL
- * editor) doesn't need to resolve the node itself.
+ * Accepts node_id, saved_query_id or metric_id, so a caller holding only the backing resource
+ * (the SQL editor, the metric page) doesn't need to resolve the node itself.
*/
export const dataModelingNodesLineageRetrieve = async (
projectId: string,
params?: DataModelingNodesLineageRetrieveParams,
options?: RequestInit
-): Promise<NodeApi> => {
- return apiMutator<NodeApi>(getDataModelingNodesLineageRetrieveUrl(projectId, params), {
+): Promise<LineageResponseApi> => {
+ return apiMutator<LineageResponseApi>(getDataModelingNodesLineageRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/data_modeling/frontend/generated/api.zod.ts b/products/data_modeling/frontend/generated/api.zod.ts
index 8f2bd088cdbc..c84f7c96ee51 100644
--- a/products/data_modeling/frontend/generated/api.zod.ts
+++ b/products/data_modeling/frontend/generated/api.zod.ts
@@ -61,9 +61,11 @@ export const dataModelingNodesCreateBodyDescriptionMax = 1024
export const DataModelingNodesCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(dataModelingNodesCreateBodyNameMax),
type: zod
- .enum(['table', 'view', 'matview', 'endpoint'])
+ .enum(['table', 'view', 'matview', 'endpoint', 'metric'])
.optional()
- .describe('\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint'),
+ .describe(
+ '\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint\n\* `metric` - Metric'
+ ),
dag: zod.uuid(),
description: zod.string().max(dataModelingNodesCreateBodyDescriptionMax).optional(),
})
@@ -75,9 +77,11 @@ export const dataModelingNodesUpdateBodyDescriptionMax = 1024
export const DataModelingNodesUpdateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(dataModelingNodesUpdateBodyNameMax),
type: zod
- .enum(['table', 'view', 'matview', 'endpoint'])
+ .enum(['table', 'view', 'matview', 'endpoint', 'metric'])
.optional()
- .describe('\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint'),
+ .describe(
+ '\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint\n\* `metric` - Metric'
+ ),
dag: zod.uuid(),
description: zod.string().max(dataModelingNodesUpdateBodyDescriptionMax).optional(),
})
@@ -89,9 +93,11 @@ export const dataModelingNodesPartialUpdateBodyDescriptionMax = 1024
export const DataModelingNodesPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(dataModelingNodesPartialUpdateBodyNameMax).optional(),
type: zod
- .enum(['table', 'view', 'matview', 'endpoint'])
+ .enum(['table', 'view', 'matview', 'endpoint', 'metric'])
.optional()
- .describe('\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint'),
+ .describe(
+ '\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint\n\* `metric` - Metric'
+ ),
dag: zod.uuid().optional(),
description: zod.string().max(dataModelingNodesPartialUpdateBodyDescriptionMax).optional(),
})
@@ -106,9 +112,11 @@ export const dataModelingNodesMaterializeCreateBodyDescriptionMax = 1024
export const DataModelingNodesMaterializeCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(dataModelingNodesMaterializeCreateBodyNameMax),
type: zod
- .enum(['table', 'view', 'matview', 'endpoint'])
+ .enum(['table', 'view', 'matview', 'endpoint', 'metric'])
.optional()
- .describe('\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint'),
+ .describe(
+ '\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint\n\* `metric` - Metric'
+ ),
dag: zod.uuid(),
description: zod.string().max(dataModelingNodesMaterializeCreateBodyDescriptionMax).optional(),
})
@@ -128,9 +136,11 @@ export const dataModelingNodesRunCreateBodyDescriptionMax = 1024
export const DataModelingNodesRunCreateBody = /* @__PURE__ */ zod.object({
name: zod.string().max(dataModelingNodesRunCreateBodyNameMax),
type: zod
- .enum(['table', 'view', 'matview', 'endpoint'])
+ .enum(['table', 'view', 'matview', 'endpoint', 'metric'])
.optional()
- .describe('\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint'),
+ .describe(
+ '\* `table` - Table\n\* `view` - View\n\* `matview` - Mat View\n\* `endpoint` - Endpoint\n\* `metric` - Metric'
+ ),
dag: zod.uuid(),
description: zod.string().max(dataModelingNodesRunCreateBodyDescriptionMax).optional(),
})
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/lineage.py b/products/data_warehouse/backend/presentation/views/saved_query/lineage.py
index 6a8a5bd14bb8..ba784b7e0a76 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/lineage.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/lineage.py
@@ -4,7 +4,7 @@ from django.db.models import Q
from rest_framework import request, serializers
-from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery, Edge, Node
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery, Edge, Node, NodeType
class SavedQueryLineageRequestSerializer(serializers.Serializer):
@@ -76,10 +76,12 @@ def _related_saved_queries(saved_query: DataWarehouseSavedQuery, *, upstream: bo
reached = _reachable_node_ids(saved_query.team_id, start_node_ids, upstream=upstream, max_depth=max_depth)
identifiers: set[str] = set()
- for saved_query_id, name, properties in Node.objects.filter(team=saved_query.team, id__in=reached).values_list(
- "saved_query_id", "name", "properties"
- ):
+ for node_type, saved_query_id, name, properties in Node.objects.filter(
+ team=saved_query.team, id__in=reached
+ ).values_list("type", "saved_query_id", "name", "properties"):
properties = properties or {}
+ if node_type == NodeType.METRIC:
+ continue
if saved_query_id is not None:
identifiers.add(str(saved_query_id))
elif properties.get("saved_query_id"):
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index 3e8b47bfa744..6f9dd7e3ecc5 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -1610,6 +1610,31 @@ class TestSavedQuery(APIBaseTest):
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response.json(), {"upstream_count": 0, "downstream_count": 2})
+ def test_descendants_omit_a_metric_that_reads_the_view(self):
+ dag = DAG.get_or_create_default(self.team)
+ view = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="accounts_view",
+ query={"kind": "HogQLQuery", "query": "select 1"},
+ created_by=self.user,
+ )
+ view_node = Node.objects.create(team=self.team, saved_query=view, dag=dag, type=NodeType.VIEW)
+ metric_node = Node.objects.create(
+ team=self.team,
+ dag=dag,
+ name="weekly_active_accounts",
+ type=NodeType.METRIC,
+ metric_id=uuid.uuid4(),
+ )
+ Edge.objects.create(team=self.team, dag=dag, source=view_node, target=metric_node)
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{view.id}/descendants",
+ )
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["descendants"], [])
+
def test_lineage_unions_the_nodes_of_one_saved_query_across_dags(self):
# A saved query may hold a node in more than one DAG. Its lineage is the union of what
# every node reaches; reading one node would silently drop the other DAG's neighbours.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bb0aeacea62e..d3d4bb14cf31 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -52292,6 +52292,121 @@ export namespace Schemas {
ByteBudget: 'byte_budget',
} as const;
+ /**
+ * * `sync_failed` - Sync Failed
+ * * `unresolved` - Unresolved
+ */
+ export type LineageIssueKindEnum = typeof LineageIssueKindEnum[keyof typeof LineageIssueKindEnum];
+
+
+ export const LineageIssueKindEnum = {
+ SyncFailed: 'sync_failed',
+ Unresolved: 'unresolved',
+ } as const;
+
+ export interface LineageIssue {
+ /** sync_failed when the last attempt to rebuild this node's edges ended in an error. unresolved when the rebuild finished but some of the names this node reads matched no node in the DAG.
+ *
+ * * `sync_failed` - Sync Failed
+ * * `unresolved` - Unresolved */
+ kind: LineageIssueKindEnum;
+ /** The error for sync_failed, or the comma-separated names that did not resolve for unresolved. */
+ detail: string;
+ /**
+ * When the issue was recorded.
+ * @nullable
+ */
+ at: string | null;
+ }
+
+ /**
+ * * `table` - Table
+ * * `view` - View
+ * * `matview` - Mat View
+ * * `endpoint` - Endpoint
+ * * `metric` - Metric
+ */
+ export type NodeTypeEnum = typeof NodeTypeEnum[keyof typeof NodeTypeEnum];
+
+
+ export const NodeTypeEnum = {
+ Table: 'table',
+ View: 'view',
+ Matview: 'matview',
+ Endpoint: 'endpoint',
+ Metric: 'metric',
+ } as const;
+
+ export interface NodeSuspension {
+ /** When the node was suspended. */
+ at: string;
+ /** Error from the materialization that tripped suspension. */
+ reason: string;
+ /** Materialization job that tripped suspension. */
+ job_id: string;
+ }
+
+ export interface NodeEndpoint {
+ /** Name of the endpoint this node's materialization backs. */
+ name: string;
+ /** Endpoint version this node's materialization backs. */
+ version: number;
+ }
+
+ /**
+ * Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed.
+ */
+ export type NodeSuspended = {[key: string]: NodeSuspension};
+
+ export interface Node {
+ readonly id: string;
+ /** @maxLength 2048 */
+ name: string;
+ type?: NodeTypeEnum;
+ dag: string;
+ readonly dag_name: string;
+ /** @maxLength 1024 */
+ description?: string;
+ /** @nullable */
+ readonly saved_query_id: string | null;
+ /** @nullable */
+ readonly metric_id: string | null;
+ readonly lineage_issue: LineageIssue | null;
+ readonly created_at: string;
+ /** @nullable */
+ readonly updated_at: string | null;
+ readonly upstream_count: number;
+ readonly downstream_count: number;
+ /** @nullable */
+ readonly last_run_at: string | null;
+ /**
+ * Skipped runs are written straight to the job table and never reach the stored status,
+ * so a blocked model would keep reporting the success before it.
+ * @nullable
+ */
+ readonly last_run_status: string | null;
+ /**
+ * Error of the run that last_run_status describes, so the two never disagree.
+ * @nullable
+ */
+ readonly last_run_error: string | null;
+ /** @nullable */
+ readonly user_tag: string | null;
+ /** @nullable */
+ readonly sync_interval: string | null;
+ /** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */
+ readonly suspended: NodeSuspended;
+ /** The endpoint version this node's materialization backs, or null for nodes that are not endpoints. */
+ readonly endpoint: NodeEndpoint | null;
+ }
+
+ export interface LineageResponse {
+ /** Every node reachable from the requested one, plus the node itself. */
+ nodes: Node[];
+ /** Every edge between two of those nodes. */
+ edges: Edge[];
+ }
+
export interface LinearIssueSignalExtra {
url: string;
identifier: string;
@@ -56395,82 +56510,6 @@ export namespace Schemas {
specificity_rejection?: SpecificityMetadata | null;
}
- export interface NodeSuspension {
- /** When the node was suspended. */
- at: string;
- /** Error from the materialization that tripped suspension. */
- reason: string;
- /** Materialization job that tripped suspension. */
- job_id: string;
- }
-
- /**
- * Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed.
- */
- export type NodeSuspended = {[key: string]: NodeSuspension};
-
- /**
- * * `table` - Table
- * * `view` - View
- * * `matview` - Mat View
- * * `endpoint` - Endpoint
- */
- export type NodeTypeEnum = typeof NodeTypeEnum[keyof typeof NodeTypeEnum];
-
-
- export const NodeTypeEnum = {
- Table: 'table',
- View: 'view',
- Matview: 'matview',
- Endpoint: 'endpoint',
- } as const;
-
- export interface NodeEndpoint {
- /** Name of the endpoint this node's materialization backs. */
- name: string;
- /** Endpoint version this node's materialization backs. */
- version: number;
- }
-
- export interface Node {
- readonly id: string;
- /** @maxLength 2048 */
- name: string;
- type?: NodeTypeEnum;
- dag: string;
- readonly dag_name: string;
- /** @maxLength 1024 */
- description?: string;
- /** @nullable */
- readonly saved_query_id: string | null;
- readonly created_at: string;
- /** @nullable */
- readonly updated_at: string | null;
- readonly upstream_count: number;
- readonly downstream_count: number;
- /** @nullable */
- readonly last_run_at: string | null;
- /**
- * Skipped runs are written straight to the job table and never reach the stored status,
- * so a blocked model would keep reporting the success before it.
- * @nullable
- */
- readonly last_run_status: string | null;
- /**
- * Error of the run that last_run_status describes, so the two never disagree.
- * @nullable
- */
- readonly last_run_error: string | null;
- /** @nullable */
- readonly user_tag: string | null;
- /** @nullable */
- readonly sync_interval: string | null;
- /** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */
- readonly suspended: NodeSuspended;
- /** The endpoint version this node's materialization backs, or null for nodes that are not endpoints. */
- readonly endpoint: NodeEndpoint | null;
- }
-
export interface NodeResume {
/** False when the node was not suspended to begin with. */
resumed: boolean;
@@ -70108,6 +70147,9 @@ export namespace Schemas {
description?: string;
/** @nullable */
readonly saved_query_id?: string | null;
+ /** @nullable */
+ readonly metric_id?: string | null;
+ readonly lineage_issue?: LineageIssue | null;
readonly created_at?: string;
/** @nullable */
readonly updated_at?: string | null;
@@ -101568,6 +101610,10 @@ export namespace Schemas {
};
export type DataModelingNodesLineageRetrieveParams = {
+ /**
+ * Data catalog metric to build lineage for, resolved to its node. Alternative to node_id.
+ */
+ metric_id?: string;
/**
* Node to build lineage for.
*/