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.

32.5 KB
Raw Blame
import type { XYPosition } from '@xyflow/react'
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { userHasAccess } from 'lib/utils/accessControlUtils'
import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import type { DataWarehouseSavedQuerySummary } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import type { DatabaseSchemaField } from '~/queries/schema/schema-general'
import {
    AccessControlLevel,
    AccessControlResourceType,
    Breadcrumb,
    DataModelingEdge,
    DataModelingNode,
    DataModelingNodeType,
    DataWarehouseSavedQuery,
    DataWarehouseTable,
    ExternalDataSchemaWithSource,
    ExternalDataSource,
} from '~/types'

import { checksApi, type DataQualitySubjectType } from 'products/data_quality/frontend/checksApi'
import type { DataQualitySubjectApi } from 'products/data_quality/frontend/generated/api.schemas'

import { MATERIALIZING_TYPES } from '../freshness'
import { dataModelingNodesRetrieve } from '../generated/api'
import { DataModelingNodesRetrieveLookup, type NodeTypeEnumApi } from '../generated/api.schemas'
import { HiddenNodeBridging, bridgeHiddenNodes } from '../lineage/lineageHiddenNodes'
import { LINEAGE_FILTER_TYPES, LINEAGE_TYPE_FILTER_CHANGED_EVENT } from '../lineage/modelsLineageLogic'

export const NODE_DETAIL_SCENE_TABS = ['query', 'lineage', 'materialization', 'data-quality', 'history'] as const
export type NodeDetailSceneTab = (typeof NODE_DETAIL_SCENE_TABS)[number]

export interface NodeDetailSceneLogicProps {
    id: string
}

/** What the embedded query editor reports for the Update view and Discard changes buttons above it. */
export interface NodeDetailQueryEditorState {
    updateDisabledReason: string | undefined
    updateLoading: boolean
    discardDisabledReason: string | undefined
    isMaterializedView: boolean
}

export const nodeDetailQueryEditorTabId = (savedQueryId: string): string => `node-detail-query-${savedQueryId}`

function isNodeLookup(value: unknown): value is DataModelingNodesRetrieveLookup {
    return (
        typeof value === 'string' &&
        Object.values(DataModelingNodesRetrieveLookup).includes(value as DataModelingNodesRetrieveLookup)
    )
}

export interface TableDetails {
    table: DataWarehouseTable
    source: ExternalDataSource | null
    schema: ExternalDataSchemaWithSource | null
}

export interface NodeDetailDataQualitySubject {
    subjectType: DataQualitySubjectType
    subjectId: string
    columns?: DatabaseSchemaField[]
    editable?: boolean
}

export interface LineageGraphData {
    /** DataModelingNode objects in the subgraph (ancestors + current + descendants) */
    nodes: DataModelingNode[]
    /** Edges between nodes in the subgraph */
    edges: DataModelingEdge[]
    /** The current node's ID */
    currentNodeId: string
}

function isNodeDetailSceneTab(tab: unknown): tab is NodeDetailSceneTab {
    return typeof tab === 'string' && (NODE_DETAIL_SCENE_TABS as readonly string[]).includes(tab)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface nodeDetailSceneLogicValues {
    currentProjectId: number | string // teamLogic
    availableTabs: NodeDetailSceneTab[]
    breadcrumbs: Breadcrumb[]
    canEditQuery: boolean
    currentTab: NodeDetailSceneTab | null
    dataQualitySubject: NodeDetailDataQualitySubject | null
    defaultTab: NodeDetailSceneTab
    effectiveLastRunAt: string | null
    effectiveLastRunStatus: string | null
    effectiveTab: NodeDetailSceneTab | null
    isMaterialized: boolean
    lineageGraph: LineageGraphData | null
    lineageGraphError: boolean
    lineageGraphLoading: boolean
    lineageHiddenNodeBridging: HiddenNodeBridging | null
    lineageModalOpen: boolean
    lineageNodePositions: Record<string, XYPosition>
    lineageTypeFilter: NodeTypeEnumApi[]
    lineageVisibleNodeIds: Set<string>
    node: DataModelingNode | null
    nodeLoading: boolean
    nodeType: NodeTypeEnumApi | null
    postHogSubject: DataQualitySubjectApi | null
    postHogSubjectAccessDenied: boolean
    postHogSubjectError: boolean
    postHogSubjectLoading: boolean
    queryEditorState: NodeDetailQueryEditorState | null
    savedQuery: DataWarehouseSavedQuery | null
    savedQueryDeleted: boolean
    savedQueryError: boolean
    savedQueryLoading: boolean
    savedQuerySettled: boolean
    sceneResolved: boolean
    tableDetails: TableDetails | null
    tableDetailsAccessDenied: boolean
    tableDetailsError: boolean
    tableDetailsLoading: boolean
    visitedTabs: NodeDetailSceneTab[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface nodeDetailSceneLogicActions {
    deleteDataWarehouseSavedQuerySuccess: (
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[],
        payload?: string | undefined
    ) => {
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]
        payload?: string
    } // dataWarehouseViewsLogic
    updateDataWarehouseSavedQuerySuccess: (
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[],
        payload?:
            | import('scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate
            | undefined
    ) => {
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]
        payload?: import('scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate
    } // dataWarehouseViewsLogic
    canonicalizeTab: () => {
        value: true
    }
    closeLineageModal: () => {
        value: true
    }
    discardQueryEditorChanges: () => {
        value: true
    }
    lineageNodeDragStopped: (
        nodeId: string,
        position: XYPosition
    ) => {
        nodeId: string
        position: XYPosition
    }
    loadLineageGraph: () => any
    loadLineageGraphFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadLineageGraphSuccess: (
        lineageGraph: {
            currentNodeId: string
            edges: DataModelingEdge[]
            nodes: DataModelingNode[]
        } | null,
        payload?: any
    ) => {
        lineageGraph: {
            currentNodeId: string
            edges: DataModelingEdge[]
            nodes: DataModelingNode[]
        } | null
        payload?: any
    }
    loadNode: () => any
    loadNodeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadNodeSuccess: (
        node: DataModelingNode | null,
        payload?: any
    ) => {
        node: DataModelingNode | null
        payload?: any
    }
    loadPostHogSubject: () => any
    loadPostHogSubjectFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPostHogSubjectSuccess: (
        postHogSubject: DataQualitySubjectApi | null,
        payload?: any
    ) => {
        postHogSubject: DataQualitySubjectApi | null
        payload?: any
    }
    loadSavedQuery: () => any
    loadSavedQueryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSavedQuerySuccess: (
        savedQuery: DataWarehouseSavedQuery | null,
        payload?: any
    ) => {
        savedQuery: DataWarehouseSavedQuery | null
        payload?: any
    }
    loadTableDetails: () => any
    loadTableDetailsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadTableDetailsSuccess: (
        tableDetails: {
            schema: ExternalDataSchemaWithSource | null
            source: ExternalDataSource | null
            table: DataWarehouseTable
        } | null,
        payload?: any
    ) => {
        tableDetails: {
            schema: ExternalDataSchemaWithSource | null
            source: ExternalDataSource | null
            table: DataWarehouseTable
        } | null
        payload?: any
    }
    markSavedQueryDeleted: () => {
        value: true
    }
    openLineageModal: () => {
        value: true
    }
    resetLineageNodePositions: () => {
        value: true
    }
    setCurrentTab: (tab: NodeDetailSceneTab | null) => {
        tab: 'data-quality' | 'history' | 'lineage' | 'materialization' | 'query' | null
    }
    setLineageTypeFilter: (typeFilter: DataModelingNodeType[]) => {
        typeFilter: NodeTypeEnumApi[]
    }
    setQueryEditorState: (state: NodeDetailQueryEditorState | null) => {
        state: NodeDetailQueryEditorState | null
    }
    updateNodeDescription: (description: string) => {
        description: string
    }
    updateNodeDescriptionFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateNodeDescriptionSuccess: (
        node: DataModelingNode,
        payload?: {
            description: string
        }
    ) => {
        node: DataModelingNode
        payload?: {
            description: string
        }
    }
    updateViewFromQueryEditor: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface nodeDetailSceneLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        breadcrumbs: (node: DataModelingNode | null) => Breadcrumb[]
        nodeType: (node: DataModelingNode | null) => NodeTypeEnumApi | null
        sceneResolved: (node: DataModelingNode | null, savedQuerySettled: boolean) => boolean
        availableTabs: (node: DataModelingNode | null, sceneResolved: boolean) => NodeDetailSceneTab[]
        dataQualitySubject: (
            node: DataModelingNode | null,
            postHogSubject: DataQualitySubjectApi | null
        ) => NodeDetailDataQualitySubject | null
        isMaterialized: (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null) => boolean
        defaultTab: (node: DataModelingNode | null, isMaterialized: boolean) => NodeDetailSceneTab
        effectiveTab: (
            currentTab: 'data-quality' | 'history' | 'lineage' | 'materialization' | 'query' | null,
            availableTabs: ('data-quality' | 'history' | 'lineage' | 'materialization' | 'query')[],
            defaultTab: 'data-quality' | 'history' | 'lineage' | 'materialization' | 'query'
        ) => NodeDetailSceneTab | null
        effectiveLastRunAt: (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null) => string | null
        effectiveLastRunStatus: (
            node: DataModelingNode | null,
            savedQuery: DataWarehouseSavedQuery | null
        ) => string | null
        canEditQuery: (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null) => boolean
        lineageVisibleNodeIds: (
            lineageGraph: LineageGraphData | null,
            lineageTypeFilter: NodeTypeEnumApi[]
        ) => Set<string>
        lineageHiddenNodeBridging: (
            lineageGraph: LineageGraphData | null,
            lineageVisibleNodeIds: Set<string>
        ) => HiddenNodeBridging | null
    }
}

export type nodeDetailSceneLogicType = MakeLogicType<
    nodeDetailSceneLogicValues,
    nodeDetailSceneLogicActions,
    NodeDetailSceneLogicProps,
    nodeDetailSceneLogicMeta
>

export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([
    props({} as NodeDetailSceneLogicProps),
    key((props) => props.id),
    path((key) => ['scenes', 'models', 'nodeDetailSceneLogic', key]),
    connect(() => ({
        values: [teamLogic, ['currentProjectId']],
        actions: [
            dataWarehouseViewsLogic,
            ['updateDataWarehouseSavedQuerySuccess', 'deleteDataWarehouseSavedQuerySuccess'],
        ],
    })),
    actions({
        updateNodeDescription: (description: string) => ({ description }),
        setCurrentTab: (tab: NodeDetailSceneTab | null) => ({ tab }),
        canonicalizeTab: true,
        setQueryEditorState: (state: NodeDetailQueryEditorState | null) => ({ state }),
        updateViewFromQueryEditor: true,
        discardQueryEditorChanges: true,
        openLineageModal: true,
        closeLineageModal: true,
        lineageNodeDragStopped: (nodeId: string, position: XYPosition) => ({ nodeId, position }),
        resetLineageNodePositions: true,
        setLineageTypeFilter: (typeFilter: DataModelingNodeType[]) => ({ typeFilter }),
        markSavedQueryDeleted: true,
    }),
    reducers({
        // Reported by the embedded query editor while it is mounted, and null otherwise.
        queryEditorState: [
            null as NodeDetailQueryEditorState | null,
            {
                setQueryEditorState: (_, { state }) => state,
            },
        ],
        // What the address bar asks for. Tab links navigate, so nothing else may write this.
        currentTab: [
            null as NodeDetailSceneTab | null,
            {
                setCurrentTab: (_, { tab }) => tab,
            },
        ],
        // Panels mount on first visit and then stay mounted, so keyed logics under them keep their
        // drafts and viewports across tab switches.
        visitedTabs: [
            [] as NodeDetailSceneTab[],
            {
                setCurrentTab: (state, { tab }) => (!tab || state.includes(tab) ? state : [...state, tab]),
            },
        ],
        savedQuerySettled: [
            false,
            {
                loadSavedQuerySuccess: () => true,
                loadSavedQueryFailure: () => true,
            },
        ],
        savedQueryDeleted: [
            false,
            {
                loadSavedQuery: () => false,
                markSavedQueryDeleted: () => true,
            },
        ],
        savedQueryError: [
            false,
            {
                loadSavedQuery: () => false,
                loadSavedQuerySuccess: () => false,
                loadSavedQueryFailure: () => true,
            },
        ],
        lineageGraphError: [
            false,
            {
                loadLineageGraph: () => false,
                loadLineageGraphSuccess: () => false,
                loadLineageGraphFailure: () => true,
            },
        ],
        tableDetailsAccessDenied: [
            false,
            {
                loadTableDetails: () => false,
                loadTableDetailsSuccess: () => false,
                loadTableDetailsFailure: (_, { errorObject }) => errorObject?.status === 403,
            },
        ],
        tableDetailsError: [
            false,
            {
                loadTableDetails: () => false,
                loadTableDetailsSuccess: () => false,
                loadTableDetailsFailure: () => true,
            },
        ],
        postHogSubjectAccessDenied: [
            false,
            {
                loadPostHogSubject: () => false,
                loadPostHogSubjectSuccess: () => false,
                loadPostHogSubjectFailure: (_, { errorObject }) => errorObject?.status === 403,
            },
        ],
        postHogSubjectError: [
            false,
            {
                loadPostHogSubject: () => false,
                loadPostHogSubjectSuccess: () => false,
                loadPostHogSubjectFailure: () => true,
            },
        ],
        lineageModalOpen: [
            false,
            {
                openLineageModal: () => true,
                closeLineageModal: () => false,
            },
        ],
        lineageNodePositions: [
            {} as Record<string, XYPosition>,
            {
                lineageNodeDragStopped: (positions, { nodeId, position }) => ({ ...positions, [nodeId]: position }),
                resetLineageNodePositions: () => ({}),
            },
        ],
        lineageTypeFilter: [
            LINEAGE_FILTER_TYPES,
            {
                setLineageTypeFilter: (_, { typeFilter }) => typeFilter,
            },
        ],
    }),
    loaders(({ actions, props, values }) => ({
        node: {
            __default: null as DataModelingNode | null,
            loadNode: async () => {
                const lookup = router.values.searchParams.lookup
                try {
                    return (await dataModelingNodesRetrieve(
                        String(values.currentProjectId),
                        props.id,
                        isNodeLookup(lookup) ? { lookup } : undefined
                    )) as DataModelingNode
                } catch (error: any) {
                    // The scene renders its not-found state for a null node, so a 404 needs no toast.
                    if (error?.status === 404) {
                        return null
                    }
                    throw error
                }
            },
            updateNodeDescription: async ({ description }) => {
                const updated = await api.dataModelingNodes.update(props.id, { description })
                return updated
            },
        },
        savedQuery: {
            __default: null as DataWarehouseSavedQuery | null,
            loadSavedQuery: async () => {
                const node = values.node
                if (!node?.saved_query_id) {
                    return null
                }
                try {
                    return await api.dataWarehouseSavedQueries.get(node.saved_query_id)
                } catch (error: any) {
                    if (error?.status === 404) {
                        actions.markSavedQueryDeleted()
                        return null
                    }
                    throw error
                }
            },
        },
        lineageGraph: {
            __default: null as LineageGraphData | null,
            loadLineageGraph: async () => {
                const node = values.node
                if (!node) {
                    return null
                }
                const { nodes, edges } = await api.dataModelingNodes.lineage({ nodeId: node.id })
                return { nodes, edges, currentNodeId: node.id }
            },
        },
        postHogSubject: {
            __default: null as DataQualitySubjectApi | null,
            loadPostHogSubject: async () => {
                const node = values.node
                if (node?.type !== 'table' || node.origin !== 'posthog') {
                    return null
                }
                const subjects = await checksApi.subjects()
                return (
                    subjects.find(
                        (subject) => subject.subject_type === 'posthog_table' && subject.name === node.name
                    ) ?? null
                )
            },
        },
        tableDetails: {
            __default: null as TableDetails | null,
            loadTableDetails: async () => {
                const node = values.node
                if (node?.type !== 'table' || !node.warehouse_table_id) {
                    return null
                }
                const table = await api.dataWarehouseTables.get(node.warehouse_table_id)
                // A grant on the table alone outranks a denial on its source, so a refused or
                // failed source or schema read narrows the summary rather than emptying it.
                const [source, schema] = await Promise.all([
                    table.external_data_source
                        ? api.externalDataSources.get(table.external_data_source.id).catch(() => null)
                        : null,
                    table.external_schema
                        ? api.externalDataSchemas.get(table.external_schema.id).catch(() => null)
                        : null,
                ])
                return { table, source, schema }
            },
        },
    })),
    selectors({
        breadcrumbs: [
            (s) => [s.node],
            (node: DataModelingNode | null): Breadcrumb[] => [
                {
                    key: 'Models',
                    name: 'Models',
                    path: urls.models('models'),
                },
                {
                    key: ['NodeDetail', node?.id || 'loading'],
                    name: node?.name || 'Loading...',
                },
            ],
        ],
        nodeType: [(s) => [s.node], (node: DataModelingNode | null) => node?.type ?? null],
        // Which tabs exist depends on the saved query too, so a node that has one is only resolved
        // once that request settles. Deciding earlier renders a tab bar we then have to change.
        sceneResolved: [
            (s) => [s.node, s.savedQuerySettled],
            (node: DataModelingNode | null, savedQuerySettled: boolean): boolean =>
                !!node && (!node.saved_query_id || savedQuerySettled),
        ],
        availableTabs: [
            (s) => [s.node, s.sceneResolved],
            (node: DataModelingNode | null, sceneResolved: boolean): NodeDetailSceneTab[] => {
                if (!sceneResolved || !node) {
                    return []
                }
                if (node.type === 'table') {
                    return [
                        'lineage',
                        ...(node.warehouse_table_id || node.origin === 'posthog' ? ['data-quality' as const] : []),
                    ]
                }
                const tabs: NodeDetailSceneTab[] = []
                if (node.saved_query_id) {
                    tabs.push('query')
                }
                tabs.push('lineage')
                // Gate on the node's saved_query_id, not the loaded savedQuery, so the tab
                // survives a saved-query load failure and its panel can show the error and retry.
                // Not gated on `is_materialized`: the panel carries its own Materialize call to
                // action, which is how a plain view becomes materialized from this page.
                if (node.saved_query_id) {
                    tabs.push('materialization')
                }
                if (node.saved_query_id) {
                    tabs.push('data-quality')
                }
                if (node.saved_query_id) {
                    tabs.push('history')
                }
                return tabs
            },
        ],
        dataQualitySubject: [
            (s) => [s.node, s.postHogSubject],
            (
                node: DataModelingNode | null,
                postHogSubject: DataQualitySubjectApi | null
            ): NodeDetailDataQualitySubject | null => {
                if (node?.type === 'table' && node.warehouse_table_id) {
                    return { subjectType: 'table', subjectId: node.warehouse_table_id }
                }
                if (node?.type === 'table' && node.origin === 'posthog' && postHogSubject) {
                    return {
                        subjectType: postHogSubject.subject_type,
                        subjectId: postHogSubject.id,
                        columns: Object.entries(postHogSubject.columns).map(([name, type]) => ({
                            name,
                            hogql_value: name,
                            type: type as DatabaseSchemaField['type'],
                            schema_valid: true,
                        })),
                        editable: postHogSubject.editable,
                    }
                }
                if (node?.saved_query_id) {
                    return { subjectType: 'view', subjectId: node.saved_query_id }
                }
                return null
            },
        ],
        // The saved query is the authority on this, but its request can fail, and the scene still
        // renders once it settles. The node's type carries the same answer, so a failed load falls
        // back to it rather than reading as not materialized -- which would contradict the
        // Materialized view tag beside it and send the default tab to Query.
        isMaterialized: [
            (s) => [s.node, s.savedQuery],
            (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null): boolean => {
                if (savedQuery) {
                    return !!savedQuery.is_materialized
                }
                return MATERIALIZING_TYPES.has(node?.type ?? 'table')
            },
        ],
        defaultTab: [
            (s) => [s.node, s.isMaterialized],
            (node: DataModelingNode | null, isMaterialized: boolean): NodeDetailSceneTab => {
                if (!node?.saved_query_id) {
                    return 'lineage'
                }
                // An endpoint's saved query is always materialized, but its materialization panel
                // strips most controls, so Query is the tab that fits it.
                if (node?.type === 'endpoint') {
                    return 'query'
                }
                return isMaterialized ? 'materialization' : 'query'
            },
        ],
        effectiveTab: [
            (s) => [s.currentTab, s.availableTabs, s.defaultTab],
            (
                currentTab: NodeDetailSceneTab | null,
                availableTabs: NodeDetailSceneTab[],
                defaultTab: NodeDetailSceneTab
            ): NodeDetailSceneTab | null => {
                if (availableTabs.length === 0) {
                    return null
                }
                if (currentTab && availableTabs.includes(currentTab)) {
                    return currentTab
                }
                return availableTabs.includes(defaultTab) ? defaultTab : availableTabs[0]
            },
        ],
        // The saved query wins over the node: the node's copy only advances on a DAG run, so after
        // a Sync now it still reports the run before it, contradicting the materialization tab.
        effectiveLastRunAt: [
            (s) => [s.node, s.savedQuery],
            (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null): string | null =>
                savedQuery?.last_run_at ?? node?.last_run_at ?? null,
        ],
        effectiveLastRunStatus: [
            (s) => [s.node, s.savedQuery],
            (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null): string | null =>
                savedQuery?.status ?? node?.last_run_status ?? null,
        ],
        // An endpoint's query is versioned by the endpoint, so it is edited there and not as a view.
        canEditQuery: [
            (s) => [s.node, s.savedQuery],
            (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null): boolean =>
                !!node?.saved_query_id &&
                node.type !== 'endpoint' &&
                typeof savedQuery?.query?.query === 'string' &&
                userHasAccess(
                    AccessControlResourceType.WarehouseObjects,
                    AccessControlLevel.Editor,
                    savedQuery.user_access_level
                ),
        ],
        lineageVisibleNodeIds: [
            (s) => [s.lineageGraph, s.lineageTypeFilter],
            (lineageGraph: LineageGraphData | null, lineageTypeFilter: DataModelingNodeType[]): Set<string> =>
                new Set(
                    (lineageGraph?.nodes ?? [])
                        .filter(
                            (node) => node.id === lineageGraph?.currentNodeId || lineageTypeFilter.includes(node.type)
                        )
                        .map((node) => node.id)
                ),
        ],
        lineageHiddenNodeBridging: [
            (s) => [s.lineageGraph, s.lineageVisibleNodeIds],
            (lineageGraph: LineageGraphData | null, lineageVisibleNodeIds: Set<string>): HiddenNodeBridging | null =>
                lineageGraph
                    ? bridgeHiddenNodes(
                          lineageGraph.edges,
                          new Set(lineageGraph.nodes.map((node) => node.id)),
                          lineageVisibleNodeIds
                      )
                    : null,
        ],
    }),
    listeners(({ actions, props, values }) => {
        const embeddedQueryEditor = (): ReturnType<typeof sqlEditorLogic.findMounted> =>
            values.node?.saved_query_id
                ? sqlEditorLogic.findMounted({
                      tabId: nodeDetailQueryEditorTabId(values.node.saved_query_id),
                      mode: SQLEditorMode.Embedded,
                  })
                : null
        return {
            updateNodeDescriptionSuccess: ({ node, payload }) => {
                // A cleared table annotation returns the source description, so read what was sent.
                posthog.capture('model description edited', {
                    node_type: node.type,
                    cleared: !payload?.description.trim(),
                })
            },
            setLineageTypeFilter: ({ typeFilter }) => {
                posthog.capture(LINEAGE_TYPE_FILTER_CHANGED_EVENT, {
                    surface: 'node_detail',
                    visible_types: typeFilter,
                    hidden_type_count: LINEAGE_FILTER_TYPES.length - typeFilter.length,
                })
            },
            loadNodeSuccess: () => {
                const node = values.node
                if (node && node.id !== props.id) {
                    router.actions.replace(urls.nodeDetail(node.id, values.currentTab ?? 'lineage'))
                    return
                }
                if (node?.saved_query_id) {
                    actions.loadSavedQuery()
                }
                if (node?.type === 'table' && node.warehouse_table_id) {
                    actions.loadTableDetails()
                }
                if (node?.type === 'table' && node.origin === 'posthog') {
                    actions.loadPostHogSubject()
                }
                actions.loadLineageGraph()
                actions.canonicalizeTab()
            },
            loadSavedQuerySuccess: () => actions.canonicalizeTab(),
            loadSavedQueryFailure: () => actions.canonicalizeTab(),
            // The address bar decides which tab shows, so once the data says which tabs exist, a URL
            // asking for one this model has no page for is corrected in place. Replace, not push: a
            // redirect the user did not ask for is not a history step.
            canonicalizeTab: () => {
                const tab = values.effectiveTab
                if (tab && tab !== values.currentTab) {
                    router.actions.replace(urls.nodeDetail(props.id, tab))
                }
            },
            updateViewFromQueryEditor: () => embeddedQueryEditor()?.actions.reviewEditingViewUpdate(),
            discardQueryEditorChanges: () => embeddedQueryEditor()?.actions.discardChanges(),
            updateDataWarehouseSavedQuerySuccess: ({ payload }) => {
                if (values.node?.saved_query_id) {
                    actions.loadSavedQuery()
                    // The server rebuilds the model's dependencies when its query changes.
                    if (payload?.query && payload.id === values.node.saved_query_id) {
                        actions.loadLineageGraph()
                    }
                }
            },
            // This page is about the deleted view, so it has nowhere left to stand. The same delete runs
            // from the SQL editor, which keeps its own tab, so the navigation belongs here and not in the
            // shared materialization logic.
            deleteDataWarehouseSavedQuerySuccess: ({ payload }) => {
                if (payload && payload === values.node?.saved_query_id) {
                    router.actions.push(urls.models())
                }
            },
        }
    }),
    urlToAction(({ actions, props }) => {
        // Clicking a node in the lineage graph navigates model to model. The outgoing model's logic
        // is still mounted while the new URL lands, so it must ignore routes for another id.
        const applyTab = (id: string | undefined, tab: unknown): void => {
            if (id !== props.id) {
                return
            }
            // `tests` is the tab's old URL segment; keep links built before the rename working.
            if (tab === 'tests') {
                router.actions.replace(urls.nodeDetail(id, 'data-quality'))
                return
            }
            actions.setCurrentTab(isNodeDetailSceneTab(tab) ? tab : null)
            actions.canonicalizeTab()
        }

        return {
            [urls.nodeDetail(':id', ':tab' as NodeDetailSceneTab)]: ({ id, tab }) => applyTab(id, tab),
            [urls.nodeDetail(':id')]: ({ id }) => applyTab(id, undefined),
        }
    }),
    afterMount(({ actions }) => {
        actions.loadNode()
    }),
])