: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-catalog): lineage tab on the metric page (#101595)
Thiago Salvatored1a3b3aa98df
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c2f38b2864c5..9bd7608d4fe6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5928,6 +5928,34 @@ snapshots:hash: v1.k794b7964.20c015c66f2a8df4b13180fe46f6ad7d23c008014120d2333305338bfd473eaa.jN29SgNagj6AhlrI5b50krX4pQlMrOA5O7iYLuVMai4products-dashboards-tiles-image-tile-modal--existing-image--light:hash: v1.k794b7964.a6f0232a7044b1a581e4beb9105ee9c00bbed9748fdfcd1c3c1a232acfa0333c.D40_QysPPcg1v2fjLF3-6qPyFXkBZ9rrdYat6l6djGU+ products-data-catalog-metric-lineage--being-prepared--dark:+ hash: v1.k794b7964.9b3dd08fa1426e0715daefdf347f20d3e251483c787dd3a9f3ad02fca88ae00b.N85-92zGL68U5fyXpoWHYbbTGLRVTOw42k7LxJ3HZHw+ products-data-catalog-metric-lineage--being-prepared--light:+ hash: v1.k794b7964.1d9442bec79157ff586c1e1baefa06a6af93faf873f16f0b1d145aad2f94b330.AkvoCIqxZnaGvJ-bwA5Wxrs6uAmv4WJOugLfPcxxTvo+ products-data-catalog-metric-lineage--graph--dark:+ hash: v1.k794b7964.28436b8e236653de8ff4f9ed90b223616a0f74c5fa0768eaa89cb8d2efabbc4c.rU1yb72_zYisx__hS1s9oPU1bvoHE5VRsK_LlGubsy8+ products-data-catalog-metric-lineage--graph--light:+ hash: v1.k794b7964.fd9cb0d75def206101cdbe40b202ce816664338aadc3cedd55d8e0c04988fbb2.pZoiwDKsy0mK_UUcYDxBU4XXhG4zBy30CPbNAREX-0o+ products-data-catalog-metric-lineage--lineage-issue--dark:+ hash: v1.k794b7964.860d27733af3926c8bb4ebcbc5a687b149ab482f097e67af410450ecc90d21d9.n7Othr89yht04LnSFImmVTHCL4HFXOOY8uZMv8Tw8yw+ products-data-catalog-metric-lineage--lineage-issue--light:+ hash: v1.k794b7964.6bbe1a96007edab5e52972199fd7ba58eb0931e882094e407e2021884ce7c389.vC05kGuAQq00QGnj-QKpGRfLXCETP75jDc00YDpn-Nw+ products-data-catalog-metric-lineage--load-failed--dark:+ hash: v1.k794b7964.dbaf9c756de48bf854da4200cd90a2a6f9eb1c9dd579c41313ea106fc952d014.EJZNZnR7SS9VqjxWGF2ewZNdCXKG7n3iCC_muZiwZng+ products-data-catalog-metric-lineage--load-failed--light:+ hash: v1.k794b7964.1b9c3b1720e0444a2f33b4ba6dc972f6a56a114c94be10cc77fa455b8441fbca.LUvQPwM50s6A-ZDh32zDhqhWWm5KAPgEFK2qa8ffmWs+ products-data-catalog-metric-lineage--loading--dark:+ hash: v1.k794b7964.10e5f42c7d9feef174fbf84585f42b3c023795a750dbbea10febeec15966f0d9.WQdI3QUiM3MPqu2jUswGuIkHtAjQlM-XV8dAV1Qpbmg+ products-data-catalog-metric-lineage--loading--light:+ hash: v1.k794b7964.5290922c579080221a18b00e7855f14d4fd4bdba8158fcb2acb0dcc1fcd1fb6c.N5PeHfKZdzMTWuAgku68dGntKgBb3tE0dqZbO6orPrY+ products-data-catalog-metric-lineage--no-definition--dark:+ hash: v1.k794b7964.0a67016ff06498b8f16e83dcbd01d03ced850f02935d9cfc555c5d321a6dc21e.SYouGVS4FM4aPQFE51xlJG_1LPN79L4zsp_xwt4mRJI+ products-data-catalog-metric-lineage--no-definition--light:+ hash: v1.k794b7964.e7ff182b23bf3b58fd4d549d50eecdd66b463ae280613b216e5f42f274cc54f5.xjRrews6K2nCNVBsfBUcesCDttL2Jw9qJ52C6IwHiQc+ products-data-catalog-metric-lineage--no-warehouse-access--dark:+ hash: v1.k794b7964.813ee6fa8c0a5d7f47883c875a17acf297b9862e9e42414ced9f0a7add680faa.2Zjf5z5DUlOijGyDJtgDa1_D52Th6qvsI1Am1FslNI0+ products-data-catalog-metric-lineage--no-warehouse-access--light:+ hash: v1.k794b7964.d24fc4898fd69d316912802e328f3a6e2e94cee4cf106d8893597da97dbf73af.UOfef0QXupztuN6lJ1r5vYH5FiYFRHx_eqHRlY-34CQproducts-data-modeling-lineage-graph--canvas--dark:hash: v1.k794b7964.c7f0f98e0d7ea29f9bc5abcdd62b882a202d35e5b62af26f363b9c1a1323a99f.EaAJ28EK8wdDcmRGmBf0dkfiuQROQE2QUkFShyE8JgUproducts-data-modeling-lineage-graph--canvas--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex cb42aa21c114..ea985a3aa3dd 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -71,6 +71,7 @@ const ERROR_FILTER_ALLOW_LIST = ['loadCoreMemory', // The PostHog AI memory setting renders its own load error banner with a retry'updateCoreMemory', // maxSettingsLogic's updateCoreMemoryFailure listener shows its own save-failure toast'loadSessionEventDeltas', // The experiment watch shelf renders the refusal, or the failure with a retry+ 'loadLineage', // MetricLineagePanel renders every failure class itself, including the not-ready 404]/*@@ -88,6 +89,7 @@ purpose, so each caller that degrades has to name itself here, next to the toast*/const NOT_FOUND_SELF_HANDLED = new Set(['loadRecordingMeta', // The player renders RecordingNotFound off sessionRecordingMetaLogic's isNotFound+ 'loadLineage', // A metric has no lineage node until the sync task runs; the panel says so and retries])/*diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 1555881d8f9d..0fd85c654bc2 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -1222,8 +1222,8 @@ export const productUrls = {`/dashboard/${id}/subscriptions/${subscriptionId}`,sharedDashboard: (shareToken: string): string => `/shared_dashboard/${shareToken}`,dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,- dataCatalogMetric: (name: string, tab?: 'definition' | 'tests'): string =>- `/data-catalog/metrics/${name}${tab === 'tests' ? '?tab=tests' : ''}`,+ dataCatalogMetric: (name: string, tab?: 'definition' | 'tests' | 'lineage'): string =>+ `/data-catalog/metrics/${name}${tab && tab !== 'definition' ? `?tab=${tab}` : ''}`,dataOps: (tab?: string): string => {const params = new URLSearchParams()if (tab) {diff --git a/products/data_catalog/frontend/DataCatalogMetricScene.tsx b/products/data_catalog/frontend/DataCatalogMetricScene.tsxindex ea9c9d55ce7d..6ee707af6b65 100644--- a/products/data_catalog/frontend/DataCatalogMetricScene.tsx+++ b/products/data_catalog/frontend/DataCatalogMetricScene.tsx@@ -54,6 +54,7 @@ import {MetricSceneTab,} from './dataCatalogMetricSceneLogic'import type { DataCatalogMetricApi } from './generated/api.schemas'+import { MetricLineageTab } from './MetricLineageTab'import { MetricTestsTab } from './tabs/MetricTestsTab'import { MetricTestsTabLabel } from './tabs/MetricTestsTabLabel'@@ -363,6 +364,7 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProponChange={setActiveTab}tabs={[{ key: 'definition', label: 'Definition' },+ { key: 'lineage', label: 'Lineage' },metricChecksEnabled && {key: 'tests',label: <MetricTestsTabLabel metricId={metric.id} />,@@ -396,6 +398,12 @@ export function DataCatalogMetricScene({ name }: DataCatalogMetricSceneLogicProp</div>)}+ {mountedTabs.includes('lineage') && (+ <div className={tabPanelClassName('lineage', activeTab)}>+ <MetricLineageTab metric={metric} />+ </div>+ )}+{metricChecksEnabled && mountedTabs.includes('tests') && (<div className={tabPanelClassName('tests', activeTab)}><MetricTestsTab />@@ -452,9 +460,6 @@ function MetricMetadata({metric: DataCatalogMetricApionSaveUnit: (unit: string) => void}): JSX.Element {- const referencedTables = Array.isArray(metric.referenced_table_names)- ? (metric.referenced_table_names as string[])- : []const showProvenance = metric.created_source === 'ai_generated'return (@@ -471,18 +476,6 @@ function MetricMetadata({label="Last run"value={metric.last_run_at ? <TZLabel time={metric.last_run_at} /> : 'Never'}/>- {referencedTables.length > 0 && (- <div className="flex flex-col gap-1">- <span className="text-secondary">Referenced tables</span>- <div className="flex flex-wrap gap-1">- {referencedTables.map((table) => (- <LemonTag key={table} type="option">- {table}- </LemonTag>- ))}- </div>- </div>- )}</div>{showProvenance && (<LemonCollapsediff --git a/products/data_catalog/frontend/MetricLineagePanel.stories.tsx b/products/data_catalog/frontend/MetricLineagePanel.stories.tsxnew file mode 100644index 000000000000..90da2a4721ce--- /dev/null+++ b/products/data_catalog/frontend/MetricLineagePanel.stories.tsx@@ -0,0 +1,117 @@+import type { Meta, StoryObj } from '@storybook/react'++import { DataModelingEdge, DataModelingNode } from '~/types'++import { DataCatalogMetricApi } from './generated/api.schemas'+import { MetricLineagePanel, MetricLineagePanelProps } from './MetricLineagePanel'++function metric(overrides: Partial<DataCatalogMetricApi> = {}): DataCatalogMetricApi {+ return {+ id: 'metric-1',+ name: 'weekly_active_accounts',+ display_name: 'Weekly active accounts',+ description: 'Accounts with at least one event in the last 7 days',+ definition: { kind: 'HogQLQuery', query: 'select count() from events' },+ definition_kind: 'HogQLQuery',+ referenced_table_names: ['events'],+ status: 'approved',+ is_drifted: false,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ ...overrides,+ } as DataCatalogMetricApi+}++const METRIC = metric()+const MARKDOWN_METRIC = metric({ definition_kind: 'MarkdownDefinition' })++function node(partial: Pick<DataModelingNode, 'id' | 'name' | 'type'> & Partial<DataModelingNode>): DataModelingNode {+ return {+ dag: 'dag-1',+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ upstream_count: 0,+ downstream_count: 0,+ ...partial,+ }+}++const NODES: DataModelingNode[] = [+ node({ id: '1', name: 'events', type: 'table' }),+ node({ id: '2', name: 'accounts_view', type: 'view' }),+ node({ id: '3', name: 'weekly_active_accounts', type: 'metric', metric_id: 'metric-1' }),+]+const EDGES: DataModelingEdge[] = [+ { id: 'e1', source_id: '1', target_id: '2', dag: 'dag-1', properties: {}, created_at: '', updated_at: '' },+ { id: 'e2', source_id: '2', target_id: '3', dag: 'dag-1', properties: {}, created_at: '', updated_at: '' },+]++const BASE: MetricLineagePanelProps = {+ metric: METRIC,+ lineage: { nodes: NODES, edges: EDGES },+ lineageLoading: false,+ lineageProblem: null,+ onRetry: () => {},+ onEditDefinition: () => {},+}++function atWidths(props: MetricLineagePanelProps): JSX.Element {+ return (+ <div className="flex flex-col gap-4 p-4">+ <div className="w-[960px]">+ <MetricLineagePanel {...props} />+ </div>+ <div className="w-[480px]">+ <MetricLineagePanel {...props} />+ </div>+ </div>+ )+}++type Story = StoryObj<typeof MetricLineagePanel>+const meta: Meta<typeof MetricLineagePanel> = {+ title: 'Products/Data catalog/Metric lineage',+ component: MetricLineagePanel,+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+}++export default meta++export const Graph: Story = { render: () => atWidths(BASE) }++export const Loading: Story = {+ render: () => atWidths({ ...BASE, lineage: null, lineageLoading: true }),+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+}++export const NoDefinition: Story = {+ render: () => atWidths({ ...BASE, metric: MARKDOWN_METRIC, lineage: null }),+}++export const BeingPrepared: Story = {+ render: () => atWidths({ ...BASE, lineage: null, lineageProblem: 'not_ready' }),+}++export const NoWarehouseAccess: Story = {+ render: () => atWidths({ ...BASE, lineage: null, lineageProblem: 'no_warehouse_access' }),+}++export const LoadFailed: Story = {+ render: () => atWidths({ ...BASE, lineage: null, lineageProblem: 'failed' }),+}++const ISOLATED_METRIC_NODE = node({+ id: '3',+ name: 'weekly_active_accounts',+ type: 'metric',+ metric_id: 'metric-1',+ lineage_issue: { kind: 'unresolved', detail: 'accounts_view', at: '2024-01-01T00:00:00Z' },+})++export const LineageIssue: Story = {+ render: () => atWidths({ ...BASE, lineage: { nodes: [ISOLATED_METRIC_NODE], edges: [] } }),+}diff --git a/products/data_catalog/frontend/MetricLineagePanel.tsx b/products/data_catalog/frontend/MetricLineagePanel.tsxnew file mode 100644index 000000000000..55c6986436fb--- /dev/null+++ b/products/data_catalog/frontend/MetricLineagePanel.tsx@@ -0,0 +1,191 @@+import { router } from 'kea-router'+import { useState } from 'react'++import { IconExternal, IconRefresh } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonSkeleton, LemonTable } from '@posthog/lemon-ui'++import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { urls } from 'scenes/urls'++import { DataModelingNode } from '~/types'++import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'+import { lineageIssueMessage } 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 { LineageLoadProblem, metricHasExecutableDefinition, MetricLineage } from './dataCatalogMetricSceneLogic'+import { DataCatalogMetricApi } from './generated/api.schemas'++type LineageView = 'graph' | 'table'++const NOTHING_UPSTREAM = "This metric doesn't read any table or view we can trace."++function LineageMessage({+ title,+ body,+ action,+}: {+ title: string+ body: string+ action?: { label: string; onClick: () => void }+}): JSX.Element {+ return (+ <div className="flex flex-col items-start gap-2 border rounded p-6 bg-surface-primary">+ <span className="font-semibold">{title}</span>+ <span className="text-secondary">{body}</span>+ {action && (+ <LemonButton type="secondary" size="small" onClick={action.onClick}>+ {action.label}+ </LemonButton>+ )}+ </div>+ )+}++function UpstreamTable({ nodes, emptyState }: { nodes: DataModelingNode[]; emptyState: string }): JSX.Element {+ return (+ <LemonTable+ size="small"+ emptyState={emptyState}+ columns={[+ {+ key: 'name',+ title: 'Name',+ render: (_, node) => <LemonTableLink to={lineageNodeUrl(node)} title={node.name} />,+ },+ { key: 'type', title: 'Type', render: (_, node) => NODE_TYPE_TAG_SETTINGS[node.type].label },+ ]}+ dataSource={nodes}+ />+ )+}++export interface MetricLineagePanelProps {+ metric: DataCatalogMetricApi+ lineage: MetricLineage | null+ lineageLoading: boolean+ lineageProblem: LineageLoadProblem | null+ onRetry: () => void+ onEditDefinition: () => void+}++export function MetricLineagePanel({+ metric,+ lineage,+ lineageLoading,+ lineageProblem,+ onRetry,+ onEditDefinition,+}: MetricLineagePanelProps): JSX.Element {+ const [view, setView] = useState<LineageView>('graph')++ if (!metricHasExecutableDefinition(metric)) {+ return (+ <LineageMessage+ title="No lineage yet"+ body="Lineage shows the tables and views a metric reads. Add a query definition to see it."+ action={{ label: 'Edit definition', onClick: onEditDefinition }}+ />+ )+ }++ if (lineageLoading && !lineage) {+ return <LemonSkeleton className="h-64 w-full" />+ }++ if (lineageProblem === 'not_ready') {+ return (+ <LineageMessage+ title="Lineage is being prepared"+ body="This usually takes a few seconds."+ action={{ label: 'Refresh', onClick: onRetry }}+ />+ )+ }++ if (lineageProblem === 'no_warehouse_access') {+ return (+ <LineageMessage+ title="Lineage needs data warehouse access"+ body="Ask an admin for viewer access to the data warehouse to see which tables this metric reads."+ />+ )+ }++ if (lineageProblem === 'failed') {+ return (+ <LemonBanner type="error" action={{ children: 'Retry', onClick: onRetry }}>+ Couldn't load lineage.+ </LemonBanner>+ )+ }++ const nodes = lineage?.nodes ?? []+ const edges = lineage?.edges ?? []+ const currentNode = nodes.find((node) => node.metric_id === metric.id)+ const upstreamNodes = nodes.filter((node) => node.id !== currentNode?.id)+ const upstreamEmptyState = currentNode?.lineage_issue+ ? lineageIssueMessage(currentNode.lineage_issue)+ : NOTHING_UPSTREAM++ return (+ <div className="@container flex flex-col gap-2">+ <div className="flex flex-wrap items-center justify-end @[40rem]:justify-between gap-2">+ <LemonSegmentedButton+ className="hidden @[40rem]:block"+ value={view}+ onChange={setView}+ options={[+ { value: 'graph', label: 'Graph' },+ { value: 'table', label: 'Table' },+ ]}+ size="small"+ />+ <div className="flex items-center gap-2">+ <LemonButton+ type="secondary"+ size="small"+ onClick={onRetry}+ loading={lineageLoading}+ icon={<IconRefresh />}+ tooltip="Refresh lineage"+ aria-label="Refresh lineage"+ />+ <LemonButton+ type="secondary"+ size="small"+ to={urls.models('lineage')}+ targetBlank+ tooltip="Open the full graph"+ aria-label="Open the full graph"+ icon={<IconExternal />}+ />+ </div>+ </div>+ {view === 'graph' && (+ <div className="hidden @[40rem]:block h-[min(45vh,500px)] border border-border rounded-md overflow-hidden">+ <LineageGraph+ nodes={nodes}+ edges={edges}+ currentNodeId={currentNode?.id}+ variant="full"+ interactive+ showControls+ emptyMessage={NOTHING_UPSTREAM}+ nodeCallbacks={(node) => ({+ onClick:+ node.id === currentNode?.id+ ? undefined+ : () => router.actions.push(lineageNodeUrl(node)),+ })}+ />+ </div>+ )}+ <div className={view === 'graph' ? '@[40rem]:hidden' : undefined}>+ <UpstreamTable nodes={upstreamNodes} emptyState={upstreamEmptyState} />+ </div>+ </div>+ )+}diff --git a/products/data_catalog/frontend/MetricLineageTab.tsx b/products/data_catalog/frontend/MetricLineageTab.tsxnew file mode 100644index 000000000000..61d4e0c025a1--- /dev/null+++ b/products/data_catalog/frontend/MetricLineageTab.tsx@@ -0,0 +1,21 @@+import { useActions, useValues } from 'kea'++import { dataCatalogMetricSceneLogic } from './dataCatalogMetricSceneLogic'+import { DataCatalogMetricApi } from './generated/api.schemas'+import { MetricLineagePanel } from './MetricLineagePanel'++export function MetricLineageTab({ metric }: { metric: DataCatalogMetricApi }): JSX.Element {+ const { lineage, lineageLoading, lineageProblem } = useValues(dataCatalogMetricSceneLogic)+ const { loadLineage, setActiveTab } = useActions(dataCatalogMetricSceneLogic)++ return (+ <MetricLineagePanel+ metric={metric}+ lineage={lineage}+ lineageLoading={lineageLoading}+ lineageProblem={lineageProblem}+ onRetry={loadLineage}+ onEditDefinition={() => setActiveTab('definition')}+ />+ )+}diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.tsindex 0b39e33eced8..d17d7888eed2 100644--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts@@ -1,6 +1,6 @@import { router } from 'kea-router'-import { ApiConfig, ApiError } from 'lib/api'+import api, { ApiConfig, ApiError } from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -10,7 +10,11 @@ import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'import { dataCatalogAgentSyncLogic } from './dataCatalogAgentSyncLogic'-import { dataCatalogMetricSceneLogic, MARKDOWN_DEFINITION_TEMPLATE } from './dataCatalogMetricSceneLogic'+import {+ dataCatalogMetricSceneLogic,+ LINEAGE_RETRY_MS,+ MARKDOWN_DEFINITION_TEMPLATE,+} from './dataCatalogMetricSceneLogic'import {dataCatalogMetricsApproveCreate,dataCatalogMetricsPartialUpdate,@@ -31,7 +35,7 @@ jest.mock('lib/api', () => {}return {__esModule: true,- default: {},+ default: { dataModelingNodes: { lineage: jest.fn() } },ApiConfig: { getCurrentTeamId: jest.fn(() => 1) },ApiError,}@@ -83,6 +87,181 @@ describe('dataCatalogMetricSceneLogic', () => {;(ApiConfig.getCurrentTeamId as jest.Mock).mockReturnValue(1)})+ const lineageRequest = (): jest.Mock => api.dataModelingNodes.lineage as unknown as jest.Mock++ it('loads lineage when the tab opens and keeps what it returned', async () => {+ lineageRequest().mockResolvedValue({ nodes: [{ id: 'node-1' }], edges: [] })++ logic.actions.setActiveTab('lineage')+ await expectLogic(logic).toFinishAllListeners()++ expect(lineageRequest()).toHaveBeenCalledWith({ metricId: 'metric-1' })+ expect(logic.values.lineage?.nodes).toHaveLength(1)+ expect(logic.values.lineageProblem).toBeNull()+ })++ it.each([+ ['replaced locally', (metric: DataCatalogMetricApi) => logic.actions.setMetric(metric)],+ [+ 'reloaded from the API',+ (metric: DataCatalogMetricApi) => {+ ;(dataCatalogMetricsRetrieve as jest.Mock).mockResolvedValue(metric)+ logic.actions.loadMetric()+ },+ ],+ ])('reloads lineage when the metric is %s under the open tab', async (_, changeMetric) => {+ lineageRequest().mockResolvedValue({ nodes: [{ id: 'node-1' }], edges: [] })+ logic.actions.setActiveTab('lineage')+ await expectLogic(logic).toFinishAllListeners()+ lineageRequest().mockClear()++ changeMetric(buildMetric({ definition: { kind: 'HogQLQuery', query: 'SELECT 2' } }))+ await expectLogic(logic).toFinishAllListeners()++ expect(lineageRequest()).toHaveBeenCalledTimes(1)+ })++ it('reloads lineage when the metric reloaded while the tab was closed', async () => {+ lineageRequest().mockResolvedValue({ nodes: [{ id: 'node-1' }], edges: [] })+ logic.actions.setActiveTab('lineage')+ await expectLogic(logic).toFinishAllListeners()+ lineageRequest().mockClear()++ logic.actions.setActiveTab('definition')+ logic.actions.loadMetric()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setActiveTab('lineage')+ await expectLogic(logic).toFinishAllListeners()++ expect(lineageRequest()).toHaveBeenCalledTimes(1)+ })++ it('asks for lineage once when the tab opens and the metric reloads together', async () => {+ lineageRequest().mockResolvedValue({ nodes: [], edges: [] })++ logic.actions.setActiveTab('lineage')+ logic.actions.loadMetric()+ await expectLogic(logic).toFinishAllListeners()++ expect(lineageRequest()).toHaveBeenCalledTimes(1)+ })++ it('asks for no lineage for a metric that cannot have one', async () => {+ const markdownMetric = buildMetric({ definition_kind: 'MarkdownDefinition' })+ ;(dataCatalogMetricsRetrieve as jest.Mock).mockResolvedValue(markdownMetric)+ logic.actions.setMetric(markdownMetric)+ await expectLogic(logic).toFinishAllListeners()+ lineageRequest().mockClear()++ logic.actions.setActiveTab('lineage')+ await expectLogic(logic).toFinishAllListeners()++ expect(lineageRequest()).not.toHaveBeenCalled()+ })++ it('retries a not-ready lineage exactly once', async () => {+ jest.useFakeTimers({ doNotFake: ['queueMicrotask', 'nextTick'] })+ try {+ lineageRequest().mockRejectedValue(new ApiError('nope', 404))+ logic.actions.setActiveTab('lineage')+ await jest.advanceTimersByTimeAsync(0)+ expect(lineageRequest()).toHaveBeenCalledTimes(1)++ await jest.advanceTimersByTimeAsync(LINEAGE_RETRY_MS)+ expect(lineageRequest()).toHaveBeenCalledTimes(2)++ await jest.advanceTimersByTimeAsync(LINEAGE_RETRY_MS * 3)+ expect(lineageRequest()).toHaveBeenCalledTimes(2)+ expect(logic.values.lineageProblem).toBe('not_ready')+ } finally {+ jest.useRealTimers()+ }+ })++ it('reloads lineage when the metric is replaced while the request is in flight', async () => {+ let finishFirstRequest: (lineage: unknown) => void = () => {}+ lineageRequest().mockReturnValueOnce(+ new Promise((resolve) => {+ finishFirstRequest = resolve+ })+ )+ lineageRequest().mockResolvedValue({ nodes: [{ id: 'node-2' }], edges: [] })++ logic.actions.setActiveTab('lineage')+ await expectLogic(logic).toDispatchActions(['loadLineage'])+ expect(lineageRequest()).toHaveBeenCalledTimes(1)++ logic.actions.setMetric(buildMetric({ definition: { kind: 'HogQLQuery', query: 'SELECT 2' } }))+ finishFirstRequest({ nodes: [{ id: 'node-1' }], edges: [] })+ await expectLogic(logic).toFinishAllListeners()++ expect(lineageRequest()).toHaveBeenCalledTimes(2)+ expect(logic.values.lineage?.nodes.map((node) => node.id)).toEqual(['node-2'])+ })++ it('keeps the delayed retry when the metric reload lands after the failure', async () => {+ jest.useFakeTimers({ doNotFake: ['queueMicrotask', 'nextTick'] })+ try {+ lineageRequest().mockRejectedValue(new ApiError('nope', 404))+ let finishReload: (metric: DataCatalogMetricApi) => void = () => {}+ ;(dataCatalogMetricsRetrieve as jest.Mock).mockReturnValue(+ new Promise<DataCatalogMetricApi>((resolve) => {+ finishReload = resolve+ })+ )++ logic.actions.setActiveTab('lineage')+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.lineageProblem).toBe('not_ready')++ finishReload(buildMetric())+ await jest.advanceTimersByTimeAsync(0)+ expect(lineageRequest()).toHaveBeenCalledTimes(1)++ await jest.advanceTimersByTimeAsync(LINEAGE_RETRY_MS)+ expect(lineageRequest()).toHaveBeenCalledTimes(2)+ } finally {+ jest.useRealTimers()+ }+ })++ it('drops the delayed retry when a refresh loaded lineage inside the window', async () => {+ jest.useFakeTimers({ doNotFake: ['queueMicrotask', 'nextTick'] })+ try {+ lineageRequest().mockRejectedValue(new ApiError('nope', 404))+ logic.actions.setActiveTab('lineage')+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.lineageProblem).toBe('not_ready')+ lineageRequest().mockClear()++ lineageRequest().mockResolvedValueOnce({ nodes: [{ id: 'node-1' }], edges: [] })+ lineageRequest().mockRejectedValue(new ApiError('boom', 500))+ logic.actions.loadLineage()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.lineage?.nodes).toHaveLength(1)++ await jest.advanceTimersByTimeAsync(LINEAGE_RETRY_MS * 2)+ expect(lineageRequest()).toHaveBeenCalledTimes(1)+ expect(logic.values.lineageProblem).toBeNull()+ } finally {+ jest.useRealTimers()+ }+ })++ it.each([+ [404, 'not_ready'],+ [403, 'no_warehouse_access'],+ [500, 'failed'],+ ])('turns a %s into the %s screen', async (status, expected) => {+ lineageRequest().mockRejectedValue(new ApiError('nope', status))++ logic.actions.setActiveTab('lineage')+ await expectLogic(logic).toDispatchActions(['loadLineageFailure'])++ expect(logic.values.lineageProblem).toBe(expected)+ expect(logic.values.lineageRetried).toBe(expected === 'not_ready')+ })+it('synchronizes the Tests tab with navigation and preserves it on rename', async () => {router.actions.push(urls.dataCatalogMetric('weekly_active_users'), { tab: 'tests' })await expectLogic(logic).toFinishAllListeners()diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsxindex 3e5c8555c922..1b38a76b877e 100644--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx@@ -15,13 +15,13 @@ import {import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'-import { ApiConfig, ApiError } from 'lib/api'+import api, { ApiConfig, ApiError } from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'-import { Breadcrumb } from '~/types'+import { Breadcrumb, DataModelingEdge, DataModelingNode } from '~/types'import { validateMetricName } from './common'import { dataCatalogAgentSyncLogic } from './dataCatalogAgentSyncLogic'@@ -43,7 +43,29 @@ export interface DataCatalogMetricSceneLogicProps {name: string}-export type MetricSceneTab = 'definition' | 'tests'+export type MetricSceneTab = 'definition' | 'tests' | 'lineage'++/** What stopped the lineage load, in the terms the tab has a screen for. */+export type LineageLoadProblem = 'not_ready' | 'no_warehouse_access' | 'failed'++export interface MetricLineage {+ nodes: DataModelingNode[]+ edges: DataModelingEdge[]+}++/** A node written moments ago may not exist yet, so one silent retry covers the common case. */+export const LINEAGE_RETRY_MS = 3000++function lineageProblem(error: unknown): LineageLoadProblem {+ const status = error instanceof ApiError ? error.status : undefined+ if (status === 404) {+ return 'not_ready'+ }+ if (status === 403) {+ return 'no_warehouse_access'+ }+ return 'failed'+}function projectId(): string {return String(ApiConfig.getCurrentTeamId())@@ -60,6 +82,17 @@ function apiErrorDetail(error: unknown): string | null {return error instanceof ApiError ? error.detail : null}+/** A metric with no query definition has no lineage to fetch; the tab says so without asking. */+export function metricHasExecutableDefinition(metric: DataCatalogMetricApi | null): boolean {+ return !!metric?.definition_kind && metric.definition_kind !== 'MarkdownDefinition'+}++// What a lineage graph was computed for. The upstream tables follow from the metric and its+// definition, so a reload that returns the same key returns the same graph.+function lineageMetricKey(metric: DataCatalogMetricApi | null): string | null {+ return metric ? `${metric.id}:${JSON.stringify(metric.definition ?? null)}` : null+}+export function definitionField(metric: DataCatalogMetricApi | null, field: string): string {const definition = metric?.definition as Record<string, unknown> | null | undefinedconst value = definition?.[field]@@ -91,6 +124,12 @@ export interface dataCatalogMetricSceneLogicValues {draftMarkdown: stringdraftSql: stringeditingDefinition: boolean+ lineage: MetricLineage | null+ lineageLoading: boolean+ lineageProblem: LineageLoadProblem | null+ lineageRequestedFor: string | null+ lineageRetried: boolean+ lineageStale: booleanmetric: DataCatalogMetricApi | nullmetricChecksEnabled: booleanmetricLoading: boolean@@ -111,6 +150,36 @@ export interface dataCatalogMetricSceneLogicActions {deleteMetric: () => {value: true}+ loadLineage: () => {+ value: true+ }+ loadLineageFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadLineageIfNeeded: () => {+ value: true+ }+ loadLineageSuccess: (+ lineage: {+ edges: DataModelingEdge[]+ nodes: DataModelingNode[]+ } | null,+ payload?: {+ value: true+ }+ ) => {+ lineage: {+ edges: DataModelingEdge[]+ nodes: DataModelingNode[]+ } | null+ payload?: {+ value: true+ }+ }loadMetric: () => {value: true}@@ -147,6 +216,9 @@ export interface dataCatalogMetricSceneLogicActions {runResult: DataCatalogMetricRunApipayload?: any}+ markLineageStale: () => {+ value: true+ }refreshMetricFromInsight: () => {value: true}@@ -168,6 +240,12 @@ export interface dataCatalogMetricSceneLogicActions {setEditingDefinition: (editingDefinition: boolean) => {editingDefinition: boolean}+ setLineageRequestedFor: (key: string | null) => {+ key: string | null+ }+ setLineageRetried: (lineageRetried: boolean) => {+ lineageRetried: boolean+ }setMetric: (metric: DataCatalogMetricApi) => {metric: DataCatalogMetricApi}@@ -234,6 +312,11 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(// Declared here as well as by the loader: the loader takes a breakpoint, so without this the// generated action would require a payload every call site has to pass.loadMetric: true,+ loadLineage: true,+ loadLineageIfNeeded: true,+ markLineageStale: true,+ setLineageRequestedFor: (key: string | null) => ({ key }),+ setLineageRetried: (lineageRetried: boolean) => ({ lineageRetried }),setMetric: (metric: DataCatalogMetricApi) => ({ metric }),approveMetric: true,refreshMetricFromInsight: true,@@ -265,6 +348,20 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(setMetric: ({ metric }) => metric,},],+ lineage: [+ null as MetricLineage | null,+ {+ loadLineage: async (_, breakpoint) => {+ const metricId = dataCatalogMetricSceneLogic.findMounted(props)?.values.metric?.id+ if (!metricId) {+ return null+ }+ const lineage = await api.dataModelingNodes.lineage({ metricId })+ breakpoint()+ return lineage+ },+ },+ ],runResult: [null as DataCatalogMetricRunApi | null,{@@ -286,6 +383,37 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(state.includes(activeTab) ? state : [...state, activeTab],},],+ lineageProblem: [+ null as LineageLoadProblem | null,+ {+ loadLineage: () => null,+ loadLineageSuccess: () => null,+ loadLineageFailure: (_, { errorObject }: { errorObject?: unknown }) => lineageProblem(errorObject),+ },+ ],+ lineageStale: [+ false,+ {+ setMetric: () => true,+ markLineageStale: () => true,+ loadLineageSuccess: () => false,+ loadLineageFailure: () => false,+ },+ ],+ lineageRequestedFor: [+ null as string | null,+ {+ setLineageRequestedFor: (_, { key }) => key,+ },+ ],+ lineageRetried: [+ false,+ {+ setLineageRetried: (_, { lineageRetried }) => lineageRetried,+ loadLineageSuccess: () => false,+ setMetric: () => false,+ },+ ],mutating: [false,{@@ -381,6 +509,51 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(actions.setPendingDefinitionEdit(false)actions.startEditingMarkdown()}+ // A reload can carry a definition the agent rewrote, so an open tab is no evidence that+ // the graph is current. Compare what the graph was requested for instead, because every+ // tab switch reloads the metric and an unchanged reload must not ask for it again.+ if (values.activeTab !== 'lineage' || lineageMetricKey(metric) !== values.lineageRequestedFor) {+ actions.markLineageStale()+ }+ actions.loadLineageIfNeeded()+ },+ setActiveTab: () => {+ actions.loadLineageIfNeeded()+ },+ loadLineageIfNeeded: () => {+ if (values.activeTab !== 'lineage' || values.lineageLoading) {+ return+ }+ if (!metricHasExecutableDefinition(values.metric)) {+ return+ }+ // The request for this metric has settled and the tab shows what it returned, so asking+ // again would repeat it. After a failure the scheduled retry owns the next attempt.+ if (!values.lineageStale && lineageMetricKey(values.metric) === values.lineageRequestedFor) {+ return+ }+ actions.setLineageRequestedFor(lineageMetricKey(values.metric))+ actions.loadLineage()+ },+ loadLineageSuccess: () => {+ // One request runs at a time, so a metric change during a request cannot start its own.+ // The graph that lands is then the previous metric's, and this asks for the current one.+ // The guard above returns for a graph that already matches, so a normal load stops here.+ actions.loadLineageIfNeeded()+ },+ loadLineageFailure: async (_, breakpoint) => {+ if (values.lineageProblem !== 'not_ready' || values.lineageRetried) {+ return+ }+ actions.setLineageRetried(true)+ await breakpoint(LINEAGE_RETRY_MS)+ // A refresh or a reload can load the graph inside the window, so ask again only while+ // the node is still missing. The retry finishes even off the tab, so the graph is there+ // when the user returns.+ if (values.lineageProblem !== 'not_ready' || values.lineageLoading) {+ return+ }+ actions.loadLineage()},loadMetricFailure: () => {// The draft is handed over for the load this instance just issued. Dropping it on a@@ -390,6 +563,7 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(setMetric: ({ metric }) => {actions.setDraftSql(definitionField(metric, 'query'))actions.setDraftMarkdown(definitionField(metric, 'markdown'))+ actions.loadLineageIfNeeded()},setEditingDefinition: ({ editingDefinition }) => {// Closing the editor discards the draft, otherwise the next edit session starts from stale text.@@ -503,7 +677,8 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(if (name !== props.name) {return}- const requestedTab = searchParams.tab === 'tests' ? 'tests' : 'definition'+ const requestedTab: MetricSceneTab =+ searchParams.tab === 'tests' || searchParams.tab === 'lineage' ? searchParams.tab : 'definition'const activeTab = requestedTab === 'tests' && !values.metricChecksEnabled ? 'definition' : requestedTabif (activeTab !== requestedTab) {// Drop the param so a refresh or a back navigation does not ask for the tab again.diff --git a/products/data_catalog/manifest.tsx b/products/data_catalog/manifest.tsxindex 064caf0a5e00..290428ad28f5 100644--- a/products/data_catalog/manifest.tsx+++ b/products/data_catalog/manifest.tsx@@ -28,8 +28,8 @@ export const manifest: ProductManifest = {redirects: {},urls: {dataCatalog: (tab?: string): string => `/data-catalog${tab ? `?tab=${tab}` : ''}`,- dataCatalogMetric: (name: string, tab?: 'definition' | 'tests'): string =>- `/data-catalog/metrics/${name}${tab === 'tests' ? '?tab=tests' : ''}`,+ dataCatalogMetric: (name: string, tab?: 'definition' | 'tests' | 'lineage'): string =>+ `/data-catalog/metrics/${name}${tab && tab !== 'definition' ? `?tab=${tab}` : ''}`,},fileSystemTypes: {},treeItemsNew: [],