: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
chore(data-modeling): remove the multi-dag api surface (#116488)
Thiago Salvatore2e811fa1f685
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsxindex cdba5f4c1395..3e5a61bbd3a1 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx@@ -378,7 +378,6 @@ export const MaterializationSettings: StoryObj = {id: 'source',name: 'orders',type: 'table',- dag: 'dag-1',upstream_count: 0,downstream_count: 1,},@@ -387,14 +386,11 @@ export const MaterializationSettings: StoryObj = {name: 'revenue_summary',type: 'matview',saved_query_id: 'settings-view',- dag: 'dag-1',upstream_count: 1,downstream_count: 0,},],- edges: [- { id: 'edge-1', source_id: 'source', target_id: 'summary', dag: 'dag-1', properties: {} },- ],+ edges: [{ id: 'edge-1', source_id: 'source', target_id: 'summary', properties: {} }],},],},diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 3353b7cdf4e9..00465a7c5c88 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -274,7 +274,6 @@ describe('sqlEditorLogic', () => {}return [404]},- '/api/environments/:team_id/data_modeling_dags/': { results: [] },'/api/environments/:team_id/data_modeling_nodes/': { results: [] },'/api/environments/:team_id/data_modeling_edges/': { results: [] },'/api/environments/:team_id/data_modeling_jobs/recent/': [],diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 32fdd8b20196..a5205e773368 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6321,10 +6321,6 @@ export interface DataModelingNode {name: stringtype: DataModelingNodeTypedescription?: string- /** UUID of the DAG this node belongs to */- dag: string- /** Human-readable DAG name */- dag_name?: stringsaved_query_id?: string/** UUID of the data catalog metric a metric node stands for */metric_id?: string | null@@ -6350,10 +6346,6 @@ export interface DataModelingEdge {id: stringsource_id: stringtarget_id: string- /** UUID of the DAG this edge belongs to */- dag: string- /** Human-readable DAG name */- dag_name?: stringproperties: Record<string, unknown>created_at: stringupdated_at: stringdiff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex a5e6e1eb6158..672de7354d3c 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -140,7 +140,6 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.dashboards.backend.api.dashboard_templates.DashboardTemplateViewSet","products.data_catalog.backend.presentation.views.MetricViewSet","products.data_catalog.backend.presentation.views.RelationshipProposalViewSet",- "products.data_modeling.backend.presentation.views.edge.EdgeViewSet","products.data_modeling.backend.presentation.views.node.NodeViewSet","products.data_quality.backend.presentation.views.DataQualityCheckViewSet","products.data_quality.backend.presentation.views.DataQualityRunViewSet",diff --git a/products/data_catalog/frontend/MetricLineagePanel.stories.tsx b/products/data_catalog/frontend/MetricLineagePanel.stories.tsxindex 90da2a4721ce..018799f1c7d1 100644--- a/products/data_catalog/frontend/MetricLineagePanel.stories.tsx+++ b/products/data_catalog/frontend/MetricLineagePanel.stories.tsx@@ -27,7 +27,6 @@ const MARKDOWN_METRIC = metric({ definition_kind: 'MarkdownDefinition' })function node(partial: Pick<DataModelingNode, 'id' | 'name' | 'type'> & Partial<DataModelingNode>): DataModelingNode {return {- dag: 'dag-1',created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',upstream_count: 0,@@ -42,8 +41,8 @@ const NODES: DataModelingNode[] = [node({ id: '3', name: 'weekly_active_accounts', type: 'metric', metric_id: 'metric-1' }),]const EDGES: DataModelingEdge[] = [- { id: 'e1', source_id: '1', target_id: '2', dag: 'dag-1', properties: {}, created_at: '', updated_at: '' },- { id: 'e2', source_id: '2', target_id: '3', dag: 'dag-1', properties: {}, created_at: '', updated_at: '' },+ { id: 'e1', source_id: '1', target_id: '2', properties: {}, created_at: '', updated_at: '' },+ { id: 'e2', source_id: '2', target_id: '3', properties: {}, created_at: '', updated_at: '' },]const BASE: MetricLineagePanelProps = {diff --git a/products/data_modeling/backend/graph.py b/products/data_modeling/backend/graph.pyindex 8b387484ae52..25f552bdb937 100644--- a/products/data_modeling/backend/graph.py+++ b/products/data_modeling/backend/graph.py@@ -24,7 +24,6 @@ class Graph:def __init__(self,team_id: int,- dag_id: UUID | str | None = None,exclude_table_sources: bool = True,exclude_table_targets: bool = True,hidden_types: frozenset[str] = frozenset(),@@ -33,7 +32,6 @@ class Graph:Args:team_id: filter edges to this team- dag_id: if set, filter to a single DAG; otherwise load all DAGsexclude_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@@ -42,8 +40,6 @@ class Graph:qs = Edge.objects.filter(team_id=team_id).exclude(Q(source__saved_query__deleted=True) | Q(target__saved_query__deleted=True))- if dag_id:- qs = qs.filter(dag_id=dag_id)# Fetch edges with source/target types in a single queryedge_rows = list(diff --git a/products/data_modeling/backend/presentation/views/__init__.py b/products/data_modeling/backend/presentation/views/__init__.pyindex c292d96da4af..1b4a7134db67 100644--- a/products/data_modeling/backend/presentation/views/__init__.py+++ b/products/data_modeling/backend/presentation/views/__init__.py@@ -1,5 +1,4 @@-from products.data_modeling.backend.presentation.views.dag import DAGViewSetfrom products.data_modeling.backend.presentation.views.edge import EdgeViewSetfrom products.data_modeling.backend.presentation.views.node import NodeViewSet-__all__ = ["DAGViewSet", "EdgeViewSet", "NodeViewSet"]+__all__ = ["EdgeViewSet", "NodeViewSet"]diff --git a/products/data_modeling/backend/presentation/views/dag.py b/products/data_modeling/backend/presentation/views/dag.pydeleted file mode 100644index 66074eec1827..000000000000--- a/products/data_modeling/backend/presentation/views/dag.py+++ /dev/null@@ -1,130 +0,0 @@-import re-from typing import cast--from django.db.models import Count--from rest_framework import serializers, status, viewsets-from rest_framework.exceptions import APIException, ValidationError--from posthog.api.routing import TeamAndOrgViewSetMixin--from products.data_modeling.backend.facade.api import delete_dag_schedules-from products.data_modeling.backend.facade.models import DAG, RESERVED_DAG_NAMES-from products.warehouse_sources.backend.facade.models import (- sync_frequency_interval_to_sync_frequency,- sync_frequency_to_sync_frequency_interval,-)--# C0 controls, DEL, C1 controls, and the Unicode line/paragraph separators.-CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]")---class ScheduleTeardownUnavailable(APIException):- status_code = status.HTTP_503_SERVICE_UNAVAILABLE- default_detail = "Couldn't remove this DAG's schedules, so it wasn't deleted. Try again in a few minutes."---class DAGSerializer(serializers.ModelSerializer):- node_count = serializers.IntegerField(read_only=True, default=0)- sync_frequency = serializers.CharField(- required=False,- allow_null=True,- help_text=(- "Legacy DAG-level cadence string (e.g. '24hour', '7day'). Scheduling is driven by each "- "model's own sync frequency, so a PATCH that changes this value is rejected."- ),- )-- class Meta:- model = DAG- fields = [- "id",- "name",- "description",- "sync_frequency",- "node_count",- "created_at",- "updated_at",- ]- read_only_fields = [- "id",- "node_count",- "created_at",- "updated_at",- ]- extra_kwargs = {- "name": {"help_text": "Human-readable name for this DAG"},- "description": {"help_text": "Optional description of the DAG's purpose"},- }-- def to_representation(self, instance: DAG) -> dict:- data = super().to_representation(instance)- data["sync_frequency"] = sync_frequency_interval_to_sync_frequency(instance.sync_frequency_interval)- return data-- def validate_sync_frequency(self, value: str | None) -> str | None:- if value is not None:- try:- sync_frequency_to_sync_frequency_interval(value)- except ValueError:- raise serializers.ValidationError(f"Invalid sync frequency: {value}")- return value-- def validate_name(self, value: str) -> str:- # DAG names are echoed into management-command output, the confirmation prompt of- # destructive fleet tooling, and logs. A control character there can erase or rewrite the- # surrounding text, so reject it at the boundary rather than escaping at each display site.- if CONTROL_CHARACTERS.search(value):- raise serializers.ValidationError("Name cannot contain control characters.")- is_rename = self.instance is not None and value != self.instance.name- if is_rename:- instance = cast(DAG, self.instance)- if instance.is_default:- raise serializers.ValidationError("The default DAG cannot be renamed.")- if instance.is_managed:- raise serializers.ValidationError("System-managed DAGs cannot be renamed.")- # Block users from claiming a reserved system name via create or rename.- if value in RESERVED_DAG_NAMES and (self.instance is None or is_rename):- raise serializers.ValidationError("This name is reserved for system-managed DAGs.")- return value-- def create(self, validated_data: dict) -> DAG:- validated_data["team_id"] = self.context["team_id"]- sync_frequency = validated_data.pop("sync_frequency", None)- if sync_frequency:- validated_data["sync_frequency_interval"] = sync_frequency_to_sync_frequency_interval(sync_frequency)- return super().create(validated_data)-- def update(self, instance: DAG, validated_data: dict) -> DAG:- if instance.is_managed:- raise serializers.ValidationError("System-managed DAGs cannot be edited.")- sync_frequency = validated_data.pop("sync_frequency", None)- if sync_frequency is not None:- # The frontend spreads the whole DAG into every PATCH, so an unchanged- # echo of the current frequency must pass; only a real change is rejected.- current = sync_frequency_interval_to_sync_frequency(instance.sync_frequency_interval)- if sync_frequency != current:- raise serializers.ValidationError(- "Sync frequency is managed per model on this team. Edit each model's sync frequency instead."- )- return super().update(instance, validated_data)---class DAGViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):- scope_object = "INTERNAL"- queryset = DAG.objects.all()- serializer_class = DAGSerializer- http_method_names = ["get", "post", "patch", "delete", "head", "options"]-- def safely_get_queryset(self, queryset):- return queryset.filter(team_id=self.team_id).annotate(node_count=Count("node")).order_by("name")-- def perform_destroy(self, instance: DAG) -> None:- if instance.is_default:- raise ValidationError("The default DAG cannot be deleted.")- if instance.is_managed:- raise ValidationError("System-managed DAGs cannot be deleted.")- # Keep the DAG row when teardown fails: it is the only handle left for finding the schedules.- if not delete_dag_schedules(str(instance.id)).ok:- raise ScheduleTeardownUnavailable()- instance.delete()diff --git a/products/data_modeling/backend/presentation/views/edge.py b/products/data_modeling/backend/presentation/views/edge.pyindex b9491db110bf..f2faff02887d 100644--- a/products/data_modeling/backend/presentation/views/edge.py+++ b/products/data_modeling/backend/presentation/views/edge.py@@ -1,9 +1,6 @@from typing import Any-from uuid import UUID-from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view-from rest_framework import filters, serializers, viewsets+from rest_framework import mixins, serializers, viewsetsfrom rest_framework.pagination import PageNumberPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -21,7 +18,6 @@ def _connects_a_metric(edge: Edge) -> bool:class EdgeSerializer(serializers.ModelSerializer):source_id = serializers.UUIDField(read_only=True, help_text="ID of the upstream node.")target_id = serializers.UUIDField(read_only=True, help_text="ID of the downstream node.")- dag_name = serializers.SerializerMethodField(read_only=True)class Meta:model = Edge@@ -29,31 +25,22 @@ class EdgeSerializer(serializers.ModelSerializer):"id","source_id","target_id",- "dag",- "dag_name","properties","created_at","updated_at",]read_only_fields = ["id",- "dag_name","created_at","updated_at",]- def get_dag_name(self, edge: Edge) -> str:- return edge.dag.name-def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:# System-managed DAGs (e.g. Revenue Analytics) own their edges; the internal sync path# maintains them directly via the ORM and bypasses this serializer. Block users from# editing managed edges or moving any edge into a managed DAG via the API.if self.instance is not None and self.instance.dag.is_managed:raise serializers.ValidationError("Edges belonging to a system-managed DAG cannot be modified.")- 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@@ -63,26 +50,19 @@ class EdgePagination(PageNumberPagination):page_size = 5000-@extend_schema_view(- list=extend_schema(- parameters=[- OpenApiParameter(- name="dag",- type=OpenApiTypes.UUID,- location=OpenApiParameter.QUERY,- required=False,- description="Return only the edges of this DAG.",- )- ]- )-)-class EdgeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+class EdgeViewSet(+ MetricNodeVisibilityMixin,+ TeamAndOrgViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ mixins.UpdateModelMixin,+ mixins.DestroyModelMixin,+ viewsets.GenericViewSet,+):scope_object = "INTERNAL"queryset = Edge.objects.select_related("dag").all()serializer_class = EdgeSerializerpagination_class = EdgePagination- filter_backends = [filters.SearchFilter]- search_fields = ["dag__name"]ordering = "-created_at"def get_serializer_context(self) -> dict[str, Any]:@@ -96,13 +76,4 @@ class EdgeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.Moinstance.delete()def safely_get_queryset(self, queryset):- qs = self._exclude_hidden_edges(queryset.filter(team_id=self.team_id))- dag_id = self.request.query_params.get("dag")- if dag_id:- try:- UUID(dag_id)- except ValueError:- dag_id = None- else:- qs = qs.filter(dag_id=dag_id)- return qs.order_by(self.ordering)+ return self._exclude_hidden_edges(queryset.filter(team_id=self.team_id)).order_by(self.ordering)diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex 60dc9bffd9d4..de5d4337e836 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -10,7 +10,7 @@ from django.db.models import Exists, OuterRef, Subqueryfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field-from rest_framework import filters, request, response, serializers, status, viewsets+from rest_framework import filters, mixins, request, response, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, PermissionDeniedfrom rest_framework.pagination import PageNumberPagination@@ -19,7 +19,6 @@ from temporalio.common import RetryPolicyfrom posthog.hogql.database.database import Databasefrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.models import Userfrom posthog.rbac.query_access import assert_user_can_read_queryfrom posthog.temporal.common.client import sync_connect@@ -33,7 +32,6 @@ from products.data_modeling.backend.facade.api import (unsuspend_nodes,)from products.data_modeling.backend.facade.models import (- DAG,SAVED_QUERY_NODE_TYPES,DataModelingJob,DataModelingJobEngine,@@ -96,11 +94,9 @@ class NodeSerializer(serializers.ModelSerializer):last_run_error = serializers.SerializerMethodField(read_only=True)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)origin = serializers.SerializerMethodField(read_only=True)warehouse_table_id = serializers.SerializerMethodField(read_only=True)- dag = TeamScopedPrimaryKeyRelatedField(queryset=DAG.objects.all())class Meta:model = Node@@ -108,8 +104,6 @@ class NodeSerializer(serializers.ModelSerializer):"id","name","type",- "dag",- "dag_name","description","saved_query_id","metric_id",@@ -137,7 +131,6 @@ class NodeSerializer(serializers.ModelSerializer):"last_run_status","user_tag","sync_interval",- "dag_name","saved_query_id","metric_id","lineage_issue",@@ -210,9 +203,6 @@ class NodeSerializer(serializers.ModelSerializer):return sync_frequency_interval_to_sync_frequency(node.saved_query.sync_frequency_interval)return None- 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@@ -249,19 +239,13 @@ class NodeSerializer(serializers.ModelSerializer):# editing managed nodes or moving any node into a managed DAG via the API.if self.instance is not None and self.instance.dag.is_managed:raise serializers.ValidationError("Nodes belonging to a system-managed DAG cannot be modified.")- 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:+ if node_type is not None and self.instance 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:+ if node_type != self.instance.type:raise serializers.ValidationError("A node's type cannot be changed through the API.")return attrs@@ -351,13 +335,21 @@ class LineageResponseSerializer(serializers.Serializer):edges = EdgeSerializer(many=True, help_text="Every edge between two of those nodes.")-class NodeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):+class NodeViewSet(+ MetricNodeVisibilityMixin,+ TeamAndOrgViewSetMixin,+ mixins.ListModelMixin,+ mixins.RetrieveModelMixin,+ mixins.UpdateModelMixin,+ mixins.DestroyModelMixin,+ viewsets.GenericViewSet,+):scope_object = "INTERNAL"queryset = Node.objects.select_related("saved_query", "dag").all()serializer_class = NodeSerializerpagination_class = NodePaginationfilter_backends = [filters.SearchFilter]- search_fields = ["name", "dag__name"]+ search_fields = ["name"]ordering = "name"def get_serializer_context(self) -> dict[str, Any]:@@ -420,17 +412,6 @@ class NodeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.Moself._require_warehouse_access(level="viewer", message=_READ_DENIED)return super().retrieve(request, *args, **kwargs)- @extend_schema(- parameters=[- OpenApiParameter(- name="dag",- type=OpenApiTypes.UUID,- location=OpenApiParameter.QUERY,- required=False,- description="Scope the lineage counts to this DAG.",- )- ]- )def list(self, request, *args, **kwargs):from products.data_modeling.backend.facade.models import Graph@@ -440,8 +421,7 @@ class NodeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.Mopage = self.paginate_queryset(queryset)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, hidden_types=self._hidden_node_types())+ graph = Graph(team_id=self.team_id, hidden_types=self._hidden_node_types())node_ids = [str(n.id) for n in nodes]counts = graph.batch_counts(node_ids)@@ -452,21 +432,10 @@ class NodeViewSet(MetricNodeVisibilityMixin, TeamAndOrgViewSetMixin, viewsets.Moreturn self.get_paginated_response(serializer.data)return response.Response(serializer.data)- def _get_dag_id_param(self) -> str | None:- dag_id = self.request.query_params.get("dag")- if dag_id:- try:- UUID(dag_id)- except ValueError:- return None- return dag_id-def safely_get_queryset(self, queryset):- 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)- return qs.order_by(self.ordering)+ return _annotate_latest_job(self._exclude_hidden_nodes(queryset.filter(team_id=self.team_id))).order_by(+ self.ordering+ )@action(methods=["POST"], detail=True)def run(self, req: request.Request, *args, **kwargs) -> response.Response:diff --git a/products/data_modeling/backend/routes.py b/products/data_modeling/backend/routes.pyindex 41f5dbe7beae..9d34ab5dc231 100644--- a/products/data_modeling/backend/routes.py+++ b/products/data_modeling/backend/routes.py@@ -1,9 +1,8 @@from posthog.api.routing import RouterRegistry-from products.data_modeling.backend.presentation.views import DAGViewSet, EdgeViewSet, NodeViewSet+from products.data_modeling.backend.presentation.views import EdgeViewSet, NodeViewSetdef register_routes(routers: RouterRegistry) -> None:- routers.projects.register(r"data_modeling_dags", DAGViewSet, "project_data_modeling_dags", ["team_id"])routers.projects.register(r"data_modeling_nodes", NodeViewSet, "project_data_modeling_nodes", ["team_id"])routers.projects.register(r"data_modeling_edges", EdgeViewSet, "project_data_modeling_edges", ["team_id"])diff --git a/products/data_modeling/backend/tests/api/test_dag_api.py b/products/data_modeling/backend/tests/api/test_dag_api.pydeleted file mode 100644index ac602090f091..000000000000--- a/products/data_modeling/backend/tests/api/test_dag_api.py+++ /dev/null@@ -1,237 +0,0 @@-from datetime import timedelta--from posthog.test.base import APIBaseTest-from unittest import mock--from parameterized import parameterized-from rest_framework import status--from products.data_modeling.backend.logic.schedule_reconcile import DagScheduleTeardown-from products.data_modeling.backend.models import DAG, Node, NodeType--VIEW = "products.data_modeling.backend.presentation.views.dag"---def _teardown(*, ok: bool) -> DagScheduleTeardown:- return DagScheduleTeardown(ok=ok, deleted=())---class TestDAGViewSet(APIBaseTest):- def test_list_dags(self):- DAG.objects.create(team=self.team, name="my_dag")- DAG.objects.create(team=self.team, name="another_dag")-- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_dags/")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["count"], 2)- names = [d["name"] for d in response.json()["results"]]- self.assertEqual(names, ["another_dag", "my_dag"])-- def test_create_dag(self):- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_dags/",- {"name": "new_dag", "description": "A test DAG"},- )-- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertEqual(response.json()["name"], "new_dag")- self.assertEqual(response.json()["description"], "A test DAG")- self.assertEqual(response.json()["node_count"], 0)- self.assertTrue(DAG.objects.filter(team=self.team, name="new_dag").exists())-- def test_retrieve_dag(self):- dag = DAG.objects.create(team=self.team, name="my_dag", description="desc")- Node.objects.create(team=self.team, dag=dag, name="events", type=NodeType.TABLE)-- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["name"], "my_dag")- self.assertEqual(response.json()["node_count"], 1)-- def test_partial_update_dag(self):- dag = DAG.objects.create(team=self.team, name="my_dag")-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"description": "updated description"},- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["description"], "updated description")-- def test_delete_dag(self):- dag = DAG.objects.create(team=self.team, name="my_dag")-- with mock.patch(f"{VIEW}.delete_dag_schedules", return_value=_teardown(ok=True)) as teardown:- response = self.client.delete(f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/")-- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)- self.assertFalse(DAG.objects.filter(team=self.team, id=dag.id).exists())- teardown.assert_called_once_with(str(dag.id))-- def test_dag_survives_a_failed_schedule_teardown(self):- dag = DAG.objects.create(team=self.team, name="my_dag")-- with mock.patch(f"{VIEW}.delete_dag_schedules", return_value=_teardown(ok=False)):- response = self.client.delete(f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/")-- self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)- self.assertTrue(DAG.objects.filter(team=self.team, id=dag.id).exists())-- def test_cannot_delete_default_dag(self):- dag = DAG.get_or_create_default(self.team)-- response = self.client.delete(f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/")-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertTrue(DAG.objects.filter(team=self.team, id=dag.id).exists())-- def test_cannot_rename_default_dag(self):- dag = DAG.get_or_create_default(self.team)-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"name": "renamed"},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- dag.refresh_from_db()- self.assertEqual(dag.name, "Default")-- def test_cannot_delete_managed_dag(self):- dag = DAG.get_or_create_revenue_analytics(self.team)-- response = self.client.delete(f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/")-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertTrue(DAG.objects.filter(team=self.team, id=dag.id).exists())-- def test_cannot_rename_managed_dag(self):- dag = DAG.get_or_create_revenue_analytics(self.team)-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"name": "renamed"},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- dag.refresh_from_db()- self.assertEqual(dag.name, "PostHog Revenue Analytics")-- def test_cannot_edit_managed_dag(self):- dag = DAG.get_or_create_revenue_analytics(self.team)-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"description": "updated description"},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- dag.refresh_from_db()- self.assertEqual(dag.description, "")-- def test_cannot_create_dag_with_reserved_name(self):- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_dags/",- {"name": "PostHog Revenue Analytics"},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertFalse(DAG.objects.filter(team=self.team, name="PostHog Revenue Analytics").exists())-- @parameterized.expand(- [- ("escape", "evil\x1b[2Kreplaced"),- ("carriage_return", "evil\rreplaced"),- ("newline", "evil\nreplaced"),- ("null", "evil\x00replaced"),- ("delete", "evil\x7freplaced"),- ]- )- def test_cannot_create_dag_with_control_characters_in_name(self, _name, dag_name):- # DAG names are echoed into management-command output and the confirmation prompt of- # destructive fleet tooling; a control character there rewrites what an operator reads- # before typing "y". NUL additionally reaches Postgres as a driver-level DataError (a 500)- # without this guard — the name is never queried back here for that reason.- before = DAG.objects.filter(team=self.team).count()-- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_dags/",- {"name": dag_name},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(DAG.objects.filter(team=self.team).count(), before)-- def test_cannot_rename_dag_to_a_name_with_control_characters(self):- dag = DAG.objects.create(team=self.team, name="my_dag")-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"name": "my_dag\x1b[2Kevil"},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- dag.refresh_from_db()- self.assertEqual(dag.name, "my_dag")-- def test_ordinary_punctuation_in_a_name_is_still_allowed(self):- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_dags/",- {"name": "Ünïcode — dbt/staging (v2)"},- )-- self.assertEqual(response.status_code, status.HTTP_201_CREATED)-- def test_cannot_rename_dag_to_reserved_name(self):- dag = DAG.objects.create(team=self.team, name="my_dag")-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"name": "PostHog Revenue Analytics"},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- dag.refresh_from_db()- self.assertEqual(dag.name, "my_dag")-- def test_cannot_set_sync_frequency(self):- dag = DAG.objects.create(team=self.team, name="my_dag")- interval_before = dag.sync_frequency_interval-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"sync_frequency": "15min"},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("managed per model", response.json()["detail"])- dag.refresh_from_db()- self.assertEqual(dag.sync_frequency_interval, interval_before)-- def test_can_still_rename_dag(self):- dag = DAG.objects.create(team=self.team, name="my_dag")-- # The frontend spreads the whole DAG into the PATCH, echoing the current- # sync_frequency back unchanged. That echo must not trip the rejection.- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/",- {"name": "renamed", "description": "still editable", "sync_frequency": "24hour"},- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- dag.refresh_from_db()- self.assertEqual(dag.name, "renamed")- self.assertEqual(dag.description, "still editable")- self.assertEqual(dag.sync_frequency_interval, timedelta(days=1))-- def test_node_count_reflects_nodes(self):- dag = DAG.objects.create(team=self.team, name="my_dag")- Node.objects.create(team=self.team, dag=dag, name="events", type=NodeType.TABLE)- Node.objects.create(team=self.team, dag=dag, name="persons", type=NodeType.TABLE)-- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_dags/{dag.id}/")-- self.assertEqual(response.json()["node_count"], 2)diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex 70dbb07f0299..c41471bf82f3 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -284,7 +284,6 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["name"], "test_view")self.assertEqual(response.json()["type"], "view")- self.assertEqual(response.json()["dag"], str(self.dag.id))@parameterized.expand([@@ -316,35 +315,6 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(response.json()["upstream_count"], 0)self.assertEqual(response.json()["downstream_count"], 0)- def test_list_nodes_with_dag_filter(self):- another_dag = DAG.objects.create(team=self.team, name="another_dag")- Node.objects.create(- team=self.team,- dag=another_dag,- name="another_table",- type=NodeType.TABLE,- )-- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/?dag={another_dag.id}")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["count"], 1)- self.assertEqual(response.json()["results"][0]["name"], "another_table")-- def test_list_nodes_without_dag_filter_returns_all(self):- another_dag = DAG.objects.create(team=self.team, name="another_dag")- Node.objects.create(- team=self.team,- dag=another_dag,- name="another_table",- type=NodeType.TABLE,- )-- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["count"], 3)-@parameterized.expand([# node target wins even when the saved-query interval disagrees (tiered v2 teams@@ -371,12 +341,6 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["sync_interval"], expected)- def test_node_response_includes_dag_name(self):- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["dag_name"], self.dag_id)-def test_run_requires_direction(self):response = self.client.post(f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/run/",@@ -691,36 +655,6 @@ class TestNodeViewSet(APIBaseTest):self.assertNotIn(str(other_table.id), node_ids)self.assertNotIn(str(other_view.id), node_ids)- @parameterized.expand(["post", "put", "patch"])- def test_dag_field_rejects_other_teams_dag(self, method):- other_team = Team.objects.create(organization=self.organization)- foreign_dag = DAG.objects.create(team=other_team, name=f"posthog_{other_team.id}")-- if method == "post":- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_nodes/",- data={"name": "new_table", "type": NodeType.TABLE, "dag": str(foreign_dag.id)},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertFalse(Node.objects.filter(name="new_table", dag=foreign_dag).exists())- return-- original_dag_id = self.view_node.dag_id- url = f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/"- if method == "patch":- response = self.client.patch(url, data={"dag": str(foreign_dag.id)}, format="json")- else:- response = self.client.put(- url,- data={"name": "test_view", "type": NodeType.VIEW, "dag": str(foreign_dag.id)},- format="json",- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.view_node.refresh_from_db()- self.assertEqual(self.view_node.dag_id, original_dag_id)-@parameterized.expand(["put", "patch"])def test_saved_query_id_cannot_be_bound_to_other_teams_query(self, method):other_team = Team.objects.create(organization=self.organization)@@ -740,7 +674,6 @@ class TestNodeViewSet(APIBaseTest):data={"name": "test_view","type": NodeType.VIEW,- "dag": str(self.dag.id),"saved_query_id": str(foreign_sq.id),},format="json",@@ -781,29 +714,6 @@ class TestNodeViewSet(APIBaseTest):node.refresh_from_db()self.assertEqual(node.description, "orig")- @parameterized.expand(["post", "patch"])- def test_cannot_add_or_move_node_into_managed_dag(self, method):- managed_dag = DAG.get_or_create_revenue_analytics(self.team)-- if method == "post":- response = self.client.post(- f"/api/environments/{self.team.id}/data_modeling_nodes/",- data={"name": "sneaky", "type": NodeType.TABLE, "dag": str(managed_dag.id)},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertFalse(Node.objects.filter(name="sneaky", dag=managed_dag).exists())- return-- response = self.client.patch(- f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/",- data={"dag": str(managed_dag.id)},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.view_node.refresh_from_db()- self.assertEqual(self.view_node.dag_id, self.dag.id)-class TestMetricNodeAPI(APIBaseTest):def setUp(self):@@ -881,16 +791,11 @@ class TestMetricNodeAPI(APIBaseTest):self.metric_node.refresh_from_db()self.assertEqual(self.metric_node.type, NodeType.METRIC)- @parameterized.expand(["name", "description", "dag_id"])+ @parameterized.expand(["name", "description"])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")+ response = self.client.patch(f"{self.url}{self.metric_node.id}/", data={field: "changed"}, format="json")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.metric_node.refresh_from_db()@@ -904,18 +809,21 @@ class TestMetricNodeAPI(APIBaseTest):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+ @parameterized.expand(+ [+ ("node", "data_modeling_nodes", {"name": "sneaky", "type": NodeType.TABLE}),+ ("edge", "data_modeling_edges", {"properties": {}}),+ ]+ )+ def test_nodes_and_edges_cannot_be_created_through_the_api(self, _name, endpoint, payload):+ nodes_before, edges_before = Node.objects.count(), Edge.objects.count()++ response = self.client.post(f"/api/environments/{self.team.id}/{endpoint}/", data=payload, format="json")+ self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)+ self.assertEqual((Node.objects.count(), Edge.objects.count()), (nodes_before, edges_before))++ def test_a_node_cannot_be_retyped_through_the_api(self):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()@@ -1121,7 +1029,6 @@ class TestEdgeViewSet(APIBaseTest):edge = response.json()["results"][0]self.assertEqual(edge["source_id"], str(self.source_node.id))self.assertEqual(edge["target_id"], str(self.target_node.id))- self.assertEqual(edge["dag"], str(self.dag.id))def test_list_edges_query_count_does_not_grow_with_edges(self):url = f"/api/environments/{self.team.id}/data_modeling_edges/"@@ -1139,39 +1046,6 @@ class TestEdgeViewSet(APIBaseTest):self.assertEqual(response.json()["count"], 6)self.assertEqual(len(grown.captured_queries), len(baseline.captured_queries))- def test_list_edges_with_dag_filter(self):- another_dag = DAG.objects.create(team=self.team, name="another_dag")- another_source = Node.objects.create(- team=self.team,- dag=another_dag,- name="another_events",- type=NodeType.TABLE,- )- another_target = Node.objects.create(- team=self.team,- dag=another_dag,- name="another_view",- type=NodeType.TABLE,- )- Edge.objects.create(- team=self.team,- dag=another_dag,- source=another_source,- target=another_target,- )-- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_edges/?dag={another_dag.id}")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["count"], 1)- self.assertEqual(response.json()["results"][0]["source_id"], str(another_source.id))-- def test_edge_response_includes_dag_name(self):- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_edges/")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["results"][0]["dag_name"], self.dag_id)-def test_list_edges_filters_by_team(self):other_team = Team.objects.create(organization=self.organization)other_dag = DAG.objects.create(team=other_team, name=f"posthog_{other_team.id}")diff --git a/products/data_modeling/frontend/ModelsOverviewTab.stories.tsx b/products/data_modeling/frontend/ModelsOverviewTab.stories.tsxindex 3261e37121a5..c7edb815d8e4 100644--- a/products/data_modeling/frontend/ModelsOverviewTab.stories.tsx+++ b/products/data_modeling/frontend/ModelsOverviewTab.stories.tsx@@ -15,7 +15,6 @@ const nodes = ['attention', 'behind'].flatMap((group) =>id: `${group}-${index + 1}`,name: `${group}_model_${index + 1}`,type: 'matview',- dag: 'example-dag',created_at: '2026-01-01T00:00:00Z',updated_at: '2026-01-01T00:00:00Z',last_run_at: '2026-09-14T00:00:00Z',@@ -40,7 +39,6 @@ const healthyNodes = Array.from({ length: 3 }, (_, index) => ({id: `healthy-${index + 1}`,name: `healthy_model_${index + 1}`,type: 'matview',- dag: 'example-dag',created_at: '2026-01-01T00:00:00Z',updated_at: '2026-01-01T00:00:00Z',last_run_at: '2026-09-15T00:00:00Z',diff --git a/products/data_modeling/frontend/generated/api.schemas.ts b/products/data_modeling/frontend/generated/api.schemas.tsindex 4aee9668fb6f..5a6db4e27355 100644--- a/products/data_modeling/frontend/generated/api.schemas.ts+++ b/products/data_modeling/frontend/generated/api.schemas.ts@@ -7,63 +7,12 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/-export interface DagApi {- readonly id: string- /**- * Human-readable name for this DAG- * @maxLength 2048- */- name: string- /** Optional description of the DAG's purpose */- description?: string- /**- * Legacy DAG-level cadence string (e.g. '24hour', '7day'). Scheduling is driven by each model's own sync frequency, so a PATCH that changes this value is rejected.- * @nullable- */- sync_frequency?: string | null- readonly node_count: number- readonly created_at: string- /** @nullable */- readonly updated_at: string | null-}--export interface PaginatedDAGListApi {- count: number- /** @nullable */- next?: string | null- /** @nullable */- previous?: string | null- results: DagApi[]-}--export interface PatchedDAGApi {- readonly id?: string- /**- * Human-readable name for this DAG- * @maxLength 2048- */- name?: string- /** Optional description of the DAG's purpose */- description?: string- /**- * Legacy DAG-level cadence string (e.g. '24hour', '7day'). Scheduling is driven by each model's own sync frequency, so a PATCH that changes this value is rejected.- * @nullable- */- sync_frequency?: string | null- readonly node_count?: number- readonly created_at?: string- /** @nullable */- readonly updated_at?: string | null-}-export interface EdgeApi {readonly id: string/** ID of the upstream node. */readonly source_id: string/** ID of the downstream node. */readonly target_id: string- dag: string- readonly dag_name: stringproperties?: unknownreadonly created_at: string/** @nullable */@@ -85,8 +34,6 @@ export interface PatchedEdgeApi {readonly source_id?: string/** ID of the downstream node. */readonly target_id?: string- dag?: string- readonly dag_name?: stringproperties?: unknownreadonly created_at?: string/** @nullable */@@ -173,8 +120,6 @@ export interface NodeApi {/** @maxLength 2048 */name: stringtype?: NodeTypeEnumApi- dag: string- readonly dag_name: string/** @maxLength 1024 */description?: string/** @nullable */@@ -239,8 +184,6 @@ export interface PatchedNodeApi {/** @maxLength 2048 */name?: stringtype?: NodeTypeEnumApi- dag?: string- readonly dag_name?: string/** @maxLength 1024 */description?: string/** @nullable */@@ -298,37 +241,14 @@ export interface LineageResponseApi {edges: EdgeApi[]}-export type DataModelingDagsListParams = {- /**- * Number of results to return per page.- */- limit?: number- /**- * The initial index from which to return the results.- */- offset?: number-}-export type DataModelingEdgesListParams = {- /**- * Return only the edges of this DAG.- */- dag?: string/*** A page number within the paginated result set.*/page?: number- /**- * A search term.- */- search?: string}export type DataModelingNodesListParams = {- /**- * Scope the lineage counts to this DAG.- */- dag?: string/*** A page number within the paginated result set.*/diff --git a/products/data_modeling/frontend/generated/api.ts b/products/data_modeling/frontend/generated/api.tsindex c575420b09f2..2211ba16bcae 100644--- a/products/data_modeling/frontend/generated/api.ts+++ b/products/data_modeling/frontend/generated/api.ts@@ -9,8 +9,6 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {- DagApi,- DataModelingDagsListParams,DataModelingEdgesListParams,DataModelingNodesLineageRetrieveParams,DataModelingNodesListParams,@@ -19,10 +17,8 @@ import type {LineageResponseApi,NodeApi,NodeResumeApi,- PaginatedDAGListApi,PaginatedEdgeListApi,PaginatedNodeListApi,- PatchedDAGApi,PatchedEdgeApi,PatchedNodeApi,} from './api.schemas'@@ -44,94 +40,6 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>-export const getDataModelingDagsListUrl = (projectId: string, params?: DataModelingDagsListParams) => {- 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_modeling_dags/?${stringifiedParams}`- : `/api/projects/${projectId}/data_modeling_dags/`-}--export const dataModelingDagsList = async (- projectId: string,- params?: DataModelingDagsListParams,- options?: RequestInit-): Promise<PaginatedDAGListApi> => {- return apiMutator<PaginatedDAGListApi>(getDataModelingDagsListUrl(projectId, params), {- ...options,- method: 'GET',- })-}--export const getDataModelingDagsCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/data_modeling_dags/`-}--export const dataModelingDagsCreate = async (- projectId: string,- dagApi: NonReadonly<DagApi>,- options?: RequestInit-): Promise<DagApi> => {- return apiMutator<DagApi>(getDataModelingDagsCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dagApi),- })-}--export const getDataModelingDagsRetrieveUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/data_modeling_dags/${id}/`-}--export const dataModelingDagsRetrieve = async (- projectId: string,- id: string,- options?: RequestInit-): Promise<DagApi> => {- return apiMutator<DagApi>(getDataModelingDagsRetrieveUrl(projectId, id), {- ...options,- method: 'GET',- })-}--export const getDataModelingDagsPartialUpdateUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/data_modeling_dags/${id}/`-}--export const dataModelingDagsPartialUpdate = async (- projectId: string,- id: string,- patchedDAGApi?: NonReadonly<PatchedDAGApi>,- options?: RequestInit-): Promise<DagApi> => {- return apiMutator<DagApi>(getDataModelingDagsPartialUpdateUrl(projectId, id), {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedDAGApi),- })-}--export const getDataModelingDagsDestroyUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/data_modeling_dags/${id}/`-}--export const dataModelingDagsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {- return apiMutator<void>(getDataModelingDagsDestroyUrl(projectId, id), {- ...options,- method: 'DELETE',- })-}-export const getDataModelingEdgesListUrl = (projectId: string, params?: DataModelingEdgesListParams) => {const normalizedParams = new URLSearchParams()@@ -159,23 +67,6 @@ export const dataModelingEdgesList = async (})}-export const getDataModelingEdgesCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/data_modeling_edges/`-}--export const dataModelingEdgesCreate = async (- projectId: string,- edgeApi: NonReadonly<EdgeApi>,- options?: RequestInit-): Promise<EdgeApi> => {- return apiMutator<EdgeApi>(getDataModelingEdgesCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(edgeApi),- })-}-export const getDataModelingEdgesRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/data_modeling_edges/${id}/`}@@ -198,7 +89,7 @@ export const getDataModelingEdgesUpdateUrl = (projectId: string, id: string) =>export const dataModelingEdgesUpdate = async (projectId: string,id: string,- edgeApi: NonReadonly<EdgeApi>,+ edgeApi?: NonReadonly<EdgeApi>,options?: RequestInit): Promise<EdgeApi> => {return apiMutator<EdgeApi>(getDataModelingEdgesUpdateUrl(projectId, id), {@@ -265,23 +156,6 @@ export const dataModelingNodesList = async (})}-export const getDataModelingNodesCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/data_modeling_nodes/`-}--export const dataModelingNodesCreate = async (- projectId: string,- nodeApi: NonReadonly<NodeApi>,- options?: RequestInit-): Promise<NodeApi> => {- return apiMutator<NodeApi>(getDataModelingNodesCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(nodeApi),- })-}-export const getDataModelingNodesRetrieveUrl = (projectId: string,id: string,diff --git a/products/data_modeling/frontend/generated/api.zod.ts b/products/data_modeling/frontend/generated/api.zod.tsindex c84f7c96ee51..3a614ed0fc8f 100644--- a/products/data_modeling/frontend/generated/api.zod.ts+++ b/products/data_modeling/frontend/generated/api.zod.ts@@ -9,67 +9,14 @@*/import * as zod from 'zod'-export const dataModelingDagsCreateBodyNameMax = 2048--export const DataModelingDagsCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(dataModelingDagsCreateBodyNameMax).describe('Human-readable name for this DAG'),- description: zod.string().optional().describe("Optional description of the DAG's purpose"),- sync_frequency: zod- .string()- .nullish()- .describe(- "Legacy DAG-level cadence string (e.g. '24hour', '7day'). Scheduling is driven by each model's own sync frequency, so a PATCH that changes this value is rejected."- ),-})--export const dataModelingDagsPartialUpdateBodyNameMax = 2048--export const DataModelingDagsPartialUpdateBody = /* @__PURE__ */ zod.object({- name: zod- .string()- .max(dataModelingDagsPartialUpdateBodyNameMax)- .optional()- .describe('Human-readable name for this DAG'),- description: zod.string().optional().describe("Optional description of the DAG's purpose"),- sync_frequency: zod- .string()- .nullish()- .describe(- "Legacy DAG-level cadence string (e.g. '24hour', '7day'). Scheduling is driven by each model's own sync frequency, so a PATCH that changes this value is rejected."- ),-})--export const DataModelingEdgesCreateBody = /* @__PURE__ */ zod.object({- dag: zod.uuid(),- properties: zod.unknown().optional(),-})-export const DataModelingEdgesUpdateBody = /* @__PURE__ */ zod.object({- dag: zod.uuid(),properties: zod.unknown().optional(),})export const DataModelingEdgesPartialUpdateBody = /* @__PURE__ */ zod.object({- dag: zod.uuid().optional(),properties: zod.unknown().optional(),})-export const dataModelingNodesCreateBodyNameMax = 2048--export const dataModelingNodesCreateBodyDescriptionMax = 1024--export const DataModelingNodesCreateBody = /* @__PURE__ */ zod.object({- name: zod.string().max(dataModelingNodesCreateBodyNameMax),- type: zod- .enum(['table', 'view', 'matview', 'endpoint', 'metric'])- .optional()- .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(),-})-export const dataModelingNodesUpdateBodyNameMax = 2048export const dataModelingNodesUpdateBodyDescriptionMax = 1024@@ -82,7 +29,6 @@ export const DataModelingNodesUpdateBody = /* @__PURE__ */ zod.object({.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(),})@@ -98,7 +44,6 @@ export const DataModelingNodesPartialUpdateBody = /* @__PURE__ */ zod.object({.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(),})@@ -117,7 +62,6 @@ export const DataModelingNodesMaterializeCreateBody = /* @__PURE__ */ zod.object.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(),})@@ -141,6 +85,5 @@ export const DataModelingNodesRunCreateBody = /* @__PURE__ */ zod.object({.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_modeling/frontend/lineage/LineageGraph.stories.tsx b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsxindex db990977cef2..066f7c8aa620 100644--- a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx+++ b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx@@ -13,7 +13,6 @@ function mockNode(partial: Pick<DataModelingNode, 'id' | 'name' | 'type'> & Partial<DataModelingNode>): DataModelingNode {return {- dag: 'dag-1',created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',upstream_count: 0,@@ -27,7 +26,6 @@ function mockEdge(id: string, sourceId: string, targetId: string): DataModelingEid,source_id: sourceId,target_id: targetId,- dag: 'dag-1',properties: {},created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',diff --git a/products/data_modeling/frontend/lineage/LineageGraphLoading.tsx b/products/data_modeling/frontend/lineage/LineageGraphLoading.tsxindex a1dda4fdfe65..1f62f9bdea8c 100644--- a/products/data_modeling/frontend/lineage/LineageGraphLoading.tsx+++ b/products/data_modeling/frontend/lineage/LineageGraphLoading.tsx@@ -25,12 +25,10 @@ function loadingGraph(edges: DataModelingEdge[]centerNodeId?: string} {- const dag = 'lineage-loading'const node = (id: string, name: string, type: DataModelingNode['type']): DataModelingNode => ({id,name,type,- dag,created_at: '',updated_at: '',upstream_count: 0,@@ -40,7 +38,6 @@ function loadingGraph(id,source_id,target_id,- dag,properties: {},created_at: '',updated_at: '',diff --git a/products/data_modeling/frontend/modelsSceneLogic.test.ts b/products/data_modeling/frontend/modelsSceneLogic.test.tsindex 722f9015227f..3993d533d120 100644--- a/products/data_modeling/frontend/modelsSceneLogic.test.ts+++ b/products/data_modeling/frontend/modelsSceneLogic.test.ts@@ -17,7 +17,6 @@ function buildNode(id: string, overrides: Partial<DataModelingNode> = {}): DataMid,name: id,type: 'matview',- dag: 'dag-1',created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',upstream_count: 0,@@ -69,8 +68,8 @@ describe('modelsSceneLogic', () => {'/api/environments/:team_id/data_modeling_edges/': {count: 2,results: [- { id: 'e1', source_id: 'broken', target_id: 'child', dag: 'dag-1' },- { id: 'e2', source_id: 'child', target_id: 'grandchild', dag: 'dag-1' },+ { id: 'e1', source_id: 'broken', target_id: 'child' },+ { id: 'e2', source_id: 'child', target_id: 'grandchild' },],},'/api/environments/:team_id/warehouse_saved_queries/': {diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsxindex d18be401eb3d..7cba241f8356 100644--- a/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsx+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsx@@ -33,7 +33,6 @@ const node = {id: 'example-node',name: 'monthly_revenue_summary_by_region_and_channel',type: 'view',- dag: 'example-dag',saved_query_id: 'example-view',created_at: '2026-01-10T10:00:00Z',updated_at: '2026-01-10T10:00:00Z',@@ -62,7 +61,6 @@ const tableNode = {id: 'orders-table-node',name: 'postgres.public.orders',type: 'table',- dag: 'example-dag',saved_query_id: null,origin: 'warehouse',warehouse_table_id: '2efce7bc-9b76-442a-8234-33f6fc3e8c7d',@@ -107,7 +105,6 @@ const tableLineage = (id: `table-edge-${index + 1}`,source_id: sourceNode.id,target_id: targetNode.id,- dag: sourceNode.dag,properties: {},created_at: sourceNode.created_at,updated_at: sourceNode.updated_at,diff --git a/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.ts b/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.tsindex 5d7b2cc10354..d8badf570512 100644--- a/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.ts+++ b/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.ts@@ -26,7 +26,6 @@ function buildNode(type: DataModelingNodeType, overrides: Partial<DataModelingNoid: NODE_ID,name: 'orders',type,- dag: 'dag-1',created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',upstream_count: 0,diff --git a/products/data_warehouse/backend/presentation/views/saved_query/editing.py b/products/data_warehouse/backend/presentation/views/saved_query/editing.pyindex aed7667787a4..ab97d1a6c877 100644--- a/products/data_warehouse/backend/presentation/views/saved_query/editing.py+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py@@ -39,7 +39,6 @@ from products.data_modeling.backend.facade import api as modeling_apifrom products.data_modeling.backend.facade.api import has_incremental_historyfrom products.data_modeling.backend.facade.modeling import ResolutionCycleError, get_parents_from_model_queryfrom products.data_modeling.backend.facade.models import (- DAG,DataWarehouseSavedQuery,DataWarehouseSavedQueryColumnAnnotation,Node,@@ -109,16 +108,6 @@ def _apply_frequency_target(return target-_MOVE_REFUSALS = {- "multiple_placements": "This view belongs to multiple DAGs and cannot be moved here.",- "blocked": "This view cannot move while its DAG is managed or other views depend on it.",- "materializing": (- "This view cannot move while it is materializing. Wait for the run to finish or cancel it, then try again."- ),- "moved": "Something else moved this view while we were moving it. Try again.",-}--def _authored_model_answering_to(team_id: int, name: str, exclude: DataWarehouseSavedQuery | None) -> DataWarehouseSavedQuery | None:@@ -132,13 +121,6 @@ def _authored_model_answering_to(return next((query for query in candidates if models_namespace_chain(query) == name.split(".")), None)-def _move_to_dag(view: DataWarehouseSavedQuery, dag: DAG) -> None:- try:- modeling_api.move_saved_query_to_dag(view.team_id, view.pk, dag.id)- except modeling_api.NodeMoveError as e:- raise serializers.ValidationError({"dag_id": _MOVE_REFUSALS[e.reason]})--class DataWarehouseSavedQuerySerializer(view_state.DataWarehouseSavedQuerySerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer):@@ -211,14 +193,6 @@ class DataWarehouseSavedQuerySerializer(help_text="If true, skip column inference and external table discovery. On update, also skip the query ""revision conflict check. Query validation and revision updates still run.",)- dag_id = TeamScopedPrimaryKeyRelatedField(- queryset=DAG.objects.all(),- pk_field=serializers.UUIDField(),- write_only=True,- required=False,- allow_null=True,- help_text="DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.",- )description = view_description.ViewDescriptionField(required=False, allow_blank=True, allow_null=True, help_text=view_description.VIEW_DESCRIPTION_HELP_TEXT)@@ -265,7 +239,6 @@ class DataWarehouseSavedQuerySerializer("edited_history_id","latest_history_id","soft_update",- "dag_id","is_materialized","origin","is_test",@@ -359,8 +332,6 @@ class DataWarehouseSavedQuerySerializer(validated_data["created_by"] = self.context["request"].uservalidated_data["origin"] = DataWarehouseSavedQuery.Origin.DATA_WAREHOUSEsoft_update = validated_data.pop("soft_update", False)- dag_given = "dag_id" in validated_data- dag_id = validated_data.pop("dag_id", None)has_description = "description" in validated_datadescription = validated_data.pop("description", None)sync_frequency = validated_data.pop("sync_frequency", None)@@ -425,16 +396,12 @@ class DataWarehouseSavedQuerySerializer(],),)- # Best-effort only when the caller left placement to us. A supplied dag_id is- # write-only, so the response cannot show that the placement was discarded.try:with transaction.atomic():- modeling_api.sync_saved_query_to_dag(view, dag=dag_id)+ modeling_api.sync_saved_query_to_dag(view)except Exception as e:capture_exception(e)logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)- if dag_given:- raise serializers.ValidationError({"dag_id": "Could not place this view in the requested DAG."})if sync_frequency is not None:if sync_frequency != "never":assert_user_can_read_query(@@ -454,8 +421,6 @@ class DataWarehouseSavedQuerySerializer(return viewdef update(self, instance: Any, validated_data: Any) -> Any:- dag_given = "dag_id" in validated_data- dag_id = validated_data.pop("dag_id", None)has_description = "description" in validated_datadescription = validated_data.pop("description", None)@@ -560,15 +525,6 @@ class DataWarehouseSavedQuerySerializer(view: DataWarehouseSavedQuery = super().update(locked_instance, validated_data)- if dag_given:- try:- _move_to_dag(view, dag_id or DAG.get_or_create_default(view.team))- except serializers.ValidationError:- raise- except Exception as e:- capture_exception(e)- raise serializers.ValidationError({"dag_id": "Could not move this view to the requested DAG."})-if frequency_changed:previous_target = modeling_api.declared_targets_by_saved_query(view.team_id, [view.pk]).get(str(view.pk)@@ -631,7 +587,7 @@ class DataWarehouseSavedQuerySerializer(# land between the read and the sync, which would then create a second node in the# DAG the move just left. The savepoint keeps a failed sync best effort without# poisoning the update's own transaction.- if "query" in validated_data and not dag_given:+ if "query" in validated_data:try:with transaction.atomic():node = Node.objects.filter(team_id=view.team_id, saved_query=view).select_related("dag").first()@@ -755,11 +711,6 @@ class DataWarehouseSavedQuerySerializer(raise serializers.ValidationError("Only staff users can create test views.")return is_test- def validate_dag_id(self, dag: DAG | None) -> DAG | None:- if dag is not None and dag.is_managed:- raise serializers.ValidationError("Choose a DAG that is not system-managed.")- return dag-def validate_folder(self, folder):if folder is not None and folder.team_id != self.context["team_id"]:raise serializers.ValidationError("Folder not found.")diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_dag_move_concurrency.py b/products/data_warehouse/backend/tests/api/test_saved_query_dag_move_concurrency.pydeleted file mode 100644index 616c15851569..000000000000--- a/products/data_warehouse/backend/tests/api/test_saved_query_dag_move_concurrency.py+++ /dev/null@@ -1,106 +0,0 @@-import time-import threading-from typing import Any--from posthog.test.base import NonAtomicAPIBaseTest-from unittest.mock import patch--from django.db import connection--from products.data_modeling.backend.facade import api as modeling_api-from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Node--BLOCKED_DEADLINE_SECONDS = 30---def wait_until_another_backend_waits_on_a_lock() -> bool:- """Whether some other connection is parked on a lock this test database can grant.-- Polled rather than slept on, so the wait ends as soon as the other thread reaches its lock- instead of after a guessed interval. `pg_locks` is read rather than `pg_stat_activity`- because the caller polls from inside an open transaction, and Postgres caches the backend- status snapshot `pg_stat_activity` reports for the length of one. A transaction the waiter- is queued behind is recorded with no database of its own, so both rows count.- """- deadline = time.monotonic() + BLOCKED_DEADLINE_SECONDS- while time.monotonic() < deadline:- with connection.cursor() as cursor:- cursor.execute(- "SELECT count(*) FROM pg_locks WHERE NOT granted AND pid <> pg_backend_pid() "- "AND (database IS NULL OR database = (SELECT oid FROM pg_database WHERE datname = current_database()))"- )- if cursor.fetchone()[0] > 0:- return True- time.sleep(0.05)- return False---class TestSavedQueryDagMoveConcurrency(NonAtomicAPIBaseTest):- # TransactionTestCase, so a second connection sees what the request under test committed.- CLASS_DATA_LEVEL_SETUP = False-- def setUp(self) -> None:- super().setUp()- patcher = patch.object(DataWarehouseSavedQuery, "get_columns", return_value={})- patcher.start()- self.addCleanup(patcher.stop)-- def _url(self, view_id: str | None = None) -> str:- base = f"/api/environments/{self.team.id}/warehouse_saved_queries/"- return f"{base}{view_id}" if view_id else base-- def test_a_move_cannot_land_between_a_query_edit_reading_a_placement_and_syncing_it(self) -> None:- created = self.client.post(- self._url(),- {"name": "event_view", "query": {"kind": "HogQLQuery", "query": "select event from events limit 100"}},- )- self.assertEqual(created.status_code, 201, created.content)- view = created.json()- origin_dag_id = Node.objects.get(saved_query_id=view["id"]).dag_id- destination = DAG.objects.create(team=self.team, name="Destination")-- def move_on_another_connection() -> None:- # A thread gets its own connection, so this move commits instead of joining the- # request's transaction and rolling back with it.- try:- modeling_api.move_saved_query_to_dag(self.team.pk, view["id"], destination.id)- finally:- connection.close()-- real_sync = modeling_api.sync_saved_query_to_dag- movers: list[threading.Thread] = []-- def sync_after_a_move_tries_to_land(*args: Any, **kwargs: Any) -> Any:- # The DAG to sync into was read just above this call, so this is the window where a- # move that commits would leave the sync writing into the DAG the node has left --- # and `get_or_create` would answer with a second node there.- mover = threading.Thread(target=move_on_another_connection)- mover.start()- movers.append(mover)- self.assertTrue(- wait_until_another_backend_waits_on_a_lock(),- "the move was not held off by the request's row lock",- )- return real_sync(*args, **kwargs)-- with patch(- "products.data_modeling.backend.facade.api.sync_saved_query_to_dag",- side_effect=sync_after_a_move_tries_to_land,- ):- response = self.client.patch(- self._url(view["id"]),- {- "query": {"kind": "HogQLQuery", "query": "select event from events limit 10"},- "edited_history_id": view["latest_history_id"],- },- )-- self.assertEqual(response.status_code, 200, response.content)- self.assertEqual(len(movers), 1)- movers[0].join(timeout=BLOCKED_DEADLINE_SECONDS)- self.assertFalse(movers[0].is_alive())-- nodes = list(Node.objects.filter(team=self.team, saved_query_id=view["id"]))- self.assertEqual(len(nodes), 1)- self.assertNotEqual(nodes[0].dag_id, origin_dag_id)- self.assertEqual(nodes[0].dag_id, destination.id)diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py b/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.pyindex c8096a8f3aa8..35e2e38480ab 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py@@ -5,17 +5,8 @@ from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch-from parameterized import parameterized--from products.data_modeling.backend.facade.api import get_declared_target, set_declared_target-from products.data_modeling.backend.facade.models import (- DAG,- DataModelingJob,- DataModelingJobStatus,- DataWarehouseSavedQuery,- Edge,- Node,-)+from products.data_modeling.backend.facade.api import get_declared_target+from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Nodeclass TestSavedQueryWriteFields(APIBaseTest):@@ -39,43 +30,20 @@ class TestSavedQueryWriteFields(APIBaseTest):self.assertEqual(response.status_code, 400, response.content)self.assertFalse(DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists())- @parameterized.expand([("supplied", True, 400), ("omitted", False, 201)])- def test_create_reports_a_discarded_dag_placement_only_when_asked_for(- self, _name: str, supply_dag_id: bool, expected_status: int- ) -> None:- dag = DAG.objects.create(team=self.team, name="Other")- fields = {"dag_id": str(dag.id)} if supply_dag_id else {}+ def test_create_keeps_the_view_when_the_dag_sync_fails(self) -> None:with patch("products.data_modeling.backend.facade.api.sync_saved_query_to_dag", side_effect=RuntimeError):- response = self._create_view(**fields)- self.assertEqual(response.status_code, expected_status, response.content)- self.assertEqual(- DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists(),- expected_status == 201,- )- self.assertFalse(Node.objects.filter(dag=dag).exists())+ response = self._create_view()+ self.assertEqual(response.status_code, 201, response.content)+ self.assertTrue(DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists())- def test_create_applies_the_requested_dag_and_cadence(self) -> None:- dag = DAG.objects.create(team=self.team, name="Other")- response = self._create_view(dag_id=str(dag.id), sync_frequency="6hour")+ def test_create_places_the_view_in_the_default_dag_with_its_cadence(self) -> None:+ other = DAG.objects.create(team=self.team, name="Other")+ response = self._create_view(dag_id=str(other.id), sync_frequency="6hour")self.assertEqual(response.status_code, 201, response.content)node = Node.objects.get(saved_query_id=response.json()["id"])- self.assertEqual(node.dag_id, dag.id)+ self.assertEqual(node.dag_id, DAG.get_or_create_default(self.team).id)self.assertEqual(get_declared_target(node), timedelta(hours=6))- @parameterized.expand([("create",), ("update",)])- def test_managed_dag_is_rejected(self, operation: str) -> None:- dag = DAG.get_or_create_revenue_analytics(self.team)- if operation == "create":- response = self._create_view(dag_id=str(dag.id))- else:- created = self._create_view().json()- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",- {"dag_id": str(dag.id)},- )- self.assertEqual(response.status_code, 400, response.content)- self.assertFalse(Node.objects.filter(dag=dag).exists())-def test_deleted_cannot_be_set_through_the_write_api(self) -> None:created = self._create_view().json()url = f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}"@@ -84,11 +52,6 @@ class TestSavedQueryWriteFields(APIBaseTest):self.assertFalse(DataWarehouseSavedQuery.objects.get(id=created["id"]).deleted)self.assertEqual(self.client.get(url).status_code, 200)- def test_create_rejects_an_unknown_dag_id(self) -> None:- response = self._create_view(dag_id=str(uuid.uuid4()))- self.assertEqual(response.status_code, 400, response.content)- self.assertFalse(DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists())-def test_create_does_not_upsert_a_deleted_view(self) -> None:view = DataWarehouseSavedQuery.objects.create(team=self.team,@@ -100,96 +63,3 @@ class TestSavedQueryWriteFields(APIBaseTest):self.assertEqual(response.status_code, 400, response.content)view.refresh_from_db()self.assertEqual(view.query, {"kind": "HogQLQuery", "query": "select event from events LIMIT 7"})-- def test_dag_id_alone_reparents_the_node(self) -> None:- created = self._create_view().json()- node = Node.objects.get(saved_query_id=created["id"])- set_declared_target(node, timedelta(hours=6))- other = DAG.objects.create(team=self.team, name="Other")- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",- {"dag_id": str(other.id)},- )- self.assertEqual(response.status_code, 200, response.content)- moved_node = Node.objects.get(saved_query_id=created["id"])- self.assertEqual(moved_node.dag_id, other.id)- self.assertEqual(moved_node.id, node.id)- self.assertEqual(get_declared_target(moved_node), timedelta(hours=6))-- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",- {- "query": {"kind": "HogQLQuery", "query": "select event from events LIMIT 7"},- "edited_history_id": created["latest_history_id"],- },- )- self.assertEqual(response.status_code, 200, response.content)- self.assertEqual(Node.objects.get(saved_query_id=created["id"]).dag_id, other.id)-- def test_failed_move_preserves_the_node_and_its_parents(self) -> None:- created = self._create_view().json()- node = Node.objects.get(saved_query_id=created["id"])- parents = set(Edge.objects.filter(target=node).values_list("id", flat=True))- self.assertTrue(parents)- other = DAG.objects.create(team=self.team, name="Other")- with patch(- "products.data_modeling.backend.logic.saved_query_dag_sync.sync_saved_query_to_dag",- side_effect=RuntimeError,- ):- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",- {"dag_id": str(other.id)},- )- self.assertEqual(response.status_code, 400, response.content)- self.assertEqual(Node.objects.get(id=node.id).dag_id, node.dag_id)- self.assertEqual(set(Edge.objects.filter(target=node).values_list("id", flat=True)), parents)-- def test_update_rejects_another_teams_dag_id(self) -> None:- created = self._create_view().json()- foreign_team = self.create_team_with_organization(organization=self.organization)- foreign_dag = DAG.objects.create(team=foreign_team, name="Foreign")- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",- {- "dag_id": str(foreign_dag.id),- "query": {"kind": "HogQLQuery", "query": "select event from events LIMIT 7"},- "edited_history_id": created["latest_history_id"],- },- )- self.assertEqual(response.status_code, 400, response.content)- self.assertEqual(Node.objects.filter(dag=foreign_dag).count(), 0)-- @parameterized.expand(- [("running", DataModelingJobStatus.RUNNING, 400), ("completed", DataModelingJobStatus.COMPLETED, 200)]- )- def test_move_waits_for_a_materialization_in_flight(- self, _name: str, job_status: str, expected_status: int- ) -> None:- created = self._create_view().json()- node = Node.objects.get(saved_query_id=created["id"])- DataModelingJob.objects.create(team=self.team, saved_query_id=created["id"], status=job_status)- other = DAG.objects.create(team=self.team, name="Other")- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",- {"dag_id": str(other.id)},- )- self.assertEqual(response.status_code, expected_status, response.content)- moved = Node.objects.get(id=node.id)- self.assertEqual(moved.dag_id, node.dag_id if expected_status == 400 else other.id)-- def test_reparenting_refuses_to_strand_dependents(self) -> None:- created = self._create_view().json()- consumer = self._create_view(- name="consumer_view",- query={"kind": "HogQLQuery", "query": "select event from event_view"},- )- self.assertEqual(consumer.status_code, 201, consumer.content)- node = Node.objects.get(saved_query_id=created["id"])- other = DAG.objects.create(team=self.team, name="Other")- response = self.client.patch(- f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",- {"dag_id": str(other.id)},- )- self.assertEqual(response.status_code, 400, response.content)- self.assertEqual(Node.objects.get(id=node.id).dag_id, node.dag_id)- self.assertTrue(Edge.objects.filter(source=node, target__saved_query_id=consumer.json()["id"]).exists())diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex dcc370987707..840141de70b0 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -1940,11 +1940,6 @@ export interface DataWarehouseSavedQueryApi {* @nullable*/soft_update?: boolean | null- /**- * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.- * @nullable- */- dag_id?: string | null/** @nullable */readonly is_materialized: boolean | null/** Where this SavedQuery is created.@@ -2069,11 +2064,6 @@ export interface PatchedDataWarehouseSavedQueryApi {* @nullable*/soft_update?: boolean | null- /**- * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.- * @nullable- */- dag_id?: string | null/** @nullable */readonly is_materialized?: boolean | null/** Where this SavedQuery is created.diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex fae32e7e4a58..cf9fd6612e35 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -538,12 +538,6 @@ export const WarehouseSavedQueriesCreateBody = /* @__PURE__ */ zod.describe('If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'),- dag_id: zod- .uuid()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(@@ -646,12 +640,6 @@ export const WarehouseSavedQueriesUpdateBody = /* @__PURE__ */ zod.describe('If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'),- dag_id: zod- .uuid()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(@@ -756,12 +744,6 @@ export const WarehouseSavedQueriesPartialUpdateBody = /* @__PURE__ */ zod.describe('If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'),- dag_id: zod- .uuid()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(@@ -881,12 +863,6 @@ export const WarehouseSavedQueriesCancelCreateBody = /* @__PURE__ */ zod.describe('If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'),- dag_id: zod- .uuid()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(@@ -1030,12 +1006,6 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = /* @__PURE__.describe('If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'),- dag_id: zod- .uuid()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 083cd092e75d..f16ddefde08e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27759,26 +27759,6 @@ export namespace Schemas {status?: CustomerTaskStatusEnum;}- export interface Dag {- readonly id: string;- /**- * Human-readable name for this DAG- * @maxLength 2048- */- name: string;- /** Optional description of the DAG's purpose */- description?: string;- /**- * Legacy DAG-level cadence string (e.g. '24hour', '7day'). Scheduling is driven by each model's own sync frequency, so a PATCH that changes this value is rejected.- * @nullable- */- sync_frequency?: string | null;- readonly node_count: number;- readonly created_at: string;- /** @nullable */- readonly updated_at: string | null;- }-export type DashboardFilters = { [key: string]: unknown };/**@@ -30413,11 +30393,6 @@ export namespace Schemas {* @nullable*/soft_update?: boolean | null;- /**- * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.- * @nullable- */- dag_id?: string | null;/** @nullable */readonly is_materialized: boolean | null;/** Where this SavedQuery is created.@@ -38525,8 +38500,6 @@ export namespace Schemas {readonly source_id: string;/** ID of the downstream node. */readonly target_id: string;- dag: string;- readonly dag_name: string;properties?: unknown;readonly created_at: string;/** @nullable */@@ -62027,8 +62000,6 @@ export namespace Schemas {/** @maxLength 2048 */name: string;type?: NodeTypeEnum;- dag: string;- readonly dag_name: string;/** @maxLength 1024 */description?: string;/** @nullable */@@ -70461,15 +70432,6 @@ export namespace Schemas {results: CustomerProfileConfig[];}- export interface PaginatedDAGList {- count: number;- /** @nullable */- next?: string | null;- /** @nullable */- previous?: string | null;- results: Dag[];- }-export interface PaginatedDashboardBasicList {count: number;/** @nullable */@@ -79155,26 +79117,6 @@ export namespace Schemas {status?: CustomerTaskStatusEnum;}- export interface PatchedDAG {- readonly id?: string;- /**- * Human-readable name for this DAG- * @maxLength 2048- */- name?: string;- /** Optional description of the DAG's purpose */- description?: string;- /**- * Legacy DAG-level cadence string (e.g. '24hour', '7day'). Scheduling is driven by each model's own sync frequency, so a PATCH that changes this value is rejected.- * @nullable- */- sync_frequency?: string | null;- readonly node_count?: number;- readonly created_at?: string;- /** @nullable */- readonly updated_at?: string | null;- }-export interface PatchedDashboardTemplate {readonly id?: string;/**@@ -79594,11 +79536,6 @@ export namespace Schemas {* @nullable*/soft_update?: boolean | null;- /**- * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.- * @nullable- */- dag_id?: string | null;/** @nullable */readonly is_materialized?: boolean | null;/** Where this SavedQuery is created.@@ -79787,8 +79724,6 @@ export namespace Schemas {readonly source_id?: string;/** ID of the downstream node. */readonly target_id?: string;- dag?: string;- readonly dag_name?: string;properties?: unknown;readonly created_at?: string;/** @nullable */@@ -82593,8 +82528,6 @@ export namespace Schemas {/** @maxLength 2048 */name?: string;type?: NodeTypeEnum;- dag?: string;- readonly dag_name?: string;/** @maxLength 1024 */description?: string;/** @nullable */@@ -121527,30 +121460,11 @@ export namespace Schemas {offset?: number;};- export type DataModelingDagsListParams = {- /**- * Number of results to return per page.- */- limit?: number;- /**- * The initial index from which to return the results.- */- offset?: number;- };-export type DataModelingEdgesListParams = {- /**- * Return only the edges of this DAG.- */- dag?: string;/*** A page number within the paginated result set.*/page?: number;- /**- * A search term.- */- search?: string;};export type DataModelingJobsListParams = {@@ -121585,10 +121499,6 @@ export namespace Schemas {} as const;export type DataModelingNodesListParams = {- /**- * Scope the lineage counts to this DAG.- */- dag?: string;/*** A page number within the paginated result set.*/diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.tsindex ad42e7499866..7b19ac0e6151 100644--- a/services/mcp/src/generated/data_warehouse/api.ts+++ b/services/mcp/src/generated/data_warehouse/api.ts@@ -450,12 +450,6 @@ export const WarehouseSavedQueriesCreateBody = () => zod.string().nullish().describe('Optional folder ID used to organize this view in the SQL editor sidebar.'),- dag_id: zod- .string()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(@@ -575,12 +569,6 @@ export const WarehouseSavedQueriesPartialUpdateBody = () => zod.describe('The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'),- dag_id: zod- .string()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(@@ -737,12 +725,6 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = () => zod.describe('If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'),- dag_id: zod- .string()- .nullish()- .describe(- 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'- ),is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),}).describe(diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.tsindex 8d8e3c4ee45c..d1532d7e5fcb 100644--- a/services/mcp/src/tools/generated/data_warehouse.ts+++ b/services/mcp/src/tools/generated/data_warehouse.ts@@ -309,9 +309,6 @@ const viewCreate = (): ToolBase<if (params.folder_id !== undefined) {body['folder_id'] = params.folder_id}- if (params.dag_id !== undefined) {- body['dag_id'] = params.dag_id- }if (params.is_test !== undefined) {body['is_test'] = params.is_test}@@ -514,9 +511,6 @@ const viewUnmaterialize = (): ToolBase<if (params.soft_update !== undefined) {body['soft_update'] = params.soft_update}- if (params.dag_id !== undefined) {- body['dag_id'] = params.dag_id- }if (params.is_test !== undefined) {body['is_test'] = params.is_test}@@ -574,9 +568,6 @@ const viewUpdate = (): ToolBase<if (params.edited_history_id !== undefined) {body['edited_history_id'] = params.edited_history_id}- if (params.dag_id !== undefined) {- body['dag_id'] = params.dag_id- }if (params.is_test !== undefined) {body['is_test'] = params.is_test}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.jsonindex 2c0f79b091b0..7cdf63ecbbbf 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json@@ -1,17 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {- "dag_id": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed."- },"description": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.jsonindex 25017dda0d1f..a6cac8eb5969 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json@@ -1,17 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {- "dag_id": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed."- },"description": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.jsonindex 7254717db045..dc0afa372afd 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json@@ -1,17 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {- "dag_id": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed."- },"description": {"anyOf": [{