:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): converge lineage UI onto one renderer and endpoint (#67542)
Jovan Sakovic01a5219af9ac
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 865af99490d6..5263d433e5fd 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4444,6 +4444,22 @@ snapshots:hash: v1.k794b7964.260c60a4a1510acae8062ebd7564bf8c3ea344b580b3c85a772605de98ad8397.AV2iNSkxr-Wh-w4qn5N6_OBQOWYf0bW8YKvlPnsBAfwposthog-3000-keyboard-shortcut--within-tooltip--light:hash: v1.k794b7964.aa2d9701c9134d5c374b6517f2fa542eb24c7e15ebf0d65f64efbc0ec2a99efa.BL1mMRm5CNDAmAMk-2pf-lp8EI6t65oBqoy990BdgyQ+ products-data-modeling-lineage-graph--canvas--dark:+ hash: v1.k794b7964.cb415b8a2cb9697e353db5cd11808642c38d589431a0cb95cb1ddf632160eed8.ND20cRcJ3o2QK0K6DSbHBN66H2HwvcsKMd8tgfSITaY+ products-data-modeling-lineage-graph--canvas--light:+ hash: v1.k794b7964.1d83ee016eddc9d8bd726d543bacbf33e268bd68d2b05e129b327df7528e1cdd.HFjJqTinLvCWNIBGwMucxzd-BxIbGg0gRSO3-a8AlVw+ products-data-modeling-lineage-graph--empty-state--dark:+ hash: v1.k794b7964.cabd444ca94a42c8f2c651ca501ba5565ff3f3c44bfe090f859b5c6810983e48.Xx1J5ap_yYDliGXI3zpmj3oRPyZAB3xj191uH9hC7yY+ products-data-modeling-lineage-graph--empty-state--light:+ hash: v1.k794b7964.7cf98856fd30a08c92b5753d92d86e5220f396bde417a6f5b78180d604e673ba.ZQWtyN1nWpt4RqBn_m2jGHm2PXC0HEaOzrTdapb-auk+ products-data-modeling-lineage-graph--full--dark:+ hash: v1.k794b7964.30f9f54de7be7442005c8c331928461a8b9f35c39a83879d512d43fc760805a7.HejGI_ne5ckT89F7KRuBZl8cHd8yxdCvDbU10jo9Zoo+ products-data-modeling-lineage-graph--full--light:+ hash: v1.k794b7964.5dad2ad87a0457c985581810013a0fa058bb4bb8f0596932bb829bfb46a2e18c.p9m_GryZwVUwkGgah-EvQZUyu1-1-I3sN8Tlu3kSYM4+ products-data-modeling-lineage-graph--single-node--dark:+ hash: v1.k794b7964.4344045fc1bada8b4f2067de9f83cdb38b5dbe14719e7b4d332c2a7689a5d8cd.NvfJs1mb9VLArjiQdsrspse5hcopmjfyz4HXvwD_MZA+ products-data-modeling-lineage-graph--single-node--light:+ hash: v1.k794b7964.965d630c09110769bac58d2fc162856dc5303d9a98e97995aec4cc48098581da.Gi_VbiOcJVaHaHybXL8911KOWXwBMAGtbHwCIA2HO0Eproducts-posthog-ai-composer--default--dark:hash: v1.k794b7964.46b58701d85781d463019c60ff4249a090bf3997b48bce436de397764443a239.r1kxyzWoJ0j9b9_aBUh9MByfQRFFKUkIP9a8eYD9qCQproducts-posthog-ai-composer--default--light:@@ -5408,18 +5424,6 @@ snapshots:hash: v1.k794b7964.e7e5e858735406f7ded52c3025d5cfbc1d8016b445c58a2c302c7c9d5549f130.BG24I9Na4XPA4mQv3TR6BigBKfhfDZDRymuVTMC9cDQscenes-app-data-pipelines-event-filtering--switch-mode-to-dry-run--light:hash: v1.k794b7964.0684c83aec77309eec98bc9ddcc03669a65d29639161823e93eeec8b4c0b41d2.WgcTT8X8F9aWW9tLGEfuundMFnE_XQ55XmR5q55aZvc- scenes-app-data-warehouse-editor-upstream-graph--empty-state--dark:- hash: v1.k794b7964.0dc97f7b0c3ae81fcac98a415c7882c3a46bd371ce72a78ed05cb64f5e5f286a.l50zfPs-m7SlrgboOciMdUkiowPG7lbs8Bwft1UarRs- scenes-app-data-warehouse-editor-upstream-graph--empty-state--light:- hash: v1.k794b7964.93a9f9591b47434fa368fa0388c560c18abfac07b819f2ddad7ae3d5d12c897a.ygLJziJehdJahbndQ_nu5mzTsfRhlANTs_4mm-cOgXg- scenes-app-data-warehouse-editor-upstream-graph--single-node--dark:- hash: v1.k794b7964.79cb06fa61c55658a80ef1e311f8d908d4c99fa83ff0eaf22eacef2c5a35fbf6.Q1Ppts8eMpAHCzdJdAx5PDMx6RCofEq3_jopmCuUdtA- scenes-app-data-warehouse-editor-upstream-graph--single-node--light:- hash: v1.k794b7964.83feb26dbe71df145a296c00fa9afd46e796caf13a66e56bebc554e121cf572d.NNHvP9Ty7FsYjPDkSyivj7pIjtXcR4NmRzHMWm9QyDA- scenes-app-data-warehouse-editor-upstream-graph--with-graph--dark:- hash: v1.k794b7964.e16eff8174b84260a05a14a9e9ab09420865df0d314abd37e5ef02c48d220b1a.bUmHQWDjrKyqCrHF1aByvKAgIbD3BkfkmHvHVL-tUTQ- scenes-app-data-warehouse-editor-upstream-graph--with-graph--light:- hash: v1.k794b7964.3fe5d6bd03f992da9c2dd13af16f53ffaae17590db416f9b963c2fc838551b54.ULQER6t0lWp3L-BLATI0B64TJgjhJr2sNtyvwnXpeFYscenes-app-data-warehouse-settings-schemas--default--dark:hash: v1.k794b7964.ea7d252b266cfaa288bfa42a5da2d38a53959d5deeab52f9fa5bc5aa41a00c86.qXiGq0njeIv-SPKcXp0HuGfzynprPoS-E0Yeojdjx1kscenes-app-data-warehouse-settings-schemas--default--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex e550d603f684..c1ecc5dbf614 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -164,7 +164,6 @@ import {LLMPrompt,LLMPromptPublic,LLMPromptResolveResponse,- LineageGraph,LinearTeamType,LinkType,LinkedInAdsAccountType,@@ -1848,15 +1847,6 @@ export class ApiRequest {return this.insightVariables(teamId).addPathComponent(variableId)}- public upstream(modelId: string, teamId?: TeamType['id']): ApiRequest {- return this.environmentsDetail(teamId)- .addPathComponent('lineage')- .addPathComponent('get_upstream')- .withQueryString({- model_id: modelId,- })- }-// ActivityLogpublic activityLog(projectId?: ProjectType['id']): ApiRequest {return this.projectsDetail(projectId).addPathComponent('activity_log')@@ -5836,10 +5826,21 @@ const api = {}> {return await new ApiRequest().dataModelingNodes().withAction('dag_ids').get()},- async lineage(- nodeId: DataModelingNode['id']- ): Promise<{ nodes: DataModelingNode[]; edges: DataModelingEdge[] }> {- return await new ApiRequest().dataModelingNode(nodeId).withAction('lineage').get()+ async lineage({+ nodeId,+ savedQueryId,+ }: {+ nodeId?: DataModelingNode['id']+ savedQueryId?: string+ }): Promise<{ nodes: DataModelingNode[]; edges: DataModelingEdge[] }> {+ const params: Record<string, string> = {}+ if (nodeId) {+ params.node_id = nodeId+ }+ if (savedQueryId) {+ params.saved_query_id = savedQueryId+ }+ return await new ApiRequest().dataModelingNodes().withAction('lineage').withQueryString(params).get()},},@@ -6149,11 +6150,6 @@ const api = {return await new ApiRequest().queryTabStateUser().withQueryString({ user_id: userId }).get()},},- upstream: {- async get(modelId: string): Promise<LineageGraph> {- return await new ApiRequest().upstream(modelId).get()- },- },insightVariables: {async list(options?: ApiMethodOptions | undefined): Promise<PaginatedResponse<Variable>> {return await new ApiRequest().insightVariables().get(options)diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 7779d4d8c876..036b410f59b7 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -1020,7 +1020,7 @@ export const productUrls = {dashboardSubscription: (id: string | number, subscriptionId: string): string =>`/dashboard/${id}/subscriptions/${subscriptionId}`,sharedDashboard: (shareToken: string): string => `/shared_dashboard/${shareToken}`,- dataOps: (tab?: string): string => (tab ? `/data-warehouse?tab=${tab}` : '/data-ops'),+ dataOps: (tab?: string): string => (tab ? `/data-ops?tab=${tab}` : '/data-ops'),models: (tab?: ModelsSceneTab): string => `/models${tab ? `/${tab}` : ''}`,nodeDetail: (id: string): string => `/models/${id}`,sources: (): string => '/data-management/sources',diff --git a/frontend/src/scenes/data-model/Node.tsx b/frontend/src/scenes/data-model/Node.tsxdeleted file mode 100644index 860fa26764b0..000000000000--- a/frontend/src/scenes/data-model/Node.tsx+++ /dev/null@@ -1,20 +0,0 @@-interface NodeProps {- pref: (el: HTMLDivElement | null) => void- width?: string- height?: string- className?: string- children: React.ReactNode-}--function GenericNode({ pref, className = '', children }: NodeProps): JSX.Element {- return (- <div- ref={pref}- className={`flex w-[200px] px-4 py-3 justify-center items-center space-between gap-1 bg-primary border border-black border-2 rounded-lg ${className}`}- >- {children}- </div>- )-}--export default GenericNodediff --git a/frontend/src/scenes/data-model/NodeCanvas.tsx b/frontend/src/scenes/data-model/NodeCanvas.tsxdeleted file mode 100644index 85702fe69d44..000000000000--- a/frontend/src/scenes/data-model/NodeCanvas.tsx+++ /dev/null@@ -1,311 +0,0 @@-import { clsx } from 'clsx'-import { useEffect, useRef, useState } from 'react'--import { Edge, Node, NodePosition, NodePositionWithBounds, NodeWithDepth } from './types'--const VERTICAL_SPACING = 300-const HORIZONTAL_SPACING = 400--// Core graph layout calculation functions-const assignDepths = (nodes: Node[]): NodeWithDepth[] => {- const nodeMap: { [id: string]: NodeWithDepth } = {}-- nodes.forEach((node) => {- nodeMap[node.nodeId] = { ...node, depth: -1 }- })-- const assignDepthRecursive = (nodeId: string, currentDepth: number): void => {- const node = nodeMap[nodeId]- if (!node) {- return- }- node.depth = currentDepth-- node.leaf.forEach((leafId) => {- if (nodeMap[leafId]) {- assignDepthRecursive(leafId, currentDepth + 1)- }- })- }-- nodes.forEach((node) => {- if (nodeMap[node.nodeId].depth === -1) {- assignDepthRecursive(node.nodeId, 0)- }- })-- return Object.values(nodeMap)-}--const calculateNodePositions = (nodesWithDepth: NodeWithDepth[]): NodePosition[] => {- const padding = 50- nodesWithDepth.sort((a, b) => a.depth - b.depth)-- const nodePositions: NodePosition[] = []- const visited: string[] = []-- const dfs = (nodeId: string, row: number = 0): number => {- if (visited.includes(nodeId)) {- return row- }- visited.push(nodeId)-- const node = nodesWithDepth.find((n) => n.nodeId === nodeId)- if (!node) {- return row- }-- const nodePosition = {- ...node,- position: {- x: padding + node.depth * HORIZONTAL_SPACING,- y: padding + row * VERTICAL_SPACING,- },- }-- nodePositions.push(nodePosition)-- let maxRow = row- node.leaf- .filter((leafId) => !leafId.includes('_joined'))- .forEach((leafId, index) => {- dfs(leafId, row + index)- maxRow = Math.max(maxRow, row + index)- })-- return maxRow- }-- let maxRow = 0- nodesWithDepth.forEach((node) => {- if (node.depth === 0) {- maxRow = dfs(node.nodeId, maxRow) + 1- }- })-- return nodePositions-}--const calculateBound = (node: NodePosition, ref: HTMLDivElement | null): NodePositionWithBounds => {- if (!ref) {- return {- ...node,- left: null,- right: null,- }- }-- const { x, y } = node.position- const { width, height } = ref.getBoundingClientRect()- return {- ...node,- left: { x, y: y + height / 2 },- right: { x: x + width, y: y + height / 2 },- }-}--const calculateEdgesFromTo = (from: NodePositionWithBounds, to: NodePositionWithBounds): Edge[] => {- if (!from.right || !to.left) {- return []- }-- const edges = []- edges.push({- from: from.right,- to: to.left,- })-- return edges-}--const calculateEdges = (nodeRefs: (HTMLDivElement | null)[], nodes: NodePosition[]): Edge[] => {- const nodes_map = nodes.reduce((acc: Record<string, NodePosition>, node) => {- acc[node.nodeId] = node- return acc- }, {})-- const dfs = (nodeId: string, visited: Set<string> = new Set()): Edge[] => {- if (visited.has(nodeId)) {- return []- }- visited.add(nodeId)-- const node = nodes_map[nodeId]- if (!node) {- return []- }-- const nodeRef = nodeRefs.find((ref) => ref?.id === nodeId)- if (!nodeRef) {- return []- }-- const edges: Edge[] = []- const fromWithBounds = calculateBound(node, nodeRef)-- for (const leafId of node.leaf) {- const toNode = nodes_map[leafId]- const toRef = nodeRefs.find((ref) => ref?.id === leafId)- if (toNode && toRef) {- const toWithBounds = calculateBound(toNode, toRef)- edges.push(...calculateEdgesFromTo(fromWithBounds, toWithBounds))- }-- edges.push(...dfs(leafId, visited))- }-- return edges- }-- const edges: Edge[] = []- const visited = new Set<string>()-- for (const node of nodes) {- if (!visited.has(node.nodeId)) {- edges.push(...dfs(node.nodeId, visited))- }- }-- return edges-}--interface NodeCanvasProps<T extends Node> {- nodes: T[]- renderNode: (node: T & NodePosition, ref: (el: HTMLDivElement | null) => void) => JSX.Element-}--export function NodeCanvas<T extends Node>({ nodes, renderNode }: NodeCanvasProps<T>): JSX.Element {- const canvasRef = useRef<HTMLCanvasElement | null>(null)- const [isDragging, setIsDragging] = useState(false)- const [offset, setOffset] = useState({ x: 0, y: 0 })- const [dragStart, setDragStart] = useState({ x: 0, y: 0 })- const nodeRefs = useRef<(HTMLDivElement | null)[]>(Array(nodes.length).fill(null))- const [nodePositions, setNodePositions] = useState<NodePosition[]>([])- const [edges, setEdges] = useState<Edge[]>([])-- useEffect(() => {- const nodesWithDepth = assignDepths(nodes)- const positions = calculateNodePositions(nodesWithDepth)- setNodePositions(positions)- }, [nodes, offset])-- useEffect(() => {- const allNodes = [...nodePositions]- const calculatedEdges = calculateEdges([...nodeRefs.current], allNodes)- setEdges(calculatedEdges)- }, [nodePositions])-- const drawGrid = (ctx: CanvasRenderingContext2D, canvasWidth: number, canvasHeight: number): void => {- ctx.fillStyle = '#000000'- ctx.imageSmoothingEnabled = true- const dotSize = 0.5- const spacing = 10-- for (let x = offset.x % spacing; x < canvasWidth; x += spacing) {- for (let y = offset.y % spacing; y < canvasHeight; y += spacing) {- ctx.fillRect(x, y, dotSize, dotSize)- }- }- }-- useEffect(() => {- const canvas = canvasRef.current- if (!canvas) {- return- }-- const ctx = canvas.getContext('2d')- if (!ctx) {- return- }-- const { width, height } = canvas.getBoundingClientRect()- canvas.width = width- canvas.height = height- drawGrid(ctx, width, height)-- const handleResize = (): void => {- if (canvas) {- const { width, height } = canvas.getBoundingClientRect()- canvas.width = width- canvas.height = height- const ctx = canvas.getContext('2d')- if (ctx) {- drawGrid(ctx, width, height)- }- }- }-- window.addEventListener('resize', handleResize)- return () => window.removeEventListener('resize', handleResize)- }, [offset, nodePositions]) // oxlint-disable-line react-hooks/exhaustive-deps-- const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>): void => {- setIsDragging(true)- setDragStart({ x: e.clientX - offset.x, y: e.clientY - offset.y })- }-- const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>): void => {- if (!isDragging) {- return- }- const newOffset = {- x: e.clientX - dragStart.x,- y: e.clientY - dragStart.y,- }- setOffset(newOffset)- }-- const handleMouseUp = (): void => {- setIsDragging(false)- }-- return (- <div className="w-full h-full relative">- <canvas- ref={canvasRef}- onMouseDown={handleMouseDown}- onMouseMove={handleMouseMove}- onMouseUp={handleMouseUp}- onMouseLeave={handleMouseUp}- className={clsx('w-full h-full absolute inset-0', isDragging ? 'cursor-grabbing' : 'cursor-grab')}- />- <svg className="absolute inset-0 w-full h-full pointer-events-none">- {edges.map((edge, index) => {- const controlPoint1X = edge.from.x + offset.x + (edge.to.x - edge.from.x) / 3- const controlPoint1Y = edge.from.y + offset.y- const controlPoint2X = edge.to.x + offset.x - (edge.to.x - edge.from.x) / 3- const controlPoint2Y = edge.to.y + offset.y- return (- <path- key={index}- d={`M ${edge.from.x + offset.x} ${edge.from.y + offset.y}- C ${controlPoint1X} ${controlPoint1Y},- ${controlPoint2X} ${controlPoint2Y},- ${edge.to.x + offset.x} ${edge.to.y + offset.y}`}- stroke="var(--text-3000)"- strokeWidth="2"- fill="none"- />- )- })}- </svg>- {nodePositions.map((nodePosition, idx) => (- <div- key={nodePosition.nodeId}- className="absolute"- // eslint-disable-next-line react/forbid-dom-props- style={{- left: `${nodePosition.position.x + offset.x}px`,- top: `${nodePosition.position.y + offset.y}px`,- }}- >- {renderNode(nodePosition as T & NodePosition, (el) => {- nodeRefs.current[idx] = el- nodeRefs.current[idx]?.setAttribute('id', nodePosition.nodeId)- })}- </div>- ))}- </div>- )-}diff --git a/frontend/src/scenes/data-model/TableFields.tsx b/frontend/src/scenes/data-model/TableFields.tsxdeleted file mode 100644index d00d1c02bee8..000000000000--- a/frontend/src/scenes/data-model/TableFields.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { useActions } from 'kea'--import { IconPlus } from '@posthog/icons'-import { LemonButton, LemonTable } from '@posthog/lemon-ui'--import { viewLinkLogic } from 'scenes/data-warehouse/viewLinkLogic'--export interface FixedField {- column: string- type: string-}--export interface JoinedField {- nodeId: string- type: string- table: string-}--export interface TableFieldsProps {- fixedFields: FixedField[]- joinedFields: JoinedField[]- rowsRefs: React.MutableRefObject<(HTMLDivElement | null)[]>- tableName: string-}--export function TableFields({ fixedFields, joinedFields, rowsRefs, tableName }: TableFieldsProps): JSX.Element {- const { toggleJoinTableModal, selectSourceTable } = useActions(viewLinkLogic)-- return (- <div className="">- <div>- <div className="pl-4 mt-4">- <h3>{tableName}</h3>- </div>- </div>- <div className="flex flex-col gap-1">- <div className="pl-4 mt-4">- <h4>Schema</h4>- </div>- <LemonTable- className="bg-primary rounded-none"- columns={[- {- key: 'column',- render: (_, { column }) => column,- },- {- key: 'type',- render: (_, { type }) => type,- },- ]}- dataSource={fixedFields}- loading={false}- showHeader={false}- />- </div>- <div>- <div className="px-4 my-4 flex flex-row justify-between">- <h4>Joined Tables</h4>- <LemonButton- type="primary"- size="xsmall"- icon={<IconPlus />}- onClick={() => {- selectSourceTable(tableName)- toggleJoinTableModal()- }}- >- Add join- </LemonButton>- </div>- <LemonTable- className="bg-primary rounded-none"- columns={[- {- key: 'name',- render: (_, { nodeId }, idx) => (- <div- ref={(el) => {- rowsRefs.current[idx] = el- rowsRefs.current[idx]?.setAttribute('id', `${nodeId}_joined`)- }}- className="flex flex-col"- >- <span className="font-bold">{nodeId}</span>- </div>- ),- },- ]}- loading={false}- showHeader={false}- dataSource={joinedFields}- />- </div>- </div>- )-}diff --git a/frontend/src/scenes/data-model/dataModelSceneLogic.tsx b/frontend/src/scenes/data-model/dataModelSceneLogic.tsxdeleted file mode 100644index ad97910f067c..000000000000--- a/frontend/src/scenes/data-model/dataModelSceneLogic.tsx+++ /dev/null@@ -1,110 +0,0 @@-import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { subscriptions } from 'kea-subscriptions'--import api from 'lib/api'-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'--import { DatabaseSchemaTable } from '~/queries/schema/schema-general'-import { DataWarehouseSavedQuery } from '~/types'--import type { dataModelSceneLogicType } from './dataModelSceneLogicType'-import { Node } from './types'--export const dataModelSceneLogic = kea<dataModelSceneLogicType>([- path(['scenes', 'data-model', 'dataModelSceneLogic']),- connect(() => ({- values: [- databaseTableListLogic,- ['database', 'posthogTablesMap', 'viewsMapById', 'dataWarehouseTablesMapById'],- ],- actions: [databaseTableListLogic, ['loadDatabase']],- })),- actions({- traverseAncestors: (viewId: DataWarehouseSavedQuery['id'], level: number) => ({ viewId, level }),- setNodes: (nodes: Record<string, Node>) => ({ nodes }),- }),- reducers({- nodeMap: [- {} as Record<string, Node>,- {- setNodes: (_, { nodes }) => nodes,- },- ],- }),- listeners(({ actions, values }) => ({- traverseAncestors: async ({ viewId, level }) => {- const result = await api.dataWarehouseSavedQueries.ancestors(viewId, level)-- if (!values.nodeMap[viewId]?.savedQueryId) {- return- }-- result.ancestors.forEach((ancestor) => {- actions.setNodes({- ...values.nodeMap,- [ancestor]: {- nodeId: ancestor,- name:- values.viewsMapById[ancestor]?.name ||- values.dataWarehouseTablesMapById[ancestor]?.name ||- ancestor,- savedQueryId: values.viewsMapById[ancestor]?.id,- leaf: [...(values.nodeMap[ancestor]?.leaf || []), viewId],- },- })- actions.traverseAncestors(ancestor, 1)- })- },- })),- selectors({- personFields: [(s) => [s.posthogTablesMap], (posthogTablesMap) => posthogTablesMap['persons']?.fields || []],- simplifiedPersonFields: [- (s) => [s.personFields],- (personFields) =>- Object.entries(personFields)- .filter(([_, data]) => data.type != 'view' && !(data.type == 'lazy_table' && data.name !== 'pdi'))- .map(([column, data]) => ({ column, type: data.type })),- ],- joinedFields: [- (s) => [s.personFields],- (personFields) =>- Object.entries(personFields)- .filter(([_, data]) => data.type == 'view' || (data.type == 'lazy_table' && data.name !== 'pdi'))- .map(([_, data]) => data),- ],- joinedFieldsAsNodes: [- (s) => [s.joinedFields],- (joinedFields) =>- joinedFields.map((field) => ({- nodeId: field.name,- type: 'view',- table: field.name,- })) || [],- ],- allNodes: [(s) => [s.nodeMap], (nodeMap) => Object.values(nodeMap)],- }),- subscriptions(({ actions, values }) => ({- joinedFields: (joinedFields) => {- joinedFields.forEach((field: DatabaseSchemaTable) => {- actions.setNodes({- ...values.nodeMap,- [field.id]: {- nodeId: field.id,- name:- values.viewsMapById[field.id]?.name ||- values.dataWarehouseTablesMapById[field.id]?.name ||- field.id,- savedQueryId: values.viewsMapById[field.id]?.id,- leaf: [`${field.name}_joined`],- },- })- field.id && actions.traverseAncestors(field.id, 1)- })- },- })),- afterMount(({ actions, values }) => {- if (!values.database) {- actions.loadDatabase()- }- }),-])diff --git a/frontend/src/scenes/data-model/types.ts b/frontend/src/scenes/data-model/types.tsdeleted file mode 100644index e73d2a626a61..000000000000--- a/frontend/src/scenes/data-model/types.ts+++ /dev/null@@ -1,29 +0,0 @@-export interface Position {- x: number- y: number-}--export interface Node {- nodeId: string- name: string- savedQueryId?: string- leaf: string[]-}--export interface NodeWithDepth extends Node {- depth: number-}--export interface NodePosition extends NodeWithDepth {- position: Position-}--export interface Edge {- from: Position- to: Position-}--export interface NodePositionWithBounds extends NodePosition {- left: Position | null- right: Position | null-}diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.tsindex ccdc8ea7f46a..3fb3eabd40f9 100644--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts@@ -26,7 +26,7 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([}),reducers({selectedTab: [- DataWarehouseTab.SETTINGS as DataWarehouseTab,+ DataWarehouseTab.MODELING as DataWarehouseTab,{setActiveTab: (_, { tab }) => tab,},@@ -37,12 +37,12 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([(s) => [s.featureFlags],(featureFlags): DataWarehouseTab[] => {const tabs: DataWarehouseTab[] = []- if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {- tabs.push(DataWarehouseTab.SETTINGS)- }if (featureFlags[FEATURE_FLAGS.DATA_MODELING_TAB]) {tabs.push(DataWarehouseTab.MODELING)}+ if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {+ tabs.push(DataWarehouseTab.SETTINGS)+ }return tabs},],diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsxindex 62f4c332f91b..2d7827e0c7f9 100644--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx@@ -1,8 +1,9 @@import { useActions, useValues } from 'kea'import { IconTarget } from '@posthog/icons'-import { LemonTable, Link, Spinner } from '@posthog/lemon-ui'+import { LemonTable, Link, Spinner, lemonToast } from '@posthog/lemon-ui'+import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'@@ -13,9 +14,12 @@ import { humanFriendlyDetailedTime } from 'lib/utils/datetime'import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'import { MaterializationStatusPanel } from 'scenes/data-warehouse/saved_queries/MaterializationStatusPanel'-import { DataWarehouseSavedQuery, LineageNode } from '~/types'+import { DataModelingNode, DataWarehouseSavedQuery } from '~/types'++import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'+import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'-import { UpstreamGraph } from '../sidebar/graph/UpstreamGraph'import { sqlEditorLogic } from '../sqlEditorLogic'import { infoTabLogic } from './infoTabLogic'@@ -29,11 +33,26 @@ export function QueryInfo({ tabId, view }: QueryInfoProps): JSX.Element {const targetView = view ?? editingViewconst infoLogic = infoTabLogic({ tabId, viewId: targetView?.id })const { sourceTableItems } = useValues(infoLogic)- const { saveAsView, setUpstreamViewMode } = useActions(sqlEditorLogic)+ const { saveAsView, setUpstreamViewMode, editView } = useActions(sqlEditorLogic)const { featureFlags } = useValues(featureFlagLogic)const isLineageDependencyViewEnabled = featureFlags[FEATURE_FLAGS.LINEAGE_DEPENDENCY_VIEW]+ const currentNodeId = upstream?.nodes.find((n) => n.saved_query_id && n.saved_query_id === targetView?.id)?.id+ const openInEditor = async (node: DataModelingNode): Promise<void> => {+ if (!node.saved_query_id) {+ return+ }+ try {+ const savedQuery = await api.dataWarehouseSavedQueries.get(node.saved_query_id)+ if (savedQuery?.query?.query) {+ editView(savedQuery.query.query, savedQuery)+ }+ } catch {+ lemonToast.error('Failed to load view details')+ }+ }+const { updatingDataWarehouseSavedQuery, initialDataWarehouseSavedQueryLoading } =useValues(dataWarehouseViewsLogic)@@ -151,8 +170,11 @@ export function QueryInfo({ tabId, view }: QueryInfoProps): JSX.Element {<div><div className="flex items-center justify-between"><div>- <h3 className="mb-1">Tables we use</h3>- <p className="text-xs mb-0">Tables and views that this query relies on.</p>+ <h3 className="mb-1">Lineage</h3>+ <p className="text-xs mb-0">+ Tables and views connected to this query — what it reads from and what builds on+ it.+ </p></div><LemonSegmentedButtonvalue={upstreamViewMode}@@ -195,21 +217,16 @@ export function QueryInfo({ tabId, view }: QueryInfoProps): JSX.Element {{key: 'type',title: 'Type',- render: (_, { type, last_run_at }) => {- if (type === 'view') {- return last_run_at ? 'Mat. View' : 'View'- }- return 'Table'- },+ render: (_, { type }) => NODE_TYPE_TAG_SETTINGS[type].label,},{key: 'upstream',title: 'Direct Upstream',render: (_, node) => {const upstreamNodes = upstream.edges- .filter((edge) => edge.target === node.id)- .map((edge) => upstream.nodes.find((n) => n.id === edge.source))- .filter((n): n is LineageNode => n !== undefined)+ .filter((edge) => edge.target_id === node.id)+ .map((edge) => upstream.nodes.find((n) => n.id === edge.source_id))+ .filter((n): n is DataModelingNode => n !== undefined)if (upstreamNodes.length === 0) {return <span className="text-secondary">None</span>@@ -229,25 +246,12 @@ export function QueryInfo({ tabId, view }: QueryInfoProps): JSX.Element {{key: 'last_run_at',title: 'Last Run At',- render: (_, { last_run_at, sync_frequency }) => {+ render: (_, { last_run_at, sync_interval }) => {if (!last_run_at) {return 'On demand'}- const numericSyncFrequency = Number(sync_frequency)- const frequencyMap: Record<string, string> = {- 300: '5 mins',- 1800: '30 mins',- 3600: '1 hour',- 21600: '6 hours',- 43200: '12 hours',- 86400: '24 hours',- 604800: '1 week',- }-- return `${humanFriendlyDetailedTime(last_run_at)} ${- frequencyMap[numericSyncFrequency]- ? `every ${frequencyMap[numericSyncFrequency]}`- : ''+ return `${humanFriendlyDetailedTime(last_run_at)}${+ sync_interval ? ` every ${syncIntervalToShorthand(sync_interval)}` : ''}`},},@@ -255,7 +259,23 @@ export function QueryInfo({ tabId, view }: QueryInfoProps): JSX.Element {dataSource={upstream.nodes}/>) : (- <UpstreamGraph tabId={tabId} />+ <div className="h-[500px] border border-border rounded-md overflow-hidden">+ <LineageGraph+ nodes={upstream.nodes}+ edges={upstream.edges}+ currentNodeId={currentNodeId}+ variant="full"+ interactive+ showControls+ showMinimap+ nodeCallbacks={(node) => ({+ onEdit:+ node.type !== 'table' && node.id !== currentNodeId+ ? () => void openInEditor(node)+ : undefined,+ })}+ />+ </div>)}</>)}diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.stories.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.stories.tsxdeleted file mode 100644index 3aa241e08f02..000000000000--- a/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.stories.tsx+++ /dev/null@@ -1,69 +0,0 @@-import type { Meta, StoryObj } from '@storybook/react'-import { useActions } from 'kea'--import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'--import { LineageGraph } from '~/types'--import { sqlEditorLogic } from '../../sqlEditorLogic'-import { UpstreamGraph } from './UpstreamGraph'--const MOCK_LINEAGE_WITH_GRAPH: LineageGraph = {- nodes: [- { id: '1', name: 'orders', type: 'table' },- { id: '2', name: 'customers', type: 'table' },- {- id: '3',- name: 'revenue_summary',- type: 'view',- last_run_at: '2024-01-15T10:30:00Z',- status: 'Completed',- },- { id: '4', name: 'monthly_report', type: 'view' },- ],- edges: [- { source: '1', target: '3' },- { source: '2', target: '3' },- { source: '3', target: '4' },- ],-}--const MOCK_LINEAGE_SINGLE_NODE: LineageGraph = {- nodes: [{ id: '1', name: 'raw_events', type: 'table' }],- edges: [],-}--const TAB_ID = 'story-tab'--function GraphLoader({ lineage }: { lineage: LineageGraph }): JSX.Element {- const { loadUpstreamSuccess } = useActions(sqlEditorLogic({ tabId: TAB_ID }))- useDelayedOnMountEffect(() => loadUpstreamSuccess(lineage))- return <UpstreamGraph tabId={TAB_ID} />-}--type Story = StoryObj<typeof UpstreamGraph>-const meta: Meta<typeof UpstreamGraph> = {- title: 'Scenes-App/Data Warehouse/Editor/Upstream graph',- component: UpstreamGraph,- parameters: {- layout: 'fullscreen',- viewMode: 'story',- testOptions: {- snapshotBrowsers: ['chromium'],- },- },-}--export default meta--export const WithGraph: Story = {- render: () => <GraphLoader lineage={MOCK_LINEAGE_WITH_GRAPH} />,-}--export const SingleNode: Story = {- render: () => <GraphLoader lineage={MOCK_LINEAGE_SINGLE_NODE} />,-}--export const EmptyState: Story = {- render: () => <UpstreamGraph tabId={TAB_ID} />,-}diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.tsxdeleted file mode 100644index 4500843d4f6a..000000000000--- a/frontend/src/scenes/data-warehouse/editor/sidebar/graph/UpstreamGraph.tsx+++ /dev/null@@ -1,305 +0,0 @@-import '@xyflow/react/dist/style.css'--import dagre from '@dagrejs/dagre'-import {- Background,- BackgroundVariant,- Controls,- Edge,- Handle,- MarkerType,- MiniMap,- Node,- NodeTypes,- Position,- ReactFlow,- ReactFlowProvider,- useReactFlow,-} from '@xyflow/react'-import { useActions, useValues } from 'kea'-import React, { useEffect, useMemo, useState } from 'react'--import { IconArchive, IconPencil, IconTarget } from '@posthog/icons'-import { LemonButton, LemonTag, LemonTagType, lemonToast } from '@posthog/lemon-ui'--import api from 'lib/api'-import { Tooltip } from 'lib/lemon-ui/Tooltip'-import { humanFriendlyDetailedTime } from 'lib/utils/datetime'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'-import { LineageNode as LineageNodeType } from '~/types'--import { dataWarehouseViewsLogic } from '../../../saved_queries/dataWarehouseViewsLogic'-import { sqlEditorLogic } from '../../sqlEditorLogic'--interface UpstreamGraphProps {- tabId: string-}--interface LineageNodeProps {- data: LineageNodeType & { isCurrentView?: boolean }- edges: { source: string; target: string }[]- tabId: string-}--const MAT_VIEW_HEIGHT = 92-const TABLE_HEIGHT = 68--const NODE_WIDTH = 300--const MARKER_SIZE = 20--const NODE_SEP = 80-const RANK_SEP = 160--const BRAND_YELLOW = '#f9bd2b'--function LineageNode({ data, edges, tabId }: LineageNodeProps): JSX.Element {- const { editView } = useActions(sqlEditorLogic({ tabId }))- const { dataWarehouseSavedQueries } = useValues(dataWarehouseViewsLogic)-- const getNodeType = (type: string, lastRunAt?: string): string => {- if (type === 'view') {- return lastRunAt ? 'Mat. view' : 'View'- }- return 'Table'- }-- const getTagType = (type: string): LemonTagType => {- return type === 'view' ? 'primary' : 'highlight'- }-- const hasIncoming = edges.some((edge) => edge.target === data.id)- const hasOutgoing = edges.some((edge) => edge.source === data.id)- const isMatView = data.type === 'view' && !!data.last_run_at- const nodeHeight = isMatView ? MAT_VIEW_HEIGHT : TABLE_HEIGHT-- const handleEditView = async (): Promise<void> => {- if (data.type === 'view') {- let view = dataWarehouseSavedQueries.find((v) => v.name === data.name)- if (view) {- // Fetch the full view with query if not already loaded- if (!view.query) {- try {- view = await api.dataWarehouseSavedQueries.get(view.id)- } catch {- lemonToast.error('Failed to load view details')- return- }- }- if (view?.query?.query) {- editView(view.query.query, view)- }- }- }- }-- return (- <div- className="bg-bg-light border border-border rounded-md p-3 min-w-[300px] shadow-sm"- style={{ minHeight: nodeHeight }}- >- {hasIncoming && <Handle type="target" position={Position.Left} className="w-2 h-2 bg-primary" />}-- <div className="flex items-center gap-2 mb-2">- {data.isCurrentView && (- <Tooltip placement="top" title="This is the currently viewed query">- <IconTarget className="text-warning text-sm" />- </Tooltip>- )}- <Tooltip title={data.name} placement="top">- <div className="flex items-center w-full justify-between">- <div className="font-medium text-sm truncate max-w-[240px] block">{data.name}</div>- {data.type === 'view' && !data.isCurrentView && (- <LemonButton- size="xxsmall"- type="secondary"- icon={<IconPencil />}- onClick={handleEditView}- />- )}- </div>- </Tooltip>- </div>-- <div className="flex items-center gap-2">- <LemonTag type={getTagType(data.type)} size="small">- {getNodeType(data.type, data.last_run_at)}- </LemonTag>- {data.status && (- <LemonTag- type={data.status === 'Failed' ? 'danger' : data.status === 'Running' ? 'warning' : 'success'}- size="small"- >- {data.status}- </LemonTag>- )}- </div>-- {data.last_run_at && (- <div className="text-xs text-muted mt-2">Last run: {humanFriendlyDetailedTime(data.last_run_at)}</div>- )}-- {hasOutgoing && <Handle type="source" position={Position.Right} className="w-2 h-2 bg-primary" />}- </div>- )-}--const getNodeTypes = (edges: { source: string; target: string }[], tabId: string): NodeTypes => ({- lineageNode: (props) => <LineageNode {...props} tabId={tabId} edges={edges} />,-})--const getLayoutedElements = (- nodes: LineageNodeType[],- edges: { source: string; target: string }[],- currentViewName?: string-): { nodes: Node[]; edges: Edge[] } => {- const dagreGraph = new dagre.graphlib.Graph()- dagreGraph.setDefaultEdgeLabel(() => ({}))- dagreGraph.setGraph({ rankdir: 'LR', nodesep: NODE_SEP, ranksep: RANK_SEP })-- nodes.forEach((node) => {- const isMatView = node.type === 'view' && !!node.last_run_at- dagreGraph.setNode(node.id, { width: NODE_WIDTH, height: isMatView ? MAT_VIEW_HEIGHT : TABLE_HEIGHT })- })- edges.forEach((edge) => {- dagreGraph.setEdge(edge.source, edge.target)- })- dagre.layout(dagreGraph)-- const layoutedNodes: Node[] = nodes.map((node) => {- const nodeWithPosition = dagreGraph.node(node.id)- const isMatView = node.type === 'view' && !!node.last_run_at- return {- id: node.id,- type: 'lineageNode',- position: {- x: nodeWithPosition.x - nodeWithPosition.width / 2,- y: nodeWithPosition.y - nodeWithPosition.height / 2,- },- data: {- ...node,- isCurrentView: node.name === currentViewName,- },- width: NODE_WIDTH,- height: isMatView ? MAT_VIEW_HEIGHT : TABLE_HEIGHT,- }- })-- const layoutedEdges: Edge[] = edges.map((edge, index) => ({- id: `edge-${index}`,- source: edge.source,- target: edge.target,- type: 'default',- animated: false,- markerEnd: {- type: MarkerType.ArrowClosed,- width: MARKER_SIZE,- height: MARKER_SIZE,- color: BRAND_YELLOW,- },- }))-- return { nodes: layoutedNodes, edges: layoutedEdges }-}--function UpstreamGraphContent({ tabId }: UpstreamGraphProps): JSX.Element {- const { upstream, editingView } = useValues(sqlEditorLogic({ tabId }))- const { fitView } = useReactFlow()- const { isDarkModeOn } = useValues(themeLogic)-- const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null)- const [hoveredEdgeId, setHoveredEdgeId] = useState<string | null>(null)-- const { nodes, edges } = useMemo(() => {- if (!upstream || upstream.nodes.length === 0) {- return { nodes: [], edges: [] }- }-- return getLayoutedElements(upstream.nodes, upstream.edges, editingView?.name)- }, [upstream, editingView?.name])-- const nodeTypes = useMemo(() => getNodeTypes(edges, tabId), [edges, tabId])-- const coloredEdges: Edge[] = edges.map((edge) => {- const isHighlighted =- edge.id === hoveredEdgeId || edge.source === hoveredNodeId || edge.target === hoveredNodeId-- return {- ...edge,- style: isHighlighted ? { stroke: BRAND_YELLOW } : undefined,- markerEnd: {- type: MarkerType.ArrowClosed,- width: MARKER_SIZE,- height: MARKER_SIZE,- ...(isHighlighted ? { color: BRAND_YELLOW } : {}),- },- }- })-- const onNodeMouseEnter = (_e: React.MouseEvent, node: Node): void => setHoveredNodeId(node.id)- const onNodeMouseLeave = (): void => setHoveredNodeId(null)- const onEdgeMouseEnter = (_e: React.MouseEvent, edge: Edge): void => setHoveredEdgeId(edge.id)- const onEdgeMouseLeave = (): void => setHoveredEdgeId(null)-- // Fit view when nodes change- useEffect(() => {- let timeoutId: ReturnType<typeof setTimeout> | null = null- if (nodes.length > 0) {- timeoutId = setTimeout(() => fitView({ padding: 0.1 }), 100)- }- return () => {- if (timeoutId) {- clearTimeout(timeoutId)- }- }- }, [nodes, fitView])-- if (!upstream || upstream.nodes.length === 0) {- return (- <div- data-attr="upstream-graph-empty-state"- className="flex flex-col flex-1 rounded p-4 w-full items-center justify-center"- >- <IconArchive className="text-5xl mb-2 text-tertiary" />- <h2 className="text-xl leading-tight">No tables or views found</h2>- <p className="text-sm text-center text-balance text-tertiary">- This query doesn't depend on any other tables or views- </p>- </div>- )- }-- return (- <div className="w-full h-full">- <ReactFlow- colorMode={isDarkModeOn ? 'dark' : 'light'}- nodes={nodes}- edges={coloredEdges}- nodeTypes={nodeTypes}- fitView- fitViewOptions={{ padding: 0.1 }}- minZoom={0.1}- maxZoom={2}- onNodeMouseEnter={onNodeMouseEnter}- onNodeMouseLeave={onNodeMouseLeave}- onEdgeMouseEnter={onEdgeMouseEnter}- onEdgeMouseLeave={onEdgeMouseLeave}- >- <Background variant={BackgroundVariant.Dots} gap={20} size={1} />- <Controls showInteractive={false} position="bottom-right" />- <MiniMap zoomable pannable position="bottom-left" nodeStrokeWidth={2} className="hidden lg:block" />- </ReactFlow>- </div>- )-}--export function UpstreamGraph({ tabId }: UpstreamGraphProps): JSX.Element {- return (- <div className="h-[500px] border border-border rounded-md overflow-hidden">- <ReactFlowProvider>- <UpstreamGraphContent tabId={tabId} />- </ReactFlowProvider>- </div>- )-}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 0cf4ded78090..9b29b8d287eb 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -203,7 +203,7 @@ describe('sqlEditorLogic', () => {'/api/environments/:team_id/data_modeling_edges/': { results: [] },'/api/environments/:team_id/data_modeling_jobs/recent/': [],'/api/environments/:team_id/data_modeling_jobs/running/': [],- '/api/environments/:team_id/lineage/get_upstream/': { nodes: [], edges: [] },+ '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },'/api/user_home_settings/@me/': {},},post: {diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 61727629085f..5968381a8301 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -61,11 +61,12 @@ import {import {AccessControlResourceType,ChartDisplayType,+ DataModelingEdge,+ DataModelingNode,DataWarehouseSavedQuery,DataWarehouseSavedQueryDraft,ExportContext,ExternalDataSource,- LineageGraph,QueryBasedInsightModel,} from '~/types'@@ -701,10 +702,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}),loaders(() => ({upstream: [- null as LineageGraph | null,+ null as { nodes: DataModelingNode[]; edges: DataModelingEdge[] } | null,{loadUpstream: async (payload: { modelId: string }) => {- return await api.upstream.get(payload.modelId)+ return await api.dataModelingNodes.lineage({ savedQueryId: payload.modelId })},},],diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/GraphView.tsx b/frontend/src/scenes/data-warehouse/scene/modeling/GraphView.tsxindex 6ca4d3729d3e..ca9bdd2e2ed4 100644--- a/frontend/src/scenes/data-warehouse/scene/modeling/GraphView.tsx+++ b/frontend/src/scenes/data-warehouse/scene/modeling/GraphView.tsx@@ -20,6 +20,8 @@ import { IconArrowDown } from 'lib/lemon-ui/icons'import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { DataModelingNodeType } from '~/types'+import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { dataModelingLogic, parseSearchTerm } from '../dataModelingLogic'import { REACT_FLOW_NODE_TYPES } from './Node'import { CreateModelNodeType, Edge, ElkDirection, Node } from './types'@@ -29,13 +31,6 @@ const FIT_VIEW_OPTIONS = {maxZoom: 1,}-const NODE_TYPE_COLORS: Record<DataModelingNodeType, string> = {- table: 'var(--muted)',- view: 'var(--primary-3000)',- matview: 'var(--success)',- endpoint: 'var(--purple)',-}-const NODES_TO_SHOW: CreateModelNodeType[] = [{type: 'view',@@ -63,7 +58,7 @@ function NodeTypeButton({isActive: booleanonClick: () => void}): JSX.Element {- const color = NODE_TYPE_COLORS[node.type]+ const color = NODE_TYPE_TAG_SETTINGS[node.type].colorreturn (<div draggable>@@ -226,6 +221,10 @@ function GraphViewContent(): JSX.Element {)}+// TODO: fold this onto the shared <LineageGraph> (products/data_modeling/frontend/lineage) once the+// DAG concept is removed from the UI and the backend resolves schedules per-node. A team then has a+// single implicit graph, so dataModelingLogic can drop its multi-DAG selection/viewport machinery and+// this canvas collapses to <LineageGraph variant="canvas"> with search/legend passed as `panels`.export function GraphView(): JSX.Element {return (<ReactFlowProvider>diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/Node.tsx b/frontend/src/scenes/data-warehouse/scene/modeling/Node.tsxindex 60d8ee5b924b..e40740114561 100644--- a/frontend/src/scenes/data-warehouse/scene/modeling/Node.tsx+++ b/frontend/src/scenes/data-warehouse/scene/modeling/Node.tsx@@ -1,292 +1,15 @@-import { Handle } from '@xyflow/react'-import clsx from 'clsx'import { useActions, useValues } from 'kea'-import React, { useCallback, useState } from 'react'+import React, { useCallback } from 'react'-import { IconActivity, IconClockRewind, IconPlay, IconPlayFilled } from '@posthog/icons'-import { LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'--import { TZLabel } from 'lib/components/TZLabel'import { newInternalTab } from 'lib/utils/newInternalTab'import { urls } from 'scenes/urls'-import { DataModelingJobStatus, DataModelingNodeType, DataModelingSyncInterval } from '~/types'--import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'+import { LineageNode } from 'products/data_modeling/frontend/lineage/LineageNode'import { dataModelingLogic } from '../dataModelingLogic'-import type { ElkDirection, NodeData, NodeHandle } from './types'--const NODE_TYPE_SETTINGS: Record<DataModelingNodeType, { label: string; color: string }> = {- table: { label: 'table', color: 'var(--muted)' },- view: { label: 'view', color: 'var(--primary-3000)' },- matview: { label: 'matview', color: 'var(--success)' },- endpoint: { label: 'endpoint', color: 'var(--purple)' },-}--function NodeHandles({ handles }: { handles: NodeHandle[] }): JSX.Element {- return (- <>- {handles.map((handle) => (- <Handle key={handle.id} className="opacity-0" {...handle} isConnectable={false} />- ))}- </>- )-}--function UpstreamArrow({- onRunUpstream,- layoutDirection,-}: {- onRunUpstream: (e: React.MouseEvent) => void- layoutDirection: ElkDirection-}): JSX.Element {- return (- <Tooltip title="Run all upstream nodes including this one">- <button- type="button"- onClick={onRunUpstream}- className={clsx(- 'absolute flex items-center justify-center cursor-pointer z-10 w-5 h-5 rounded-full bg-[var(--primary-3000)]',- layoutDirection === 'DOWN' ? 'left-1/2 -translate-x-1/2 -top-3' : 'top-1/2 -translate-y-1/2 -left-3'- )}- >- <IconPlayFilled- className={clsx('w-2 h-2 text-white/80', layoutDirection === 'DOWN' ? '-rotate-90' : 'rotate-180')}- />- </button>- </Tooltip>- )-}--function DownstreamArrow({- layoutDirection,- onRunDownstream,-}: {- onRunDownstream: (e: React.MouseEvent) => void- layoutDirection: ElkDirection-}): JSX.Element {- return (- <Tooltip title="Run all downstream nodes including this one">- <button- type="button"- onClick={onRunDownstream}- className={clsx(- 'absolute flex items-center justify-center cursor-pointer z-10 w-5 h-5 rounded-full bg-[var(--primary-3000)]',- layoutDirection === 'DOWN'- ? 'left-1/2 -translate-x-1/2 -bottom-3'- : 'top-1/2 -translate-y-1/2 -right-3'- )}- >- <IconPlayFilled- className={clsx('w-2 h-2 text-white/80', layoutDirection === 'DOWN' ? 'rotate-90' : '')}- />- </button>- </Tooltip>- )-}--export interface NodeInnerProps extends NodeData {- layoutDirection: ElkDirection- onRunUpstream: (e: React.MouseEvent) => void- onRunDownstream: (e: React.MouseEvent) => void- onMaterialize: (e: React.MouseEvent) => void- onNodeClick: () => void- onMouseEnter: () => void- onMouseLeave: () => void-}--function NodeTags({ label, color, userTag }: { label: string; color: string; userTag?: string }): JSX.Element {- return (- <div className="flex justify-between items-start">- <span- className="text-[10px] lowercase tracking-wide px-1 rounded border-1"- // eslint-disable-next-line react/forbid-dom-props- style={{- color: color,- backgroundColor: `color-mix(in srgb, ${color} 20%, transparent)`,- borderColor: `color-mix(in srgb, ${color} 80%, transparent)`,- }}- >- {label}- </span>- {userTag && (- <span className="text-[10px] text-muted lowercase tracking-wide px-1 rounded bg-primary dark:bg-primary/20 border-1 border-black/20">- #{userTag}- </span>- )}- </div>- )-}--function NodeLabelAndAction({- label,- showAction,- action,- isActionRunning,-}: {- label: string- showAction: boolean- isActionRunning: boolean- action: (e: React.MouseEvent) => void-}): JSX.Element {- return (- <div className="flex items-center justify-between py-2">- <Tooltip title={label}>- <span className="font-medium text-sm truncate">{label}</span>- </Tooltip>- {showAction && (- <Tooltip title={isActionRunning ? null : 'Run this node'}>- <LemonButton- size="xsmall"- type="secondary"- onClick={action}- disabledReason={isActionRunning && 'This node is already running...'}- icon={isActionRunning ? <Spinner textColored /> : <IconPlay className="w-3 h-3" />}- />- </Tooltip>- )}- </div>- )-}--function NodeMetadata({- type,- syncInterval,- lastRunAt,- lastJobStatus,-}: {- type: DataModelingNodeType- syncInterval?: DataModelingSyncInterval- lastRunAt?: string- lastJobStatus?: DataModelingJobStatus | null-}): JSX.Element | null {- const shortHandSyncInterval = syncIntervalToShorthand(syncInterval)- switch (type) {- case 'matview':- case 'endpoint':- return (- <div className="flex items-center bg-primary dark:bg-primary/60 rounded-b-lg px-2.5 py-1.5 justify-between">- <div className="flex gap-1 text-[10px]">- <IconClockRewind className="scale-x-[-1]" />- {syncInterval ? (- shortHandSyncInterval- ) : (- <Tooltip title="This node is not set to sync on a schedule yet">- {shortHandSyncInterval}- </Tooltip>- )}- <IconActivity />- {lastRunAt ? (- <TZLabel- className="text-[10px]"- time={lastRunAt}- formatDate="MMM D"- formatTime="HH:mm"- showPopover={false}- />- ) : (- <Tooltip title="This node has not been run yet">Never</Tooltip>- )}- </div>- <Tooltip title={lastJobStatus ?? 'This node has not been run yet'}>- <div- className={clsx(- 'rounded-full w-4 h-4',- lastJobStatus === 'Completed' && 'bg-success border-primary border-1',- lastJobStatus === 'Failed' && 'bg-danger border-primary border-1',- lastJobStatus === 'Cancelled' && 'bg-warning border-primary border-1',- !lastJobStatus && 'bg-surface-primary border-primary border-1'- )}- />- </Tooltip>- </div>- )- default:- return null- }-}+import type { NodeData } from './types'-export const NodeInner = React.memo(function NodeInner({- name,- type,- handles,- layoutDirection,- isRunning,- isSearchMatch,- isTypeHighlighted,- lastJobStatus,- lastRunAt,- userTag,- syncInterval,- upstreamCount,- downstreamCount,- onRunUpstream,- onRunDownstream,- onMaterialize,- onNodeClick,- onMouseEnter,- onMouseLeave,-}: NodeInnerProps): JSX.Element {- const [isHovered, setIsHovered] = useState(false)-- const nodeTypeSettings = NODE_TYPE_SETTINGS[type]-- const canRun = type === 'matview' || type === 'view' || type === 'endpoint'- const shouldRenderArrows = canRun && isHovered && !isRunning-- const handleMouseEnter = useCallback(() => {- setIsHovered(true)- onMouseEnter()- }, [onMouseEnter])- const handleMouseLeave = useCallback(() => {- setIsHovered(false)- onMouseLeave()- }, [onMouseLeave])-- return (- <div- className={clsx(- 'relative rounded-lg border dark:border-none bg-bg-light',- isRunning && 'border-warning ring-2 ring-warning/30 animate-pulse',- !isRunning && (isSearchMatch || isTypeHighlighted) && 'border-link ring-2 ring-link/30',- !isRunning && !isSearchMatch && !isTypeHighlighted && 'border-border',- 'cursor-pointer'- )}- // eslint-disable-next-line react/forbid-dom-props- style={{- // dims non matched nodes, search match is undefined when the debounced query value is unset- opacity: isSearchMatch === undefined || isSearchMatch ? 1 : 0.5,- }}- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- onClick={onNodeClick}- >- {handles && <NodeHandles handles={handles} />}-- {shouldRenderArrows && upstreamCount > 0 && (- <UpstreamArrow onRunUpstream={onRunUpstream} layoutDirection={layoutDirection} />- )}-- {shouldRenderArrows && downstreamCount > 0 && (- <DownstreamArrow onRunDownstream={onRunDownstream} layoutDirection={layoutDirection} />- )}-- <div className="flex flex-col justify-around px-3 pt-3">- <NodeTags color={nodeTypeSettings.color} label={nodeTypeSettings.label} userTag={userTag} />- <NodeLabelAndAction- label={name}- showAction={canRun && (type === 'matview' || type === 'endpoint')}- isActionRunning={isRunning ?? false}- action={onMaterialize}- />- </div>- <NodeMetadata type={type} syncInterval={syncInterval} lastRunAt={lastRunAt} lastJobStatus={lastJobStatus} />- </div>- )-})--const NodeComponent = React.memo(function NodeComponent(props: { id: string; data: NodeData }): JSX.Element | null {+const NodeComponent = React.memo(function NodeComponent(props: { id: string; data: NodeData }): JSX.Element {const { runNode, materializeNode, setHoveredNodeId } = useActions(dataModelingLogic)const { layoutDirection, highlightedNodeIds, debouncedSearchTerm, parsedSearch } = useValues(dataModelingLogic)@@ -294,7 +17,6 @@ const NodeComponent = React.memo(function NodeComponent(props: { id: string; datconst {name,type,- savedQueryId,handles,upstreamCount,downstreamCount,@@ -306,86 +28,62 @@ const NodeComponent = React.memo(function NodeComponent(props: { id: string; datuserTag,} = props.data- const isSearchMatch = (() => {+ const isSearchMatch = ((): boolean | undefined => {if (debouncedSearchTerm.length === 0) {return undefined}if (parsedSearch.mode !== 'search') {- // graph traversal for +name, name+, or +name+ syntax- const highlighted = highlightedNodeIds(parsedSearch.baseName, parsedSearch.mode)- return highlighted.has(props.id)+ return highlightedNodeIds(parsedSearch.baseName, parsedSearch.mode).has(id)}- // default text searchreturn name.toLowerCase().includes(parsedSearch.baseName.toLowerCase())})()- const handleRunUpstream = useCallback(- (e: React.MouseEvent): void => {- e.stopPropagation()- runNode(id, 'upstream')- },- [id, runNode]- )-- const handleRunDownstream = useCallback(- (e: React.MouseEvent): void => {- e.stopPropagation()- runNode(id, 'downstream')- },- [id, runNode]- )-- const handleMaterialize = useCallback(- (e: React.MouseEvent): void => {- e.stopPropagation()- materializeNode(id)- },- [id, materializeNode]- )-const handleNodeClick = useCallback((): void => {if (type === 'endpoint') {const versionMatch = name.match(/^(.+)_v(\d+)$/)- if (versionMatch) {- newInternalTab(urls.endpoint(versionMatch[1], parseInt(versionMatch[2])))- } else {- newInternalTab(urls.endpoint(name))- }+ newInternalTab(+ versionMatch ? urls.endpoint(versionMatch[1], parseInt(versionMatch[2])) : urls.endpoint(name)+ )} else {newInternalTab(urls.nodeDetail(id))}- }, [type, id, props.data.name, name])+ }, [type, id, name])- const handleMouseEnter = useCallback(() => setHoveredNodeId(id), [id, setHoveredNodeId])- const handleMouseLeave = useCallback(() => setHoveredNodeId(null), [setHoveredNodeId])+ const canRun = type !== 'table'return (- <NodeInner- id={id}- name={name}- type={type}- savedQueryId={savedQueryId}- handles={handles}- layoutDirection={layoutDirection}- isRunning={isRunning ?? false}- isSearchMatch={isSearchMatch}- isTypeHighlighted={isTypeHighlighted ?? false}- lastJobStatus={lastJobStatus}- lastRunAt={lastRunAt}- userTag={userTag}- syncInterval={syncInterval}- upstreamCount={upstreamCount}- downstreamCount={downstreamCount}- onRunUpstream={handleRunUpstream}- onRunDownstream={handleRunDownstream}- onMaterialize={handleMaterialize}- onNodeClick={handleNodeClick}- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}+ <LineageNode+ data={{+ node: {+ id,+ name,+ type,+ sync_interval: syncInterval,+ last_run_at: lastRunAt,+ last_run_status: lastJobStatus,+ upstream_count: upstreamCount,+ downstream_count: downstreamCount,+ user_tag: userTag,+ },+ variant: 'canvas',+ direction: layoutDirection,+ state: {+ isRunning: isRunning ?? false,+ isHighlighted: (isTypeHighlighted ?? false) || isSearchMatch === true,+ isDimmed: isSearchMatch === false,+ },+ callbacks: {+ onClick: handleNodeClick,+ onMaterialize: type === 'matview' || type === 'endpoint' ? () => materializeNode(id) : undefined,+ onRunUpstream: canRun ? () => runNode(id, 'upstream') : undefined,+ onRunDownstream: canRun ? () => runNode(id, 'downstream') : undefined,+ onMouseEnter: () => setHoveredNodeId(id),+ onMouseLeave: () => setHoveredNodeId(null),+ },+ handles: handles ?? [],+ }}/>)})-export const REACT_FLOW_NODE_TYPES = {- model: NodeComponent,-}+export const REACT_FLOW_NODE_TYPES = { model: NodeComponent }diff --git a/frontend/src/scenes/models/nodeDetailConstants.ts b/frontend/src/scenes/models/nodeDetailConstants.tsindex 073ffd16f828..4d4b121fe04f 100644--- a/frontend/src/scenes/models/nodeDetailConstants.ts+++ b/frontend/src/scenes/models/nodeDetailConstants.ts@@ -1,21 +1 @@-import { LemonTagType } from '@posthog/lemon-ui'--import { DataModelingNodeType } from '~/types'--export const NODE_TYPE_TAG_SETTINGS: Record<- DataModelingNodeType,- { label: string; type: LemonTagType; color: string }-> = {- table: { label: 'Table', type: 'default', color: 'var(--muted)' },- view: { label: 'View', type: 'primary', color: 'var(--primary-3000)' },- matview: { label: 'Materialized view', type: 'success', color: 'var(--success)' },- endpoint: { label: 'Endpoint', type: 'completion', color: 'var(--purple)' },-}--export const STATUS_TAG_SETTINGS: Record<string, LemonTagType> = {- Running: 'primary',- Completed: 'success',- Failed: 'danger',- Cancelled: 'muted',- Modified: 'warning',-}+export { NODE_TYPE_TAG_SETTINGS, STATUS_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'diff --git a/frontend/src/scenes/models/nodeDetailSceneLogic.ts b/frontend/src/scenes/models/nodeDetailSceneLogic.tsindex 913fc354e882..5672d53b6554 100644--- a/frontend/src/scenes/models/nodeDetailSceneLogic.ts+++ b/frontend/src/scenes/models/nodeDetailSceneLogic.ts@@ -92,7 +92,7 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([if (!node) {return null}- const { nodes, edges } = await api.dataModelingNodes.lineage(node.id)+ const { nodes, edges } = await api.dataModelingNodes.lineage({ nodeId: node.id })return { nodes, edges, currentNodeId: node.id }},},diff --git a/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx b/frontend/src/scenes/models/tabs/NodeDetailLineage.tsxindex 33ad8aefa1f4..eb5947a75c37 100644--- a/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx+++ b/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx@@ -1,396 +1,42 @@-import '@xyflow/react/dist/style.css'--import {- Background,- Controls,- Handle,- MarkerType,- Panel,- Position,- ReactFlow,- ReactFlowProvider,- type Edge as ReactFlowEdge,- type Node as ReactFlowNode,-} from '@xyflow/react'-import clsx from 'clsx'import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { type ComponentType, useCallback, useEffect, useMemo, useState } from 'react'+import { useMemo } from 'react'-import { IconActivity, IconClockRewind, IconExternal } from '@posthog/icons'-import { LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'+import { IconExternal } from '@posthog/icons'+import { LemonButton, Spinner } from '@posthog/lemon-ui'-import { TZLabel } from 'lib/components/TZLabel'import { IconFullScreen } from 'lib/lemon-ui/icons'import { LemonModal } from 'lib/lemon-ui/LemonModal/LemonModal'-import { getFormattedNodes } from 'scenes/data-warehouse/scene/modeling/autolayout'import { urls } from 'scenes/urls'-import { DataModelingJobStatus, DataModelingNodeType, DataModelingSyncInterval } from '~/types'--import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'--import { NODE_TYPE_TAG_SETTINGS } from '../nodeDetailConstants'-import { LineageGraphData, nodeDetailSceneLogic } from '../nodeDetailSceneLogic'--// Shared node data used by both compact and fullscreen nodes-interface LineageNodeData extends Record<string, unknown> {- nodeId: string- name: string- nodeType: DataModelingNodeType- isCurrent: boolean- lastJobStatus?: DataModelingJobStatus- lastRunAt?: string- syncInterval?: DataModelingSyncInterval- upstreamCount: number- downstreamCount: number- /** The scene-level node ID, used to key nodeDetailSceneLogic */- sceneId: string-}--// --- Shared sub-components -----function NodeTypeTag({ nodeType }: { nodeType: DataModelingNodeType }): JSX.Element {- const tagSettings = NODE_TYPE_TAG_SETTINGS[nodeType]- return (- <span- className="text-[10px] lowercase tracking-wide px-1 rounded border-1"- // eslint-disable-next-line react/forbid-dom-props- style={{- color: tagSettings.color,- backgroundColor: `color-mix(in srgb, ${tagSettings.color} 20%, transparent)`,- borderColor: `color-mix(in srgb, ${tagSettings.color} 80%, transparent)`,- }}- >- {tagSettings.label}- </span>- )-}--function StatusDot({ status }: { status?: DataModelingJobStatus }): JSX.Element {- return (- <Tooltip title={status ?? 'Not run yet'}>- <div- className={clsx(- 'rounded-full w-3 h-3 border-1 border-primary',- status === 'Completed' && 'bg-success',- status === 'Running' && 'bg-warning',- status === 'Failed' && 'bg-danger',- status === 'Cancelled' && 'bg-warning',- !status && 'bg-surface-primary'- )}- />- </Tooltip>- )-}--function NodeHandles({ nodeId }: { nodeId: string }): JSX.Element {- return (- <>- <Handle- id={`target_${nodeId}`}- type="target"- position={Position.Left}- className="opacity-0"- isConnectable={false}- />- <Handle- id={`source_${nodeId}`}- type="source"- position={Position.Right}- className="opacity-0"- isConnectable={false}- />- </>- )-}--// --- Compact node (used in inline partial lineage) -----function LineageNodeCompact({ data }: { data: LineageNodeData }): JSX.Element {- const tagSettings = NODE_TYPE_TAG_SETTINGS[data.nodeType]- const handleClick = useCallback(() => {- if (!data.isCurrent) {- router.actions.push(urls.nodeDetail(data.nodeId))- }- }, [data.nodeId, data.isCurrent])-- return (- <div- className="px-3 py-2 bg-bg-light border rounded-lg cursor-pointer min-w-[140px]"- // eslint-disable-next-line react/forbid-dom-props- style={{- borderColor: data.isCurrent ? tagSettings.color : 'var(--border)',- borderWidth: data.isCurrent ? 2 : 1,- }}- onClick={handleClick}- >- <NodeHandles nodeId={data.nodeId} />- <div className="flex items-center justify-between gap-2">- <NodeTypeTag nodeType={data.nodeType} />- {(data.nodeType === 'matview' || data.nodeType === 'endpoint') && (- <StatusDot status={data.lastJobStatus} />- )}- </div>- <div className="text-sm font-medium truncate mt-1">{data.name}</div>- </div>- )-}--// --- Fullscreen node (self-contained with metadata) -----function FullscreenLineageNode({ data }: { data: LineageNodeData }): JSX.Element {- const tagSettings = NODE_TYPE_TAG_SETTINGS[data.nodeType]- const { closeLineageModal } = useActions(nodeDetailSceneLogic({ id: data.sceneId }))- const handleClick = useCallback(() => {- if (!data.isCurrent) {- closeLineageModal()- router.actions.push(urls.nodeDetail(data.nodeId))- }- }, [data.nodeId, data.isCurrent, closeLineageModal])-- const showMetadata = data.nodeType === 'matview' || data.nodeType === 'endpoint'-- return (- <div- className={clsx(- 'relative rounded-lg border bg-bg-light cursor-pointer min-w-[200px]',- data.isCurrent && 'border-2'- )}- // eslint-disable-next-line react/forbid-dom-props- style={{- borderColor: data.isCurrent ? tagSettings.color : 'var(--border)',- }}- onClick={handleClick}- >- <NodeHandles nodeId={data.nodeId} />- <div className="px-3 pt-3">- <NodeTypeTag nodeType={data.nodeType} />- <div className="text-sm font-medium truncate py-2">{data.name}</div>- </div>- {showMetadata && (- <div className="flex items-center bg-primary dark:bg-primary/60 rounded-b-lg px-2.5 py-1.5 justify-between">- <div className="flex gap-1 text-[10px] items-center">- <IconClockRewind className="scale-x-[-1]" />- {syncIntervalToShorthand(data.syncInterval)}- <IconActivity />- {data.lastRunAt ? (- <TZLabel- className="text-[10px]"- time={data.lastRunAt}- formatDate="MMM DD, YYYY"- formatTime="HH:mm"- showPopover={false}- />- ) : (- <span>Never</span>- )}- </div>- <StatusDot status={data.lastJobStatus} />- </div>- )}- </div>- )-}--// --- Node type registrations -----const compactNodeTypes = { lineage: LineageNodeCompact }-const fullscreenNodeTypes = { lineage: FullscreenLineageNode }--// --- Layout -----interface LayoutResult {- nodes: ReactFlowNode<LineageNodeData>[]- edges: ReactFlowEdge[]-}--interface BuildLayoutOptions {- /** Override lastJobStatus for the current node (derived from materialization jobs) */- currentNodeStatus?: string- /** Override lastRunAt for the current node (derived from materialization jobs) */- currentNodeLastRunAt?: string- /** Node dimensions for ELK layout — should match actual rendered size */- nodeWidth?: number- nodeHeight?: number-}--const COMPACT_NODE_WIDTH = 160-const COMPACT_NODE_HEIGHT = 55-const FULLSCREEN_NODE_WIDTH = 200-const FULLSCREEN_NODE_HEIGHT = 90--/** Convert LineageGraphData (from kea) into laid-out ReactFlow nodes + edges */-async function buildLineageLayout(data: LineageGraphData, options?: BuildLayoutOptions): Promise<LayoutResult> {- const nodeWidth = options?.nodeWidth ?? COMPACT_NODE_WIDTH- const nodeHeight = options?.nodeHeight ?? COMPACT_NODE_HEIGHT-- const rfNodes: ReactFlowNode<LineageNodeData>[] = data.nodes.map((n) => {- const isCurrent = n.id === data.currentNodeId- return {- id: n.id,- type: 'lineage',- position: { x: 0, y: 0 },- width: nodeWidth,- height: nodeHeight,- data: {- name: n.name,- nodeType: n.type,- isCurrent,- nodeId: n.id,- sceneId: data.currentNodeId,- lastJobStatus:- isCurrent && options?.currentNodeStatus- ? (options.currentNodeStatus as DataModelingJobStatus)- : n.last_run_status,- lastRunAt: isCurrent && options?.currentNodeLastRunAt ? options.currentNodeLastRunAt : n.last_run_at,- syncInterval: n.sync_interval,- upstreamCount: n.upstream_count,- downstreamCount: n.downstream_count,- // handles needed by getFormattedNodes for ELK port layout- handles: [- {- id: `target_${n.id}`,- type: 'target' as const,- position: Position.Left,- },- {- id: `source_${n.id}`,- type: 'source' as const,- position: Position.Right,- },- ],- },- }- })-- const rfEdges: ReactFlowEdge[] = data.edges.map((e) => ({- id: e.id,- source: e.source_id,- target: e.target_id,- sourceHandle: `source_${e.source_id}`,- targetHandle: `target_${e.target_id}`,- markerEnd: { type: MarkerType.ArrowClosed, width: 20, height: 20 },- }))-- // Use ELK layout (same as the full DAG view)- const laidOutNodes = await getFormattedNodes(rfNodes as any, rfEdges, 'RIGHT')-- return {- nodes: laidOutNodes as unknown as ReactFlowNode<LineageNodeData>[],- edges: rfEdges,- }-}--// --- Graph content ---+import { DataModelingJobStatus, DataModelingNode } from '~/types'-function LineageGraphContent({- layout,- interactive,- nodeTypes,- onFullscreen,-}: {- layout: LayoutResult- interactive?: boolean- nodeTypes: Record<string, ComponentType<any>>- onFullscreen?: () => void-}): JSX.Element {- return (- <ReactFlow- nodes={layout.nodes}- edges={layout.edges}- nodeTypes={nodeTypes}- nodesDraggable={false}- nodesConnectable={false}- fitView- minZoom={0.3}- maxZoom={1.5}- zoomOnScroll={interactive ?? false}- panOnScroll={interactive ?? false}- zoomOnPinch={interactive ?? false}- zoomOnDoubleClick={interactive ?? false}- >- <Background />- {interactive && <Controls showInteractive={false} />}- {onFullscreen && (- <Panel position="bottom-left">- <div className="flex flex-col gap-1">- <LemonButton- type="secondary"- size="small"- to={urls.dataOps('modeling')}- tooltip="Open full DAG view"- >- <IconExternal />- </LemonButton>- <LemonButton type="secondary" size="small" onClick={onFullscreen} tooltip="Fullscreen">- <IconFullScreen />- </LemonButton>- </div>- </Panel>- )}- </ReactFlow>- )-}+import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'-// --- Main export ---+import { nodeDetailSceneLogic } from '../nodeDetailSceneLogic'export function NodeDetailLineage({ id }: { id: string }): JSX.Element | null {const { lineageGraph, lineageGraphLoading, effectiveLastRunAt, effectiveLastRunStatus, lineageModalOpen } =useValues(nodeDetailSceneLogic({ id }))const { openLineageModal, closeLineageModal } = useActions(nodeDetailSceneLogic({ id }))- const [compactLayout, setCompactLayout] = useState<LayoutResult | null>(null)- const [fullscreenLayout, setFullscreenLayout] = useState<LayoutResult | null>(null)-- const overrides = useMemo(- () => ({- currentNodeStatus: effectiveLastRunStatus ?? undefined,- currentNodeLastRunAt: effectiveLastRunAt ?? undefined,- }),- [effectiveLastRunStatus, effectiveLastRunAt]- )-- // Run ELK layout when lineageGraph data or derived status changes- useEffect(() => {- if (!lineageGraph || lineageGraph.nodes.length <= 1) {- setCompactLayout(null)- setFullscreenLayout(null)- return- }- let cancelled = false- const compactOpts = {- ...overrides,- nodeWidth: COMPACT_NODE_WIDTH,- nodeHeight: COMPACT_NODE_HEIGHT,- }- const fullscreenOpts = {- ...overrides,- nodeWidth: FULLSCREEN_NODE_WIDTH,- nodeHeight: FULLSCREEN_NODE_HEIGHT,- }- Promise.all([- buildLineageLayout(lineageGraph, compactOpts),- buildLineageLayout(lineageGraph, fullscreenOpts),- ]).then(([compact, fullscreen]) => {- if (!cancelled) {- setCompactLayout(compact)- setFullscreenLayout(fullscreen)- }- })- return () => {- cancelled = true+ // The current node's freshest status/run come from its materialization jobs, not the graph payload+ const nodes = useMemo((): DataModelingNode[] => {+ if (!lineageGraph) {+ return []}- }, [lineageGraph, overrides])-- // Memoize node types to avoid ReactFlow re-registering on every render- const stableCompactNodeTypes = useMemo(() => compactNodeTypes, [])- const stableFullscreenNodeTypes = useMemo(() => fullscreenNodeTypes, [])-- // Show spinner while fetching lineage data OR while ELK is computing the layout- const isLayoutPending = !compactLayout && !!lineageGraph && lineageGraph.nodes.length > 1+ return lineageGraph.nodes.map((node) =>+ node.id === lineageGraph.currentNodeId+ ? {+ ...node,+ last_run_at: effectiveLastRunAt ?? node.last_run_at,+ last_run_status: (effectiveLastRunStatus as DataModelingJobStatus) ?? node.last_run_status,+ }+ : node+ )+ }, [lineageGraph, effectiveLastRunAt, effectiveLastRunStatus])- if (lineageGraphLoading || isLayoutPending) {+ if (lineageGraphLoading) {return (<div className="space-y-2 mt-4"><h3 className="text-lg font-semibold">Lineage</h3>@@ -401,7 +47,7 @@ export function NodeDetailLineage({ id }: { id: string }): JSX.Element | null {)}- if (!compactLayout || compactLayout.nodes.length <= 1) {+ if (nodes.length <= 1) {return (<div className="space-y-2 mt-4"><h3 className="text-lg font-semibold">Lineage</h3>@@ -413,14 +59,35 @@ export function NodeDetailLineage({ id }: { id: string }): JSX.Element | null {return (<div className="space-y-2 mt-4"><h3 className="text-lg font-semibold">Lineage</h3>- <div className="h-72 w-full border rounded bg-bg-light">- <ReactFlowProvider>- <LineageGraphContent- layout={compactLayout}- nodeTypes={stableCompactNodeTypes}- onFullscreen={openLineageModal}- />- </ReactFlowProvider>+ <div className="h-[500px] w-full border rounded bg-bg-light">+ <LineageGraph+ nodes={nodes}+ edges={lineageGraph?.edges ?? []}+ currentNodeId={lineageGraph?.currentNodeId}+ variant="full"+ interactive+ showControls+ showMinimap+ onNodeClick={(node) => router.actions.push(urls.nodeDetail(node.id))}+ panels={+ <div className="flex flex-col gap-1">+ <LemonButton+ type="secondary"+ size="small"+ to={urls.dataOps('modeling')}+ tooltip="Open full DAG view"+ icon={<IconExternal />}+ />+ <LemonButton+ type="secondary"+ size="small"+ onClick={openLineageModal}+ tooltip="Fullscreen"+ icon={<IconFullScreen />}+ />+ </div>+ }+ /></div><LemonModalisOpen={lineageModalOpen}@@ -429,14 +96,19 @@ export function NodeDetailLineage({ id }: { id: string }): JSX.Element | null {width="calc(100vw - 4rem)"maxWidth="calc(100vw - 4rem)">- <div style={{ height: 'calc(100vh - 12rem)' }}>- <ReactFlowProvider>- <LineageGraphContent- layout={fullscreenLayout ?? compactLayout}- nodeTypes={stableFullscreenNodeTypes}- interactive- />- </ReactFlowProvider>+ <div className="h-[calc(100vh-12rem)]">+ <LineageGraph+ nodes={nodes}+ edges={lineageGraph?.edges ?? []}+ currentNodeId={lineageGraph?.currentNodeId}+ variant="full"+ interactive+ showControls+ onNodeClick={(node) => {+ closeLineageModal()+ router.actions.push(urls.nodeDetail(node.id))+ }}+ /></div></LemonModal></div>diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 78c1bad2bf65..704891e1d54e 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7498,25 +7498,6 @@ export type LinkType = {_create_in_folder?: string | null}-export interface LineageNode {- id: string- name: string- type: 'view' | 'table'- sync_frequency?: DataWarehouseSyncInterval- last_run_at?: string- status?: string-}--export interface LineageEdge {- source: string- target: string-}--export interface LineageGraph {- nodes: LineageNode[]- edges: LineageEdge[]-}-export interface DataWarehouseSourceRowCount {breakdown_of_rows_by_source: Record<string, number>billing_available: booleandiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d276c1c6d0d4..e633df090e9d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2994,6 +2994,12 @@ importers:'@types/react':specifier: 18.3.27version: 18.3.27+ '@xyflow/react':+ specifier: '*'+ version: 12.6.0(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ clsx:+ specifier: '*'+ version: 1.2.1kea:specifier: 'catalog:'version: 4.0.0-pre.5([email protected])@@ -3012,6 +3018,10 @@ importers:react-dom:specifier: 18.3.1version: 18.3.1([email protected])+ devDependencies:+ '@storybook/react':+ specifier: 'catalog:'+ version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])products/data_tools: {}diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex 05f3b115f30a..1956288f8a67 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -8,8 +8,11 @@ from django.conf import settingsfrom django.db import modelsfrom django.db.models import OuterRef, Subquery+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schemafrom rest_framework import filters, request, response, serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import PermissionDeniedfrom rest_framework.pagination import PageNumberPaginationfrom temporalio.common import RetryPolicy@@ -111,7 +114,6 @@ class NodePagination(PageNumberPagination):# TODO: consolidate graph traversal logic. similar implementations exist in:-# - products/data_warehouse/backend/api/lineage.py (get_upstream_dag) should be deleted after new system takes over# - posthog/temporal/data_modeling/workflows/execute_dag.py (_get_edge_lookup, _get_downstream_lookup)# - products/data_modeling/backend/graph.py (Graph) — shared in-memory graph used by list endpoint# the temporal workflow and lineage API should migrate to Graph@@ -321,12 +323,51 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return response.Response({"node_ids": list(node_ids)}, status=status.HTTP_200_OK)- @action(methods=["GET"], detail=True)+ @extend_schema(+ parameters=[+ OpenApiParameter("node_id", OpenApiTypes.UUID, description="Node to build lineage for."),+ OpenApiParameter(+ "saved_query_id",+ OpenApiTypes.UUID,+ description="Saved query to build lineage for, resolved to its node. Alternative to node_id.",+ ),+ ]+ )+ @action(methods=["GET"], detail=False)def lineage(self, req: request.Request, *args, **kwargs) -> response.Response:- """Return the subgraph of nodes and edges reachable from this node (upstream + downstream)."""+ """Return the subgraph of nodes and edges reachable from a node (upstream + downstream).++ Accepts either node_id or saved_query_id, so a caller holding only a saved query (the SQL+ editor) doesn't need to resolve the node itself.+ """from products.data_modeling.backend.presentation.views.edge import EdgeSerializer- node = self.get_object()+ # NodeViewSet is `scope_object = "INTERNAL"`, so AccessControlPermission does not gate it on+ # any resource. Lineage exposes warehouse view/table names, types, and edges — the same+ # metadata the deleted `warehouse_view`-scoped upstream endpoint gated on. Re-apply that gate+ # here so warehouse RBAC still governs the read (warehouse_view inherits warehouse_objects).+ if not self.user_access_control.check_access_level_for_resource("warehouse_view", required_level="viewer"):+ raise PermissionDenied("Reading lineage requires data warehouse read access.")++ node_id = req.query_params.get("node_id")+ saved_query_id = req.query_params.get("saved_query_id")+ if not node_id and not saved_query_id:+ return response.Response(+ {"error": "node_id or saved_query_id is required"}, status=status.HTTP_400_BAD_REQUEST+ )+ # Parse UUIDs up front: unlike the detail route, query params aren't validated by URL+ # routing, so an invalid string would surface as a 500 from the ORM instead of a 400.+ try:+ lookup = {"id": UUID(node_id)} if node_id else {"saved_query_id": UUID(cast(str, saved_query_id))}+ except ValueError:+ return response.Response({"error": "Invalid UUID"}, status=status.HTTP_400_BAD_REQUEST)++ # saved_query is a non-unique FK: a saved query synced into multiple DAGs has multiple nodes.+ # Order for a deterministic pick (the graphs are equivalent for lineage purposes).+ node = Node.objects.filter(team_id=self.team_id, **lookup).order_by("created_at").first()+ if node is None:+ return response.Response({"error": "Node not found"}, status=status.HTTP_404_NOT_FOUND)+upstream_ids = _get_upstream_nodes(node, include_tables=True)downstream_ids = _get_downstream_nodes(node)all_ids = upstream_ids | downstream_ids | {str(node.id)}diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex 93cfcba14b86..cc37b56ad20c 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -264,7 +264,9 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(call_args[0][0], "data-modeling-run")def test_lineage_returns_subgraph(self):- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/lineage/")+ response = self.client.get(+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?node_id={self.view_node.id}"+ )self.assertEqual(response.status_code, status.HTTP_200_OK)node_ids = {n["id"] for n in response.json()["nodes"]}@@ -273,6 +275,47 @@ class TestNodeViewSet(APIBaseTest):edge_source_ids = {e["source_id"] for e in response.json()["edges"]}self.assertIn(str(self.table_node.id), edge_source_ids)+ def test_lineage_by_saved_query_id(self):+ response = self.client.get(+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?saved_query_id={self.view_node.saved_query_id}"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ node_ids = {n["id"] for n in response.json()["nodes"]}+ self.assertIn(str(self.view_node.id), node_ids)+ self.assertIn(str(self.table_node.id), node_ids)++ def test_lineage_requires_node_id_or_saved_query_id(self):+ response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @parameterized.expand(["node_id", "saved_query_id"])+ def test_lineage_invalid_uuid_returns_400(self, lookup_param):+ response = self.client.get(+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?{lookup_param}=not-a-uuid"+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @parameterized.expand(["node_id", "saved_query_id"])+ def test_lineage_does_not_leak_other_teams_nodes(self, lookup_param):+ other_team = Team.objects.create(organization=self.organization)+ other_dag = DAG.objects.create(team=other_team, name=f"posthog_{other_team.id}")+ other_saved_query = DataWarehouseSavedQuery.objects.create(+ name="other_view", team=other_team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )+ other_node = Node.objects.create(+ team=other_team, dag=other_dag, saved_query=other_saved_query, type=NodeType.VIEW+ )++ lookup_value = other_node.id if lookup_param == "node_id" else other_saved_query.id+ response = self.client.get(+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?{lookup_param}={lookup_value}"+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+def test_lineage_multi_level(self):sq_b = DataWarehouseSavedQuery.objects.create(name="view_b", team=self.team, query={"query": "SELECT 1", "kind": "HogQLQuery"}@@ -297,7 +340,7 @@ class TestNodeViewSet(APIBaseTest):Edge.objects.create(team=self.team, dag=self.dag, source=self.view_node, target=view_b)Edge.objects.create(team=self.team, dag=self.dag, source=view_b, target=view_c)- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{view_b.id}/lineage/")+ response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?node_id={view_b.id}")self.assertEqual(response.status_code, status.HTTP_200_OK)node_ids = {n["id"] for n in response.json()["nodes"]}@@ -318,7 +361,9 @@ class TestNodeViewSet(APIBaseTest):saved_query=sq_standalone,)- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{standalone.id}/lineage/")+ response = self.client.get(+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?node_id={standalone.id}"+ )self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(len(response.json()["nodes"]), 1)@@ -351,7 +396,9 @@ class TestNodeViewSet(APIBaseTest):target=other_view,)- response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/lineage/")+ response = self.client.get(+ f"/api/environments/{self.team.id}/data_modeling_nodes/lineage/?node_id={self.view_node.id}"+ )self.assertEqual(response.status_code, status.HTTP_200_OK)node_ids = {n["id"] for n in response.json()["nodes"]}diff --git a/products/data_modeling/frontend/generated/api.schemas.ts b/products/data_modeling/frontend/generated/api.schemas.tsindex be082c487711..72793c0071cd 100644--- a/products/data_modeling/frontend/generated/api.schemas.ts+++ b/products/data_modeling/frontend/generated/api.schemas.ts@@ -197,3 +197,14 @@ export type DataModelingNodesListParams = {*/search?: string}++export type DataModelingNodesLineageRetrieveParams = {+ /**+ * Node to build lineage for.+ */+ node_id?: string+ /**+ * Saved query to build lineage for, resolved to its node. Alternative to node_id.+ */+ saved_query_id?: string+}diff --git a/products/data_modeling/frontend/generated/api.ts b/products/data_modeling/frontend/generated/api.tsindex a42faf8fc3fb..e2c40dabf3e2 100644--- a/products/data_modeling/frontend/generated/api.ts+++ b/products/data_modeling/frontend/generated/api.ts@@ -12,6 +12,7 @@ import type {DagApi,DataModelingDagsListParams,DataModelingEdgesListParams,+ DataModelingNodesLineageRetrieveParams,DataModelingNodesListParams,EdgeApi,NodeApi,@@ -340,24 +341,6 @@ export const dataModelingNodesDestroy = async (projectId: string, id: string, op})}-export const getDataModelingNodesLineageRetrieveUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/data_modeling_nodes/${id}/lineage/`-}--/**- * Return the subgraph of nodes and edges reachable from this node (upstream + downstream).- */-export const dataModelingNodesLineageRetrieve = async (- projectId: string,- id: string,- options?: RequestInit-): Promise<NodeApi> => {- return apiMutator<NodeApi>(getDataModelingNodesLineageRetrieveUrl(projectId, id), {- ...options,- method: 'GET',- })-}-export const getDataModelingNodesMaterializeCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/data_modeling_nodes/${id}/materialize/`}@@ -418,3 +401,39 @@ export const dataModelingNodesDagIdsRetrieve = async (projectId: string, optionsmethod: 'GET',})}++export const getDataModelingNodesLineageRetrieveUrl = (+ projectId: string,+ params?: DataModelingNodesLineageRetrieveParams+) => {+ 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_nodes/lineage/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_modeling_nodes/lineage/`+}++/**+ * Return the subgraph of nodes and edges reachable from a node (upstream + downstream).+ *+ * Accepts either node_id or saved_query_id, so a caller holding only a saved query (the SQL+ * editor) doesn't need to resolve the node itself.+ */+export const dataModelingNodesLineageRetrieve = async (+ projectId: string,+ params?: DataModelingNodesLineageRetrieveParams,+ options?: RequestInit+): Promise<NodeApi> => {+ return apiMutator<NodeApi>(getDataModelingNodesLineageRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsxnew file mode 100644index 000000000000..af9f48d198b5--- /dev/null+++ b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx@@ -0,0 +1,89 @@+import type { Meta, StoryObj } from '@storybook/react'++import { DataModelingEdge, DataModelingNode } from '~/types'++import { LineageGraph } from './LineageGraph'++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,+ downstream_count: 0,+ ...partial,+ }+}++function mockEdge(id: string, sourceId: string, targetId: string): DataModelingEdge {+ return {+ id,+ source_id: sourceId,+ target_id: targetId,+ dag: 'dag-1',+ properties: {},+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ }+}++const GRAPH_NODES: DataModelingNode[] = [+ mockNode({ id: '1', name: 'orders', type: 'table' }),+ mockNode({ id: '2', name: 'customers', type: 'table' }),+ mockNode({+ id: '3',+ name: 'revenue_summary',+ type: 'matview',+ last_run_at: '2024-01-15T10:30:00Z',+ last_run_status: 'Completed',+ sync_interval: '1hour',+ }),+ mockNode({ id: '4', name: 'monthly_report', type: 'view' }),+]+const GRAPH_EDGES: DataModelingEdge[] = [mockEdge('e1', '1', '3'), mockEdge('e2', '2', '3'), mockEdge('e3', '3', '4')]++type Story = StoryObj<typeof LineageGraph>+const meta: Meta<typeof LineageGraph> = {+ title: 'Products/Data modeling/Lineage graph',+ component: LineageGraph,+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ testOptions: {+ snapshotBrowsers: ['chromium'],+ },+ },+ decorators: [+ (StoryFn) => (+ <div className="h-[500px]">+ <StoryFn />+ </div>+ ),+ ],+}++export default meta++export const Full: Story = {+ render: () => (+ <LineageGraph nodes={GRAPH_NODES} edges={GRAPH_EDGES} currentNodeId="4" variant="full" showControls />+ ),+}++export const Canvas: Story = {+ render: () => (+ <LineageGraph nodes={GRAPH_NODES} edges={GRAPH_EDGES} variant="canvas" showControls showMinimap interactive />+ ),+}++export const SingleNode: Story = {+ render: () => <LineageGraph nodes={[mockNode({ id: '1', name: 'raw_events', type: 'table' })]} edges={[]} />,+}++export const EmptyState: Story = {+ render: () => (+ <LineageGraph nodes={[]} edges={[]} emptyMessage="This query doesn't depend on any other tables or views" />+ ),+}diff --git a/products/data_modeling/frontend/lineage/LineageGraph.tsx b/products/data_modeling/frontend/lineage/LineageGraph.tsxnew file mode 100644index 000000000000..20534546793b--- /dev/null+++ b/products/data_modeling/frontend/lineage/LineageGraph.tsx@@ -0,0 +1,129 @@+import '@xyflow/react/dist/style.css'++import { Background, BackgroundVariant, Controls, MiniMap, Panel, ReactFlow, ReactFlowProvider } from '@xyflow/react'+import { useValues } from 'kea'+import { ReactNode } from 'react'++import { IconArchive } from '@posthog/icons'+import { Spinner } from '@posthog/lemon-ui'++import { ElkDirection } from 'scenes/data-warehouse/scene/modeling/types'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { DataModelingEdge, DataModelingNode } from '~/types'++import { lineageGraphLogic } from './lineageGraphLogic'+import { LINEAGE_NODE_TYPES, LineageNodeCallbacks, LineageNodeState, LineageVariant } from './LineageNode'++export type { LineageVariant, LineageNodeState, LineageNodeCallbacks } from './LineageNode'++export interface LineageGraphProps {+ nodes: DataModelingNode[]+ edges: DataModelingEdge[]+ /** Highlighted "you are here" node, rendered with a target marker + accent border */+ currentNodeId?: string+ variant?: LineageVariant+ direction?: ElkDirection+ /** Enable zoom/pan. Off by default for inline previews */+ interactive?: boolean+ showMinimap?: boolean+ showControls?: boolean+ className?: string+ loading?: boolean+ emptyMessage?: string+ /** Per-node visual state (running, dimmed, highlighted), computed by the caller */+ nodeState?: (node: DataModelingNode) => LineageNodeState+ /** Per-node affordances (click, run, edit), wired by the caller to its own logic */+ nodeCallbacks?: (node: DataModelingNode) => LineageNodeCallbacks+ /** Convenience click handler, used when nodeCallbacks is not provided */+ onNodeClick?: (node: DataModelingNode) => void+ /** Caller-specific chrome (search, legend, layout toggle) rendered over the canvas */+ panels?: ReactNode+}++function LineageGraphContent(props: LineageGraphProps): JSX.Element {+ const { isDarkModeOn } = useValues(themeLogic)+ const { currentNodeId, nodeState, nodeCallbacks, onNodeClick } = props+ const { layout } = useValues(+ lineageGraphLogic({+ nodes: props.nodes,+ edges: props.edges,+ variant: props.variant ?? 'full',+ direction: props.direction ?? 'RIGHT',+ })+ )++ if (!layout) {+ return (+ <div className="flex items-center justify-center w-full h-full">+ <Spinner />+ </div>+ )+ }++ // Cheap per-render pass: current-node highlight, state, and callbacks change without relayout+ const decoratedNodes = layout.nodes.map((rfNode) => {+ const node = rfNode.data.node as DataModelingNode+ return {+ ...rfNode,+ data: {+ ...rfNode.data,+ state: { isCurrent: node.id === currentNodeId, ...nodeState?.(node) },+ callbacks: nodeCallbacks?.(node) ?? {+ onClick: onNodeClick ? () => onNodeClick(node) : undefined,+ },+ },+ }+ })++ return (+ <ReactFlow+ colorMode={isDarkModeOn ? 'dark' : 'light'}+ nodes={decoratedNodes}+ edges={layout.edges}+ nodeTypes={LINEAGE_NODE_TYPES}+ nodesDraggable={false}+ nodesConnectable={false}+ fitView+ minZoom={0.1}+ maxZoom={2}+ zoomOnScroll={props.interactive ?? false}+ panOnScroll={props.interactive ?? false}+ zoomOnPinch={props.interactive ?? false}+ zoomOnDoubleClick={props.interactive ?? false}+ proOptions={{ hideAttribution: true }}+ >+ <Background variant={BackgroundVariant.Dots} gap={20} size={1} />+ {props.showControls && <Controls showInteractive={false} position="bottom-right" />}+ {props.showMinimap && (+ <MiniMap zoomable pannable position="bottom-left" nodeStrokeWidth={2} className="hidden lg:block" />+ )}+ {props.panels && <Panel position="top-right">{props.panels}</Panel>}+ </ReactFlow>+ )+}++export function LineageGraph(props: LineageGraphProps): JSX.Element {+ if (props.loading) {+ return (+ <div className="flex items-center justify-center w-full h-full">+ <Spinner />+ </div>+ )+ }+ if (props.nodes.length === 0) {+ return (+ <div className="flex flex-col w-full h-full items-center justify-center p-4">+ <IconArchive className="text-5xl mb-2 text-tertiary" />+ <p className="text-sm text-center text-balance text-tertiary">+ {props.emptyMessage ?? 'No tables or views found'}+ </p>+ </div>+ )+ }+ return (+ <ReactFlowProvider>+ <LineageGraphContent {...props} />+ </ReactFlowProvider>+ )+}diff --git a/products/data_modeling/frontend/lineage/LineageNode.tsx b/products/data_modeling/frontend/lineage/LineageNode.tsxnew file mode 100644index 000000000000..f00787780e8b--- /dev/null+++ b/products/data_modeling/frontend/lineage/LineageNode.tsx@@ -0,0 +1,270 @@+import { Handle, Position } from '@xyflow/react'+import clsx from 'clsx'+import React, { useCallback, useState } from 'react'++import { IconActivity, IconClockRewind, IconPencil, IconPlay, IconPlayFilled, IconTarget } from '@posthog/icons'+import { LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { ElkDirection, NodeHandle } from 'scenes/data-warehouse/scene/modeling/types'++import { DataModelingJobStatus, DataModelingNode } from '~/types'++import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'++import { NODE_TYPE_TAG_SETTINGS } from './nodeStyles'++export type LineageVariant = 'full' | 'canvas'++/** Fields the node renders — a superset caller (DataModelingNode) satisfies this structurally. */+export type LineageNodeShape = Pick<+ DataModelingNode,+ | 'id'+ | 'name'+ | 'type'+ | 'sync_interval'+ | 'last_run_at'+ | 'last_run_status'+ | 'upstream_count'+ | 'downstream_count'+ | 'user_tag'+>++export interface LineageNodeState {+ isCurrent?: boolean+ isRunning?: boolean+ /** Dimmed when a search is active and this node is not a match */+ isDimmed?: boolean+ /** Ringed when a search or type filter highlights this node */+ isHighlighted?: boolean+}++export interface LineageNodeCallbacks {+ onClick?: () => void+ onEdit?: () => void+ onMaterialize?: () => void+ onRunUpstream?: () => void+ onRunDownstream?: () => void+ onMouseEnter?: () => void+ onMouseLeave?: () => void+}++export interface LineageNodeData extends Record<string, unknown> {+ node: LineageNodeShape+ variant: LineageVariant+ direction: ElkDirection+ state: LineageNodeState+ callbacks: LineageNodeCallbacks+ handles: NodeHandle[]+}++function NodeTypeTag({ type }: { type: DataModelingNode['type'] }): JSX.Element {+ const { label, color } = NODE_TYPE_TAG_SETTINGS[type]+ return (+ <span+ className="text-[10px] lowercase tracking-wide px-1 rounded border-1"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ color,+ backgroundColor: `color-mix(in srgb, ${color} 20%, transparent)`,+ borderColor: `color-mix(in srgb, ${color} 80%, transparent)`,+ }}+ >+ {label}+ </span>+ )+}++function StatusDot({ status }: { status?: DataModelingJobStatus }): JSX.Element {+ return (+ <Tooltip title={status ?? 'Not run yet'}>+ <div+ className={clsx(+ 'rounded-full w-3 h-3 border-1 border-primary',+ status === 'Completed' && 'bg-success',+ status === 'Running' && 'bg-warning',+ status === 'Failed' && 'bg-danger',+ status === 'Cancelled' && 'bg-warning',+ !status && 'bg-surface-primary'+ )}+ />+ </Tooltip>+ )+}++function RunArrow({+ direction,+ layoutDirection,+ onClick,+}: {+ direction: 'upstream' | 'downstream'+ layoutDirection: ElkDirection+ onClick: (e: React.MouseEvent) => void+}): JSX.Element {+ const upstream = direction === 'upstream'+ return (+ <Tooltip title={`Run all ${direction} nodes including this one`}>+ <button+ type="button"+ onClick={onClick}+ className={clsx(+ 'absolute flex items-center justify-center cursor-pointer z-10 w-5 h-5 rounded-full bg-[var(--primary-3000)]',+ layoutDirection === 'DOWN'+ ? upstream+ ? 'left-1/2 -translate-x-1/2 -top-3'+ : 'left-1/2 -translate-x-1/2 -bottom-3'+ : upstream+ ? 'top-1/2 -translate-y-1/2 -left-3'+ : 'top-1/2 -translate-y-1/2 -right-3'+ )}+ >+ <IconPlayFilled+ className={clsx(+ 'w-2 h-2 text-white/80',+ layoutDirection === 'DOWN'+ ? upstream+ ? '-rotate-90'+ : 'rotate-90'+ : upstream+ ? 'rotate-180'+ : ''+ )}+ />+ </button>+ </Tooltip>+ )+}++function MetadataBar({ node }: { node: LineageNodeShape }): JSX.Element {+ return (+ <div className="flex items-center bg-primary dark:bg-primary/60 rounded-b-lg px-2.5 py-1.5 justify-between">+ <div className="flex gap-1 text-[10px] items-center">+ <IconClockRewind className="scale-x-[-1]" />+ <Tooltip title={node.sync_interval ? null : 'This node is not set to sync on a schedule yet'}>+ {syncIntervalToShorthand(node.sync_interval)}+ </Tooltip>+ <IconActivity />+ {node.last_run_at ? (+ <TZLabel+ className="text-[10px]"+ time={node.last_run_at}+ formatDate="MMM D"+ formatTime="HH:mm"+ showPopover={false}+ />+ ) : (+ <Tooltip title="This node has not been run yet">Never</Tooltip>+ )}+ </div>+ <StatusDot status={node.last_run_status} />+ </div>+ )+}++export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {+ const { node, variant, direction, state, callbacks } = data+ const [isHovered, setIsHovered] = useState(false)++ const showMetadata = node.type === 'matview' || node.type === 'endpoint'+ const showRunArrows = variant === 'canvas' && isHovered && !state.isRunning+ const { color } = NODE_TYPE_TAG_SETTINGS[node.type]++ const handleMouseEnter = useCallback(() => {+ setIsHovered(true)+ callbacks.onMouseEnter?.()+ }, [callbacks])+ const handleMouseLeave = useCallback(() => {+ setIsHovered(false)+ callbacks.onMouseLeave?.()+ }, [callbacks])++ const stop = (fn?: () => void) => (e: React.MouseEvent) => {+ e.stopPropagation()+ fn?.()+ }++ return (+ <div+ className={clsx(+ 'relative rounded-lg border bg-bg-light cursor-pointer min-w-[180px]',+ state.isRunning && 'border-warning ring-2 ring-warning/30 animate-pulse',+ !state.isRunning && state.isHighlighted && 'border-link ring-2 ring-link/30',+ !state.isRunning && !state.isHighlighted && !state.isCurrent && 'border-border',+ state.isCurrent && 'border-2'+ )}+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ opacity: state.isDimmed ? 0.5 : 1,+ borderColor: state.isCurrent ? color : undefined,+ }}+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ onClick={callbacks.onClick}+ >+ {data.handles.map((handle) => (+ <Handle+ key={handle.id}+ id={handle.id}+ type={handle.type}+ position={handle.position ?? (handle.type === 'target' ? Position.Left : Position.Right)}+ className="opacity-0"+ isConnectable={false}+ />+ ))}++ {showRunArrows && node.upstream_count > 0 && callbacks.onRunUpstream && (+ <RunArrow direction="upstream" layoutDirection={direction} onClick={stop(callbacks.onRunUpstream)} />+ )}+ {showRunArrows && node.downstream_count > 0 && callbacks.onRunDownstream && (+ <RunArrow+ direction="downstream"+ layoutDirection={direction}+ onClick={stop(callbacks.onRunDownstream)}+ />+ )}++ <div className="px-3 pt-3">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1 min-w-0">+ {state.isCurrent && (+ <Tooltip title="This is the currently viewed node">+ <IconTarget className="text-warning text-sm shrink-0" />+ </Tooltip>+ )}+ <NodeTypeTag type={node.type} />+ </div>+ {node.user_tag && (+ <span className="text-[10px] text-muted lowercase tracking-wide px-1 rounded bg-primary dark:bg-primary/20 border-1 border-black/20">+ #{node.user_tag}+ </span>+ )}+ </div>+ <div className="flex items-center justify-between gap-2 py-2">+ <span className="font-medium text-sm truncate">{node.name}</span>+ {callbacks.onEdit && (+ <LemonButton+ size="xxsmall"+ type="secondary"+ icon={<IconPencil />}+ onClick={stop(callbacks.onEdit)}+ />+ )}+ {callbacks.onMaterialize && (node.type === 'matview' || node.type === 'endpoint') && (+ <Tooltip title={state.isRunning ? null : 'Run this node'}>+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={stop(callbacks.onMaterialize)}+ disabledReason={state.isRunning && 'This node is already running...'}+ icon={state.isRunning ? <Spinner textColored /> : <IconPlay className="w-3 h-3" />}+ />+ </Tooltip>+ )}+ </div>+ </div>+ {showMetadata && <MetadataBar node={node} />}+ </div>+ )+}++export const LINEAGE_NODE_TYPES = { lineage: LineageNode }diff --git a/products/data_modeling/frontend/lineage/lineageGraphLogic.ts b/products/data_modeling/frontend/lineage/lineageGraphLogic.tsnew file mode 100644index 000000000000..1a624948fdf9--- /dev/null+++ b/products/data_modeling/frontend/lineage/lineageGraphLogic.ts@@ -0,0 +1,112 @@+import { MarkerType, Position, type Edge as ReactFlowEdge, type Node as ReactFlowNode } from '@xyflow/react'+import { actions, afterMount, kea, key, listeners, path, props, propsChanged, reducers } from 'kea'++import { getFormattedNodes } from 'scenes/data-warehouse/scene/modeling/autolayout'+import { ElkDirection, NodeHandle } from 'scenes/data-warehouse/scene/modeling/types'++import { DataModelingEdge, DataModelingNode } from '~/types'++import type { lineageGraphLogicType } from './lineageGraphLogicType'+import { LineageNodeData, LineageVariant } from './LineageNode'++const NODE_SIZES: Record<LineageVariant, { width: number; height: number }> = {+ full: { width: 200, height: 90 },+ canvas: { width: 180, height: 120 },+}++export interface LineageGraphLayout {+ nodes: ReactFlowNode<LineageNodeData>[]+ edges: ReactFlowEdge[]+}++export interface LineageGraphLogicProps {+ nodes: DataModelingNode[]+ edges: DataModelingEdge[]+ variant: LineageVariant+ direction: ElkDirection+}++function handlesForDirection(nodeId: string, direction: ElkDirection): NodeHandle[] {+ const isDown = direction === 'DOWN'+ return [+ { id: `target_${nodeId}`, type: 'target', position: isDown ? Position.Top : Position.Left },+ { id: `source_${nodeId}`, type: 'source', position: isDown ? Position.Bottom : Position.Right },+ ]+}++// Layout depends only on the graph's structure — per-node state/callbacks are decorated onto the+// laid-out nodes at render time, so caller-supplied inline callbacks never retrigger the ELK pass.+async function layoutGraph(+ nodes: DataModelingNode[],+ edges: DataModelingEdge[],+ variant: LineageVariant,+ direction: ElkDirection+): Promise<LineageGraphLayout> {+ const { width, height } = NODE_SIZES[variant]++ const rfNodes: ReactFlowNode<LineageNodeData>[] = nodes.map((node) => ({+ id: node.id,+ type: 'lineage',+ position: { x: 0, y: 0 },+ width,+ height,+ data: {+ node,+ variant,+ direction,+ state: {},+ callbacks: {},+ handles: handlesForDirection(node.id, direction),+ },+ }))++ const rfEdges: ReactFlowEdge[] = edges.map((edge) => ({+ id: edge.id,+ source: edge.source_id,+ target: edge.target_id,+ sourceHandle: `source_${edge.source_id}`,+ targetHandle: `target_${edge.target_id}`,+ markerEnd: { type: MarkerType.ArrowClosed, width: 20, height: 20 },+ }))++ const laidOut = await getFormattedNodes(rfNodes as any, rfEdges, direction)+ return { nodes: laidOut as unknown as ReactFlowNode<LineageNodeData>[], edges: rfEdges }+}++export const lineageGraphLogic = kea<lineageGraphLogicType>([+ path(['products', 'data_modeling', 'frontend', 'lineage', 'lineageGraphLogic']),+ props({} as LineageGraphLogicProps),+ key((props) => `${props.variant}-${props.direction}-${props.nodes.map((n) => n.id).join(',')}`),+ actions({+ computeLayout: true,+ layoutComputed: (layout: LineageGraphLayout) => ({ layout }),+ }),+ reducers({+ layout: [+ null as LineageGraphLayout | null,+ {+ layoutComputed: (_, { layout }) => layout,+ },+ ],+ }),+ listeners(({ actions, props }) => ({+ computeLayout: async (_, breakpoint) => {+ const layout = await layoutGraph(props.nodes, props.edges, props.variant, props.direction)+ breakpoint()+ actions.layoutComputed(layout)+ },+ })),+ propsChanged(({ actions, props }, oldProps) => {+ if (+ props.nodes !== oldProps.nodes ||+ props.edges !== oldProps.edges ||+ props.variant !== oldProps.variant ||+ props.direction !== oldProps.direction+ ) {+ actions.computeLayout()+ }+ }),+ afterMount(({ actions }) => {+ actions.computeLayout()+ }),+])diff --git a/products/data_modeling/frontend/lineage/nodeStyles.ts b/products/data_modeling/frontend/lineage/nodeStyles.tsnew file mode 100644index 000000000000..073ffd16f828--- /dev/null+++ b/products/data_modeling/frontend/lineage/nodeStyles.ts@@ -0,0 +1,21 @@+import { LemonTagType } from '@posthog/lemon-ui'++import { DataModelingNodeType } from '~/types'++export const NODE_TYPE_TAG_SETTINGS: Record<+ DataModelingNodeType,+ { label: string; type: LemonTagType; color: string }+> = {+ table: { label: 'Table', type: 'default', color: 'var(--muted)' },+ view: { label: 'View', type: 'primary', color: 'var(--primary-3000)' },+ matview: { label: 'Materialized view', type: 'success', color: 'var(--success)' },+ endpoint: { label: 'Endpoint', type: 'completion', color: 'var(--purple)' },+}++export const STATUS_TAG_SETTINGS: Record<string, LemonTagType> = {+ Running: 'primary',+ Completed: 'success',+ Failed: 'danger',+ Cancelled: 'muted',+ Modified: 'warning',+}diff --git a/products/data_modeling/package.json b/products/data_modeling/package.jsonindex 67b64efd6fca..a37ea2018f52 100644--- a/products/data_modeling/package.json+++ b/products/data_modeling/package.json@@ -10,9 +10,14 @@"kea-loaders": "catalog:","kea-router": "catalog:"},+ "devDependencies": {+ "@storybook/react": "catalog:"+ },"peerDependencies": {"@posthog/icons": "catalog:","@types/react": "*",+ "@xyflow/react": "*",+ "clsx": "*","react": "*","react-dom": "*"}diff --git a/products/data_warehouse/backend/presentation/views/lineage.py b/products/data_warehouse/backend/presentation/views/lineage.pydeleted file mode 100644index 40f9f5dacb03..000000000000--- a/products/data_warehouse/backend/presentation/views/lineage.py+++ /dev/null@@ -1,149 +0,0 @@-import logging-from collections import defaultdict, deque-from typing import Any--from rest_framework import viewsets-from rest_framework.decorators import action-from rest_framework.response import Response--from posthog.api.documentation import _FallbackSerializer-from posthog.api.routing import TeamAndOrgViewSetMixin--from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery-from products.warehouse_sources.backend.facade.models import DataWarehouseTable---class LineageViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):- scope_object = "warehouse_view"- serializer_class = _FallbackSerializer-- def safely_get_queryset(self, queryset=None):- return super().safely_get_queryset(queryset).filter(team_id=self.team_id)-- @action(detail=False, methods=["GET"])- def get_upstream(self, request, *args, **kwargs):- model_id = request.query_params.get("model_id")-- if not model_id:- return Response({"error": "model_id is required"}, status=400)-- return Response(get_upstream_dag(self.team_id, model_id))---def topological_sort(nodes: list[str], edges: list[dict[str, str]]) -> list[str]:- """- Performs a topological sort on the DAG to determine execution order.- Returns nodes ordered from most upstream to the node itself.- """- # Build adjacency list and in-degree count- graph = defaultdict(list)- in_degree: dict[str, int] = defaultdict(int)-- for edge in edges:- source, target = edge["source"], edge["target"]- graph[source].append(target)- in_degree[target] += 1- if source not in in_degree:- in_degree[source] = 0-- # Initialize queue with nodes that have no incoming edges- queue = deque([node for node in nodes if in_degree[node] == 0])- result = []-- # Process nodes- while queue:- node = queue.popleft()- result.append(node)-- for neighbor in graph[node]:- in_degree[neighbor] -= 1- if in_degree[neighbor] == 0:- queue.append(neighbor)-- return result---def get_upstream_dag(team_id: int, model_id: str) -> dict[str, list[Any]]:- dag: dict[str, list[Any]] = {"nodes": [], "edges": []}- seen_nodes: set[str] = set()- node_data: dict[str, dict] = {}-- # root node and its external tables- root_query = DataWarehouseSavedQuery.objects.filter(id=model_id, team_id=team_id).first()- if not root_query:- return dag-- node_data[root_query.name] = {- "id": root_query.name,- "type": "view",- "name": root_query.name,- "sync_frequency": root_query.sync_frequency_interval,- "last_run_at": root_query.last_run_at,- "status": root_query.status,- }- seen_nodes.add(root_query.name)-- # Recursively fetch all dependencies with a bfs- # Fetch everything by names, ids and names are the same right now- to_process = [(root_query.name, root_query.external_tables)]-- while to_process:- current_id, external_tables = to_process.pop(0)- current_external_tables = external_tables if isinstance(external_tables, list) else []-- # Batch lookup all external tables at this level- unseen_external_tables = [et for et in current_external_tables if isinstance(et, str) and et not in seen_nodes]- if unseen_external_tables:- saved_queries = {- sq.name: sq- for sq in DataWarehouseSavedQuery.objects.filter(name__in=unseen_external_tables, team_id=team_id)- }- tables = {- t.name: t for t in DataWarehouseTable.objects.filter(name__in=unseen_external_tables, team_id=team_id)- }-- for external_table in current_external_tables:- edge = {"source": external_table, "target": current_id}- if edge not in dag["edges"]:- dag["edges"].append(edge)-- if external_table not in seen_nodes:- seen_nodes.add(external_table)-- # Process the current external table- saved_query = saved_queries.get(external_table)- if saved_query:- node_data[external_table] = {- "id": external_table,- "type": "view",- "name": saved_query.name,- "sync_frequency": saved_query.sync_frequency_interval,- "last_run_at": saved_query.last_run_at,- "status": saved_query.status,- }- to_process.append((external_table, saved_query.external_tables))- else:- table = tables.get(external_table)- if not table:- logging.warning(f"Upstream table not found for external_table: {external_table}")- node_data[external_table] = {- "id": external_table,- "type": "table",- "name": table.name if table else external_table,- }-- view_names = [name for name, data in node_data.items() if data["type"] == "view"]- latest_runs = dict(- DataModelingJob.objects.filter(team_id=team_id, saved_query__name__in=view_names)- .order_by("saved_query__name", "-last_run_at")- .distinct("saved_query__name")- .values_list("saved_query__name", "last_run_at")- )- for name, last_run_at in latest_runs.items():- node_data[name]["last_run_at"] = last_run_at-- # Order nodes by dependency order- ordered_nodes = topological_sort(list(node_data.keys()), dag["edges"])- dag["nodes"] = [node_data[node_id] for node_id in ordered_nodes]-- return dagdiff --git a/products/data_warehouse/backend/routes.py b/products/data_warehouse/backend/routes.pyindex 276aad5e0690..872b89202520 100644--- a/products/data_warehouse/backend/routes.py+++ b/products/data_warehouse/backend/routes.py@@ -17,7 +17,6 @@ from products.data_warehouse.backend.presentation.views import (table,view_link,)-from products.data_warehouse.backend.presentation.views.lineage import LineageViewSetdef register_routes(routers: RouterRegistry) -> None:@@ -82,7 +81,6 @@ def register_routes(routers: RouterRegistry) -> None:routers.register_legacy_dual_route(r"data_modeling_jobs", data_modeling_job.DataModelingJobViewSet, "environment_data_modeling_jobs", ["team_id"])- routers.register_legacy_dual_route(r"lineage", LineageViewSet, "project_lineage", ["team_id"])routers.projects.register(r"warehouse_column_annotations",column_annotation.WarehouseColumnAnnotationViewSet,diff --git a/products/data_warehouse/backend/tests/api/test_lineage.py b/products/data_warehouse/backend/tests/api/test_lineage.pydeleted file mode 100644index 1fbbe2376a6d..000000000000--- a/products/data_warehouse/backend/tests/api/test_lineage.py+++ /dev/null@@ -1,270 +0,0 @@-from datetime import UTC, datetime--from posthog.test.base import APIBaseTest--from posthog.test.db_context_capturing import capture_db_queries--from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery-from products.data_warehouse.backend.presentation.views.lineage import topological_sort-from products.warehouse_sources.backend.facade.models import DataWarehouseTable---class TestLineage(APIBaseTest):- def test_get_upstream_simple_chain(self):- DataWarehouseSavedQuery.objects.create(- team=self.team,- name="base_query",- query={- "kind": "HogQLQuery",- "query": "select event as event from postgres.supabase.users LIMIT 100",- },- external_tables=["postgres.supabase.users"],- )-- DataWarehouseSavedQuery.objects.create(- team=self.team,- name="intermediate_query",- query={- "kind": "HogQLQuery",- "query": "select event as event from base_query LIMIT 100",- },- external_tables=["base_query"],- )-- final_query = DataWarehouseSavedQuery.objects.create(- team=self.team,- name="final_query",- query={- "kind": "HogQLQuery",- "query": "select event as event from intermediate_query LIMIT 100",- },- external_tables=["intermediate_query"],- )-- with capture_db_queries() as context:- response = self.client.get(- f"/api/environments/{self.team.id}/lineage/get_upstream/?model_id={final_query.id}"- )- self.assertEqual(response.status_code, 200)- data = response.json()-- self.assertEqual(len(data["nodes"]), 4)-- nodes = {node["id"]: node for node in data["nodes"]}- self.assertEqual(nodes["final_query"]["type"], "view")- self.assertEqual(nodes["intermediate_query"]["type"], "view")- self.assertEqual(nodes["base_query"]["type"], "view")- self.assertEqual(nodes["postgres.supabase.users"]["type"], "table")-- edges = {(edge["source"], edge["target"]) for edge in data["edges"]}- expected_edges = {- ("intermediate_query", "final_query"),- ("base_query", "intermediate_query"),- ("postgres.supabase.users", "base_query"),- }- self.assertEqual(edges, expected_edges)-- view_queries = [- q- for q in context.captured_queries- if "datawarehousesavedquery" in q["sql"].lower() or "datawarehousetable" in q["sql"].lower()- ]- self.assertLessEqual(len(view_queries), 8, f"Expected at most 8 queries, got {len(view_queries)}")-- def test_get_upstream_with_datawarehouse_table(self):- DataWarehouseTable.objects.create(- team=self.team,- name="my_table",- url_pattern="https://example.com/data",- format="JSONEachRow",- )-- saved_query = DataWarehouseSavedQuery.objects.create(- team=self.team,- name="test_query",- query={- "kind": "HogQLQuery",- "query": "select * from my_table",- },- external_tables=["my_table"],- )-- response = self.client.get(f"/api/environments/{self.team.id}/lineage/get_upstream/?model_id={saved_query.id}")- self.assertEqual(response.status_code, 200)- data = response.json()-- self.assertEqual(len(data["nodes"]), 2)-- nodes = {node["id"]: node for node in data["nodes"]}- self.assertEqual(nodes["test_query"]["type"], "view")- self.assertEqual(nodes["my_table"]["type"], "table")- self.assertEqual(nodes["my_table"]["name"], "my_table")-- edges = {(edge["source"], edge["target"]) for edge in data["edges"]}- expected_edges = {("my_table", "test_query")}- self.assertEqual(edges, expected_edges)-- def test_get_upstream_mixed_dependencies(self):- DataWarehouseSavedQuery.objects.create(- team=self.team,- name="base_query",- query={- "kind": "HogQLQuery",- "query": "select * from postgres.supabase.users",- },- external_tables=["postgres.supabase.users"],- )-- mixed_query = DataWarehouseSavedQuery.objects.create(- team=self.team,- name="mixed_query",- query={- "kind": "HogQLQuery",- "query": "select * from base_query join postgres.supabase.events",- },- external_tables=["base_query", "postgres.supabase.events"],- )-- response = self.client.get(f"/api/environments/{self.team.id}/lineage/get_upstream/?model_id={mixed_query.id}")- self.assertEqual(response.status_code, 200)- data = response.json()-- self.assertEqual(len(data["nodes"]), 4)-- nodes = {node["id"]: node for node in data["nodes"]}- self.assertEqual(nodes["mixed_query"]["type"], "view")- self.assertEqual(nodes["base_query"]["type"], "view")- self.assertEqual(nodes["postgres.supabase.users"]["type"], "table")- self.assertEqual(nodes["postgres.supabase.events"]["type"], "table")-- edges = {(edge["source"], edge["target"]) for edge in data["edges"]}- expected_edges = {- ("base_query", "mixed_query"),- ("postgres.supabase.events", "mixed_query"),- ("postgres.supabase.users", "base_query"),- }- self.assertEqual(edges, expected_edges)-- saved_query = DataWarehouseSavedQuery.objects.create(- team=self.team,- name="test_query",- query={- "kind": "HogQLQuery",- "query": "select * from postgres.supabase.users",- },- external_tables=["postgres.supabase.users", "postgres.supabase.events"],- )-- response = self.client.get(f"/api/environments/{self.team.id}/lineage/get_upstream/?model_id={saved_query.id}")- self.assertEqual(response.status_code, 200)- data = response.json()-- self.assertEqual(len(data["nodes"]), 3)-- nodes = {node["id"]: node for node in data["nodes"]}- self.assertEqual(nodes["test_query"]["type"], "view")- self.assertEqual(nodes["postgres.supabase.users"]["type"], "table")- self.assertEqual(nodes["postgres.supabase.events"]["type"], "table")-- edges = {(edge["source"], edge["target"]) for edge in data["edges"]}- expected_edges = {- ("postgres.supabase.users", "test_query"),- ("postgres.supabase.events", "test_query"),- }- self.assertEqual(edges, expected_edges)-- def test_get_upstream_no_external_tables(self):- saved_query = DataWarehouseSavedQuery.objects.create(- team=self.team,- name="test_query",- query={- "kind": "HogQLQuery",- "query": "select 1 as value",- },- external_tables=[],- )-- response = self.client.get(f"/api/environments/{self.team.id}/lineage/get_upstream/?model_id={saved_query.id}")- self.assertEqual(response.status_code, 200)- data = response.json()-- self.assertEqual(len(data["nodes"]), 1)- self.assertEqual(len(data["edges"]), 0)-- nodes = {node["id"]: node for node in data["nodes"]}- self.assertEqual(nodes["test_query"]["type"], "view")-- def test_get_upstream_last_run_at_uses_latest_job_not_stale_model_field(self):- stale = datetime(2026, 4, 29, 9, 0, 0, tzinfo=UTC)-- DataWarehouseSavedQuery.objects.create(- team=self.team,- name="base_q",- query={"kind": "HogQLQuery", "query": "select * from postgres.supabase.users"},- external_tables=["postgres.supabase.users"],- last_run_at=stale,- status="Modified",- )- final_q = DataWarehouseSavedQuery.objects.create(- team=self.team,- name="final_q",- query={"kind": "HogQLQuery", "query": "select * from base_q"},- external_tables=["base_q"],- last_run_at=stale,- status="Modified",- )-- DataModelingJob.objects.create(- team=self.team,- saved_query=final_q,- status="Completed",- last_run_at=datetime(2026, 5, 1, 0, 0, 0, tzinfo=UTC),- )- DataModelingJob.objects.create(- team=self.team,- saved_query=final_q,- status="Completed",- last_run_at=datetime(2026, 6, 30, 10, 0, 0, tzinfo=UTC),- )-- with capture_db_queries() as context:- response = self.client.get(f"/api/environments/{self.team.id}/lineage/get_upstream/?model_id={final_q.id}")- self.assertEqual(response.status_code, 200)- data = response.json()-- nodes = {node["id"]: node for node in data["nodes"]}- self.assertTrue(nodes["final_q"]["last_run_at"].startswith("2026-06-30T10:00:00"))- self.assertTrue(nodes["base_q"]["last_run_at"].startswith("2026-04-29T09:00:00"))-- job_queries = [q for q in context.captured_queries if "posthog_datamodelingjob" in q["sql"].lower()]- self.assertEqual(len(job_queries), 1, "Latest job per saved query must be a single batched query")-- def test_topological_sort(self):- nodes = ["A", "B", "C"]- edges = [{"source": "A", "target": "B"}, {"source": "B", "target": "C"}]- result = topological_sort(nodes, edges)- self.assertEqual(result, ["A", "B", "C"])-- # Test DAG with multiple paths and random order- nodes = ["E", "D", "C", "B", "A"]- edges = [- {"source": "D", "target": "E"},- {"source": "C", "target": "D"},- {"source": "B", "target": "D"},- {"source": "A", "target": "C"},- {"source": "A", "target": "B"},- ]- result = topological_sort(nodes, edges)- # A must come before B and C, B and C must come before D, D must come before E- self.assertEqual(result[0], "A")- self.assertEqual(result[-1], "E")- self.assertIn(result[1], ["B", "C"])- self.assertIn(result[2], ["B", "C"])- self.assertEqual(result[3], "D")-- nodes = ["A", "B", "C", "D"]- edges = [{"source": "A", "target": "B"}, {"source": "C", "target": "D"}]- result = topological_sort(nodes, edges)- # A must come before B, C must come before D- self.assertLess(result.index("A"), result.index("B"))- self.assertLess(result.index("C"), result.index("D"))diff --git a/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py b/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.pyindex 085dbbfb6e12..3632f054a09c 100644--- a/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py+++ b/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py@@ -15,7 +15,13 @@ from rest_framework.response import Responsefrom posthog.models.organization import OrganizationMembership-from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet, DataWarehouseSavedQuery+from products.data_modeling.backend.facade.models import (+ DAG,+ DataWarehouseManagedViewSet,+ DataWarehouseSavedQuery,+ Node,+ NodeType,+)from products.warehouse_sources.backend.tests.api._access_control_base import WarehouseAccessControlTestMixinMANAGED_VIEWSET_KIND = "revenue_analytics"@@ -244,7 +250,12 @@ class TestDataModelingJobViewSetAccessControl(WarehouseAccessControlTestMixin):@pytest.mark.eeclass TestLineageAccessControl(WarehouseAccessControlTestMixin):- """Upstream lineage read — viewer OK, none blocked."""+ """Lineage read on the merged data_modeling_nodes endpoint — viewer OK, none blocked.++ NodeViewSet is `scope_object = "INTERNAL"`, so the lineage action gates on warehouse RBAC+ itself. Without that explicit check any project member could read lineage metadata (node+ names/types/edges) — the regression this guards against.+ """resource = "warehouse_objects"@@ -256,9 +267,16 @@ class TestLineageAccessControl(WarehouseAccessControlTestMixin):query={"kind": "HogQLQuery", "query": "select 1"},created_by=self.viewer_user,)+ self.dag = DAG.objects.create(team=self.team, name="test")+ self.node = Node.objects.create(+ team=self.team,+ dag=self.dag,+ saved_query=self.saved_query,+ type=NodeType.VIEW,+ )def _url(self) -> str:- return f"/api/environments/{self.team.pk}/lineage/get_upstream/?model_id={self.saved_query.id}"+ return f"/api/environments/{self.team.pk}/data_modeling_nodes/lineage/?saved_query_id={self.saved_query.id}"def test_viewer_can_read(self):self._create_access_control(self.viewer_user, access_level="viewer")diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex f60b9a73d792..56c7b5343717 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -614,17 +614,6 @@ export const insightVariablesDestroy = async (projectId: string, id: string, opt})}-export const getLineageGetUpstreamRetrieveUrl = (projectId: string) => {- return `/api/projects/${projectId}/lineage/get_upstream/`-}--export const lineageGetUpstreamRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {- return apiMutator<void>(getLineageGetUpstreamRetrieveUrl(projectId), {- ...options,- method: 'GET',- })-}-export const getManagedViewsetsRetrieveUrl = (projectId: string, kind: 'revenue_analytics') => {return `/api/projects/${projectId}/managed_viewsets/${kind}/`}diff --git a/products/data_warehouse/manifest.tsx b/products/data_warehouse/manifest.tsxindex 0e50dbb95c81..5222f2952ce2 100644--- a/products/data_warehouse/manifest.tsx+++ b/products/data_warehouse/manifest.tsx@@ -95,7 +95,7 @@ export const manifest: ProductManifest = {'/data-warehouse/sources/:id/:tab': ({ id, tab }) => urls.dataWarehouseSource(id, tab as SourceSceneTab),},urls: {- dataOps: (tab?: string): string => (tab ? `/data-warehouse?tab=${tab}` : '/data-ops'),+ dataOps: (tab?: string): string => (tab ? `/data-ops?tab=${tab}` : '/data-ops'),models: (tab?: ModelsSceneTab): string => `/models${tab ? `/${tab}` : ''}`,nodeDetail: (id: string): string => `/models/${id}`,sources: (): string => '/data-management/sources',diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex 03934d8d1645..436175b19302 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -90,9 +90,6 @@ tools:insight-variables-update:operation: insight_variables_updateenabled: false- lineage-get-upstream-retrieve:- operation: lineage_get_upstream_retrieve- enabled: falsemanaged-viewsets-retrieve:operation: managed_viewsets_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c69136c64007..2dc022f9aa79 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58186,6 +58186,17 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsDataModelingNodesLineageRetrieveParams = {+ /**+ * Node to build lineage for.+ */+ node_id?: string;+ /**+ * Saved query to build lineage for, resolved to its node. Alternative to node_id.+ */+ saved_query_id?: string;+ };+export type EnvironmentsDataWarehouseCheckDatabaseNameRetrieveParams = {/*** Database name to check@@ -64402,6 +64413,17 @@ export namespace Schemas {search?: string;};+ export type DataModelingNodesLineageRetrieveParams = {+ /**+ * Node to build lineage for.+ */+ node_id?: string;+ /**+ * Saved query to build lineage for, resolved to its node. Alternative to node_id.+ */+ saved_query_id?: string;+ };+export type DataWarehouseCheckDatabaseNameRetrieveParams = {/*** Database name to check