: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
fix(data-modeling): hide deleted endpoint nodes (#114715)
Jovan Sakovic6a5b168c626c
diff --git a/products/data_modeling/backend/graph.py b/products/data_modeling/backend/graph.pyindex 23350da3854f..8b387484ae52 100644--- a/products/data_modeling/backend/graph.py+++ b/products/data_modeling/backend/graph.py@@ -7,6 +7,8 @@ instead of running recursive DB queries per node.from collections import defaultdictfrom uuid import UUID+from django.db.models import Q+from products.data_modeling.backend.logic.graph_traversal import reachablefrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.node import NodeType@@ -37,7 +39,9 @@ class Graph:hidden_types: node types the reader may not see, dropped from both sides so a countnever reports a node the same reader's node list omits"""- qs = Edge.objects.filter(team_id=team_id)+ 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)diff --git a/products/data_modeling/backend/presentation/views/metric_visibility.py b/products/data_modeling/backend/presentation/views/metric_visibility.pyindex d86fadabc671..4d5c55619744 100644--- a/products/data_modeling/backend/presentation/views/metric_visibility.py+++ b/products/data_modeling/backend/presentation/views/metric_visibility.py@@ -18,11 +18,13 @@ class MetricNodeVisibilityMixin:return frozenset({NodeType.METRIC}) if self._metric_nodes_hidden() else frozenset()def _exclude_hidden_nodes(self, queryset: QuerySet) -> QuerySet:+ queryset = queryset.exclude(saved_query__deleted=True)if self._metric_nodes_hidden():return queryset.exclude(type=NodeType.METRIC)return querysetdef _exclude_hidden_edges(self, queryset: QuerySet) -> QuerySet:+ queryset = queryset.exclude(Q(source__saved_query__deleted=True) | Q(target__saved_query__deleted=True))if self._metric_nodes_hidden():return queryset.exclude(Q(source__type=NodeType.METRIC) | Q(target__type=NodeType.METRIC))return querysetdiff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex da1f3ca90af0..c084bfff0345 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -285,7 +285,7 @@ def _get_upstream_nodes(team_id=node.team_id,dag=node.dag,target_id__in=current,- )+ ).exclude(models.Q(source__saved_query__deleted=True) | models.Q(target__saved_query__deleted=True))if not include_tables:qs = qs.exclude(source__type=NodeType.TABLE)if hidden_types:@@ -300,10 +300,14 @@ def _get_downstream_nodes(node: Node, hidden_types: frozenset[str] = frozenset()nodes: set[str] = set()current = [node.id]while current:- qs = Edge.objects.exclude(target__type=NodeType.TABLE).filter(- team_id=node.team_id,- dag=node.dag,- source_id__in=current,+ qs = (+ Edge.objects.exclude(target__type=NodeType.TABLE)+ .filter(+ team_id=node.team_id,+ dag=node.dag,+ source_id__in=current,+ )+ .exclude(models.Q(source__saved_query__deleted=True) | models.Q(target__saved_query__deleted=True)))if hidden_types:qs = qs.exclude(target__type__in=hidden_types)diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex 781ab75646c8..39090b213555 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -69,6 +69,25 @@ class TestNodeViewSet(APIBaseTest):names = {node["name"] for node in response.json()["results"]}self.assertEqual(names, {"events", "test_view"})+ def test_deleted_saved_query_nodes_are_hidden_from_the_graph(self):+ self.saved_query.soft_delete()++ nodes_response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/")+ edges_response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_edges/")+ lineage_response = self.client.get(+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?node_id={self.table_node.id}"+ )++ self.assertEqual(nodes_response.status_code, status.HTTP_200_OK)+ self.assertEqual(nodes_response.json()["count"], 1)+ self.assertEqual(nodes_response.json()["results"][0]["name"], "events")+ self.assertEqual(nodes_response.json()["results"][0]["downstream_count"], 0)+ self.assertEqual(edges_response.status_code, status.HTTP_200_OK)+ self.assertEqual(edges_response.json()["count"], 0)+ self.assertEqual(lineage_response.status_code, status.HTTP_200_OK)+ self.assertEqual([node["name"] for node in lineage_response.json()["nodes"]], ["events"])+ self.assertEqual(lineage_response.json()["edges"], [])+def _node_payload(self) -> dict: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)diff --git a/products/endpoints/backend/logic/crud.py b/products/endpoints/backend/logic/crud.pyindex 338592e1aaa9..a646c9a669cc 100644--- a/products/endpoints/backend/logic/crud.py+++ b/products/endpoints/backend/logic/crud.py@@ -26,7 +26,7 @@ from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, changes_between, log_activityfrom posthog.types import InsightQueryNode-from products.data_modeling.backend.facade.api import delete_node_from_dag, materialize_saved_query+from products.data_modeling.backend.facade.api import HasDependentsError, delete_node_from_dag, materialize_saved_queryfrom products.endpoints.backend.constants import DEFAULT_DATA_FRESHNESS_SECONDSfrom products.endpoints.backend.logic.activity import EndpointContextfrom products.endpoints.backend.logic.materialization import EndpointMaterializationService@@ -486,29 +486,32 @@ class EndpointCrudService:endpoint_id = str(endpoint.id)endpoint_name = endpoint.name- # DAG cleanup only — the saved queries themselves are reverted and soft-deleted- # by endpoint.soft_delete() via version.disable_materialization().- for version in endpoint.versions.filter(saved_query__isnull=False):- try:- if version.saved_query:- delete_node_from_dag(version.saved_query)- except Exception as e:- logger.exception(- "Failed to remove endpoint node from DAG on destroy",- endpoint_name=endpoint.name,- saved_query_id=version.saved_query.id if version.saved_query else None,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team.pk,- "endpoint_name": endpoint.name,- "saved_query_id": version.saved_query.id if version and version.saved_query else None,- },- )+ with transaction.atomic():+ # DAG cleanup only — the saved queries themselves are reverted and soft-deleted+ # by endpoint.soft_delete() via version.disable_materialization().+ for version in endpoint.versions.filter(saved_query__isnull=False):+ try:+ if version.saved_query:+ delete_node_from_dag(version.saved_query)+ except HasDependentsError:+ raise+ except Exception as e:+ logger.exception(+ "Failed to remove endpoint node from DAG on destroy",+ endpoint_name=endpoint.name,+ saved_query_id=version.saved_query.id if version.saved_query else None,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ "saved_query_id": version.saved_query.id if version and version.saved_query else None,+ },+ )- endpoint.soft_delete()+ endpoint.soft_delete()clear_endpoint_materialization_cache(self.team.pk, endpoint.name, versions=endpoint.versions.values_list("version", flat=True))diff --git a/products/endpoints/backend/presentation/views/api.py b/products/endpoints/backend/presentation/views/api.pyindex da5f7faeeb65..861c2cc9d0e5 100644--- a/products/endpoints/backend/presentation/views/api.py+++ b/products/endpoints/backend/presentation/views/api.py@@ -58,6 +58,7 @@ from posthog.schema_migrations.upgrade import upgradefrom products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resourcefrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixin+from products.data_modeling.backend.facade.api import HasDependentsErrorfrom products.data_modeling.backend.facade.models import DataModelingJobfrom products.endpoints.backend.facade.api import (REWRITE_CONTRACT,@@ -94,6 +95,13 @@ from products.endpoints.backend.presentation.throttles import ()+class EndpointDependentsValidationError(serializers.ValidationError):+ def __init__(self, detail: str, node_id: str | None = None) -> None:+ super().__init__(detail, code="has_dependents")+ if node_id:+ self.extra = {"node_id": node_id}++class MaterializationPreviewRequestSerializer(serializers.Serializer):version = serializers.IntegerField(required=False, help_text="Endpoint version to preview. Defaults to the current version."@@ -560,7 +568,15 @@ class EndpointViewSet(def destroy(self, request: Request, name=None, *args, **kwargs) -> Response:"""Delete an endpoint and clean up materialized query."""endpoint = self._get_endpoint_with_object_access(name)- EndpointCrudService(self.team, request).destroy(endpoint)+ try:+ EndpointCrudService(self.team, request).destroy(endpoint)+ except HasDependentsError as error:+ can_read_lineage = self.user_access_control.check_access_level_for_resource(+ "warehouse_view", required_level="viewer"+ )+ raise EndpointDependentsValidationError(+ str(error), node_id=error.fallback_node_id if can_read_lineage else None+ )return Response(status=status.HTTP_204_NO_CONTENT)# ------------------------------------------------------------------diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex c88e2d4e93a7..df81e806a104 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -21,7 +21,14 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery+from products.data_modeling.backend.facade.models import (+ DAG,+ DataModelingJob,+ DataWarehouseSavedQuery,+ Edge,+ Node,+ NodeType,+)from products.endpoints.backend.models import Endpoint, EndpointVersionfrom products.endpoints.backend.rate_limit import is_endpoint_materialization_ready, set_endpoint_materialization_readyfrom products.endpoints.backend.tests.conftest import create_endpoint_with_version@@ -414,6 +421,57 @@ class TestEndpoint(ClickhouseTestMixin, APIBaseTest):assert log.detail is not Noneself.assertEqual(log.detail.get("name"), "delete_test")+ def test_delete_endpoint_is_refused_when_a_model_depends_on_it(self):+ endpoint = create_endpoint_with_version(+ name="blocked_endpoint",+ team=self.team,+ query=self.sample_hogql_query,+ created_by=self.user,+ )+ version = endpoint.get_version()+ backing_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="blocked_endpoint_v1",+ query=self.sample_hogql_query,+ )+ version.enable_materialization(backing_query)+ downstream_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="downstream_view",+ query={"kind": "HogQLQuery", "query": "SELECT * FROM blocked_endpoint_v1"},+ )+ dag = DAG.get_or_create_default(self.team)+ endpoint_node = Node.objects.create(+ team=self.team,+ dag=dag,+ saved_query=backing_query,+ type=NodeType.ENDPOINT,+ )+ downstream_node = Node.objects.create(+ team=self.team,+ dag=dag,+ saved_query=downstream_query,+ type=NodeType.VIEW,+ )+ Edge.objects.create(team=self.team, dag=dag, source=endpoint_node, target=downstream_node)++ response = self.client.delete(f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "has_dependents")+ self.assertEqual(response.json()["extra"], {"node_id": str(endpoint_node.id)})+ self.assertEqual(+ response.json()["detail"],+ "Can't delete blocked_endpoint_v1 yet. Something else reads from it. Update or delete it first.",+ )+ endpoint.refresh_from_db()+ backing_query.refresh_from_db()+ version.refresh_from_db()+ self.assertFalse(endpoint.deleted)+ self.assertFalse(backing_query.deleted)+ self.assertEqual(version.saved_query_id, backing_query.id)+ self.assertTrue(Node.objects.filter(id=endpoint_node.id).exists())+def test_delete_endpoint_prevents_hard_delete(self):endpoint = create_endpoint_with_version(name="hard_delete_test",diff --git a/products/endpoints/frontend/EndpointScene.tsx b/products/endpoints/frontend/EndpointScene.tsxindex 0010c043feb1..9db23f0555f1 100644--- a/products/endpoints/frontend/EndpointScene.tsx+++ b/products/endpoints/frontend/EndpointScene.tsx@@ -173,7 +173,6 @@ export function EndpointScene(): JSX.Element {status: 'danger',onClick: () => {deleteEndpoint(endpoint.name)- router.actions.push(urls.endpoints())},size: 'small',},diff --git a/products/endpoints/frontend/endpointLogic.test.ts b/products/endpoints/frontend/endpointLogic.test.tsindex b374a4a52c03..c121540fe843 100644--- a/products/endpoints/frontend/endpointLogic.test.ts+++ b/products/endpoints/frontend/endpointLogic.test.ts@@ -1,5 +1,8 @@+import { router } from 'kea-router'+import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'@@ -10,6 +13,8 @@ jest.mock('lib/api', () => ({__esModule: true,default: {endpoint: {+ delete: jest.fn(),+ list: jest.fn().mockResolvedValue({ results: [] }),update: jest.fn(),},},@@ -39,4 +44,40 @@ describe('endpointLogic', () => {'Failed to update endpoint: Cannot materialize endpoint. Reason: The referenced table does not exist.')})++ it('opens lineage from a refused endpoint delete', async () => {+ const error = {+ detail: "Can't delete example-endpoint_v1 yet. Something else reads from it. Update or delete it first.",+ data: { extra: { node_id: 'node-7' } },+ }+ ;(api.endpoint.delete as jest.Mock).mockRejectedValue(error)+ const logic = endpointLogic()+ logic.mount()+ router.actions.push(urls.endpoint('example-endpoint'))++ logic.actions.deleteEndpoint('example-endpoint')+ await expectLogic(logic).toFinishAllListeners()++ expect(router.values.location.pathname).toContain(urls.endpoint('example-endpoint'))+ const options = (lemonToast.error as jest.Mock).mock.calls[0][1] as {+ button?: { label: string; action: () => void }+ }+ expect(lemonToast.error).toHaveBeenCalledWith(error.detail, expect.any(Object))+ expect(options.button?.label).toBe('Open lineage')+ options.button?.action()+ expect(router.values.location.pathname).toContain(urls.nodeDetail('node-7', 'lineage'))+ })++ it('returns to the endpoint list after a successful delete', async () => {+ ;(api.endpoint.delete as jest.Mock).mockResolvedValue(undefined)+ const logic = endpointLogic()+ logic.mount()+ router.actions.push(urls.endpoint('example-endpoint'))++ logic.actions.deleteEndpoint('example-endpoint')+ await expectLogic(logic).toFinishAllListeners()++ expect(lemonToast.success).toHaveBeenCalledWith('Endpoint deleted')+ expect(router.values.location.pathname).toContain(urls.endpoints())+ })})diff --git a/products/endpoints/frontend/endpointLogic.tsx b/products/endpoints/frontend/endpointLogic.tsxindex f40333df1a18..8e9e12d1b35c 100644--- a/products/endpoints/frontend/endpointLogic.tsx+++ b/products/endpoints/frontend/endpointLogic.tsx@@ -70,7 +70,9 @@ export interface endpointLogicActions {deleteEndpoint: (name: string) => {name: string}- deleteEndpointFailure: () => {}+ deleteEndpointFailure: (errorObject?: any) => {+ errorObject: any+ }deleteEndpointSuccess: (response: any) => {response: any}@@ -243,7 +245,7 @@ export const endpointLogic = kea<endpointLogicType>([deleteEndpoint: (name: string) => ({ name }),deleteEndpointSuccess: (response: any) => ({ response }),clearMaterializationStatus: true,- deleteEndpointFailure: () => ({}),+ deleteEndpointFailure: (errorObject?: any) => ({ errorObject }),confirmToggleActive: (endpoint: EndpointType) => ({ endpoint }),saveTagsInline: (tags: string[]) => ({ tags }),}),@@ -495,17 +497,26 @@ export const endpointLogic = kea<endpointLogicType>([try {await api.endpoint.delete(name)actions.deleteEndpointSuccess(name)- } catch (error) {+ } catch (error: any) {console.error('Failed to delete endpoint:', error)- actions.deleteEndpointFailure()+ actions.deleteEndpointFailure(error)}},deleteEndpointSuccess: () => {lemonToast.success('Endpoint deleted')actions.loadEndpoints()+ router.actions.push(urls.endpoints())},- deleteEndpointFailure: () => {- lemonToast.error('Failed to delete endpoint')+ deleteEndpointFailure: ({ errorObject }) => {+ const nodeId = errorObject?.data?.extra?.node_id+ lemonToast.error(errorObject?.detail || 'Failed to delete endpoint', {+ button: nodeId+ ? {+ label: 'Open lineage',+ action: () => router.actions.push(urls.nodeDetail(nodeId, 'lineage')),+ }+ : undefined,+ })},confirmToggleActive: ({ endpoint }) => {const isActivating = !endpoint.is_active