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.

22.5 KB
Raw Blame
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { createElement } from 'react'

import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'
import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'
import {
    DataWarehouseSavedQueryUpdate,
    dataWarehouseViewsLogic,
} from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { materializationJobsLogic } from 'scenes/data-warehouse/saved_queries/materializationJobsLogic'
import { urls } from 'scenes/urls'

import { useMocks } from '~/mocks/jest'
import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { AccessControlLevel, DataModelingNode, DataModelingNodeType, DataWarehouseSavedQuery } from '~/types'

import { NodeDetailOverview } from './NodeDetailOverview'
import { NodeDetailQuery } from './NodeDetailQuery'
import { NodeDetailSceneTab, nodeDetailQueryEditorTabId, nodeDetailSceneLogic } from './nodeDetailSceneLogic'
import { NodeDetailTests } from './NodeDetailTests'

const NODE_ID = 'node-1'
const SAVED_QUERY_ID = 'saved-query-1'

function buildNode(type: DataModelingNodeType, overrides: Partial<DataModelingNode> = {}): DataModelingNode {
    return {
        id: NODE_ID,
        name: 'orders',
        type,
        created_at: '2024-01-01T00:00:00Z',
        updated_at: '2024-01-01T00:00:00Z',
        upstream_count: 0,
        downstream_count: 0,
        saved_query_id: type === 'table' || type === 'metric' ? undefined : SAVED_QUERY_ID,
        ...overrides,
    }
}

describe('nodeDetailSceneLogic', () => {
    let logic: ReturnType<typeof nodeDetailSceneLogic.build>
    let node: DataModelingNode
    let savedQuery: Partial<DataWarehouseSavedQuery>

    const mountScene = async (path: string, id = NODE_ID): Promise<void> => {
        router.actions.push(path)
        logic = nodeDetailSceneLogic({ id })
        logic.mount()
        await expectLogic(logic).toFinishAllListeners()
    }

    beforeEach(() => {
        node = buildNode('view')
        savedQuery = { id: SAVED_QUERY_ID, name: 'orders', columns: [], is_materialized: false }
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/environments/:team_id/warehouse_saved_queries/:id/': () => [200, savedQuery],
            },
        })
        initKeaTests()
    })

    afterEach(() => {
        cleanup()
        logic?.unmount()
    })

    it.each([undefined, {}])(
        'uses node suspension only until saved-query suspension is available (%s)',
        async (savedSuspension) => {
            node = buildNode('matview', {
                suspended: {
                    clickhouse: { at: '2026-09-13T12:00:00Z', reason: 'Source unavailable', job_id: 'job-1' },
                },
            })
            savedQuery = { ...savedQuery, is_materialized: true, status: 'Failed', suspended: savedSuspension }
            await mountScene(urls.nodeDetail(NODE_ID))
            const jobs = materializationJobsLogic({ viewId: SAVED_QUERY_ID })
            jobs.mount()
            try {
                await expectLogic(jobs).toDispatchActions(['loadSavedQuerySuccess'])
                render(createElement(NodeDetailOverview, { id: NODE_ID }))
                expect(screen.queryByText('Suspended') !== null).toBe(savedSuspension === undefined)
            } finally {
                jobs.unmount()
            }
        }
    )

    // A model with no tab in the URL has to land somewhere useful for its kind, and the URL has to
    // say where it landed — otherwise a refresh or a shared link reopens a different tab.
    it.each<[string, DataModelingNodeType, boolean, NodeDetailSceneTab]>([
        ['a materialized view', 'matview', true, 'materialization'],
        ['a plain view', 'view', false, 'query'],
        ['an endpoint', 'endpoint', true, 'query'],
        ['a table', 'table', false, 'lineage'],
    ])('opens %s on its own default tab', async (_case, type, materialized, expectedTab) => {
        node = buildNode(type)
        savedQuery = { ...savedQuery, is_materialized: materialized }

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.effectiveTab).toEqual(expectedTab)
        expect(logic.values.currentTab).toEqual(expectedTab)
    })

    // An endpoint's query is versioned by the endpoint, and a viewer cannot save a view, so only
    // an editor on a plain or materialized view gets the editable query.
    it.each<[string, DataModelingNodeType, AccessControlLevel, boolean]>([
        ['an editor on a view', 'view', AccessControlLevel.Editor, true],
        ['an editor on a materialized view', 'matview', AccessControlLevel.Editor, true],
        ['a viewer on a view', 'view', AccessControlLevel.Viewer, false],
        ['an editor on an endpoint', 'endpoint', AccessControlLevel.Editor, false],
    ])('decides whether the query is editable for %s', async (_case, type, accessLevel, expected) => {
        node = buildNode(type)
        savedQuery = {
            ...savedQuery,
            user_access_level: accessLevel,
            query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },
        }

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.canEditQuery).toBe(expected)
    })

    // The buttons above the editor have no access to its bindings, so they act through the editor
    // mounted under the scene's tab id. A wrong id would leave them clicking into nothing.
    it('sends Update view and Discard changes to the mounted query editor', async () => {
        savedQuery = { ...savedQuery, query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' } }
        await mountScene(urls.nodeDetail(NODE_ID))
        const editor = sqlEditorLogic({
            tabId: nodeDetailQueryEditorTabId(SAVED_QUERY_ID),
            mode: SQLEditorMode.Embedded,
        })
        editor.mount()
        try {
            editor.actions.editView('SELECT 1', savedQuery as DataWarehouseSavedQuery)
            await expectLogic(editor).toDispatchActions(['editView', 'createTab', 'updateTab'])
            editor.actions.setQueryInput('SELECT 2')

            logic.actions.updateViewFromQueryEditor()
            await expectLogic(editor).toDispatchActions(['reviewEditingViewUpdate', 'reviewViewUpdate'])

            logic.actions.discardQueryEditorChanges()
            await expectLogic(editor).toDispatchActions(['discardChanges'])
        } finally {
            editor.unmount()
        }
    })

    // Saving a new query from this page changes what the model depends on, and the lineage tab stays
    // mounted, so it must reload. A frequency change reaches the same success action without a query.
    it.each<[string, Partial<DataWarehouseSavedQueryUpdate>, number]>([
        ['changes the query', { query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' } }, 1],
        ['changes only the sync frequency', { sync_frequency: '24hour' }, 0],
    ])('reloads the lineage graph only when an update %s', async (_case, change, expectedReloads) => {
        const lineageRequests = jest.fn(() => [200, { nodes: [], edges: [] }])
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': lineageRequests,
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/environments/:team_id/warehouse_saved_queries/:id/': () => [200, savedQuery],
            },
        })
        await mountScene(urls.nodeDetail(NODE_ID))
        const requestsBefore = lineageRequests.mock.calls.length

        dataWarehouseViewsLogic.actions.updateDataWarehouseSavedQuerySuccess([], { id: SAVED_QUERY_ID, ...change })
        await expectLogic(logic).toFinishAllListeners()

        expect(lineageRequests.mock.calls.length - requestsBefore).toBe(expectedReloads)
    })

    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('keeps the current model in its lineage when its type is hidden', async () => {
        await mountScene(urls.nodeDetail(NODE_ID, 'lineage'))
        logic.actions.loadLineageGraphSuccess({
            currentNodeId: NODE_ID,
            nodes: [buildNode('table', { id: 'source' }), node, buildNode('metric', { id: 'revenue' })],
            edges: [
                { id: 'e1', source_id: 'source', target_id: NODE_ID },
                { id: 'e2', source_id: NODE_ID, target_id: 'revenue' },
            ],
        })

        logic.actions.setLineageTypeFilter(['table'])

        expect(logic.values.lineageVisibleNodeIds).toEqual(new Set(['source', NODE_ID]))
    })

    it('replaces a backing-resource URL with the canonical node URL', async () => {
        await mountScene(
            combineUrl(urls.nodeDetail(SAVED_QUERY_ID, 'lineage'), { lookup: 'saved_query' }).url,
            SAVED_QUERY_ID
        )

        expect(router.values.location.pathname).toEqual(`/project/997${urls.nodeDetail(NODE_ID, 'lineage')}`)
        expect(router.values.searchParams).toEqual({})
    })

    it('adds data quality for a warehouse table ID and loads its details', async () => {
        node = buildNode('table', { warehouse_table_id: 'table-1' })
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/environments/:team_id/warehouse_tables/:id/': {
                    id: 'table-1',
                    name: 'orders',
                    format: 'Parquet',
                    external_data_source: { id: 'source-1' },
                    external_schema: { id: 'schema-1' },
                },
                '/api/environments/:team_id/external_data_sources/:id/': {
                    id: 'source-1',
                    source_type: 'Stripe',
                },
                '/api/environments/:team_id/external_data_schemas/:id/': {
                    id: 'schema-1',
                    sync_type: 'incremental',
                    sync_frequency: '24hour',
                },
            },
        })

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.availableTabs).toEqual(['lineage', 'data-quality'])
        expect(logic.values.dataQualitySubject).toEqual({ subjectType: 'table', subjectId: 'table-1' })
        expect(logic.values.tableDetails).toMatchObject({
            table: { id: 'table-1' },
            source: { id: 'source-1' },
            schema: { id: 'schema-1' },
        })
    })

    it.each(['events', 'persons', 'groups'])(
        'loads the matching %s subject for data quality without loading warehouse details',
        async (tableName) => {
            node = buildNode('table', { name: tableName, origin: 'posthog' })
            useMocks({
                get: {
                    '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                    '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                    '/api/projects/:team_id/data_quality_checks/subjects/': () => [
                        200,
                        [
                            {
                                subject_type: 'posthog_table',
                                id: `${tableName}-subject`,
                                name: tableName,
                                display_name: '',
                                time_column: 'timestamp',
                                columns: { id: 'String', timestamp: 'DateTime' },
                                editable: true,
                            },
                        ],
                    ],
                },
            })

            await mountScene(urls.nodeDetail(NODE_ID))

            expect(logic.values.availableTabs).toEqual(['lineage', 'data-quality'])
            expect(logic.values.dataQualitySubject).toEqual({
                subjectType: 'posthog_table',
                subjectId: `${tableName}-subject`,
                columns: [
                    { name: 'id', hogql_value: 'id', type: 'String', schema_valid: true },
                    { name: 'timestamp', hogql_value: 'timestamp', type: 'DateTime', schema_valid: true },
                ],
                editable: true,
            })
            expect(logic.values.tableDetails).toBeNull()
            expect(logic.values.tableDetailsError).toBe(false)
        }
    )

    it('keeps the data quality tab for an unsupported PostHog table', async () => {
        node = buildNode('table', { name: 'unsupported_table', origin: 'posthog' })
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/projects/:team_id/data_quality_checks/subjects/': () => [200, []],
            },
        })

        await mountScene(`/models/${NODE_ID}/tests`)

        expect(logic.values.effectiveTab).toEqual('data-quality')
        expect(router.values.location.pathname).toEqual(`/project/997${urls.nodeDetail(NODE_ID, 'data-quality')}`)
        expect(logic.values.dataQualitySubject).toBeNull()

        render(createElement(NodeDetailTests, { id: NODE_ID }))

        expect(screen.getByText('Data quality is not available for this table.')).toBeTruthy()
    })

    it('keeps Lineage available while the PostHog subject request fails', async () => {
        node = buildNode('table', { name: 'events', origin: 'posthog' })
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/projects/:team_id/data_quality_checks/subjects/': () => [500, {}],
            },
        })

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.availableTabs).toEqual(['lineage', 'data-quality'])
        expect(logic.values.lineageGraph).toEqual({ currentNodeId: NODE_ID, nodes: [], edges: [] })
        expect(logic.values.postHogSubjectError).toBe(true)

        render(createElement(NodeDetailTests, { id: NODE_ID }))

        expect(screen.getByText("Couldn't load data quality for this table. Try again.")).toBeTruthy()
    })

    it('records PostHog subject access denials', async () => {
        node = buildNode('table', { name: 'events', origin: 'posthog' })
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/projects/:team_id/data_quality_checks/subjects/': () => [403, {}],
            },
        })

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.postHogSubjectAccessDenied).toBe(true)
        expect(logic.values.postHogSubjectError).toBe(true)

        render(createElement(NodeDetailTests, { id: NODE_ID }))

        expect(
            screen.getByText("You don't have access to data quality for this table. Ask a project admin for access.")
        ).toBeTruthy()
    })

    it('records table detail access denials', async () => {
        node = buildNode('table', { warehouse_table_id: 'table-1' })
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/environments/:team_id/warehouse_tables/:id/': () => [403, {}],
            },
        })

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.tableDetailsAccessDenied).toBe(true)
        expect(logic.values.tableDetailsError).toBe(true)
    })

    it('shows ten columns on each query page', async () => {
        savedQuery = {
            ...savedQuery,
            columns: Array.from({ length: 11 }, (_, index) => ({
                name: `column_${index + 1}`,
                hogql_value: `column_${index + 1}`,
                type: 'string',
                schema_valid: true,
            })),
        }
        await mountScene(urls.nodeDetail(NODE_ID, 'query'))

        render(createElement(NodeDetailQuery, { id: NODE_ID }))

        // The columns panel is collapsed by default.
        expect(screen.queryByText('column_1')).toBeNull()
        fireEvent.click(screen.getByText('Columns (11)'))

        expect(screen.getByText('column_10')).toBeTruthy()
        expect(screen.queryByText('column_11')).toBeNull()
        expect(screen.getByText('1-10 of 11 columns')).toBeTruthy()

        fireEvent.click(screen.getByLabelText('Next page'))

        expect(screen.queryByText('column_10')).toBeNull()
        expect(screen.getByText('column_11')).toBeTruthy()
        expect(screen.getByText('11 of 11 columns')).toBeTruthy()
    })

    it('lists every tab a saved query supports when data quality checks are on', async () => {
        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.availableTabs).toEqual(['query', 'lineage', 'materialization', 'data-quality', 'history'])
    })

    // The tab is gated on the node's saved_query_id, not the loaded saved query, so a load failure
    // leaves it available for its panel to show the error and retry, and a deep link to it holds.
    it('keeps the materialization tab when the saved query fails to load', async () => {
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/environments/:team_id/warehouse_saved_queries/:id/': () => [500, {}],
            },
        })

        await mountScene(urls.nodeDetail(NODE_ID, 'materialization'))

        expect(logic.values.savedQueryError).toBe(true)
        expect(logic.values.availableTabs).toContain('materialization')
        expect(logic.values.effectiveTab).toEqual('materialization')
    })

    it('marks the saved query deleted instead of failing when it returns 404', async () => {
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/environments/:team_id/warehouse_saved_queries/:id/': () => [404, { detail: 'Not found.' }],
            },
        })

        await mountScene(urls.nodeDetail(NODE_ID))

        await expectLogic(logic)
            .toDispatchActions(['loadSavedQuerySuccess'])
            .toNotHaveDispatchedActions(['loadSavedQueryFailure'])
        expect(logic.values.savedQueryDeleted).toBe(true)
        expect(logic.values.savedQueryError).toBe(false)
    })

    // A failed saved-query request leaves the scene rendering with nothing to read is_materialized
    // from. Reading that absence as "not materialized" would open a matview on Query and print
    // "Materialization: Off" under its own Materialized view tag.
    it('falls back to the node type for materialization when the saved query fails to load', async () => {
        node = buildNode('matview')
        useMocks({
            get: {
                '/api/environments/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
                '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],
                '/api/environments/:team_id/warehouse_saved_queries/:id/': () => [500, {}],
            },
        })

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.savedQueryError).toBe(true)
        expect(logic.values.isMaterialized).toBe(true)
        expect(logic.values.effectiveTab).toEqual('materialization')
    })

    it('falls back to the default tab when the URL names a tab this model does not have', async () => {
        node = buildNode('table')

        await mountScene(urls.nodeDetail(NODE_ID, 'data-quality'))

        expect(logic.values.effectiveTab).toEqual('lineage')
        expect(logic.values.currentTab).toEqual('lineage')
    })

    // Clicking through the lineage graph navigates model to model. The outgoing model's logic is
    // still mounted when the next URL lands, and must not adopt the tab meant for its successor.
    it('ignores a route for a different model', async () => {
        await mountScene(urls.nodeDetail(NODE_ID, 'query'))

        router.actions.push(urls.nodeDetail('node-2', 'lineage'))

        expect(logic.values.currentTab).toEqual('query')
    })

    // The node's copy of the run state only advances on a DAG run, so after a Sync now it reports
    // the run before it — and the strip would contradict the materialization tab beside it.
    it('reads the run state from the saved query, falling back to the node', async () => {
        node = buildNode('matview', { last_run_at: '2026-08-06T19:00:00Z', last_run_status: 'Failed' })
        savedQuery = { ...savedQuery, last_run_at: '2026-08-24T15:36:00Z', status: 'Completed' }

        await mountScene(urls.nodeDetail(NODE_ID))

        expect(logic.values.effectiveLastRunAt).toEqual('2026-08-24T15:36:00Z')
        expect(logic.values.effectiveLastRunStatus).toEqual('Completed')
    })

    // The delete runs from a shared component that also renders in the SQL editor, so the page the
    // deleted view owns is the one that has to leave — and only for its own view.
    it.each([
        ['its own view', SAVED_QUERY_ID, '/project/997/models'],
        ['another view', 'saved-query-2', `/project/997${urls.nodeDetail(NODE_ID, 'query')}`],
    ])('leaves for Models when %s is deleted', async (_name, deletedId, expectedPath) => {
        await mountScene(urls.nodeDetail(NODE_ID))

        dataWarehouseViewsLogic.actions.deleteDataWarehouseSavedQuerySuccess([], deletedId)

        expect(router.values.location.pathname).toEqual(expectedPath)
    })

    it('keeps a tab mounted once it has been visited', async () => {
        await mountScene(urls.nodeDetail(NODE_ID))

        router.actions.push(urls.nodeDetail(NODE_ID, 'lineage'))

        expect(logic.values.visitedTabs).toEqual(['query', 'lineage'])
    })
})