Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-modeling): show metric nodes in the lineage graph (#101593)

Thiago Salvatore672139e4f331
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3c6227dfd136..c359bb776719 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5917,25 +5917,29 @@ snapshots:
products-dashboards-tiles-image-tile-modal--existing-image--light:
hash: v1.k794b7964.a6f0232a7044b1a581e4beb9105ee9c00bbed9748fdfcd1c3c1a232acfa0333c.D40_QysPPcg1v2fjLF3-6qPyFXkBZ9rrdYat6l6djGU
products-data-modeling-lineage-graph--canvas--dark:
- hash: v1.k794b7964.cb415b8a2cb9697e353db5cd11808642c38d589431a0cb95cb1ddf632160eed8.ND20cRcJ3o2QK0K6DSbHBN66H2HwvcsKMd8tgfSITaY
+ hash: v1.k794b7964.c7f0f98e0d7ea29f9bc5abcdd62b882a202d35e5b62af26f363b9c1a1323a99f.EaAJ28EK8wdDcmRGmBf0dkfiuQROQE2QUkFShyE8JgU
products-data-modeling-lineage-graph--canvas--light:
- hash: v1.k794b7964.1d83ee016eddc9d8bd726d543bacbf33e268bd68d2b05e129b327df7528e1cdd.HFjJqTinLvCWNIBGwMucxzd-BxIbGg0gRSO3-a8AlVw
+ hash: v1.k794b7964.8123e85693b4e4f1675fb7fba771dbbab268da7247ea3481872ec04653f19dbb.32Hmv5ou0iPAsy1NQubyB_RYDgYWJQWPgL1WFGNn_tQ
+ products-data-modeling-lineage-graph--dark-mode--dark:
+ hash: v1.k794b7964.7d91aad4b98dbff40bd8b3a9c5d8f600f69b892dd61b204d3563f94ca72ed4ea.D1YqS2betpNrFP_VLnnNHStCNy03Wi14pmGF3TP4ZoU
+ products-data-modeling-lineage-graph--dark-mode--light:
+ hash: v1.k794b7964.62fda4d26e38e85486f11884c2497da55df2180934b54b8e3939226406d5569a.SBCXKXcOB-DwMt8gabA5vzB3qcC4EpPyu4YVYvZwLYw
products-data-modeling-lineage-graph--empty-state--dark:
- hash: v1.k794b7964.cabd444ca94a42c8f2c651ca501ba5565ff3f3c44bfe090f859b5c6810983e48.Xx1J5ap_yYDliGXI3zpmj3oRPyZAB3xj191uH9hC7yY
+ hash: v1.k794b7964.9870c50d45ee1583472d6a98917a350892a8c2d8e29c20d17138eb68b8b52d60.yi6jAXaHCs0dh9kUIVgf6aWiVa8Btlb2b9xUQw_q4VE
products-data-modeling-lineage-graph--empty-state--light:
- hash: v1.k794b7964.7cf98856fd30a08c92b5753d92d86e5220f396bde417a6f5b78180d604e673ba.ZQWtyN1nWpt4RqBn_m2jGHm2PXC0HEaOzrTdapb-auk
+ hash: v1.k794b7964.5c6a3999ee44ecbce5db4d57dba01765e599c0c1874eab79eb80e71956d85fd7.AHbnj5yPLIkfMm6oHanSnhhQVEoBO0o5BcRYmK9DSgY
products-data-modeling-lineage-graph--full--dark:
- hash: v1.k794b7964.30f9f54de7be7442005c8c331928461a8b9f35c39a83879d512d43fc760805a7.HejGI_ne5ckT89F7KRuBZl8cHd8yxdCvDbU10jo9Zoo
+ hash: v1.k794b7964.112213e8e69bef1f6e8aab90994d6e0be0c7fcb922965b6834c1081d3d3805c0.CDKiRu_VCNR1dBVF3-l8EfsSBvtbYuQPHWFYHyXbIoI
products-data-modeling-lineage-graph--full--light:
- hash: v1.k794b7964.5dad2ad87a0457c985581810013a0fa058bb4bb8f0596932bb829bfb46a2e18c.p9m_GryZwVUwkGgah-EvQZUyu1-1-I3sN8Tlu3kSYM4
+ hash: v1.k794b7964.3d2a0a0a6ff2a27f3f8d682857757695b61970b3bfdc3f50e7508c86257aa4ad.S_I2CjkAMi3HiNyo014ZRrZHZbcDaVTQwF4718lZNws
products-data-modeling-lineage-graph--search-focus--dark:
- hash: v1.k794b7964.83557b90965eed58b573e33d1a1ecb02472e478bd44052a8bf700762e2fe999e.nfjZIFH3OJCiGVyevJLYvQqPTsMKbHNYAGNiBfgqyeE
+ hash: v1.k794b7964.b4d9053ce873f58fd7242899886a9732c0daaa37eefe75fdf02b157608030db0.ZZPDrU7QcCWBEqceYc4pO5Xh6UHGMhyDXx_fN8UpsCg
products-data-modeling-lineage-graph--search-focus--light:
- hash: v1.k794b7964.995c9c098971ab98f9f32c46e6a57b1b0e7630e093dad764a0bf68257944a7ee.Mi221xUsgkZxFcp3XfVyNrKo25mtsN8px73JtiB92hY
+ hash: v1.k794b7964.b740c4a0f8c1a657d2d87e3a2ba94082ccf74c65fe5a7fc52c1fa7804e3b900a.d2mXFF2Jwsu9Hjf3JVkojpMjZbV99slRc3Ol5S4418I
products-data-modeling-lineage-graph--single-node--dark:
- hash: v1.k794b7964.4344045fc1bada8b4f2067de9f83cdb38b5dbe14719e7b4d332c2a7689a5d8cd.NvfJs1mb9VLArjiQdsrspse5hcopmjfyz4HXvwD_MZA
+ hash: v1.k794b7964.3a7800242792b8dd49d06a252b0ccf609de5be3bf5b077e28904ca2ef46b9150.3jN6spC1a4TJhjq6LOuaDGym92gQz9Xw2KUfy0Br-D8
products-data-modeling-lineage-graph--single-node--light:
- hash: v1.k794b7964.965d630c09110769bac58d2fc162856dc5303d9a98e97995aec4cc48098581da.Gi_VbiOcJVaHaHybXL8911KOWXwBMAGtbHwCIA2HO0E
+ hash: v1.k794b7964.5186ea6f0e3e73faf479dd5e239019d6b392eedce4836210feaa8fb17cfb3774.lSXgpKEJsG5EhdpJR_oSUb0VbDLxt-W0AaBPgqdwlKM
products-data-modeling-model-downstream-summary--default--dark:
hash: v1.k794b7964.a6cec9f5859620c7f565017842d23f3852e741e775ce012643e3f9e920fe5cae.LXneGLcgtJXSQsL5y5Ru1j9lJ5bDiwov4_nwQ4EAAbk
products-data-modeling-model-downstream-summary--default--light:
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 61dfe5b0a13d..cb42aa21c114 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -96,6 +96,8 @@ generic toast would be a second one. Owned by featureFlagLogic's saveFeatureFlag
*/
const DUPLICATE_KEY_SELF_HANDLED = new Set(['saveFeatureFlag'])
+const HAS_DEPENDENTS_SELF_HANDLED = new Set(['deleteDataWarehouseSavedQuery'])
+
interface InitKeaProps {
state?: Record<string, any>
routerHistory?: any
@@ -185,6 +187,8 @@ export function initKea({
error.code === 'unique' &&
error.attr === 'key' &&
DUPLICATE_KEY_SELF_HANDLED.has(String(actionKey))
+ const isHasDependentsError =
+ error.code === 'has_dependents' && HAS_DEPENDENTS_SELF_HANDLED.has(String(actionKey))
if (!errorMessage && error.status === 404) {
errorMessage = 'URL not found'
@@ -201,7 +205,8 @@ export function initKea({
isTwoFactorError ||
isSensitiveActionError ||
isVerifiedDomainError ||
- isFeatureFlagDuplicateKey
+ isFeatureFlagDuplicateKey ||
+ isHasDependentsError
) {
// These are handled by their own dedicated toasts elsewhere.
errorMessage = null
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ac44c28e3963..74e7ce90e172 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5794,9 +5794,11 @@ const api = {
async lineage({
nodeId,
savedQueryId,
+ metricId,
}: {
nodeId?: DataModelingNode['id']
savedQueryId?: string
+ metricId?: string
}): Promise<{ nodes: DataModelingNode[]; edges: DataModelingEdge[] }> {
const params: Record<string, string> = {}
if (nodeId) {
@@ -5805,6 +5807,9 @@ const api = {
if (savedQueryId) {
params.saved_query_id = savedQueryId
}
+ if (metricId) {
+ params.metric_id = metricId
+ }
return await new ApiRequest().dataModelingNodes().withAction('lineage').withQueryString(params).get()
},
},
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.tsx
index ac8b9307ae89..236af6f4b9d6 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,4 +1,5 @@
import { useActions, useMountedLogic, useValues } from 'kea'
+import { router } from 'kea-router'
import { IconExternal, IconTarget } from '@posthog/icons'
import { LemonBanner, LemonTable, Link, Spinner, lemonToast } from '@posthog/lemon-ui'
@@ -19,6 +20,8 @@ import { urls } from 'scenes/urls'
import { DataModelingNode, DataWarehouseSavedQuery } from '~/types'
import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'
+import { LineageIssueMarker } from 'products/data_modeling/frontend/lineage/LineageNode'
+import { lineageNodeUrl } from 'products/data_modeling/frontend/lineage/lineageNodeUrl'
import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'
import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'
@@ -193,7 +196,7 @@ export function QueryInfo({ tabId, view, tabbed = false }: QueryInfoProps): JSX.
{
key: 'name',
title: 'Name',
- render: (_, { name }) => (
+ render: (_, { name, lineage_issue }) => (
<div className="flex items-center gap-1">
{name === targetView?.name && (
<Tooltip
@@ -204,6 +207,7 @@ export function QueryInfo({ tabId, view, tabbed = false }: QueryInfoProps): JSX.
</Tooltip>
)}
{name}
+ {lineage_issue && <LineageIssueMarker issue={lineage_issue} />}
</div>
),
},
@@ -214,7 +218,7 @@ export function QueryInfo({ tabId, view, tabbed = false }: QueryInfoProps): JSX.
},
{
key: 'upstream',
- title: 'Direct Upstream',
+ title: 'Direct upstream',
render: (_, node) => {
const upstreamNodes = upstream.edges
.filter((edge) => edge.target_id === node.id)
@@ -238,8 +242,11 @@ export function QueryInfo({ tabId, view, tabbed = false }: QueryInfoProps): JSX.
},
{
key: 'last_run_at',
- title: 'Last Run At',
- render: (_, { last_run_at, sync_interval }) => {
+ title: 'Last run',
+ render: (_, { type, last_run_at, sync_interval }) => {
+ if (type === 'metric') {
+ return <span className="text-secondary">&mdash;</span>
+ }
if (!last_run_at) {
return 'On demand'
}
@@ -283,9 +290,13 @@ export function QueryInfo({ tabId, view, tabbed = false }: QueryInfoProps): JSX.
}
nodeCallbacks={(node) => ({
onEdit:
- node.type !== 'table' && node.id !== currentNodeId
+ node.saved_query_id && node.id !== currentNodeId
? () => void openInEditor(node)
: undefined,
+ onClick:
+ node.type === 'metric'
+ ? () => router.actions.push(lineageNodeUrl(node))
+ : undefined,
})}
/>
</div>
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
index 425ddef7ab63..0370c776addd 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
@@ -1,9 +1,11 @@
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
// Imported from the source module rather than the `@posthog/lemon-ui` barrel so the spy replaces
// `.error` on the same `lemonToast` singleton the logic calls at runtime.
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -17,6 +19,14 @@ const rejection = {
attr: null,
}
+const deleteRefusal = {
+ type: 'validation_error',
+ code: 'has_dependents',
+ detail: "Can't delete orders yet. These read from it: orders_daily (view). Update or delete them first.",
+ attr: null,
+ extra: { node_id: 'node-7' },
+}
+
describe('dataWarehouseViewsLogic', () => {
let logic: ReturnType<typeof dataWarehouseViewsLogic.build>
let databaseLogic: ReturnType<typeof databaseTableListLogic.build>
@@ -118,6 +128,29 @@ describe('dataWarehouseViewsLogic', () => {
expect(logic.values.dataWarehouseSavedQueries).toEqual([])
})
+ // Regression: the blocked node's id arrives on the response body's `extra`, which the error
+ // object keeps on `data`. Read off the error's root it was always undefined, so a refused
+ // delete offered no way to see what reads the view.
+ it('points a refused delete at the lineage of the node that blocked it', async () => {
+ const toastErrorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => ({ id: 'x' }) as any)
+ useMocks({
+ delete: { '/api/environments/:team_id/warehouse_saved_queries/:id/': [400, deleteRefusal] },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.deleteDataWarehouseSavedQuery('view-blocked')
+ }).toDispatchActions(['deleteDataWarehouseSavedQueryFailure'])
+
+ const refusalToast = toastErrorSpy.mock.calls.find(([message]) => message === deleteRefusal.detail)?.[1] as
+ | { button?: { label: string; action: () => void } }
+ | undefined
+ expect(refusalToast?.button?.label).toBe('Open lineage')
+
+ refusalToast?.button?.action()
+ expect(router.values.location.pathname).toContain(urls.nodeDetail('node-7', 'lineage'))
+ toastErrorSpy.mockRestore()
+ })
+
// Regression: a freshly materialized view showed as a plain view in the sidebar until a manual
// refresh because is_materialized flips asynchronously and the list was fetched only once. The
// poll must keep reloading until it settles, then stop (not loop forever).
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
index 4c763ec023ab..c0f2a142ec0b 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
@@ -1,5 +1,6 @@
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -7,6 +8,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api, { ApiConfig } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import {
@@ -627,6 +629,19 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
lemonToast.error(errorObject?.detail || 'Failed to update view')
actions.loadDataWarehouseSavedQueries()
},
+ deleteDataWarehouseSavedQueryFailure: ({ errorObject }) => {
+ // The blocked node's id rides on the response body's `extra`, and ApiError keeps the
+ // parsed body on `data` instead of lifting that key onto itself.
+ const nodeId = errorObject?.data?.extra?.node_id
+ lemonToast.error(errorObject?.detail || 'Failed to delete view', {
+ button: nodeId
+ ? {
+ label: 'Open lineage',
+ action: () => router.actions.push(urls.nodeDetail(nodeId, 'lineage')),
+ }
+ : undefined,
+ })
+ },
deleteDataWarehouseSavedQuerySuccess: () => {
lemonToast.success('View deleted')
// The delete loader already filters the view out of the list, so the sidebar row leaves
diff --git a/frontend/src/scenes/models/NodeDetailHeader.tsx b/frontend/src/scenes/models/NodeDetailHeader.tsx
index 5fcbfd2d91eb..b45c33e7084c 100644
--- a/frontend/src/scenes/models/NodeDetailHeader.tsx
+++ b/frontend/src/scenes/models/NodeDetailHeader.tsx
@@ -40,11 +40,13 @@ export function NodeDetailHeader({ id }: { id: string }): JSX.Element {
: node.type
: node?.type
const typeTag = nodeType ? NODE_TYPE_TAG_SETTINGS[nodeType] : null
- const canEdit = userHasAccess(
- AccessControlResourceType.WarehouseObjects,
- AccessControlLevel.Editor,
- savedQuery?.user_access_level
- )
+ const canEdit =
+ node?.type !== 'metric' &&
+ userHasAccess(
+ AccessControlResourceType.WarehouseObjects,
+ AccessControlLevel.Editor,
+ savedQuery?.user_access_level
+ )
return (
<>
diff --git a/frontend/src/scenes/models/modelsLineageLogic.ts b/frontend/src/scenes/models/modelsLineageLogic.ts
index 45d46e859b60..47a87962f708 100644
--- a/frontend/src/scenes/models/modelsLineageLogic.ts
+++ b/frontend/src/scenes/models/modelsLineageLogic.ts
@@ -2,6 +2,7 @@ import { MakeLogicType, actions, connect, kea, listeners, path, reducers, select
import { DataModelingEdge, DataModelingNode, DataModelingNodeType } from '~/types'
+import { NodeTypeEnumApi } from 'products/data_modeling/frontend/generated/api.schemas'
import { lineageDataLogic } from 'products/data_modeling/frontend/lineage/lineageDataLogic'
import {
ParsedLineageSearch,
@@ -11,7 +12,7 @@ import {
parseLineageSearch,
} from 'products/data_modeling/frontend/lineage/lineageSearch'
-export const LINEAGE_FILTER_TYPES: DataModelingNodeType[] = ['table', 'view', 'matview', 'endpoint']
+export const LINEAGE_FILTER_TYPES: DataModelingNodeType[] = Object.values(NodeTypeEnumApi)
export interface modelsLineageLogicValues {
nodes: DataModelingNode[] // lineageDataLogic
diff --git a/frontend/src/scenes/models/nodeDetailSceneLogic.test.ts b/frontend/src/scenes/models/nodeDetailSceneLogic.test.ts
index cdd60811b0ec..5e5936d35962 100644
--- a/frontend/src/scenes/models/nodeDetailSceneLogic.test.ts
+++ b/frontend/src/scenes/models/nodeDetailSceneLogic.test.ts
@@ -30,7 +30,7 @@ function buildNode(type: DataModelingNodeType, overrides: Partial<DataModelingNo
updated_at: '2024-01-01T00:00:00Z',
upstream_count: 0,
downstream_count: 0,
- saved_query_id: type === 'table' ? undefined : SAVED_QUERY_ID,
+ saved_query_id: type === 'table' || type === 'metric' ? undefined : SAVED_QUERY_ID,
...overrides,
}
}
@@ -111,12 +111,13 @@ describe('nodeDetailSceneLogic', () => {
expect(logic.values.currentTab).toEqual(expectedTab)
})
- it('offers a table only its lineage, so the scene renders no tab bar', async () => {
- node = buildNode('table')
+ it.each(['table', 'metric'] as const)('offers a %s only its lineage, and opens on it', async (type) => {
+ node = buildNode(type)
await mountScene(urls.nodeDetail(NODE_ID))
expect(logic.values.availableTabs).toEqual(['lineage'])
+ expect(logic.values.currentTab).toEqual('lineage')
})
it('shows ten columns on each query page', async () => {
diff --git a/frontend/src/scenes/models/nodeDetailSceneLogic.ts b/frontend/src/scenes/models/nodeDetailSceneLogic.ts
index 0474f3333356..b3aa1d2dfadf 100644
--- a/frontend/src/scenes/models/nodeDetailSceneLogic.ts
+++ b/frontend/src/scenes/models/nodeDetailSceneLogic.ts
@@ -11,7 +11,9 @@ import { urls } from 'scenes/urls'
import { Breadcrumb, DataModelingEdge, DataModelingNode, DataWarehouseSavedQuery } from '~/types'
-import type { DataModelingNodeType } from '../../types'
+import { MATERIALIZING_TYPES } from 'products/data_modeling/frontend/freshness'
+
+import type { NodeTypeEnumApi } from '../../../../products/data_modeling/frontend/generated/api.schemas'
export const NODE_DETAIL_SCENE_TABS = ['query', 'lineage', 'materialization', 'tests', 'history'] as const
export type NodeDetailSceneTab = (typeof NODE_DETAIL_SCENE_TABS)[number]
@@ -50,7 +52,7 @@ export interface nodeDetailSceneLogicValues {
lineageModalOpen: boolean
node: DataModelingNode | null
nodeLoading: boolean
- nodeType: DataModelingNodeType | null
+ nodeType: NodeTypeEnumApi | null
savedQuery: DataWarehouseSavedQuery | null
savedQueryError: boolean
savedQueryLoading: boolean
@@ -170,7 +172,7 @@ export interface nodeDetailSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
breadcrumbs: (node: DataModelingNode | null) => Breadcrumb[]
- nodeType: (node: DataModelingNode | null) => DataModelingNodeType | null
+ nodeType: (node: DataModelingNode | null) => NodeTypeEnumApi | null
sceneResolved: (node: DataModelingNode | null, savedQuerySettled: boolean) => boolean
availableTabs: (
node: DataModelingNode | null,
@@ -331,7 +333,7 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([
return []
}
const tabs: NodeDetailSceneTab[] = []
- if (node.type !== 'table') {
+ if (node.saved_query_id) {
tabs.push('query')
}
tabs.push('lineage')
@@ -361,13 +363,13 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([
if (savedQuery) {
return !!savedQuery.is_materialized
}
- return node?.type === 'matview' || node?.type === 'endpoint'
+ return MATERIALIZING_TYPES.has(node?.type ?? 'table')
},
],
defaultTab: [
(s) => [s.node, s.isMaterialized],
(node: DataModelingNode | null, isMaterialized: boolean): NodeDetailSceneTab => {
- if (node?.type === 'table') {
+ if (!node?.saved_query_id) {
return 'lineage'
}
// An endpoint's saved query is always materialized, but its materialization panel
diff --git a/frontend/src/scenes/models/tabs/ModelsLineageTab.tsx b/frontend/src/scenes/models/tabs/ModelsLineageTab.tsx
index f4b0ffd225fa..0d60339c5f1c 100644
--- a/frontend/src/scenes/models/tabs/ModelsLineageTab.tsx
+++ b/frontend/src/scenes/models/tabs/ModelsLineageTab.tsx
@@ -7,11 +7,11 @@ import { LemonButton, LemonInput, Tooltip } from '@posthog/lemon-ui'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect'
import { pluralize } from 'lib/utils/strings'
-import { urls } from 'scenes/urls'
import { DataModelingNodeType } from '~/types'
import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'
+import { lineageNodeUrl } from 'products/data_modeling/frontend/lineage/lineageNodeUrl'
import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'
import { NodeTypeLegend } from 'products/data_modeling/frontend/lineage/NodeTypeLegend'
import { SEARCH_SYNTAX_HELP } from 'products/data_modeling/frontend/lineage/SearchSyntaxHelp'
@@ -102,7 +102,7 @@ export function ModelsLineageTab(): JSX.Element {
isHighlighted: highlightedNodeIds.has(node.id),
isRunning: node.last_run_status === 'Running',
})}
- onNodeClick={(node) => router.actions.push(urls.nodeDetail(node.id))}
+ onNodeClick={(node) => router.actions.push(lineageNodeUrl(node))}
panelPosition="bottom-left"
panels={<NodeTypeLegend collapsed={legendCollapsed} onToggleCollapse={toggleLegendCollapsed} />}
/>
diff --git a/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx b/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx
index e40dab2deb87..4bd26c73d7f8 100644
--- a/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx
+++ b/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx
@@ -12,6 +12,7 @@ import { urls } from 'scenes/urls'
import { DataModelingJobStatus, DataModelingNode } from '~/types'
import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'
+import { lineageNodeUrl } from 'products/data_modeling/frontend/lineage/lineageNodeUrl'
import { nodeDetailSceneLogic } from '../nodeDetailSceneLogic'
@@ -43,7 +44,7 @@ export function NodeDetailLineage({ id }: { id: string }): JSX.Element {
}, [lineageGraph, effectiveLastRunAt, effectiveLastRunStatus])
const openNode = (node: DataModelingNode): void => {
- router.actions.push(urls.nodeDetail(node.id, 'lineage'))
+ router.actions.push(lineageNodeUrl(node, 'lineage'))
}
if (lineageGraphLoading) {
@@ -62,7 +63,7 @@ export function NodeDetailLineage({ id }: { id: string }): JSX.Element {
)
}
- if (nodes.length <= 1) {
+ if (nodes.length <= 1 && !nodes[0]?.lineage_issue) {
return (
<div className="flex min-h-64 flex-col items-center justify-center gap-3 rounded border bg-bg-light p-6 text-center">
<div className="max-w-120">
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index e5b1e9d56cf4..3987ac392e09 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -83,7 +83,12 @@ import { QueryContext } from '~/queries/types'
import { AlertType } from 'products/alerts/frontend/types'
import type { CohortRealtimeReadinessApi } from 'products/cohorts/frontend/generated/api.schemas'
-import type { NodeApiSuspended, NodeEndpointApi } from 'products/data_modeling/frontend/generated/api.schemas'
+import {
+ type LineageIssueApi,
+ type NodeApiSuspended,
+ type NodeEndpointApi,
+ NodeTypeEnumApi,
+} from 'products/data_modeling/frontend/generated/api.schemas'
import type {
DataWarehouseSavedQueryApi,
DataWarehouseSavedQueryApiSuspended,
@@ -6288,7 +6293,7 @@ export interface DataWarehouseSavedQueryDependencies {
downstream_count: number
}
-export type DataModelingNodeType = 'table' | 'view' | 'matview' | 'endpoint'
+export type DataModelingNodeType = NodeTypeEnumApi
export interface DataModelingNode {
/** UUID */
@@ -6301,6 +6306,9 @@ export interface DataModelingNode {
/** Human-readable DAG name */
dag_name?: string
saved_query_id?: string
+ /** UUID of the data catalog metric a metric node stands for */
+ metric_id?: string | null
+ lineage_issue?: LineageIssueApi | null
created_at: string
updated_at: string
upstream_count: number
diff --git a/products/data_modeling/frontend/freshness.ts b/products/data_modeling/frontend/freshness.ts
index 18d7d14c5415..bad97bbdc8b5 100644
--- a/products/data_modeling/frontend/freshness.ts
+++ b/products/data_modeling/frontend/freshness.ts
@@ -1,4 +1,4 @@
-import { DataModelingNode, DataModelingSyncInterval } from '~/types'
+import { DataModelingNode, DataModelingNodeType, DataModelingSyncInterval } from '~/types'
export const SYNC_INTERVAL_SECONDS: Record<DataModelingSyncInterval, number> = {
'15min': 900,
@@ -12,7 +12,7 @@ export const SYNC_INTERVAL_SECONDS: Record<DataModelingSyncInterval, number> = {
}
/** A plain view runs its query on read, so it stores nothing that can go stale. */
-const MATERIALIZING_TYPES = new Set(['matview', 'endpoint'])
+export const MATERIALIZING_TYPES = new Set<DataModelingNodeType>(['matview', 'endpoint'])
/**
* Age climbs to a full interval between every pair of runs, so a one-interval bar would
diff --git a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
index d28b75d09752..e5fbc620c34e 100644
--- a/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
+++ b/products/data_modeling/frontend/lineage/LineageGraph.stories.tsx
@@ -45,8 +45,22 @@ const GRAPH_NODES: DataModelingNode[] = [
sync_interval: '1hour',
}),
mockNode({ id: '4', name: 'monthly_report', type: 'view' }),
+ mockNode({ id: '5', name: 'weekly_active_accounts', type: 'metric', metric_id: 'metric-1' }),
+ mockNode({
+ id: '6',
+ name: 'monthly_recurring_revenue',
+ type: 'metric',
+ metric_id: 'metric-2',
+ lineage_issue: { kind: 'unresolved', detail: 'legacy_orders', at: '2024-01-15T10:30:00Z' },
+ }),
+]
+const GRAPH_EDGES: DataModelingEdge[] = [
+ mockEdge('e1', '1', '3'),
+ mockEdge('e2', '2', '3'),
+ mockEdge('e3', '3', '4'),
+ mockEdge('e4', '3', '5'),
+ mockEdge('e5', '4', '6'),
]
-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> = {
@@ -61,7 +75,7 @@ const meta: Meta<typeof LineageGraph> = {
},
decorators: [
(StoryFn) => (
- <div className="h-[500px]">
+ <div className="h-[500px] w-[1200px]">
<StoryFn />
</div>
),
@@ -124,3 +138,10 @@ export const SearchFocus: Story = {
}
},
}
+
+export const DarkMode: Story = {
+ render: () => (
+ <LineageGraph nodes={GRAPH_NODES} edges={GRAPH_EDGES} currentNodeId="5" variant="full" showControls />
+ ),
+ globals: { theme: 'dark' },
+}
diff --git a/products/data_modeling/frontend/lineage/LineageGraph.tsx b/products/data_modeling/frontend/lineage/LineageGraph.tsx
index 262c5b59b1d6..25bbf00f707e 100644
--- a/products/data_modeling/frontend/lineage/LineageGraph.tsx
+++ b/products/data_modeling/frontend/lineage/LineageGraph.tsx
@@ -116,6 +116,9 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {
nodeTypes={LINEAGE_NODE_TYPES}
nodesDraggable={false}
nodesConnectable={false}
+ // The card inside each node is the focus target and carries the key handler. A focusable
+ // wrapper would add a second tab stop per node that only selects and never navigates.
+ nodesFocusable={false}
fitView
fitViewOptions={props.fitViewOptions}
minZoom={0.1}
diff --git a/products/data_modeling/frontend/lineage/LineageNode.tsx b/products/data_modeling/frontend/lineage/LineageNode.tsx
index 68ba757743a6..3c6189ff09b4 100644
--- a/products/data_modeling/frontend/lineage/LineageNode.tsx
+++ b/products/data_modeling/frontend/lineage/LineageNode.tsx
@@ -10,6 +10,7 @@ import {
IconPlay,
IconPlayFilled,
IconTarget,
+ IconWarning,
} from '@posthog/icons'
import { LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'
@@ -17,6 +18,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { DataModelingNode } from '~/types'
+import { MATERIALIZING_TYPES } from 'products/data_modeling/frontend/freshness'
import { servingSuspension } from 'products/data_modeling/frontend/suspension'
import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'
@@ -39,6 +41,7 @@ export type LineageNodeShape = Pick<
| 'downstream_count'
| 'user_tag'
| 'suspended'
+ | 'lineage_issue'
>
export interface LineageNodeState {
@@ -67,6 +70,25 @@ export interface LineageNodeData extends Record<string, unknown> {
handles: NodeHandle[]
}
+export function lineageIssueMessage(issue: NonNullable<DataModelingNode['lineage_issue']>): string {
+ if (issue.kind === 'sync_failed') {
+ return `Lineage could not be refreshed: ${issue.detail}`
+ }
+ return `Couldn't find ${issue.detail}. This may read a table that was renamed or removed.`
+}
+
+/** The warning mark drawn on a lineage node, and repeated beside the name in the editor's table. */
+export function LineageIssueMarker({ issue }: { issue: NonNullable<DataModelingNode['lineage_issue']> }): JSX.Element {
+ const message = lineageIssueMessage(issue)
+ return (
+ <Tooltip title={message}>
+ <span className="flex items-center" role="img" aria-label={message}>
+ <IconWarning className="text-warning text-sm" />
+ </span>
+ </Tooltip>
+ )
+}
+
function StatusDot({ node }: { node: LineageNodeShape }): JSX.Element {
const suspension = servingSuspension(node.suspended)
if (suspension) {
@@ -171,7 +193,7 @@ 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 showMetadata = MATERIALIZING_TYPES.has(node.type)
const showRunArrows = variant === 'canvas' && isHovered && !state.isRunning
const { color } = NODE_TYPE_TAG_SETTINGS[node.type]
@@ -189,6 +211,21 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
fn?.()
}
+ const handleKeyDown = (e: React.KeyboardEvent): void => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ callbacks.onClick?.()
+ }
+ }
+
+ const destination = node.type === 'metric' ? 'the metric' : 'the model'
+ const ariaLabel = [
+ `${node.name}, ${NODE_TYPE_TAG_SETTINGS[node.type].label.toLowerCase()}, opens ${destination}`,
+ node.lineage_issue && lineageIssueMessage(node.lineage_issue),
+ ]
+ .filter(Boolean)
+ .join('. ')
+
return (
<Tooltip title={node.name} delayMs={500}>
<div
@@ -197,6 +234,7 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
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',
+ node.lineage_issue && !state.isRunning && !state.isHighlighted && 'border-warning',
state.isCurrent && 'border-2'
)}
// eslint-disable-next-line react/forbid-dom-props
@@ -206,6 +244,10 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onClick={callbacks.onClick}
+ onKeyDown={callbacks.onClick ? handleKeyDown : undefined}
+ role={callbacks.onClick ? 'button' : undefined}
+ tabIndex={callbacks.onClick ? 0 : undefined}
+ aria-label={callbacks.onClick ? ariaLabel : undefined}
>
{data.handles.map((handle) => (
<Handle
@@ -242,6 +284,7 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
</Tooltip>
)}
<NodeTypeTag type={node.type} />
+ {node.lineage_issue && <LineageIssueMarker issue={node.lineage_issue} />}
</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">
@@ -259,7 +302,7 @@ export function LineageNode({ data }: { data: LineageNodeData }): JSX.Element {
onClick={stop(callbacks.onEdit)}
/>
)}
- {callbacks.onMaterialize && (node.type === 'matview' || node.type === 'endpoint') && (
+ {callbacks.onMaterialize && MATERIALIZING_TYPES.has(node.type) && (
<Tooltip title={state.isRunning ? null : 'Run this node'}>
<LemonButton
size="xsmall"
diff --git a/products/data_modeling/frontend/lineage/NodeTypeLegend.tsx b/products/data_modeling/frontend/lineage/NodeTypeLegend.tsx
index 17370a6184f3..ac09970498f5 100644
--- a/products/data_modeling/frontend/lineage/NodeTypeLegend.tsx
+++ b/products/data_modeling/frontend/lineage/NodeTypeLegend.tsx
@@ -9,6 +9,7 @@ const LEGEND_ENTRIES: { type: DataModelingNodeType; description: string }[] = [
{ type: 'view', description: 'A virtual table based on a SQL query' },
{ type: 'matview', description: 'A persisted view with improved query performance' },
{ type: 'endpoint', description: 'A materialized endpoint for API access' },
+ { type: 'metric', description: 'A governed metric from the data catalog' },
]
export interface NodeTypeLegendProps {
diff --git a/products/data_modeling/frontend/lineage/lineageNodeUrl.test.ts b/products/data_modeling/frontend/lineage/lineageNodeUrl.test.ts
new file mode 100644
index 000000000000..cd903a5103cd
--- /dev/null
+++ b/products/data_modeling/frontend/lineage/lineageNodeUrl.test.ts
@@ -0,0 +1,13 @@
+import { lineageNodeUrl } from './lineageNodeUrl'
+
+describe('lineageNodeUrl', () => {
+ it('sends a metric node to its catalog page, keyed by name', () => {
+ expect(lineageNodeUrl({ id: 'node-1', name: 'weekly_active_accounts', type: 'metric' })).toEqual(
+ '/data-catalog/metrics/weekly_active_accounts'
+ )
+ })
+
+ it.each(['table', 'view', 'matview', 'endpoint'] as const)('sends a %s node to its node page', (type) => {
+ expect(lineageNodeUrl({ id: 'node-1', name: 'orders', type }, 'lineage')).toEqual('/models/node-1/lineage')
+ })
+})
diff --git a/products/data_modeling/frontend/lineage/lineageNodeUrl.ts b/products/data_modeling/frontend/lineage/lineageNodeUrl.ts
new file mode 100644
index 000000000000..011c4b196d3b
--- /dev/null
+++ b/products/data_modeling/frontend/lineage/lineageNodeUrl.ts
@@ -0,0 +1,13 @@
+import { urls } from 'scenes/urls'
+
+import { DataModelingNode } from '~/types'
+
+type NodeDetailTab = Parameters<typeof urls.nodeDetail>[1]
+
+/** Where clicking a lineage node takes you: a metric to its catalog page, anything else to its node. */
+export function lineageNodeUrl(node: Pick<DataModelingNode, 'id' | 'name' | 'type'>, tab?: NodeDetailTab): string {
+ if (node.type === 'metric') {
+ return urls.dataCatalogMetric(node.name)
+ }
+ return urls.nodeDetail(node.id, tab)
+}
diff --git a/products/data_modeling/frontend/lineage/nodeStyles.test.ts b/products/data_modeling/frontend/lineage/nodeStyles.test.ts
index a077bcb972d4..e3ca14a025ec 100644
--- a/products/data_modeling/frontend/lineage/nodeStyles.test.ts
+++ b/products/data_modeling/frontend/lineage/nodeStyles.test.ts
@@ -1,6 +1,17 @@
-import { STATUS_MARK_BACKGROUNDS, STATUS_TAG_SETTINGS, statusBackgroundClass } from './nodeStyles'
+import { NodeTypeEnumApi } from 'products/data_modeling/frontend/generated/api.schemas'
+
+import {
+ NODE_TYPE_TAG_SETTINGS,
+ STATUS_MARK_BACKGROUNDS,
+ STATUS_TAG_SETTINGS,
+ statusBackgroundClass,
+} from './nodeStyles'
describe('nodeStyles', () => {
+ it('gives every node type the API can return a label and a color', () => {
+ expect(Object.keys(NODE_TYPE_TAG_SETTINGS).sort()).toEqual(Object.values(NodeTypeEnumApi).sort())
+ })
+
describe('statusBackgroundClass', () => {
it.each([
['Completed', 'bg-success'],
diff --git a/products/data_modeling/frontend/lineage/nodeStyles.ts b/products/data_modeling/frontend/lineage/nodeStyles.ts
index ded9427a60a3..c8ca67c73316 100644
--- a/products/data_modeling/frontend/lineage/nodeStyles.ts
+++ b/products/data_modeling/frontend/lineage/nodeStyles.ts
@@ -10,6 +10,7 @@ export const NODE_TYPE_TAG_SETTINGS: Record<
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)' },
+ metric: { label: 'Metric', type: 'info', color: 'var(--blue)' },
}
export const STATUS_TAG_SETTINGS: Record<string, LemonTagType> = {
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
index 827136db47b4..05c864e2bd62 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
@@ -42,6 +42,9 @@ class _CancelTarget:
workflow_run_id: str | None
+HAS_DEPENDENTS_CODE = "has_dependents"
+
+
class DependentsValidationError(serializers.ValidationError):
"""A refused delete, carrying the blocked view's node id for a link to its lineage.
@@ -50,7 +53,7 @@ class DependentsValidationError(serializers.ValidationError):
"""
def __init__(self, detail: str, node_id: str | None = None) -> None:
- super().__init__(detail)
+ super().__init__(detail, code=HAS_DEPENDENTS_CODE)
if node_id:
self.extra = {"node_id": node_id}
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index 83f067ea3b30..16ad2ab098cc 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -568,6 +568,7 @@ class TestSavedQuery(APIBaseTest):
"Can't delete accounts_view yet. These read from it: weekly_active_accounts (metric). "
"Update or delete them first."
)
+ assert body["code"] == "has_dependents"
assert body["extra"] == {"node_id": str(view_node.id)}
view.refresh_from_db()
assert view.deleted is not True