:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): health, runs and graph tabs on the models page (#96890)
Jovan Sakovic16ce5fe3842d
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex d3fa78a1601d..f66b29198d3c 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -294,7 +294,6 @@ export const FEATURE_FLAGS = {DASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platformDATA_MODELING_INCREMENTAL_VIEWS: 'data-modeling-incremental-views', // owner: #team-data-modelingDATA_MODELING_SUSPEND_FAILING_NODES: 'data-modeling-suspend-failing-nodes', // owner: #team-data-modeling- DATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modelingDATA_QUALITY_CHECKS: 'data-quality-checks', // owner: #team-data-modelingDATA_WAREHOUSE_COLUMN_STATISTICS: 'data-warehouse-column-statistics', // owner: #team-warehouse-sourcesDATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sourcesdiff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex fc22006d425a..27ba236e0870 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -42,6 +42,7 @@ import type { SourceSceneTab } from '../../products/data_warehouse/frontend/scenimport { configurationRedirect, resolveSettingSlug } from '../../products/error_tracking/frontend/settingsRedirects'import type { InboxTabKey } from '../../products/signals/frontend/inbox/types'import type { WorkflowsSceneTab } from '../../products/workflows/frontend/WorkflowsScene'+import type { ModelsSceneTab } from './scenes/models/modelsSceneLogic'import type { NodeDetailSceneTab } from './scenes/models/nodeDetailSceneLogic'import {ActionType,@@ -1168,7 +1169,7 @@ export const productUrls = {const query = params.toString()return query ? `/data-ops?${query}` : '/data-ops'},- models: (): string => '/models',+ models: (tab?: ModelsSceneTab): string => (tab && tab !== 'overview' ? `/models?tab=${tab}` : '/models'),nodeDetail: (id: string, tab?: NodeDetailSceneTab): string => `/models/${id}${tab ? `/${tab}` : ''}`,sources: (): string => '/data-management/sources',dataWarehouseSource: (id: string, tab?: SourceSceneTab): string =>diff --git a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsxindex 20c8d8f00515..6aa2b7940669 100644--- a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx+++ b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx@@ -15,7 +15,6 @@ import { ProductKey } from '~/queries/schema/schema-general'import { DataQualityOverview } from 'products/data_quality/frontend/overview/DataQualityOverview'import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'-import { DataModelingTab } from './scene/DataModelingTab'import { MonitoringTab } from './scene/MonitoringTab'import { OverviewTab } from './scene/OverviewTab'import { SettingsTab } from './scene/SettingsTab'@@ -30,7 +29,6 @@ const TAB_LABELS: Record<DataWarehouseTab, string> = {[DataWarehouseTab.OVERVIEW]: 'Overview',[DataWarehouseTab.MONITORING]: 'Monitoring',[DataWarehouseTab.SETTINGS]: 'Settings',- [DataWarehouseTab.MODELING]: 'Modeling',[DataWarehouseTab.DATA_QUALITY]: 'Data quality',}@@ -42,8 +40,6 @@ function tabContent(tab: DataWarehouseTab): JSX.Element {return <MonitoringTab />case DataWarehouseTab.SETTINGS:return <SettingsTab />- case DataWarehouseTab.MODELING:- return <DataModelingTab />case DataWarehouseTab.DATA_QUALITY:return <DataQualityOverview />}diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.tsindex 90900eec7699..6a5529ff91e7 100644--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts@@ -15,7 +15,6 @@ export enum DataWarehouseTab {OVERVIEW = 'overview',MONITORING = 'monitoring',SETTINGS = 'settings',- MODELING = 'modeling',DATA_QUALITY = 'data-quality',}@@ -123,9 +122,6 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([tabs.push(DataWarehouseTab.OVERVIEW)tabs.push(DataWarehouseTab.MONITORING)}- if (featureFlags[FEATURE_FLAGS.DATA_MODELING_TAB]) {- tabs.push(DataWarehouseTab.MODELING)- }if (featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS]) {tabs.push(DataWarehouseTab.DATA_QUALITY)}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 4d2d6007ddbc..9d28255d6e25 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -44,7 +44,7 @@ import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'import { findQueryAtCursor, type QueryRange, splitQueries } from 'lib/monaco/multiQueryUtils'import { objectsEqual } from 'lib/utils/objects'-import { lazyWithRetry, retryImport } from 'lib/utils/retryImport'+import { lazyWithRetry } from 'lib/utils/retryImport'import { slugify } from 'lib/utils/strings'import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'@@ -2443,14 +2443,6 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([actions.deleteDraft(fromDraft, savedQuery?.name)}- // reload DAGs so newly created default DAG appears. Imported on demand: the data- // modeling logic pulls in the graph library, which nothing else on the SQL editor path needs.- void retryImport(() => import('../scene/dataModelingLogic'))- .then(({ dataModelingLogic }) => dataModelingLogic.findMounted()?.actions.loadDags())- .catch(() => {- /* best-effort DAG refresh; a stale chunk load isn't worth failing the save for */- })-if (isPartialSave && savedQuery) {actions.createTab(savedQuery.query?.query ?? queryToSave.query, savedQuery)}diff --git a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsxindex 354117b20dd9..89315e2bdca5 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx+++ b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx@@ -18,6 +18,7 @@ import { userLogic } from 'scenes/userLogic'import { AccessControlLevel, AccessControlResourceType, DataModelingJob, LogEntryLevel } from '~/types'+import { SERVING_ENGINE } from 'products/data_modeling/frontend/suspension'import { MaterializationRunErrorCell } from 'products/data_warehouse/frontend/shared/components/MaterializationRunErrorCell'import { IncrementalConfigOptions } from '../editor/IncrementalConfigFields'@@ -34,9 +35,6 @@ import {const LOG_LEVELS: LogEntryLevel[] = ['LOG', 'INFO', 'WARN', 'WARNING', 'ERROR']-// Matches DataModelingJobEngine.CLICKHOUSE, the engine materialized queries are served from.-const SERVING_ENGINE = 'clickhouse'-interface MaterializationStatusPanelProps {viewId: string/**diff --git a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsxindex 49238e99d276..633dfce2fec0 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx+++ b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx@@ -13,7 +13,8 @@ export type SyncFrequencyValue = DataModelingSyncInterval | 'never'* request the scheduler quietly tightens. The bar carries the wording once in its label, so each* segment only has to say which duration it is.*/-const CADENCE_LABELS: Record<DataModelingSyncInterval, string> = {+/** How a cadence is spoken after "every", so every surface says "every 6 hours" the same way. */+export const CADENCE_LABELS: Record<DataModelingSyncInterval, string> = {'15min': '15 minutes','30min': '30 minutes','1hour': '1 hour',diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.tsindex 722c09a1c227..5128cc2ae5da 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.ts@@ -5,6 +5,9 @@ import { DataModelingJob } from '~/types'const LOGS_FILTER_FORMAT = 'YYYY-MM-DD HH:mm:ss'+/** The fields the duration helpers read. Both the handwritten job type and the generated `DataModelingJobApi` satisfy it. */+type JobTiming = Pick<DataModelingJob, 'created_at' | 'updated_at' | 'last_run_at'> & { status: string }+function isParseableDate(value: string | null | undefined): value is string {return !!value && dayjs(value).isValid()}@@ -21,7 +24,7 @@ function latestOf(...values: (string | null | undefined)[]): string | null {* stamped by different write paths: a model save advances both fields, a bulk `QuerySet.update()`* skips the `auto_now` on `updated_at`, and rows predating the failure stamp still carry the run's* start time in `last_run_at`. Whichever is later is the end in all three cases. */-function jobEndTimestamp(job: DataModelingJob): string | null {+function jobEndTimestamp(job: JobTiming): string | null {if (job.status === 'Running') {return null}@@ -31,7 +34,7 @@ function jobEndTimestamp(job: DataModelingJob): string | null {return latestOf(job.updated_at, job.last_run_at)}-export function computeJobDuration(job: DataModelingJob): string {+export function computeJobDuration(job: JobTiming): string {if (job.status === 'Running') {return 'In progress'}diff --git a/frontend/src/scenes/data-warehouse/scene/DataModelingTab.tsx b/frontend/src/scenes/data-warehouse/scene/DataModelingTab.tsxdeleted file mode 100644index fd977a639e17..000000000000--- a/frontend/src/scenes/data-warehouse/scene/DataModelingTab.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconDirectedGraph, IconList } from '@posthog/icons'-import { LemonInput, LemonSegmentedButton, Spinner } from '@posthog/lemon-ui'--import { dataModelingLogic } from './dataModelingLogic'-import { GraphView } from './modeling/GraphView'-import { TableView } from './modeling/TableView'--function ToolBar(): JSX.Element {- const { viewNodes, searchTerm, viewMode } = useValues(dataModelingLogic)- const { setSearchTerm, setViewMode } = useActions(dataModelingLogic)-- return (- <div className="flex gap-2 items-center">- {(viewNodes.length > 0 || searchTerm) && (- <LemonInput type="search" placeholder="Search models..." onChange={setSearchTerm} value={searchTerm} />- )}- <div className="flex gap-2 ml-auto items-center">- <LemonSegmentedButton- value={viewMode}- onChange={(value) => setViewMode(value)}- options={[- {- value: 'graph',- icon: <IconDirectedGraph />,- tooltip: 'Graph view',- },- { value: 'list', icon: <IconList />, tooltip: 'List view' },- ]}- size="small"- />- </div>- </div>- )-}--export function DataModelingTab(): JSX.Element {- const { viewMode, nodesLoading } = useValues(dataModelingLogic)-- if (nodesLoading) {- return (- <div className="flex items-center justify-center h-[calc(100vh-17rem)]">- <Spinner className="text-4xl" />- </div>- )- }-- return (- <div className="space-y-4 h-full">- <ToolBar />- {viewMode === 'graph' ? <GraphView /> : <TableView />}- </div>- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsx b/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsxindex 3caa290b12e8..161f1325b713 100644--- a/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsx+++ b/frontend/src/scenes/data-warehouse/scene/ViewsTab.tsx@@ -1,11 +1,14 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonInput, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { IconInfo } from '@posthog/icons'+import { LemonButton, LemonInput, LemonSelect, LemonTable, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'import { urls } from 'scenes/urls'@@ -19,10 +22,26 @@ import {DataWarehouseSavedQueryRunHistory,} from '~/types'-import { STATUS_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { NodeSuspensionApi } from 'products/data_modeling/frontend/generated/api.schemas'+import { statusBackgroundClass } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { SEARCH_SYNTAX_HELP } from 'products/data_modeling/frontend/lineage/SearchSyntaxHelp'+import { StatusTag } from 'products/data_modeling/frontend/lineage/StatusTag'import { TableCertificationTag } from '../TableCertificationBadge'-import { PAGE_SIZE, viewsTabLogic } from './viewsTabLogic'+import { PAGE_SIZE, ViewTypeFilter, viewsTabLogic } from './viewsTabLogic'++type ViewColumn = LemonTableColumn<DataWarehouseSavedQuery, keyof DataWarehouseSavedQuery | undefined>++const VIEW_TYPE_TOOLTIPS = {+ materialized: 'Refreshed on a schedule and stored as a table, so a read hits stored rows.',+ view: 'Runs its query every time it is read.',+}++const TYPE_FILTER_OPTIONS: { value: ViewTypeFilter; label: string }[] = [+ { value: 'all', label: 'All types' },+ { value: 'materialized', label: 'Materialized views' },+ { value: 'view', label: 'Views' },+]const getDisabledReason = (view: DataWarehouseSavedQuery): string | undefined => {if (view.managed_viewset_kind !== null) {@@ -31,7 +50,6 @@ const getDisabledReason = (view: DataWarehouseSavedQuery): string | undefined =>if (view.origin === DataWarehouseSavedQueryOrigin.ENDPOINT) {return `Cannot delete a view that belongs to an endpoint. You can disable materialization on this endpoint's page.`}-return undefined}@@ -42,15 +60,13 @@ function RunHistoryDisplay({runHistory?: DataWarehouseSavedQueryRunHistory[]loading?: boolean}): JSX.Element {- if (loading) {+ if (loading && !runHistory) {return <Spinner className="text-sm" />}-if (!runHistory || runHistory.length === 0) {return <span className="text-muted">-</span>}- // Show up to 5 most recent runs, reversed so the most recent is on the rightconst displayRuns = runHistory.slice(0, 5).reverse()return (@@ -63,9 +79,7 @@ function RunHistoryDisplay({title={`${run.status}${friendlyTime ? ` - ${friendlyTime}` : ''}`}placement="top">- <div- className={`w-4 h-4 rounded-sm ${run.status === 'Completed' ? 'bg-success' : 'bg-danger'}`}- />+ <div className={`w-4 h-4 rounded-sm ${statusBackgroundClass(run.status)}`} /></Tooltip>)})}@@ -73,31 +87,60 @@ function RunHistoryDisplay({)}-function DependencyCount({ count, loading }: { count?: number; loading?: boolean }): JSX.Element {- if (loading || count === undefined) {- return <Spinner className="text-sm" />+function StatusCell({+ view,+ suspension,+}: {+ view: DataWarehouseSavedQuery+ suspension?: NodeSuspensionApi+}): JSX.Element {+ if (!view.is_materialized) {+ return <span className="text-muted">-</span>}- return <span>{count}</span>+ if (suspension) {+ return (+ <Tooltip+ title={+ <div className="flex flex-col gap-1">+ <div>Scheduled runs stopped after this model failed repeatedly.</div>+ <div className="opacity-75">{suspension.reason}</div>+ </div>+ }+ interactive+ >+ <LemonTag type="warning">Suspended</LemonTag>+ </Tooltip>+ )+ }+ if (!view.status) {+ return <span className="text-muted">-</span>+ }+ if (view.latest_error && view.status === 'Failed') {+ return (+ <Tooltip title={view.latest_error} interactive>+ <LemonTag type="danger">Failed</LemonTag>+ </Tooltip>+ )+ }+ return <StatusTag status={view.status} />}interface ViewsTabProps {/** Optional function to build the URL when clicking on a view. Defaults to SQL editor. */getViewUrl?: (view: DataWarehouseSavedQuery) => string+ /** Saved query id -> suspension. List responses carry no suspension, so the scene passes it in. */+ suspensionByViewId?: Record<string, NodeSuspensionApi | undefined>}-export function ViewsTab({ getViewUrl }: ViewsTabProps = {}): JSX.Element {+export function ViewsTab({ getViewUrl, suspensionByViewId }: ViewsTabProps = {}): JSX.Element {const {filteredViews,- filteredMaterializedViews,- visibleMaterializedViews,visibleViews,viewsLoading,searchTerm,- materializedViewDependenciesMapLoading,- viewDependenciesMapLoading,+ typeFilter,+ currentPage,runHistoryMapLoading,- materializedViewsCurrentPage,- viewsCurrentPage,accessControlModalOpen,editingAccessControlView,featureFlags,@@ -105,30 +148,139 @@ export function ViewsTab({ getViewUrl }: ViewsTabProps = {}): JSX.Element {} = useValues(viewsTabLogic)const {setSearchTerm,+ setTypeFilter,+ setPage,deleteView,runMaterialization,- setMaterializedViewsPage,- setViewsPage,openAccessControlModal,closeAccessControlModal,} = useActions(viewsTabLogic)const warehouseAccessControlEnabled = !!featureFlags[FEATURE_FLAGS.HOGQL_WAREHOUSE_ACCESS_CONTROL]- const nameWithCertification = (view: DataWarehouseSavedQuery, content: JSX.Element): JSX.Element => (- <div className="flex items-center gap-2">- <div>{content}</div>- <TableCertificationTag certification={viewsMapById[view.id]?.certification} />- </div>- )-- const accessControlMenuButton = (view: DataWarehouseSavedQuery): JSX.Element | null => {- if (!warehouseAccessControlEnabled || view.managed_viewset_kind !== null) {- return null+ const viewLink = (view: DataWarehouseSavedQuery): { to: string; description?: string } => {+ if (view.origin === DataWarehouseSavedQueryOrigin.ENDPOINT) {+ return { to: urls.endpoint(view.name), description: `Created by the ${view.name} endpoint` }+ }+ if (view.managed_viewset_kind !== null) {+ return {+ to: getViewUrl?.(view) ?? urls.dataWarehouseManagedViewsets(),+ description: `Managed by the ${view.managed_viewset_kind} viewset`,+ }}- return <LemonButton onClick={() => openAccessControlModal(view)}>Access control</LemonButton>+ return { to: getViewUrl?.(view) ?? urls.sqlEditor({ view_id: view.id }) }}+ const columns: LemonTableColumns<DataWarehouseSavedQuery> = [+ {+ title: 'Name',+ key: 'name',+ render: (_, view) => {+ const { to, description } = viewLink(view)+ return (+ <LemonTableLink+ to={to}+ title={+ <>+ {view.name}+ <Tooltip+ title={+ view.is_materialized ? VIEW_TYPE_TOOLTIPS.materialized : VIEW_TYPE_TOOLTIPS.view+ }+ >+ <LemonTag+ type={view.is_materialized ? 'highlight' : 'option'}+ size="small"+ className="mr-1"+ >+ {view.is_materialized ? 'Materialized' : 'View'}+ </LemonTag>+ </Tooltip>+ <TableCertificationTag certification={viewsMapById[view.id]?.certification} />+ </>+ }+ description={description}+ />+ )+ },+ } as ViewColumn,+ {+ title: 'Status',+ key: 'status',+ render: (_, view) => <StatusCell view={view} suspension={suspensionByViewId?.[view.id]} />,+ } as ViewColumn,+ {+ title: 'Last run',+ key: 'last_run_at',+ render: (_, view) => {+ if (!view.is_materialized) {+ return <span className="text-muted">-</span>+ }+ return view.last_run_at ? (+ <TZLabel time={view.last_run_at} formatDate="MMM DD, YYYY" formatTime="HH:mm" />+ ) : (+ 'Never'+ )+ },+ } as ViewColumn,+ {+ title: 'Run history',+ key: 'run_history',+ tooltip: 'Up to 5 most recent runs, oldest first',+ render: (_, view) =>+ view.is_materialized ? (+ <RunHistoryDisplay runHistory={view.run_history} loading={runHistoryMapLoading} />+ ) : (+ <span className="text-muted">-</span>+ ),+ } as ViewColumn,+ createdByColumn<DataWarehouseSavedQuery>() as ViewColumn,+ createdAtColumn<DataWarehouseSavedQuery>() as ViewColumn,+ {+ key: 'actions',+ width: 0,+ render: (_, view) => (+ <More+ overlay={+ <>+ {view.is_materialized && (+ <AccessControlAction+ resourceType={AccessControlResourceType.WarehouseObjects}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ onClick={() => runMaterialization(view.id)}+ disabledReason={+ view.status === 'Running' ? 'Materialization is already running' : undefined+ }+ >+ Sync now+ </LemonButton>+ </AccessControlAction>+ )}+ {warehouseAccessControlEnabled && view.managed_viewset_kind === null && (+ <LemonButton onClick={() => openAccessControlModal(view)}>Access control</LemonButton>+ )}+ <AccessControlAction+ resourceType={AccessControlResourceType.WarehouseObjects}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={view.user_access_level}+ >+ <LemonButton+ status="danger"+ onClick={() => deleteView(view.id)}+ disabledReason={getDisabledReason(view)}+ >+ Delete+ </LemonButton>+ </AccessControlAction>+ </>+ }+ />+ ),+ } as ViewColumn,+ ]+return (<div className="space-y-4">{editingAccessControlView ? (@@ -141,349 +293,58 @@ export function ViewsTab({ getViewUrl }: ViewsTabProps = {}): JSX.Element {description="Control who can query this view. Users without access won't see it and queries referencing it will fail for them."/>) : null}- {(filteredViews.length > 0 || filteredMaterializedViews.length > 0 || searchTerm) && (- <div className="flex gap-2 justify-between items-center">- <LemonInput- type="search"- placeholder="Search views..."- onChange={setSearchTerm}- value={searchTerm}- />- </div>- )}-- {/* Materialized Views Section */}- {filteredMaterializedViews.length > 0 && (- <div>- <h3 className="text-lg font-semibold mb-2">Materialized views</h3>- <p className="text-muted mb-2">- Materialized views are refreshed on a schedule and stored as tables for faster query- performance.- </p>- <LemonTable- dataSource={visibleMaterializedViews}- loading={viewsLoading}- columns={[- {- title: 'Name',- key: 'name',- render: (_, view: DataWarehouseSavedQuery) =>- nameWithCertification(- view,- view.managed_viewset_kind !== null ? (- <>- <Tooltip- interactive- title={- <>- You cannot edit the definition for a view that belongs to a- managed viewset. You can enable/disable the viewset in the{' '}- <Link to={urls.dataWarehouseManagedViewsets()}>- Managed Viewsets- </Link>{' '}- page.- </>- }- >- <span className="font-bold text-primary">{view.name}</span>- </Tooltip>- <br />- <span className="text-muted text-xs">- Created by the{' '}- <Link- to={urls.dataWarehouseManagedViewsets()}- className="text-muted"- >- <code>{view.managed_viewset_kind}</code>- </Link>{' '}- managed viewset- </span>- </>- ) : view.origin === DataWarehouseSavedQueryOrigin.ENDPOINT ? (- <LemonTableLink- to={urls.endpoint(view.name)}- title={view.name}- description={`Created by the ${view.name} endpoint.`}- />- ) : (- <LemonTableLink- to={getViewUrl?.(view) ?? urls.sqlEditor({ view_id: view.id })}- title={view.name}- description="Materialized view"- />- )- ),- },- {- title: 'Last run',- key: 'last_run_at',- render: (_, view) => {- return view.last_run_at ? (- <TZLabel time={view.last_run_at} formatDate="MMM DD, YYYY" formatTime="HH:mm" />- ) : (- 'Never'- )- },- },- {- title: 'Status',- key: 'status',- render: (_, view) => {- if (!view.status) {- return null- }- if (view.latest_error && view.status === 'Failed') {- return (- <Tooltip title={view.latest_error} interactive>- <LemonTag type="danger">Failed</LemonTag>- </Tooltip>- )- }- return (- <LemonTag type={STATUS_TAG_SETTINGS[view.status] || 'default'}>- {view.status}- </LemonTag>- )- },- },- {- title: 'Run history',- key: 'run_history',- tooltip: 'Recent run status (up to 5 most recent)',- render: (_, view) => (- <RunHistoryDisplay runHistory={view.run_history} loading={runHistoryMapLoading} />- ),- },- {- title: 'Upstream',- key: 'upstream_count',- tooltip: 'Number of immediate upstream dependencies',- render: (_, view) => (- <DependencyCount- count={view.upstream_dependency_count}- loading={materializedViewDependenciesMapLoading}- />- ),- },- {- title: 'Downstream',- key: 'downstream_count',- tooltip: 'Number of immediate downstream dependencies',- render: (_, view) => (- <DependencyCount- count={view.downstream_dependency_count}- loading={materializedViewDependenciesMapLoading}- />- ),- },- {- key: 'actions',- width: 0,- render: (_, view) => (- <More- overlay={- <>- <AccessControlAction- resourceType={AccessControlResourceType.WarehouseObjects}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton- onClick={() => runMaterialization(view.id)}- disabledReason={- view.status === 'Running'- ? 'Materialization is already running'- : undefined- }- >- Sync now- </LemonButton>- </AccessControlAction>- {accessControlMenuButton(view)}- <AccessControlAction- resourceType={AccessControlResourceType.WarehouseObjects}- minAccessLevel={AccessControlLevel.Editor}- userAccessLevel={view.user_access_level}- >- <LemonButton- status="danger"- onClick={() => deleteView(view.id)}- disabledReason={getDisabledReason(view)}- >- Delete- </LemonButton>- </AccessControlAction>- </>- }- />- ),- },- ]}- pagination={{- controlled: true,- pageSize: PAGE_SIZE,- currentPage: materializedViewsCurrentPage,- entryCount: filteredMaterializedViews.length,- onForward: () => {- setMaterializedViewsPage(materializedViewsCurrentPage + 1)- },- onBackward: () => {- setMaterializedViewsPage(materializedViewsCurrentPage - 1)- },- }}- />- </div>- )}-- {/* Regular Views Section */}- {filteredViews.length > 0 && (- <div>- <h3 className="text-lg font-semibold mb-2">Views</h3>- <p className="text-muted mb-2">- Views are virtual tables created from SQL queries. They are computed on-the-fly when queried.- </p>- <LemonTable- dataSource={visibleViews}- loading={viewsLoading}- columns={[- {- title: 'Name',- key: 'name',- render: (_, view: DataWarehouseSavedQuery) =>- nameWithCertification(- view,- view.managed_viewset_kind !== null ? (- <>- <Tooltip- interactive- title={- <>- You cannot edit the definition for a view that belongs to a- managed viewset. You can enable/disable the viewset in the{' '}- <Link to={urls.dataWarehouseManagedViewsets()}>- Managed Viewsets- </Link>{' '}- page.- </>- }- >- <span className="font-bold text-primary">{view.name}</span>- </Tooltip>- <br />- <span className="text-muted text-xs">- Created by the{' '}- <Link- to={urls.dataWarehouseManagedViewsets()}- className="text-muted"- >- <code>{view.managed_viewset_kind}</code>- </Link>{' '}- managed viewset- </span>- </>- ) : (- <LemonTableLink- to={getViewUrl?.(view) ?? urls.sqlEditor({ view_id: view.id })}- title={view.name}- />- )- ),- },- {- title: 'Created',- key: 'created_at',- render: (_, view) =>- view.created_at ? (- <TZLabel time={view.created_at} formatDate="MMM DD, YYYY" formatTime="HH:mm" />- ) : (- '-'- ),- },- {- title: 'Upstream',- key: 'upstream_count',- tooltip: 'Number of immediate upstream dependencies',- render: (_, view) => (- <DependencyCount- count={view.upstream_dependency_count}- loading={viewDependenciesMapLoading}- />- ),- },- {- title: 'Downstream',- key: 'downstream_count',- tooltip: 'Number of immediate downstream dependencies',- render: (_, view) => (- <DependencyCount- count={view.downstream_dependency_count}- loading={viewDependenciesMapLoading}- />- ),- },- {- key: 'actions',- width: 0,- render: (_, view) => (- <More- overlay={- <>- {accessControlMenuButton(view)}- <AccessControlAction- resourceType={AccessControlResourceType.WarehouseObjects}- minAccessLevel={AccessControlLevel.Editor}- userAccessLevel={view.user_access_level}- >- <LemonButton- status="danger"- onClick={() => deleteView(view.id)}- disabledReason={getDisabledReason(view)}- >- Delete- </LemonButton>- </AccessControlAction>- </>- }- />- ),- },- ]}- pagination={{- controlled: true,- pageSize: PAGE_SIZE,- currentPage: viewsCurrentPage,- entryCount: filteredViews.length,- onForward: () => {- setViewsPage(viewsCurrentPage + 1)- },- onBackward: () => {- setViewsPage(viewsCurrentPage - 1)- },- }}- />- </div>- )}-- {/* Empty State */}- {!viewsLoading && filteredViews.length === 0 && filteredMaterializedViews.length === 0 && (- <div className="text-center py-12">- <h3 className="text-xl font-semibold mb-2">No views found</h3>- {searchTerm ? (- <p className="text-muted">No views match your search. Try adjusting your search term.</p>+ <div className="flex flex-wrap gap-2 items-center">+ <LemonInput+ type="search"+ size="small"+ placeholder="Search, or +name for upstream"+ value={searchTerm}+ onChange={setSearchTerm}+ className="w-72"+ data-attr="views-search"+ />+ <Tooltip title={SEARCH_SYNTAX_HELP}>+ <IconInfo className="text-base text-secondary" />+ </Tooltip>+ <LemonSelect+ value={typeFilter}+ onChange={setTypeFilter}+ options={TYPE_FILTER_OPTIONS}+ size="small"+ data-attr="views-type-filter"+ />+ </div>+ <LemonTable+ dataSource={visibleViews}+ loading={viewsLoading}+ columns={columns}+ rowKey="id"+ emptyState={+ searchTerm || typeFilter !== 'all' ? (+ 'No views match your filters.') : (- <p className="text-muted">- Create your first view to transform and organize your data warehouse tables.- </p>- )}- <AccessControlAction- resourceType={AccessControlResourceType.WarehouseObjects}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton type="primary" to={urls.sqlEditor({ source: 'view' })} className="inline-block">- Create view- </LemonButton>- </AccessControlAction>- </div>- )}+ <div className="flex flex-col items-start gap-2">+ <span>Create your first view to transform and organize your data warehouse tables.</span>+ <AccessControlAction+ resourceType={AccessControlResourceType.WarehouseObjects}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton type="primary" size="small" to={urls.sqlEditor({ source: 'view' })}>+ Create view+ </LemonButton>+ </AccessControlAction>+ </div>+ )+ }+ pagination={{+ controlled: true,+ pageSize: PAGE_SIZE,+ currentPage,+ entryCount: filteredViews.length,+ onForward: () => setPage(currentPage + 1),+ onBackward: () => setPage(currentPage - 1),+ }}+ /></div>)}diff --git a/frontend/src/scenes/data-warehouse/scene/dataModelingLogic.test.ts b/frontend/src/scenes/data-warehouse/scene/dataModelingLogic.test.tsdeleted file mode 100644index e2744a205307..000000000000--- a/frontend/src/scenes/data-warehouse/scene/dataModelingLogic.test.ts+++ /dev/null@@ -1,226 +0,0 @@-import { expectLogic } from 'kea-test-utils'--import { useMocks } from '~/mocks/jest'-import { initKeaTests } from '~/test/init'--import { dataModelingLogic } from './dataModelingLogic'-import type { Edge, Node } from './modeling/types'--describe('dataModelingLogic', () => {- let logic: ReturnType<typeof dataModelingLogic.build>-- beforeEach(() => {- localStorage.clear()- useMocks({- get: {- '/api/environments/:team_id/data_modeling_dags/': {- results: [- {- id: 'dag-123',- name: 'Test DAG',- description: '',- sync_frequency: '24hour',- node_count: 0,- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- },- ],- },- '/api/environments/:team_id/data_modeling_nodes/': { results: [] },- '/api/environments/:team_id/data_modeling_edges/': { results: [] },- '/api/environments/:team_id/data_modeling_jobs/recent/': [],- '/api/environments/:team_id/data_modeling_jobs/running/': [],- },- })- initKeaTests()- })-- afterEach(() => {- logic?.unmount()- })-- it('lays out only the nodes matched by a lineage search', async () => {- logic = dataModelingLogic()- logic.mount()- await expectLogic(logic)- .toDispatchActions(['loadDataModelingNodesSuccess', 'loadDataModelingEdgesSuccess'])- .toFinishAllListeners()-- const nodes: Node[] = [- {- id: 'source',- type: 'model',- position: { x: 0, y: 0 },- data: {- id: 'source',- name: 'this_view',- type: 'view',- upstreamCount: 0,- downstreamCount: 1,- },- },- {- id: 'unrelated',- type: 'model',- position: { x: 5000, y: 0 },- data: {- id: 'unrelated',- name: 'unrelated_view',- type: 'view',- upstreamCount: 0,- downstreamCount: 0,- },- },- {- id: 'target',- type: 'model',- position: { x: 10000, y: 0 },- data: {- id: 'target',- name: 'dependent_view',- type: 'view',- upstreamCount: 1,- downstreamCount: 0,- },- },- ]- const edges: Edge[] = [- {- id: 'source->target',- source: 'source',- target: 'target',- },- ]-- logic.actions.setNodesRaw(nodes)- logic.actions.setEdges(edges)- logic.actions.setDebouncedSearchTerm('this_view+')- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.enrichedNodes.map((node) => node.id)).toEqual(['source', 'target'])- const [source, target] = logic.values.enrichedNodes- expect(Math.abs(target.position.x - source.position.x)).toBeLessThan(1000)- })-- // A typo must still find the model, matching the SQL editor sidebar. A revert to String.includes()- // would drop these hits and make a failed search look like a missing model.- it('fuzzy-matches the list search so a near-miss term still finds the node', async () => {- useMocks({- get: {- '/api/environments/:team_id/data_modeling_nodes/': {- results: [- {- id: 'n1',- name: 'customer_orders',- type: 'view',- dag: 'dag-123',- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- upstream_count: 0,- downstream_count: 0,- },- ],- },- },- })- logic = dataModelingLogic()- logic.mount()- await expectLogic(logic).toDispatchActions(['loadDataModelingNodesSuccess'])-- logic.actions.setSearchTerm('custmer')- expect(logic.values.filteredNodes.map((n) => n.name)).toEqual(['customer_orders'])- })-- it('fuzzy-matches the graph search so a near-miss term still highlights the node', async () => {- logic = dataModelingLogic()- logic.mount()- await expectLogic(logic)- .toDispatchActions(['loadDataModelingNodesSuccess', 'loadDataModelingEdgesSuccess'])- .toFinishAllListeners()-- const nodes: Node[] = [- {- id: 'match',- type: 'model',- position: { x: 0, y: 0 },- data: { id: 'match', name: 'customer_orders', type: 'view', upstreamCount: 0, downstreamCount: 0 },- },- {- id: 'other',- type: 'model',- position: { x: 100, y: 0 },- data: { id: 'other', name: 'sessions', type: 'view', upstreamCount: 0, downstreamCount: 0 },- },- ]- logic.actions.setNodesRaw(nodes)- logic.actions.setDebouncedSearchTerm('custmer')- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.searchMatchedNodeIds).toEqual(new Set(['match']))- })-- // A typo combined with the +/- lineage syntax must still resolve the start node, matching the- // plain graph search. Reverting the start-node lookup to exact/substring returns an empty set,- // which blanks the canvas while the list view still finds the model.- it.each([- ['+custmer', ['upstream_view', 'customer_orders']],- ['custmer+', ['customer_orders', 'downstream_view']],- ['+custmer+', ['upstream_view', 'customer_orders', 'downstream_view']],- ])('fuzzy-matches a near-miss lineage term (%s) so the graph is not left blank', async (term, expectedIds) => {- logic = dataModelingLogic()- logic.mount()- await expectLogic(logic)- .toDispatchActions(['loadDataModelingNodesSuccess', 'loadDataModelingEdgesSuccess'])- .toFinishAllListeners()-- const nodes: Node[] = [- {- id: 'upstream_view',- type: 'model',- position: { x: 0, y: 0 },- data: {- id: 'upstream_view',- name: 'upstream_view',- type: 'view',- upstreamCount: 0,- downstreamCount: 1,- },- },- {- id: 'customer_orders',- type: 'model',- position: { x: 100, y: 0 },- data: {- id: 'customer_orders',- name: 'customer_orders',- type: 'view',- upstreamCount: 1,- downstreamCount: 1,- },- },- {- id: 'downstream_view',- type: 'model',- position: { x: 200, y: 0 },- data: {- id: 'downstream_view',- name: 'downstream_view',- type: 'view',- upstreamCount: 1,- downstreamCount: 0,- },- },- ]- const edges: Edge[] = [- { id: 'upstream_view->customer_orders', source: 'upstream_view', target: 'customer_orders' },- { id: 'customer_orders->downstream_view', source: 'customer_orders', target: 'downstream_view' },- ]-- logic.actions.setNodesRaw(nodes)- logic.actions.setEdges(edges)- logic.actions.setDebouncedSearchTerm(term)- await expectLogic(logic).toFinishAllListeners()-- expect(logic.values.searchMatchedNodeIds).toEqual(new Set(expectedIds))- })-})diff --git a/frontend/src/scenes/data-warehouse/scene/dataModelingLogic.ts b/frontend/src/scenes/data-warehouse/scene/dataModelingLogic.tsdeleted file mode 100644index 86e373cdedf3..000000000000--- a/frontend/src/scenes/data-warehouse/scene/dataModelingLogic.ts+++ /dev/null@@ -1,1198 +0,0 @@-import {- EdgeChange,- MarkerType,- NodeChange,- Position,- ReactFlowInstance,- Viewport,- applyEdgeChanges,- applyNodeChanges,-} from '@xyflow/react'-import { deepEqual as equal } from 'fast-equals'-import { MakeLogicType, actions, afterMount, beforeUnmount, kea, listeners, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'-import type { RefObject } from 'react'--import api from 'lib/api'-import { createFuse } from 'lib/utils/fuseSearch'--import {- DataModelingDAG,- DataModelingEdge,- DataModelingJob,- DataModelingJobStatus,- DataModelingNode,- DataModelingNodeType,-} from '~/types'--import { getFormattedNodes } from './modeling/autolayout'-import { PAGE_SIZE } from './modeling/constants'-import { Edge, ElkDirection, Node, NodeHandle, SearchMode, ViewMode } from './modeling/types'--const POLL_INTERVAL_MS = 5000-const MIN_RUNNING_DURATION_MS = 2000--// Match the SQL editor sidebar's fuzzy search (queryDatabaseLogic) so the same term gives the same-// answer in both places. ignoreLocation lets a match land anywhere in the name.-const graphNodeFuse = createFuse<Node>([], { keys: ['data.name'], ignoreLocation: true })-const modelingNodeFuse = createFuse<DataModelingNode>([], { keys: ['name'], ignoreLocation: true })--const nodeStartTimes: Map<string, number> = new Map()--const getEdgeId = (from: string, to: string): string => `${from}->${to}`--interface AdjacencyMaps {- upstream: Map<string, string[]>- downstream: Map<string, string[]>-}--function buildAdjacencyMaps(edges: Edge[]): AdjacencyMaps {- const upstream = new Map<string, string[]>()- const downstream = new Map<string, string[]>()- for (const edge of edges) {- if (!upstream.has(edge.target)) {- upstream.set(edge.target, [])- }- upstream.get(edge.target)!.push(edge.source)- if (!downstream.has(edge.source)) {- downstream.set(edge.source, [])- }- downstream.get(edge.source)!.push(edge.target)- }- return { upstream, downstream }-}--function traverseGraph(startId: string, adjacencyMap: Map<string, string[]>): Set<string> {- const result = new Set<string>()- const queue = [startId]- while (queue.length > 0) {- const current = queue.shift()!- const neighbors = adjacencyMap.get(current) ?? []- for (const neighbor of neighbors) {- if (!result.has(neighbor)) {- result.add(neighbor)- queue.push(neighbor)- }- }- }- return result-}--export interface ParsedSearch {- mode: SearchMode- baseName: string-}--/** Parse search term for +name (upstream), name+ (downstream), or +name+ (both) syntax */-export function parseSearchTerm(searchTerm: string): ParsedSearch {- const trimmed = searchTerm.trim()- if (trimmed.startsWith('+') && trimmed.endsWith('+') && trimmed.length > 2) {- return { mode: 'all', baseName: trimmed.slice(1, -1) }- }- if (trimmed.startsWith('+') && trimmed.length > 1) {- return { mode: 'upstream', baseName: trimmed.slice(1) }- }- if (trimmed.endsWith('+') && trimmed.length > 1) {- return { mode: 'downstream', baseName: trimmed.slice(0, -1) }- }- return { mode: 'search', baseName: trimmed }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface dataModelingLogicValues {- availableDagIds: string[]- availableTypes: DataModelingNodeType[]- currentPage: number- dags: DataModelingDAG[]- dagsLoading: boolean- dataModelingEdges: DataModelingEdge[]- dataModelingEdgesLoading: boolean- dataModelingNodes: DataModelingNode[]- dataModelingNodesLoading: boolean- debouncedSearchTerm: string- edges: Edge[]- enrichedEdges: Edge[]- enrichedNodes: Node[]- filterDagIds: string[]- filterTypes: DataModelingNodeType[]- filteredNodes: DataModelingNode[]- graphReady: boolean- highlightedNodeIds: (baseName: string, mode: 'all' | 'downstream' | 'upstream') => Set<string>- highlightedNodeType: DataModelingNodeType | null- hoveredNodeId: string | null- latestJobMetadataByNodeId: Record<- string,- {- lastRunAt: string | null- status: DataModelingJobStatus- }- >- latestJobMetadataBySavedQueryId: Record<- string,- {- lastRunAt: string | null- status: DataModelingJobStatus- }- >- layoutDirection: ElkDirection- nodeTypePanelCollapsed: boolean- nodes: Node[]- nodesById: Record<string, Node>- nodesLoading: boolean- parsedSearch: ParsedSearch- reactFlowInstance: ReactFlowInstance<Node, Edge> | null- reactFlowWrapper: RefObject<HTMLDivElement> | null- runningNodeIds: Set<string>- savedViewport: Viewport | null- searchLayoutNodes: Node[] | null- searchMatchedNodeIds: Set<string> | null- searchTerm: string- selectedDag: DataModelingDAG | null- selectedDagId: string | null- viewMode: ViewMode- viewNodes: DataModelingNode[]- visibleNodes: DataModelingNode[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface dataModelingLogicActions {- clearFilterDagIds: () => {- value: true- }- clearFilterTypes: () => {- value: true- }- layoutSearchResults: () => {- value: true- }- loadDags: () => any- loadDagsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadDagsSuccess: (- dags: DataModelingDAG[],- payload?: any- ) => {- dags: DataModelingDAG[]- payload?: any- }- loadDataModelingEdges: () => any- loadDataModelingEdgesFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadDataModelingEdgesSuccess: (- dataModelingEdges: DataModelingEdge[],- payload?: any- ) => {- dataModelingEdges: DataModelingEdge[]- payload?: any- }- loadDataModelingNodes: () => any- loadDataModelingNodesFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadDataModelingNodesSuccess: (- dataModelingNodes: DataModelingNode[],- payload?: any- ) => {- dataModelingNodes: DataModelingNode[]- payload?: any- }- loadRecentJobs: () => {- value: true- }- loadRecentJobsSuccess: (recentJobs: DataModelingJob[]) => {- recentJobs: DataModelingJob[]- }- materializeNode: (nodeId: string) => {- nodeId: string- }- materializeNodeFailure: (- nodeId: string,- error: string- ) => {- error: string- nodeId: string- }- materializeNodeSuccess: (nodeId: string) => {- nodeId: string- }- onEdgesChange: (edges: EdgeChange<Edge>[]) => {- edges: EdgeChange<Edge>[]- }- onNodesChange: (nodes: NodeChange<Node>[]) => {- nodes: NodeChange<Node>[]- }- pollRunningJobs: () => {- value: true- }- pollRunningJobsSuccess: (runningJobs: DataModelingJob[]) => {- runningJobs: DataModelingJob[]- }- resetGraph: (- dataModelingNodes: DataModelingNode[],- dataModelingEdges: DataModelingEdge[],- fitViewAfter?: boolean- ) => {- dataModelingEdges: DataModelingEdge[]- dataModelingNodes: DataModelingNode[]- fitViewAfter: boolean | undefined- }- runNode: (- nodeId: string,- direction: 'downstream' | 'upstream'- ) => {- direction: 'downstream' | 'upstream'- nodeId: string- }- runNodeFailure: (- nodeId: string,- direction: 'downstream' | 'upstream',- error: string- ) => {- direction: 'downstream' | 'upstream'- error: string- nodeId: string- }- runNodeSuccess: (- nodeId: string,- direction: 'downstream' | 'upstream',- runningNodeIds: string[]- ) => {- direction: 'downstream' | 'upstream'- nodeId: string- runningNodeIds: string[]- }- setCurrentPage: (page: number) => {- page: number- }- setDebouncedSearchTerm: (debouncedSearchTerm: string) => {- debouncedSearchTerm: string- }- setEdges: (edges: Edge[]) => {- edges: Edge[]- }- setGraphReady: (ready: boolean) => {- ready: boolean- }- setHighlightedNodeType: (highlightedNodeType: DataModelingNodeType | null) => {- highlightedNodeType: DataModelingNodeType | null- }- setHoveredNodeId: (hoveredNodeId: string | null) => {- hoveredNodeId: string | null- }- setLayoutDirection: (layoutDirection: ElkDirection) => {- layoutDirection: ElkDirection- }- setNodeTypePanelCollapsed: (collapsed: boolean) => {- collapsed: boolean- }- setNodes: (- nodes: Node[],- fitViewAfter?: boolean- ) => {- fitViewAfter: boolean | undefined- nodes: Node[]- }- setNodesRaw: (nodes: Node[]) => {- nodes: Node[]- }- setReactFlowInstance: (reactFlowInstance: ReactFlowInstance<Node, Edge>) => {- reactFlowInstance: ReactFlowInstance<Node, Edge>- }- setReactFlowWrapper: (reactFlowWrapper: RefObject<HTMLDivElement>) => {- reactFlowWrapper: RefObject<HTMLDivElement>- }- setRunningNodeIds: (runningNodeIds: Set<string>) => {- runningNodeIds: Set<string>- }- setSavedViewport: (viewport: Viewport) => {- viewport: Viewport- }- setSearchLayoutNodes: (nodes: Node[] | null) => {- nodes: Node[] | null- }- setSearchTerm: (searchTerm: string) => {- searchTerm: string- }- setSelectedDagId: (dagId: string | null) => {- dagId: string | null- }- setViewMode: (viewMode: ViewMode) => {- viewMode: ViewMode- }- startPollingRunningJobs: () => {- value: true- }- stopPollingRunningJobs: () => {- value: true- }- toggleFilterDagId: (dagId: string) => {- dagId: string- }- toggleFilterType: (nodeType: DataModelingNodeType) => {- nodeType: DataModelingNodeType- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface dataModelingLogicMeta {- __keaTypeGenInternalSelectorTypes: {- nodesById: (nodes: Node[]) => Record<string, Node>- nodesLoading: (- dataModelingNodesLoading: boolean,- dataModelingEdgesLoading: boolean,- graphReady: boolean,- viewMode: ViewMode- ) => boolean- latestJobMetadataByNodeId: (- nodes: Node[],- latestJobMetadataBySavedQueryId: Record<- string,- {- lastRunAt: string | null- status: DataModelingJobStatus- }- >- ) => Record<- string,- {- lastRunAt: string | null- status: DataModelingJobStatus- }- >- enrichedNodes: (- nodes: Node[],- searchLayoutNodes: Node[] | null,- runningNodeIds: Set<string>,- highlightedNodeType: DataModelingNodeType | null,- latestJobMetadataByNodeId: Record<- string,- {- lastRunAt: string | null- status: DataModelingJobStatus- }- >,- searchMatchedNodeIds: Set<string> | null- ) => Node[]- enrichedEdges: (edges: Edge[], hoveredNodeId: string | null, searchMatchedNodeIds: Set<string> | null) => Edge[]- highlightedNodeIds: (- nodes: Node[],- edges: Edge[]- ) => (baseName: string, mode: 'all' | 'downstream' | 'upstream') => Set<string>- parsedSearch: (debouncedSearchTerm: string) => ParsedSearch- searchMatchedNodeIds: (- nodes: Node[],- debouncedSearchTerm: string,- parsedSearch: ParsedSearch,- highlightedNodeIds: (baseName: string, mode: 'all' | 'downstream' | 'upstream') => Set<string>- ) => Set<string> | null- filteredNodes: (dataModelingNodes: DataModelingNode[], searchTerm: string) => DataModelingNode[]- selectedDag: (dags: DataModelingDAG[], selectedDagId: string | null) => DataModelingDAG | null- availableDagIds: (filteredNodes: DataModelingNode[]) => string[]- availableTypes: (filteredNodes: DataModelingNode[]) => DataModelingNodeType[]- viewNodes: (- filteredNodes: DataModelingNode[],- filterDagIds: string[],- filterTypes: DataModelingNodeType[]- ) => DataModelingNode[]- visibleNodes: (viewNodes: DataModelingNode[], currentPage: number) => DataModelingNode[]- }-}--export type dataModelingLogicType = MakeLogicType<- dataModelingLogicValues,- dataModelingLogicActions,- Record<string, any>,- dataModelingLogicMeta->--export const dataModelingLogic = kea<dataModelingLogicType>([- path(['scenes', 'data-warehouse', 'scene', 'dataModelingLogic']),- actions({- onEdgesChange: (edges: EdgeChange<Edge>[]) => ({ edges }),- onNodesChange: (nodes: NodeChange<Node>[]) => ({ nodes }),- setNodes: (nodes: Node[], fitViewAfter?: boolean) => ({ nodes, fitViewAfter }),- setNodesRaw: (nodes: Node[]) => ({ nodes }),- setSearchLayoutNodes: (nodes: Node[] | null) => ({ nodes }),- setEdges: (edges: Edge[]) => ({ edges }),- layoutSearchResults: true,- setReactFlowInstance: (reactFlowInstance: ReactFlowInstance<Node, Edge>) => ({- reactFlowInstance,- }),- setReactFlowWrapper: (reactFlowWrapper: RefObject<HTMLDivElement>) => ({ reactFlowWrapper }),- setHighlightedNodeType: (highlightedNodeType: DataModelingNodeType | null) => ({ highlightedNodeType }),- setHoveredNodeId: (hoveredNodeId: string | null) => ({ hoveredNodeId }),- setSavedViewport: (viewport: Viewport) => ({ viewport }),- resetGraph: (- dataModelingNodes: DataModelingNode[],- dataModelingEdges: DataModelingEdge[],- fitViewAfter?: boolean- ) => ({- dataModelingNodes,- dataModelingEdges,- fitViewAfter,- }),- runNode: (nodeId: string, direction: 'upstream' | 'downstream') => ({ nodeId, direction }),- runNodeSuccess: (nodeId: string, direction: 'upstream' | 'downstream', runningNodeIds: string[]) => ({- nodeId,- direction,- runningNodeIds,- }),- runNodeFailure: (nodeId: string, direction: 'upstream' | 'downstream', error: string) => ({- nodeId,- direction,- error,- }),- materializeNode: (nodeId: string) => ({ nodeId }),- materializeNodeSuccess: (nodeId: string) => ({ nodeId }),- materializeNodeFailure: (nodeId: string, error: string) => ({ nodeId, error }),- setRunningNodeIds: (runningNodeIds: Set<string>) => ({ runningNodeIds }),- startPollingRunningJobs: true,- stopPollingRunningJobs: true,- pollRunningJobs: true,- pollRunningJobsSuccess: (runningJobs: DataModelingJob[]) => ({ runningJobs }),- loadRecentJobs: true,- loadRecentJobsSuccess: (recentJobs: DataModelingJob[]) => ({ recentJobs }),- setLayoutDirection: (layoutDirection: ElkDirection) => ({ layoutDirection }),- // View/filter actions (previously in dataModelingNodesLogic)- setViewMode: (viewMode: ViewMode) => ({ viewMode }),- setSearchTerm: (searchTerm: string) => ({ searchTerm }),- setDebouncedSearchTerm: (debouncedSearchTerm: string) => ({ debouncedSearchTerm }),- setCurrentPage: (page: number) => ({ page }),- toggleFilterDagId: (dagId: string) => ({ dagId }),- clearFilterDagIds: true,- toggleFilterType: (nodeType: DataModelingNodeType) => ({ nodeType }),- clearFilterTypes: true,- setNodeTypePanelCollapsed: (collapsed: boolean) => ({ collapsed }),- setSelectedDagId: (dagId: string | null) => ({ dagId }),- setGraphReady: (ready: boolean) => ({ ready }),- }),- loaders(({ values }) => ({- dags: [- [] as DataModelingDAG[],- {- loadDags: async () => {- const response = await api.dataModelingDags.list()- return response.results- },- },- ],- dataModelingNodes: [- [] as DataModelingNode[],- {- loadDataModelingNodes: async () => {- const dagId = values.selectedDagId ?? undefined- const response = await api.dataModelingNodes.list(dagId)- return response.results- },- },- ],- dataModelingEdges: [- [] as DataModelingEdge[],- {- loadDataModelingEdges: async () => {- const dagId = values.selectedDagId ?? undefined- const response = await api.dataModelingEdges.list(dagId)- return response.results- },- },- ],- })),- reducers(() => ({- nodes: [- [] as Node[],- {- setNodesRaw: (_, { nodes }) => nodes,- },- ],- searchLayoutNodes: [- null as Node[] | null,- {- setSearchLayoutNodes: (_, { nodes }) => nodes,- setDebouncedSearchTerm: () => null,- resetGraph: () => null,- },- ],- highlightedNodeType: [- null as DataModelingNodeType | null,- {- setHighlightedNodeType: (_, { highlightedNodeType }) => highlightedNodeType,- },- ],- hoveredNodeId: [- null as string | null,- {- setHoveredNodeId: (_, { hoveredNodeId }) => hoveredNodeId,- },- ],- savedViewport: [- null as Viewport | null,- {- setSavedViewport: (_, { viewport }) => viewport,- },- ],- edges: [- [] as Edge[],- {- setEdges: (_, { edges }) => edges,- },- ],- reactFlowInstance: [- null as ReactFlowInstance<Node, Edge> | null,- {- setReactFlowInstance: (_, { reactFlowInstance }) => reactFlowInstance,- },- ],- reactFlowWrapper: [- null as RefObject<HTMLDivElement> | null,- {- setReactFlowWrapper: (_, { reactFlowWrapper }) => reactFlowWrapper,- },- ],- runningNodeIds: [- new Set<string>(),- {- setRunningNodeIds: (_, { runningNodeIds }) => {- for (const nodeId of nodeStartTimes.keys()) {- if (!runningNodeIds.has(nodeId)) {- nodeStartTimes.delete(nodeId)- }- }- return runningNodeIds- },- runNodeSuccess: (state, { runningNodeIds }) => {- const now = Date.now()- for (const nodeId of runningNodeIds) {- if (!nodeStartTimes.has(nodeId)) {- nodeStartTimes.set(nodeId, now)- }- }- return new Set([...state, ...runningNodeIds])- },- materializeNode: (state, { nodeId }) => {- if (!nodeStartTimes.has(nodeId)) {- nodeStartTimes.set(nodeId, Date.now())- }- return new Set([...state, nodeId])- },- },- ],- layoutDirection: [- 'RIGHT' as ElkDirection,- { persist: true },- {- setLayoutDirection: (_, { layoutDirection }) => layoutDirection,- },- ],- nodeTypePanelCollapsed: [- false,- { persist: true },- {- setNodeTypePanelCollapsed: (_, { collapsed }) => collapsed,- },- ],- selectedDagId: [- null as string | null,- { persist: true },- {- setSelectedDagId: (_, { dagId }) => dagId,- },- ],- graphReady: [- false as boolean,- {- setGraphReady: (_, { ready }) => ready,- // reset when DAG changes so spinner shows immediately- setSelectedDagId: () => false,- // reset on initial load- loadDataModelingNodes: () => false,- },- ],- viewMode: [- 'graph' as ViewMode,- { persist: true },- {- setViewMode: (_, { viewMode }) => viewMode,- },- ],- searchTerm: [- '' as string,- {- setSearchTerm: (_, { searchTerm }) => searchTerm,- },- ],- debouncedSearchTerm: [- '' as string,- {- setDebouncedSearchTerm: (_, { debouncedSearchTerm }) => debouncedSearchTerm,- },- ],- currentPage: [- 1 as number,- {- setCurrentPage: (_, { page }) => page,- setSearchTerm: () => 1,- toggleFilterDagId: () => 1,- clearFilterDagIds: () => 1,- toggleFilterType: () => 1,- clearFilterTypes: () => 1,- },- ],- filterDagIds: [- [] as string[],- {- toggleFilterDagId: (state, { dagId }) =>- state.includes(dagId) ? state.filter((id) => id !== dagId) : [...state, dagId],- clearFilterDagIds: () => [],- },- ],- filterTypes: [- [] as DataModelingNodeType[],- {- toggleFilterType: (state, { nodeType }) =>- state.includes(nodeType) ? state.filter((t) => t !== nodeType) : [...state, nodeType],- clearFilterTypes: () => [],- },- ],- latestJobMetadataBySavedQueryId: [- {} as Record<string, { status: DataModelingJobStatus; lastRunAt: string | null }>,- {- loadRecentJobsSuccess: (state, { recentJobs }) => {- const map: Record<string, { status: DataModelingJobStatus; lastRunAt: string | null }> = {}- for (const job of recentJobs) {- if (job.saved_query_id) {- map[job.saved_query_id] = {- status: job.status,- lastRunAt: job.last_run_at,- }- }- }- return equal(state, map) ? state : map- },- },- ],- })),- selectors({- nodesById: [- (s) => [s.nodes],- (nodes: Node[]): Record<string, Node> => {- return nodes.reduce(- (acc, node) => {- acc[node.id] = node- return acc- },- {} as Record<string, Node>- )- },- { resultEqualityCheck: equal },- ],- nodesLoading: [- (s) => [s.dataModelingNodesLoading, s.dataModelingEdgesLoading, s.graphReady, s.viewMode],- (- dataModelingNodesLoading: boolean,- dataModelingEdgesLoading: boolean,- graphReady: boolean,- viewMode: ViewMode- ): boolean => dataModelingNodesLoading || dataModelingEdgesLoading || (viewMode === 'graph' && !graphReady),- ],- latestJobMetadataByNodeId: [- (s) => [s.nodes, s.latestJobMetadataBySavedQueryId],- (- nodes: Node[],- latestJobMetadataBySavedQueryId: Record<- string,- {- lastRunAt: string | null- status: DataModelingJobStatus- }- >- ): Record<string, { status: DataModelingJobStatus; lastRunAt: string | null }> => {- const map: Record<string, { status: DataModelingJobStatus; lastRunAt: string | null }> = {}- for (const node of nodes) {- if (node.data.savedQueryId && latestJobMetadataBySavedQueryId[node.data.savedQueryId]) {- map[node.id] = latestJobMetadataBySavedQueryId[node.data.savedQueryId]- }- }- return map- },- { resultEqualityCheck: equal },- ],- enrichedNodes: [- (s) => [- s.nodes,- s.searchLayoutNodes,- s.runningNodeIds,- s.highlightedNodeType,- s.latestJobMetadataByNodeId,- s.searchMatchedNodeIds,- ],- (- nodes: Node[],- searchLayoutNodes: Node[] | null,- runningNodeIds: Set<string>,- highlightedNodeType: DataModelingNodeType | null,- latestJobMetadataByNodeId: Record<- string,- {- lastRunAt: string | null- status: DataModelingJobStatus- }- >,- searchMatchedNodeIds: Set<string> | null- ): Node[] => {- const layoutNodes = searchLayoutNodes ?? nodes- const visibleNodes = searchMatchedNodeIds- ? layoutNodes.filter((node) => searchMatchedNodeIds.has(node.id))- : layoutNodes- return visibleNodes.map((node) => {- const isRunning = runningNodeIds.has(node.id)- const isTypeHighlighted = highlightedNodeType !== null && highlightedNodeType === node.data.type- const isSearchMatch = searchMatchedNodeIds !== null- const metadata = latestJobMetadataByNodeId[node.id]- const lastJobStatus = metadata?.status ?? node.data.lastJobStatus- const lastRunAt = metadata?.lastRunAt ?? node.data.lastRunAt- if (- node.data.isRunning === isRunning &&- node.data.isTypeHighlighted === isTypeHighlighted &&- node.data.isSearchMatch === isSearchMatch &&- node.data.lastJobStatus === lastJobStatus &&- node.data.lastRunAt === lastRunAt- ) {- return node- }- return {- ...node,- data: {- ...node.data,- isRunning,- isTypeHighlighted,- isSearchMatch,- lastJobStatus,- lastRunAt,- },- }- })- },- {- resultEqualityCheck: (a: Node[], b: Node[]): boolean =>- a.length === b.length && a.every((node, i) => node === b[i]),- },- ],- enrichedEdges: [- (s) => [s.edges, s.hoveredNodeId, s.searchMatchedNodeIds],- (edges: Edge[], hoveredNodeId: string | null, searchMatchedNodeIds: Set<string> | null): Edge[] => {- const visibleEdges = searchMatchedNodeIds- ? edges.filter(- (edge) => searchMatchedNodeIds.has(edge.source) && searchMatchedNodeIds.has(edge.target)- )- : edges- if (!hoveredNodeId) {- return visibleEdges- }- return visibleEdges.map((edge) => {- const isConnected = edge.source === hoveredNodeId || edge.target === hoveredNodeId- if (!isConnected) {- return edge- }- return {- ...edge,- style: { stroke: 'var(--primary-3000)' },- markerEnd: { type: MarkerType.ArrowClosed, color: 'var(--primary-3000)' },- }- })- },- {- resultEqualityCheck: (a: Edge[], b: Edge[]): boolean =>- a.length === b.length && a.every((edge, i) => edge === b[i]),- },- ],- highlightedNodeIds: [- (s) => [s.nodes, s.edges],- (- nodes: Node[],- edges: Edge[]- ): ((baseName: string, mode: 'upstream' | 'downstream' | 'all') => Set<string>) => {- const { upstream, downstream } = buildAdjacencyMaps(edges)-- return (baseName: string, mode: 'upstream' | 'downstream' | 'all'): Set<string> => {- // Resolve the lineage start node through the same fuzzy instance the plain search- // uses, so a near-miss term like `custmer+` finds `customer_orders` here too.- // Exact/substring matching left the graph blank while the list view found the model.- graphNodeFuse.setCollection(nodes)- const startNode = graphNodeFuse.search(baseName)[0]?.item- if (!startNode) {- return new Set()- }-- const result = new Set<string>([startNode.id])-- if (mode === 'upstream' || mode === 'all') {- for (const id of traverseGraph(startNode.id, upstream)) {- result.add(id)- }- }- if (mode === 'downstream' || mode === 'all') {- for (const id of traverseGraph(startNode.id, downstream)) {- result.add(id)- }- }-- return result- }- },- ],- // View/filter selectors (previously in dataModelingNodesLogic)- parsedSearch: [- (s) => [s.debouncedSearchTerm],- (debouncedSearchTerm: string): ParsedSearch => parseSearchTerm(debouncedSearchTerm),- ],- /** Node ids to show on the graph canvas for the active search — null means no filter (show everything) */- searchMatchedNodeIds: [- (s) => [s.nodes, s.debouncedSearchTerm, s.parsedSearch, s.highlightedNodeIds],- (- nodes: Node[],- debouncedSearchTerm: string,- parsedSearch: ParsedSearch,- highlightedNodeIds: (baseName: string, mode: 'upstream' | 'downstream' | 'all') => Set<string>- ): Set<string> | null => {- if (debouncedSearchTerm.length === 0) {- return null- }- if (parsedSearch.mode !== 'search') {- return highlightedNodeIds(parsedSearch.baseName, parsedSearch.mode)- }- if (!parsedSearch.baseName) {- return null- }- graphNodeFuse.setCollection(nodes)- return new Set(graphNodeFuse.search(parsedSearch.baseName).map((r) => r.item.id))- },- ],- filteredNodes: [- (s) => [s.dataModelingNodes, s.searchTerm],- (dataModelingNodes: DataModelingNode[], searchTerm: string): DataModelingNode[] => {- if (!searchTerm) {- return dataModelingNodes- }- const { baseName } = parseSearchTerm(searchTerm)- if (!baseName) {- return dataModelingNodes- }- modelingNodeFuse.setCollection(dataModelingNodes)- return modelingNodeFuse.search(baseName).map((r) => r.item)- },- ],- selectedDag: [- (s) => [s.dags, s.selectedDagId],- (dags: DataModelingDAG[], selectedDagId: string | null): DataModelingDAG | null => {- if (!selectedDagId) {- return null- }- return dags.find((d) => d.id === selectedDagId) ?? null- },- ],- availableDagIds: [- (s) => [s.filteredNodes],- (nodes: DataModelingNode[]): string[] => {- const viewableNodes = nodes.filter(- (n) => n.type === 'matview' || n.type === 'view' || n.type === 'endpoint'- )- return [...new Set(viewableNodes.map((n) => n.dag_name).filter(Boolean) as string[])].sort()- },- ],- availableTypes: [- (s) => [s.filteredNodes],- (nodes: DataModelingNode[]): DataModelingNodeType[] => {- const viewableNodes = nodes.filter(- (n) => n.type === 'matview' || n.type === 'view' || n.type === 'endpoint'- )- return [...new Set(viewableNodes.map((n) => n.type))].sort()- },- ],- viewNodes: [- (s) => [s.filteredNodes, s.filterDagIds, s.filterTypes],- (- nodes: DataModelingNode[],- filterDagIds: string[],- filterTypes: DataModelingNodeType[]- ): DataModelingNode[] => {- return nodes- .filter((n) => n.type === 'matview' || n.type === 'view' || n.type === 'endpoint')- .filter((n) => filterDagIds.length === 0 || (n.dag_name && filterDagIds.includes(n.dag_name)))- .filter((n) => filterTypes.length === 0 || filterTypes.includes(n.type))- },- ],- visibleNodes: [- (s) => [s.viewNodes, s.currentPage],- (nodes: DataModelingNode[], currentPage: number): DataModelingNode[] => {- const startIndex = (currentPage - 1) * PAGE_SIZE- const endIndex = startIndex + PAGE_SIZE- return nodes.slice(startIndex, endIndex)- },- ],- }),- listeners(({ values, actions, cache }) => ({- setViewMode: ({ viewMode }) => {- if (viewMode !== 'graph' && values.reactFlowInstance) {- actions.setSavedViewport(values.reactFlowInstance.getViewport())- }- // graph view requires a single DAG — auto-select the first one- if (viewMode === 'graph' && !values.selectedDagId && values.dags.length > 0) {- actions.setSelectedDagId(values.dags[0].id)- }- },- onEdgesChange: ({ edges }) => {- actions.setEdges(applyEdgeChanges(edges, values.edges))- },- onNodesChange: ({ nodes }) => {- // apply ReactFlow's dimension/position changes directly without re-running layout- actions.setNodesRaw(applyNodeChanges(nodes, values.nodes))- },- loadDagsSuccess: ({ dags }) => {- const isStale = values.selectedDagId && !dags.some((d) => d.id === values.selectedDagId)- // graph view requires a single DAG — auto-select the first one, or reset stale persisted ID- if (values.viewMode === 'graph' && (!values.selectedDagId || isStale) && dags.length > 0) {- actions.setSelectedDagId(dags[0].id)- } else if (isStale) {- actions.setSelectedDagId(null)- }- },- loadDataModelingNodesSuccess: () => {- if (!values.dataModelingEdgesLoading) {- actions.resetGraph(values.dataModelingNodes, values.dataModelingEdges)- }- },- loadDataModelingEdgesSuccess: () => {- if (!values.dataModelingNodesLoading) {- actions.resetGraph(values.dataModelingNodes, values.dataModelingEdges)- }- },- resetGraph: async ({ dataModelingNodes, dataModelingEdges, fitViewAfter }) => {- const nodeIds = new Set(dataModelingNodes.map((n) => n.id))- const isHorizontal = values.layoutDirection === 'RIGHT'-- const handlesByNodeId: Record<string, Record<string, NodeHandle>> = {}-- dataModelingNodes.forEach((node) => {- handlesByNodeId[node.id] = {- [`target_${node.id}`]: {- id: `target_${node.id}`,- type: 'target',- position: isHorizontal ? Position.Left : Position.Top,- },- [`source_${node.id}`]: {- id: `source_${node.id}`,- type: 'source',- position: isHorizontal ? Position.Right : Position.Bottom,- },- }- })-- const sortedNodes = [...dataModelingNodes].sort((a, b) =>- a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })- )-- const nodes: Node[] = sortedNodes.map((node) => {- return {- id: node.id,- type: 'model',- data: {- id: node.id,- name: node.name,- type: node.type,- dag: node.dag,- dagName: node.dag_name,- savedQueryId: node.saved_query_id,- handles: Object.values(handlesByNodeId[node.id] ?? {}),- upstreamCount: node.upstream_count,- downstreamCount: node.downstream_count,- userTag: node.user_tag,- lastJobStatus: node.last_run_status,- lastRunAt: node.last_run_at,- syncInterval: node.sync_interval,- },- position: { x: 0, y: 0 },- deletable: true,- selectable: true,- draggable: false,- connectable: false,- }- })-- const edges: Edge[] = dataModelingEdges- .filter((edge) => nodeIds.has(edge.source_id) && nodeIds.has(edge.target_id))- .map((edge) => ({- id: getEdgeId(edge.source_id, edge.target_id),- source: edge.source_id,- target: edge.target_id,- type: 'straight',- deletable: false,- markerEnd: { type: MarkerType.ArrowClosed },- sourceHandle: `source_${edge.source_id}`,- targetHandle: `target_${edge.target_id}`,- }))-- actions.setEdges(edges)- actions.setNodes(nodes, fitViewAfter)- },- setNodes: async ({ nodes, fitViewAfter }) => {- if (nodes.length === 0) {- actions.setNodesRaw([])- actions.setGraphReady(true)- return- }- const formattedNodes = await getFormattedNodes(nodes, values.edges, values.layoutDirection)- actions.setNodesRaw(formattedNodes)- if (values.debouncedSearchTerm.length > 0) {- actions.layoutSearchResults()- }- if (fitViewAfter) {- values.reactFlowInstance?.fitView({ padding: 0.2, maxZoom: 1 })- }- actions.setGraphReady(true)- },- layoutSearchResults: async (_, breakpoint) => {- const matchedNodeIds = values.searchMatchedNodeIds- if (matchedNodeIds === null) {- actions.setSearchLayoutNodes(null)- return- }- const matchedNodes = values.nodes.filter((node) => matchedNodeIds.has(node.id))- const matchedEdges = values.edges.filter(- (edge) => matchedNodeIds.has(edge.source) && matchedNodeIds.has(edge.target)- )- const formattedNodes = await getFormattedNodes(matchedNodes, matchedEdges, values.layoutDirection)- await breakpoint()- actions.setSearchLayoutNodes(formattedNodes)- },- setLayoutDirection: () => {- if (values.dataModelingNodes.length > 0) {- actions.resetGraph(values.dataModelingNodes, values.dataModelingEdges, true)- }- },- setSearchTerm: async ({ searchTerm }, breakpoint) => {- if (searchTerm.length > 0) {- actions.setHighlightedNodeType(null)- }- await breakpoint(150)- actions.setDebouncedSearchTerm(searchTerm)- },- setDebouncedSearchTerm: () => {- actions.layoutSearchResults()- },- runNode: async ({ nodeId, direction }) => {- const { upstream, downstream } = buildAdjacencyMaps(values.edges)- const adjacency = direction === 'upstream' ? upstream : downstream- const optimisticIds = traverseGraph(nodeId, adjacency)- optimisticIds.add(nodeId)- const now = Date.now()- for (const id of optimisticIds) {- if (!nodeStartTimes.has(id)) {- nodeStartTimes.set(id, now)- }- }- actions.setRunningNodeIds(new Set([...values.runningNodeIds, ...optimisticIds]))-- try {- const response = await api.dataModelingNodes.run(nodeId, direction)- actions.runNodeSuccess(nodeId, direction, response.node_ids)- actions.startPollingRunningJobs()- } catch (e) {- actions.runNodeFailure(nodeId, direction, String(e))- }- },- materializeNode: async ({ nodeId }) => {- try {- await api.dataModelingNodes.materialize(nodeId)- actions.materializeNodeSuccess(nodeId)- actions.startPollingRunningJobs()- } catch (e) {- actions.materializeNodeFailure(nodeId, String(e))- }- },- pollRunningJobs: async () => {- actions.loadRecentJobs()- try {- const running = await api.dataModelingJobs.listRunning()- actions.pollRunningJobsSuccess(running)- } catch {- // keep stale data during transient failures- }- },- pollRunningJobsSuccess: ({ runningJobs }) => {- const now = Date.now()- const runningSavedQueryIds = new Set(runningJobs.map((job) => job.saved_query_id))- const newRunningNodeIds = new Set<string>()-- for (const node of values.nodes) {- if (node.data.savedQueryId && runningSavedQueryIds.has(node.data.savedQueryId)) {- newRunningNodeIds.add(node.id)- }- }- for (const nodeId of values.runningNodeIds) {- const startTime = nodeStartTimes.get(nodeId)- if (startTime && now - startTime < MIN_RUNNING_DURATION_MS) {- newRunningNodeIds.add(nodeId)- }- }-- actions.setRunningNodeIds(newRunningNodeIds)- if (newRunningNodeIds.size === 0) {- actions.stopPollingRunningJobs()- }- },- loadRecentJobs: async () => {- try {- const recent = await api.dataModelingJobs.listRecent()- actions.loadRecentJobsSuccess(recent)- } catch {- // silent failure- }- },- startPollingRunningJobs: () => {- actions.pollRunningJobs()- cache.disposables.add(() => {- const intervalId = setInterval(() => {- actions.pollRunningJobs()- }, POLL_INTERVAL_MS)- return () => clearInterval(intervalId)- }, 'pollRunningJobs')- },-- stopPollingRunningJobs: () => {- if (cache.disposables.dispose('pollRunningJobs')) {- actions.loadRecentJobs()- }- },- setSelectedDagId: () => {- // clear stale graph immediately so old nodes don't flash- actions.setNodesRaw([])- actions.setEdges([])- actions.loadDataModelingNodes()- actions.loadDataModelingEdges()- },- })),- afterMount(({ actions }) => {- actions.loadDags()- actions.loadDataModelingNodes()- actions.loadDataModelingEdges()- actions.loadRecentJobs()- actions.startPollingRunningJobs()- }),- beforeUnmount(({ actions }) => {- actions.stopPollingRunningJobs()- }),-])diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/GraphView.tsx b/frontend/src/scenes/data-warehouse/scene/modeling/GraphView.tsxdeleted file mode 100644index b0c869b53a64..000000000000--- a/frontend/src/scenes/data-warehouse/scene/modeling/GraphView.tsx+++ /dev/null@@ -1,222 +0,0 @@-import '@xyflow/react/dist/style.css'--import {- Background,- BackgroundVariant,- Controls,- NodeTypes,- ReactFlow,- ReactFlowProvider,- useReactFlow,-} from '@xyflow/react'-import { useActions, useValues } from 'kea'-import { useEffect, useRef } from 'react'--import { IconArrowRight, IconCollapse, IconDatabase, IconExpand } from '@posthog/icons'-import { LemonButton, LemonSegmentedButton } from '@posthog/lemon-ui'--import { IconArrowDown } from 'lib/lemon-ui/icons'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'-import { DataModelingNodeType } from '~/types'--import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'--import { dataModelingLogic } from '../dataModelingLogic'-import { REACT_FLOW_NODE_TYPES } from './Node'-import { CreateModelNodeType, Edge, ElkDirection, Node } from './types'--const FIT_VIEW_OPTIONS = {- padding: 0.2,- maxZoom: 1,-}--const NODES_TO_SHOW: CreateModelNodeType[] = [- {- type: 'view',- name: 'View',- description: 'A virtual table based on a SQL query',- },- {- type: 'matview',- name: 'Materialized view',- description: 'A persisted view with improved query performance',- },- {- type: 'endpoint',- name: 'Endpoint',- description: 'A materialized endpoint for API access',- },-]--function NodeTypeButton({- node,- isActive,- onClick,-}: {- node: CreateModelNodeType- isActive: boolean- onClick: () => void-}): JSX.Element {- const color = NODE_TYPE_TAG_SETTINGS[node.type].color-- return (- <div draggable>- <LemonButton- icon={- <span style={{ color }}>- <IconDatabase />- </span>- }- fullWidth- active={isActive}- onClick={onClick}- >- <div className="flex flex-col items-start flex-1">- <span>{node.name}</span>- {node.description && <span className="text-xs text-muted font-normal">{node.description}</span>}- </div>- </LemonButton>- </div>- )-}--export function NodeTypePanel(): JSX.Element {- const { highlightedNodeType, layoutDirection, nodeTypePanelCollapsed } = useValues(dataModelingLogic)- const { setHighlightedNodeType, setLayoutDirection, setSearchTerm, setNodeTypePanelCollapsed } =- useActions(dataModelingLogic)-- const handleNodeTypeClick = (type: DataModelingNodeType): void => {- if (highlightedNodeType === type) {- setHighlightedNodeType(null)- } else {- setHighlightedNodeType(type)- setSearchTerm('')- }- }-- if (nodeTypePanelCollapsed) {- return (- <div className="absolute right-1.5 bottom-1.5 z-10 bg-transparent p-2">- <LemonButton- className="dark:bg-primary bg-white"- icon={<IconExpand />}- type="secondary"- size="small"- onClick={() => setNodeTypePanelCollapsed(false)}- tooltip="Expand panel"- />- </div>- )- }-- return (- <div className="absolute right-4 top-4 bottom-4 w-64 bg-primary border rounded-lg shadow-xs overflow-hidden z-10">- <div className="flex flex-col gap-1 p-4">- <span className="flex gap-2 text-xs font-semibold items-center text-muted">Node types</span>- {NODES_TO_SHOW.map((node, index) => (- <NodeTypeButton- key={`${node.type}-${index}`}- node={node}- isActive={highlightedNodeType === node.type}- onClick={() => handleNodeTypeClick(node.type)}- />- ))}- </div>- <div className="absolute bottom-4 left-4 right-4 flex items-center justify-between">- <LemonSegmentedButton- value={layoutDirection}- onChange={(value) => setLayoutDirection(value as ElkDirection)}- options={[- {- value: 'RIGHT',- icon: <IconArrowRight />,- tooltip: 'Left to right',- },- {- value: 'DOWN',- icon: <IconArrowDown />,- tooltip: 'Top to bottom',- },- ]}- size="small"- />- <LemonButton- className="dark:bg-primary bg-white"- icon={<IconCollapse />}- type="secondary"- size="small"- onClick={() => setNodeTypePanelCollapsed(true)}- tooltip="Collapse panel"- />- </div>- </div>- )-}--function GraphViewContent(): JSX.Element {- const { isDarkModeOn } = useValues(themeLogic)-- const { enrichedNodes, enrichedEdges, debouncedSearchTerm, savedViewport, searchLayoutNodes } =- useValues(dataModelingLogic)- const { onEdgesChange, onNodesChange, setReactFlowInstance, setReactFlowWrapper } = useActions(dataModelingLogic)-- const reactFlowWrapper = useRef<HTMLDivElement>(null)- const reactFlowInstance = useReactFlow<Node, Edge>()-- useEffect(() => {- setReactFlowInstance(reactFlowInstance)- }, [reactFlowInstance, setReactFlowInstance])-- useEffect(() => {- setReactFlowWrapper(reactFlowWrapper)- }, [setReactFlowWrapper])-- useEffect(() => {- if (debouncedSearchTerm.length > 0 && searchLayoutNodes && searchLayoutNodes.length > 0) {- reactFlowInstance.fitView({- nodes: searchLayoutNodes,- duration: 400,- maxZoom: 1,- })- }- }, [debouncedSearchTerm, reactFlowInstance, searchLayoutNodes])-- return (- <div ref={reactFlowWrapper} className="relative w-full border rounded-lg overflow-hidden h-[calc(100vh-17rem)]">- <ReactFlow<Node, Edge>- fitView={!savedViewport}- defaultViewport={savedViewport ?? undefined}- nodes={enrichedNodes}- edges={enrichedEdges}- onNodesChange={onNodesChange}- onEdgesChange={onEdgesChange}- nodeTypes={REACT_FLOW_NODE_TYPES as NodeTypes}- nodesDraggable={false}- colorMode={isDarkModeOn ? 'dark' : 'light'}- fitViewOptions={FIT_VIEW_OPTIONS}- proOptions={{ hideAttribution: true }}- elevateNodesOnSelect={false}- minZoom={0.25}- maxZoom={1.5}- onlyRenderVisibleElements- >- <Background gap={36} variant={BackgroundVariant.Dots} bgColor="var(--color-bg-primary)" />- <Controls showInteractive={false} fitViewOptions={FIT_VIEW_OPTIONS} />- <NodeTypePanel />- </ReactFlow>- </div>- )-}--// TODO: fold this onto the shared <LineageGraph> (products/data_modeling/frontend/lineage) once the-// DAG concept is removed from the UI and the backend resolves schedules per-node. A team then has a-// single implicit graph, so dataModelingLogic can drop its multi-DAG selection/viewport machinery and-// this canvas collapses to <LineageGraph variant="canvas"> with search/legend passed as `panels`.-export function GraphView(): JSX.Element {- return (- <ReactFlowProvider>- <GraphViewContent />- </ReactFlowProvider>- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/Node.tsx b/frontend/src/scenes/data-warehouse/scene/modeling/Node.tsxdeleted file mode 100644index 6e98f4d18496..000000000000--- a/frontend/src/scenes/data-warehouse/scene/modeling/Node.tsx+++ /dev/null@@ -1,79 +0,0 @@-import { useActions, useValues } from 'kea'-import React, { useCallback } from 'react'--import { newInternalTab } from 'lib/utils/newInternalTab'-import { urls } from 'scenes/urls'--import { LineageNode } from 'products/data_modeling/frontend/lineage/LineageNode'--import { dataModelingLogic } from '../dataModelingLogic'-import type { NodeData } from './types'--const NodeComponent = React.memo(function NodeComponent(props: { id: string; data: NodeData }): JSX.Element {- const { runNode, materializeNode, setHoveredNodeId } = useActions(dataModelingLogic)- const { layoutDirection } = useValues(dataModelingLogic)-- const { id } = props- const {- name,- type,- handles,- upstreamCount,- downstreamCount,- isRunning,- isTypeHighlighted,- isSearchMatch,- lastJobStatus,- lastRunAt,- syncInterval,- userTag,- } = props.data-- const handleNodeClick = useCallback((): void => {- if (type === 'endpoint') {- const versionMatch = name.match(/^(.+)_v(\d+)$/)- newInternalTab(- versionMatch ? urls.endpoint(versionMatch[1], parseInt(versionMatch[2])) : urls.endpoint(name)- )- } else {- newInternalTab(urls.nodeDetail(id))- }- }, [type, id, name])-- const canRun = type !== 'table'-- return (- <LineageNode- data={{- node: {- id,- name,- type,- sync_interval: syncInterval,- last_run_at: lastRunAt,- last_run_status: lastJobStatus,- upstream_count: upstreamCount,- downstream_count: downstreamCount,- user_tag: userTag,- },- variant: 'canvas',- direction: layoutDirection,- state: {- isRunning: isRunning ?? false,- isHighlighted: (isTypeHighlighted ?? false) || (isSearchMatch ?? false),- },- callbacks: {- onClick: handleNodeClick,- onMaterialize: type === 'matview' || type === 'endpoint' ? () => materializeNode(id) : undefined,- onRunUpstream: canRun ? () => runNode(id, 'upstream') : undefined,- onRunDownstream: canRun ? () => runNode(id, 'downstream') : undefined,- onMouseEnter: () => setHoveredNodeId(id),- onMouseLeave: () => setHoveredNodeId(null),- },- handles: handles ?? [],- }}- />- )-})--export const REACT_FLOW_NODE_TYPES = { model: NodeComponent }diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/TableView.tsx b/frontend/src/scenes/data-warehouse/scene/modeling/TableView.tsxdeleted file mode 100644index 3b27b125dc7c..000000000000--- a/frontend/src/scenes/data-warehouse/scene/modeling/TableView.tsx+++ /dev/null@@ -1,180 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconFilter } from '@posthog/icons'-import { LemonButton, LemonCheckbox, LemonDivider, LemonTable, LemonTag, Link, Spinner } from '@posthog/lemon-ui'--import { TZLabel } from 'lib/components/TZLabel'-import { urls } from 'scenes/urls'--import { DataModelingNode, DataModelingNodeType } from '~/types'--import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'--import { dataModelingLogic } from '../dataModelingLogic'-import { PAGE_SIZE } from './constants'--function NodeDependencyCount({ count, loading }: { count?: number; loading?: boolean }): JSX.Element {- if (loading || count === undefined) {- return <Spinner className="text-sm" />- }- return <span>{count}</span>-}--export function TableView(): JSX.Element {- const {- viewNodes,- visibleNodes,- nodesLoading,- currentPage,- debouncedSearchTerm,- availableDagIds,- availableTypes,- filterDagIds,- filterTypes,- } = useValues(dataModelingLogic)- const { setCurrentPage, toggleFilterDagId, clearFilterDagIds, toggleFilterType, clearFilterTypes } =- useActions(dataModelingLogic)-- if (!nodesLoading && viewNodes.length === 0) {- return (- <div className="text-center py-12">- <h3 className="text-xl font-semibold mb-2">No models found</h3>- {debouncedSearchTerm ? (- <p className="text-muted">No models match your search. Try adjusting your search term.</p>- ) : (- <p className="text-muted">Models will appear here when views or materialized views are created.</p>- )}- </div>- )- }- return (- <LemonTable- dataSource={visibleNodes}- loading={nodesLoading}- columns={[- {- title: 'Name',- key: 'name',- render: (_, node: DataModelingNode) => (- <Link to={node.type === 'endpoint' ? urls.endpoint(node.name) : urls.nodeDetail(node.id)}>- <span className="font-bold text-primary">{node.name}</span>- </Link>- ),- },- {- title: 'Type',- key: 'type',- render: (_, node: DataModelingNode) => {- const settings = NODE_TYPE_TAG_SETTINGS[node.type]- return <LemonTag type={settings.type}>{settings.label}</LemonTag>- },- moreIcon: <IconFilter className="w-4 h-4" />,- moreFilterCount: filterTypes.length,- more: (- <div className="space-y-1">- <div className="px-2 py-1 space-y-1">- {availableTypes.map((type: DataModelingNodeType) => (- <LemonCheckbox- key={type}- label={NODE_TYPE_TAG_SETTINGS[type].label}- checked={filterTypes.includes(type)}- onChange={() => toggleFilterType(type)}- size="small"- fullWidth- />- ))}- {availableTypes.length === 0 && <span className="text-muted text-xs">No types</span>}- </div>- <LemonDivider className="my-1" />- <LemonButton size="small" fullWidth onClick={clearFilterTypes}>- Clear filters- </LemonButton>- </div>- ),- },- {- title: 'DAG',- key: 'dag_id',- render: (_, node: DataModelingNode) => (- <span className="text-muted">{node.dag_name ?? node.dag}</span>- ),- moreIcon: <IconFilter className="w-4 h-4" />,- moreFilterCount: filterDagIds.length,- more: (- <div className="space-y-1">- <div className="px-2 py-1 space-y-1 max-h-60 overflow-y-auto">- {availableDagIds.map((dagId: string) => (- <LemonCheckbox- key={dagId}- label={dagId}- checked={filterDagIds.includes(dagId)}- onChange={() => toggleFilterDagId(dagId)}- size="small"- fullWidth- />- ))}- {availableDagIds.length === 0 && <span className="text-muted text-xs">No DAGs</span>}- </div>- <LemonDivider className="my-1" />- <LemonButton size="small" fullWidth onClick={clearFilterDagIds}>- Clear filters- </LemonButton>- </div>- ),- },- {- title: 'Upstream',- key: 'upstream_count',- tooltip: 'Total number of upstream nodes',- render: (_, node: DataModelingNode) => (- <NodeDependencyCount count={node.upstream_count} loading={nodesLoading} />- ),- },- {- title: 'Downstream',- key: 'downstream_count',- tooltip: 'Total number of downstream nodes',- render: (_, node: DataModelingNode) => (- <NodeDependencyCount count={node.downstream_count} loading={nodesLoading} />- ),- },- {- title: 'Created',- key: 'created_at',- render: (_, node: DataModelingNode) =>- node.created_at ? (- <TZLabel time={node.created_at} formatDate="MMM DD, YYYY" formatTime="HH:mm" />- ) : (- '-'- ),- },- {- title: 'Last run',- key: 'last_run_at',- render: (_, node: DataModelingNode) => {- return node.last_run_at ? <TZLabel time={node.last_run_at} /> : '-'- },- },- {- title: 'Tag',- key: 'tag',- render: (_, node: DataModelingNode) => {- return node.user_tag ? <span className="font-semibold italic">#{node.user_tag}</span> : '-'- },- },- ]}- pagination={{- controlled: true,- pageSize: PAGE_SIZE,- currentPage: currentPage,- entryCount: viewNodes.length,- onForward: () => {- setCurrentPage(currentPage + 1)- },- onBackward: () => {- setCurrentPage(currentPage - 1)- },- }}- />- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/constants.ts b/frontend/src/scenes/data-warehouse/scene/modeling/constants.tsdeleted file mode 100644index 548b08ba6b72..000000000000--- a/frontend/src/scenes/data-warehouse/scene/modeling/constants.ts+++ /dev/null@@ -1,29 +0,0 @@-export const PAGE_SIZE = 25-export const NODE_WIDTH = 180-export const NODE_HEIGHT = 120--// Above this node count, ELK's NETWORK_SIMPLEX node placement (which scales-// super-linearly and runs on the main thread) becomes the dominant cost of-// showing the graph. We switch to the much cheaper BRANDES_KOEPF placement for-// large graphs; smaller graphs keep NETWORK_SIMPLEX for its tighter layout.-export const LARGE_GRAPH_NODE_THRESHOLD = 150--export const TOP_HANDLE_POSITION = {- x: NODE_WIDTH / 2,- y: 0,-}--export const BOTTOM_HANDLE_POSITION = {- x: NODE_WIDTH / 2,- y: NODE_HEIGHT,-}--export const LEFT_HANDLE_POSITION = {- x: 0,- y: NODE_HEIGHT / 2,-}--export const RIGHT_HANDLE_POSITION = {- x: NODE_WIDTH,- y: NODE_HEIGHT / 2,-}diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/types.ts b/frontend/src/scenes/data-warehouse/scene/modeling/types.tsdeleted file mode 100644index 1dd6457108c8..000000000000--- a/frontend/src/scenes/data-warehouse/scene/modeling/types.ts+++ /dev/null@@ -1,57 +0,0 @@-import { Position, Edge as ReactFlowEdge, Node as ReactFlowNode } from '@xyflow/react'--import { DataModelingJobStatus, DataModelingNodeType, DataModelingSyncInterval } from '~/types'--export interface NodeHandle {- id?: string- type: 'source' | 'target'- position: Position- x?: number- y?: number-}--export interface NodeData extends Record<string, unknown> {- id: string- name: string- type: DataModelingNodeType- dag?: string- dagName?: string- savedQueryId?: string- handles?: NodeHandle[]- upstreamCount: number- downstreamCount: number- // derived state for reactflow optimization- isRunning?: boolean- isTypeHighlighted?: boolean- isSearchMatch?: boolean- userTag?: string- lastRunAt?: string- lastJobStatus?: DataModelingJobStatus- syncInterval?: DataModelingSyncInterval-}--export interface EdgeData extends Record<string, unknown> {- from: string- to: string- type: 'dependency'-}--export type ViewMode = 'list' | 'graph'--export type SearchMode = 'search' | 'upstream' | 'downstream' | 'all'--export type ElkDirection = 'DOWN' | 'RIGHT'--export type Node = ReactFlowNode<NodeData>-export type Edge = ReactFlowEdge<EdgeData>--export interface Graph {- nodes: Node[]- edges: Edge[]-}--export interface CreateModelNodeType {- type: DataModelingNodeType- name: string- description?: string-}diff --git a/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.test.ts b/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.test.tsnew file mode 100644index 000000000000..b3cf4e1a7395--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.test.ts@@ -0,0 +1,74 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { lineageDataLogic } from 'products/data_modeling/frontend/lineage/lineageDataLogic'++import { PAGE_SIZE, viewsTabLogic } from './viewsTabLogic'++function buildView(id: string, isMaterialized: boolean): Record<string, unknown> {+ return { id, name: id, columns: [], is_materialized: isMaterialized, created_at: '2024-01-01T00:00:00Z' }+}++describe('viewsTabLogic', () => {+ let logic: ReturnType<typeof viewsTabLogic.build>+ let runHistoryRequests: string[]++ beforeEach(async () => {+ runHistoryRequests = []+ const views = [+ ...Array.from({ length: PAGE_SIZE + 1 }, (_, i) => buildView(`mat-${i}`, true)),+ buildView('plain-a', false),+ buildView('plain-b', false),+ ]+ useMocks({+ get: {+ '/api/environments/:team_id/warehouse_saved_queries/': { count: views.length, results: views },+ '/api/environments/:team_id/data_modeling_nodes/': { count: 0, results: [] },+ '/api/environments/:team_id/data_modeling_edges/': { count: 0, results: [] },+ '/api/environments/:team_id/warehouse_saved_queries/:id/run_history/': (req) => {+ runHistoryRequests.push(String(req.params.id))+ return [200, { run_history: [] }]+ },+ },+ post: { '/api/environments/:team_id/query/': { tables: {} } },+ })+ initKeaTests()+ logic = viewsTabLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ it('loads run history only for the materialized views on the visible page', () => {+ expect(logic.values.visibleViews).toHaveLength(PAGE_SIZE)+ expect(runHistoryRequests).toHaveLength(PAGE_SIZE)+ expect(runHistoryRequests.every((id) => id.startsWith('mat-'))).toBe(true)+ })++ it('narrows the list by type and resets to the first page', async () => {+ logic.actions.setPage(2)+ expect(logic.values.currentPage).toEqual(2)++ logic.actions.setTypeFilter('view')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.currentPage).toEqual(1)+ expect(logic.values.filteredViews.map((view) => view.id)).toEqual(['plain-a', 'plain-b'])+ })++ it('search and type filter compose', async () => {+ logic.actions.setTypeFilter('materialized')+ logic.actions.setSearchTerm('mat-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.filteredViews.map((view) => view.id)).toEqual(['mat-1', 'mat-10'])+ })++ it('keeps name matches visible while lineage data reloads', () => {+ lineageDataLogic.actions.loadNodes()+ logic.actions.setSearchTerm('+mat-1')++ expect(logic.values.filteredViews.map((view) => view.id)).toEqual(['mat-1', 'mat-10'])+ })+})diff --git a/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.ts b/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.tsindex d1026da78769..742de2ad6675 100644--- a/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.ts+++ b/frontend/src/scenes/data-warehouse/scene/viewsTabLogic.ts@@ -8,11 +8,14 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { DataModelingEdge, DataModelingNode, DataWarehouseSavedQuery, DataWarehouseSavedQueryRunHistory } from '~/types'++import { lineageDataLogic } from 'products/data_modeling/frontend/lineage/lineageDataLogic'import {- DataWarehouseSavedQuery,- DataWarehouseSavedQueryDependencies,- DataWarehouseSavedQueryRunHistory,-} from '~/types'+ ParsedLineageSearch,+ nodeIdsForLineageSearch,+ parseLineageSearch,+} from 'products/data_modeling/frontend/lineage/lineageSearch'import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'import type {@@ -25,34 +28,33 @@ import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogiexport const PAGE_SIZE = 10-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export type ViewTypeFilter = 'all' | 'materialized' | 'view'+export interface viewsTabLogicValues {dataWarehouseSavedQueries: DataWarehouseSavedQuery[] // dataWarehouseViewsLogicdataWarehouseSavedQueriesLoading: boolean // dataWarehouseViewsLogicdatabase: Required<DatabaseSchemaQueryResponse> | null // databaseTableListLogicviewsMapById: Record<string, DatabaseSchemaEndpointTable | DatabaseSchemaManagedViewTable | DatabaseSchemaViewTable> // databaseTableListLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic+ nodes: DataModelingNode[] // modelsLineageLogic+ nodesLoading: boolean // modelsLineageLogic+ edges: DataModelingEdge[] // modelsLineageLogic+ edgesLoading: boolean // modelsLineageLogicaccessControlModalOpen: boolean+ currentPage: numbereditingAccessControlView: DataWarehouseSavedQuery | null- enrichedMaterializedViews: DataWarehouseSavedQuery[]enrichedViews: DataWarehouseSavedQuery[]- filteredMaterializedViews: DataWarehouseSavedQuery[]filteredViews: DataWarehouseSavedQuery[]- materializedViewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>- materializedViewDependenciesMapLoading: boolean- materializedViewsCurrentPage: number+ lineageNames: Set<string> | null+ parsedSearch: ParsedLineageSearchrunHistoryMap: Record<string, DataWarehouseSavedQueryRunHistory[]>runHistoryMapLoading: booleansearchTerm: string- viewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>- viewDependenciesMapLoading: boolean- viewsCurrentPage: number+ typeFilter: ViewTypeFilterviewsLoading: boolean- visibleMaterializedViews: DataWarehouseSavedQuery[]visibleViews: DataWarehouseSavedQuery[]}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewsTabLogicActions {deleteDataWarehouseSavedQuery: (viewId: string) => string // dataWarehouseViewsLogicrunDataWarehouseSavedQuery: (@@ -62,6 +64,7 @@ export interface viewsTabLogicActions {fullRefresh: boolean | undefinedviewId: string} // dataWarehouseViewsLogic+ loadDataWarehouseSavedQueriesSuccess: (dataWarehouseSavedQueries: DataWarehouseSavedQuery[], payload?: any) => any // dataWarehouseViewsLogicloadDatabase: (args_0?:| {@@ -79,59 +82,17 @@ export interface viewsTabLogicActions {deleteView: (viewId: string) => {viewId: string}- loadDependenciesForMaterializedViews: (viewIds: string[]) => {- viewIds: string[]- }- loadDependenciesForMaterializedViewsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadDependenciesForMaterializedViewsSuccess: (- materializedViewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>,- payload?: {- viewIds: string[]- }- ) => {- materializedViewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>- payload?: {- viewIds: string[]- }- }- loadDependenciesForViews: (viewIds: string[]) => {- viewIds: string[]- }- loadDependenciesForViewsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadDependenciesForViewsSuccess: (- viewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>,- payload?: {- viewIds: string[]- }- ) => {- viewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>- payload?: {- viewIds: string[]- }- }- loadRunHistoryForViews: (viewIds: string[]) => {+ loadRunHistory: (viewIds: string[]) => {viewIds: string[]}- loadRunHistoryForViewsFailure: (+ loadRunHistoryFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- loadRunHistoryForViewsSuccess: (+ loadRunHistorySuccess: (runHistoryMap: Record<string, DataWarehouseSavedQueryRunHistory[]>,payload?: {viewIds: string[]@@ -151,40 +112,30 @@ export interface viewsTabLogicActions {runMaterialization: (viewId: string) => {viewId: string}- setMaterializedViewsPage: (page: number) => {+ setPage: (page: number) => {page: number}setSearchTerm: (searchTerm: string) => {searchTerm: string}- setViewsPage: (page: number) => {- page: number+ setTypeFilter: (typeFilter: ViewTypeFilter) => {+ typeFilter: ViewTypeFilter}}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewsTabLogicMeta {__keaTypeGenInternalSelectorTypes: {viewsLoading: (dataWarehouseSavedQueriesLoading: boolean) => boolean- enrichedMaterializedViews: (- dataWarehouseSavedQueries: DataWarehouseSavedQuery[],- materializedViewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>,- runHistoryMap: Record<string, DataWarehouseSavedQueryRunHistory[]>- ) => DataWarehouseSavedQuery[]enrichedViews: (dataWarehouseSavedQueries: DataWarehouseSavedQuery[],- viewDependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>- ) => DataWarehouseSavedQuery[]- filteredViews: (enrichedViews: DataWarehouseSavedQuery[], searchTerm: string) => DataWarehouseSavedQuery[]- filteredMaterializedViews: (- enrichedMaterializedViews: DataWarehouseSavedQuery[],- searchTerm: string+ runHistoryMap: Record<string, DataWarehouseSavedQueryRunHistory[]>) => DataWarehouseSavedQuery[]- visibleMaterializedViews: (- filteredMaterializedViews: DataWarehouseSavedQuery[],- materializedViewsCurrentPage: number+ filteredViews: (+ enrichedViews: DataWarehouseSavedQuery[],+ searchTerm: string,+ typeFilter: ViewTypeFilter) => DataWarehouseSavedQuery[]- visibleViews: (filteredViews: DataWarehouseSavedQuery[], viewsCurrentPage: number) => DataWarehouseSavedQuery[]+ visibleViews: (filteredViews: DataWarehouseSavedQuery[], currentPage: number) => DataWarehouseSavedQuery[]}}@@ -205,23 +156,23 @@ export const viewsTabLogic = kea<viewsTabLogicType>([['featureFlags'],databaseTableListLogic,['database', 'viewsMapById'],+ lineageDataLogic,+ ['nodes', 'nodesLoading', 'edges', 'edgesLoading'],],actions: [dataWarehouseViewsLogic,- ['deleteDataWarehouseSavedQuery', 'runDataWarehouseSavedQuery'],+ ['deleteDataWarehouseSavedQuery', 'runDataWarehouseSavedQuery', 'loadDataWarehouseSavedQueriesSuccess'],databaseTableListLogic,['loadDatabase'],],})),actions({setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setTypeFilter: (typeFilter: ViewTypeFilter) => ({ typeFilter }),+ setPage: (page: number) => ({ page }),deleteView: (viewId: string) => ({ viewId }),runMaterialization: (viewId: string) => ({ viewId }),- loadDependenciesForMaterializedViews: (viewIds: string[]) => ({ viewIds }),- loadDependenciesForViews: (viewIds: string[]) => ({ viewIds }),- loadRunHistoryForViews: (viewIds: string[]) => ({ viewIds }),- setMaterializedViewsPage: (page: number) => ({ page }),- setViewsPage: (page: number) => ({ page }),+ loadRunHistory: (viewIds: string[]) => ({ viewIds }),loadVisibleData: true,openAccessControlModal: (view: DataWarehouseSavedQuery) => ({ view }),closeAccessControlModal: true,@@ -233,18 +184,18 @@ export const viewsTabLogic = kea<viewsTabLogicType>([setSearchTerm: (_, { searchTerm }) => searchTerm,},],- materializedViewsCurrentPage: [- 1 as number,+ typeFilter: [+ 'all' as ViewTypeFilter,{- setMaterializedViewsPage: (_, { page }) => page,- setSearchTerm: () => 1, // Reset to page 1 on search+ setTypeFilter: (_, { typeFilter }) => typeFilter,},],- viewsCurrentPage: [+ currentPage: [1 as number,{- setViewsPage: (_, { page }) => page,- setSearchTerm: () => 1, // Reset to page 1 on search+ setPage: (_, { page }) => page,+ setSearchTerm: () => 1,+ setTypeFilter: () => 1,},],accessControlModalOpen: [@@ -263,75 +214,11 @@ export const viewsTabLogic = kea<viewsTabLogicType>([],}),loaders(({ values }) => ({- materializedViewDependenciesMap: [- {} as Record<string, DataWarehouseSavedQueryDependencies>,- {- loadDependenciesForMaterializedViews: async ({ viewIds }) => {- // Filter out views we've already loaded- const viewsToLoad = viewIds.filter((id) => !values.materializedViewDependenciesMap[id])-- if (viewsToLoad.length === 0) {- return values.materializedViewDependenciesMap- }-- const results = await Promise.all(- viewsToLoad.map(async (viewId) => {- try {- const data = await api.dataWarehouseSavedQueries.dependencies(viewId)- return { viewId, data }- } catch (error) {- console.error(`Failed to load dependencies for view ${viewId}:`, error)- return { viewId, data: { upstream_count: 0, downstream_count: 0 } }- }- })- )-- const newMap = { ...values.materializedViewDependenciesMap }- results.forEach(({ viewId, data }) => {- newMap[viewId] = data- })- return newMap- },- },- ],- viewDependenciesMap: [- {} as Record<string, DataWarehouseSavedQueryDependencies>,- {- loadDependenciesForViews: async ({ viewIds }) => {- // Filter out views we've already loaded- const viewsToLoad = viewIds.filter((id) => !values.viewDependenciesMap[id])-- if (viewsToLoad.length === 0) {- return values.viewDependenciesMap- }-- const results = await Promise.all(- viewsToLoad.map(async (viewId) => {- try {- const data = await api.dataWarehouseSavedQueries.dependencies(viewId)- return { viewId, data }- } catch (error) {- console.error(`Failed to load dependencies for view ${viewId}:`, error)- return { viewId, data: { upstream_count: 0, downstream_count: 0 } }- }- })- )-- const newMap = { ...values.viewDependenciesMap }- results.forEach(({ viewId, data }) => {- newMap[viewId] = data- })- return newMap- },- },- ],runHistoryMap: [{} as Record<string, DataWarehouseSavedQueryRunHistory[]>,{- loadRunHistoryForViews: async ({ viewIds }) => {- // Filter out views we've already loaded+ loadRunHistory: async ({ viewIds }) => {const viewsToLoad = viewIds.filter((id) => !values.runHistoryMap[id])-if (viewsToLoad.length === 0) {return values.runHistoryMap}@@ -359,70 +246,65 @@ export const viewsTabLogic = kea<viewsTabLogicType>([})),selectors({viewsLoading: [(s) => [s.dataWarehouseSavedQueriesLoading], (loading: boolean): boolean => loading],- enrichedMaterializedViews: [- (s) => [s.dataWarehouseSavedQueries, s.materializedViewDependenciesMap, s.runHistoryMap],+ enrichedViews: [+ (s) => [s.dataWarehouseSavedQueries, s.runHistoryMap],(queries: DataWarehouseSavedQuery[],- dependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>,runHistoryMap: Record<string, DataWarehouseSavedQueryRunHistory[]>- ): DataWarehouseSavedQuery[] => {- return queries- .filter((q) => q.is_materialized)- .map((query) => ({- ...query,- upstream_dependency_count: dependenciesMap[query.id]?.upstream_count,- downstream_dependency_count: dependenciesMap[query.id]?.downstream_count,- run_history: runHistoryMap[query.id],- }))- },+ ): DataWarehouseSavedQuery[] =>+ queries.map((query) => ({+ ...query,+ run_history: query.is_materialized ? runHistoryMap[query.id] : undefined,+ })),],- enrichedViews: [- (s) => [s.dataWarehouseSavedQueries, s.viewDependenciesMap],+ parsedSearch: [(s) => [s.searchTerm], (searchTerm: string) => parseLineageSearch(searchTerm)],++ // Lineage names the rows to keep; the graph keys on node id, this table on view name.+ lineageNames: [+ (s) => [s.nodes, s.edges, s.nodesLoading, s.edgesLoading, s.parsedSearch],(- queries: DataWarehouseSavedQuery[],- dependenciesMap: Record<string, DataWarehouseSavedQueryDependencies>- ): DataWarehouseSavedQuery[] => {- return queries- .filter((q) => !q.is_materialized)- .map((query) => ({- ...query,- upstream_dependency_count: dependenciesMap[query.id]?.upstream_count,- downstream_dependency_count: dependenciesMap[query.id]?.downstream_count,- }))- },- ],- filteredViews: [- (s) => [s.enrichedViews, s.searchTerm],- (views: DataWarehouseSavedQuery[], searchTerm: string): DataWarehouseSavedQuery[] => {- if (!searchTerm) {- return views- }- return views.filter((v) => v.name.toLowerCase().includes(searchTerm.toLowerCase()))- },- ],- filteredMaterializedViews: [- (s) => [s.enrichedMaterializedViews, s.searchTerm],- (views: DataWarehouseSavedQuery[], searchTerm: string): DataWarehouseSavedQuery[] => {- if (!searchTerm) {- return views+ nodes: DataModelingNode[],+ edges: DataModelingEdge[],+ nodesLoading: boolean,+ edgesLoading: boolean,+ parsedSearch: ParsedLineageSearch+ ): Set<string> | null => {+ if (parsedSearch.mode !== 'search' && (nodesLoading || edgesLoading)) {+ return null}- return views.filter((v) => v.name.toLowerCase().includes(searchTerm.toLowerCase()))+ const reached = nodeIdsForLineageSearch(nodes, edges, parsedSearch)+ return reached && new Set(nodes.filter((node) => reached.has(node.id)).map((node) => node.name))},],- visibleMaterializedViews: [- (s) => [s.filteredMaterializedViews, s.materializedViewsCurrentPage],- (views: DataWarehouseSavedQuery[], currentPage: number): DataWarehouseSavedQuery[] => {- const startIndex = (currentPage - 1) * PAGE_SIZE- const endIndex = startIndex + PAGE_SIZE- return views.slice(startIndex, endIndex)++ filteredViews: [+ (s) => [s.enrichedViews, s.parsedSearch, s.lineageNames, s.typeFilter],+ (+ views: DataWarehouseSavedQuery[],+ parsedSearch: ParsedLineageSearch,+ lineageNames: Set<string> | null,+ typeFilter: ViewTypeFilter+ ): DataWarehouseSavedQuery[] => {+ const term = parsedSearch.term.toLowerCase()+ return views.filter((view) => {+ if (typeFilter === 'materialized' && !view.is_materialized) {+ return false+ }+ if (typeFilter === 'view' && view.is_materialized) {+ return false+ }+ if (lineageNames) {+ return lineageNames.has(view.name)+ }+ return !term || view.name.toLowerCase().includes(term)+ })},],visibleViews: [- (s) => [s.filteredViews, s.viewsCurrentPage],+ (s) => [s.filteredViews, s.currentPage],(views: DataWarehouseSavedQuery[], currentPage: number): DataWarehouseSavedQuery[] => {const startIndex = (currentPage - 1) * PAGE_SIZE- const endIndex = startIndex + PAGE_SIZE- return views.slice(startIndex, endIndex)+ return views.slice(startIndex, startIndex + PAGE_SIZE)},],}),@@ -448,44 +330,32 @@ export const viewsTabLogic = kea<viewsTabLogicType>([actions.runDataWarehouseSavedQuery(viewId)},loadDataWarehouseSavedQueriesSuccess: () => {- // Load data for initially visible itemsactions.loadVisibleData()},- setMaterializedViewsPage: () => {- // Load data when page changes+ setPage: () => {actions.loadVisibleData()},- setViewsPage: () => {- // Load data when page changes+ setSearchTerm: () => {actions.loadVisibleData()},- setSearchTerm: () => {- // Load data when search changes (pagination resets to page 1)+ setTypeFilter: () => {actions.loadVisibleData()},loadVisibleData: () => {- // Get IDs of all currently visible items- const visibleMaterializedViewIds = values.visibleMaterializedViews.map((v) => v.id)- const visibleViewIds = values.visibleViews.map((v) => v.id)-- // Load dependencies for materialized views (if not already loaded)- if (visibleMaterializedViewIds.length > 0) {- actions.loadDependenciesForMaterializedViews(visibleMaterializedViewIds)- actions.loadRunHistoryForViews(visibleMaterializedViewIds)+ const visible = values.visibleViews+ if (visible.length === 0) {+ return}-- // Load dependencies for regular views (if not already loaded)- if (visibleViewIds.length > 0) {- actions.loadDependenciesForViews(visibleViewIds)+ const materializedIds = visible.filter((view) => view.is_materialized).map((view) => view.id)+ if (materializedIds.length > 0) {+ actions.loadRunHistory(materializedIds)}},})),afterMount(({ actions, values }) => {- // If views are already loaded (e.g., from cache), load visible data immediatelyif (values.dataWarehouseSavedQueries.length > 0) {actions.loadVisibleData()}- // Certification badges come from the schema response; reuse it when already loadedif (!values.database) {actions.loadDatabase()}diff --git a/frontend/src/scenes/models/ModelsScene.tsx b/frontend/src/scenes/models/ModelsScene.tsxindex f8a0b49f7252..03d9e517c29e 100644--- a/frontend/src/scenes/models/ModelsScene.tsx+++ b/frontend/src/scenes/models/ModelsScene.tsx@@ -1,7 +1,7 @@import { useValues } from 'kea'import { useCallback } from 'react'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonButton, LemonTab, LemonTabs } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { AccessDenied } from 'lib/components/AccessDenied'@@ -17,8 +17,12 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, DataWarehouseSavedQuery } from '~/types'+import { DataQualityOverview } from 'products/data_quality/frontend/overview/DataQualityOverview'+import { ViewsTab } from '../data-warehouse/scene/ViewsTab'-import { modelsSceneLogic } from './modelsSceneLogic'+import { ModelsSceneTab, modelsSceneLogic } from './modelsSceneLogic'+import { ModelsLineageTab } from './tabs/ModelsLineageTab'+import { ModelsOverviewTab } from './tabs/ModelsOverviewTab'export const scene: SceneExport = {component: ModelsScene,@@ -27,7 +31,8 @@ export const scene: SceneExport = {}export function ModelsScene(): JSX.Element {- const { savedQueryIdToNodeId } = useValues(modelsSceneLogic)+ const { savedQueryIdToNodeId, activeTab, dataQualityTabEnabled, suspensionBySavedQueryId } =+ useValues(modelsSceneLogic)const getViewUrl = useCallback((view: DataWarehouseSavedQuery): string => {@@ -43,6 +48,41 @@ export function ModelsScene(): JSX.Element {)}+ const tabs: LemonTab<ModelsSceneTab>[] = [+ {+ key: 'overview',+ label: 'Overview',+ link: urls.models(),+ content: <ModelsOverviewTab />,+ 'data-attr': 'models-tab-overview',+ },+ {+ key: 'models',+ label: 'Models',+ link: urls.models('models'),+ content: <ViewsTab getViewUrl={getViewUrl} suspensionByViewId={suspensionBySavedQueryId} />,+ 'data-attr': 'models-tab-models',+ },+ {+ key: 'lineage',+ label: 'Lineage',+ link: urls.models('lineage'),+ content: <ModelsLineageTab />,+ 'data-attr': 'models-tab-lineage',+ },+ ...(dataQualityTabEnabled+ ? [+ {+ key: 'data-quality' as const,+ label: 'Data quality',+ link: urls.models('data-quality'),+ content: <DataQualityOverview />,+ 'data-attr': 'models-tab-data-quality',+ },+ ]+ : []),+ ]+return (<SceneContent><SceneTitleSection@@ -78,7 +118,7 @@ export function ModelsScene(): JSX.Element {</div>}/>- <ViewsTab getViewUrl={getViewUrl} />+ <LemonTabs activeKey={activeTab} tabs={tabs} sceneInset /></SceneContent>)}diff --git a/frontend/src/scenes/models/NodeDetailOverview.tsx b/frontend/src/scenes/models/NodeDetailOverview.tsxindex 4fcbf670f9d4..bdf902d16cd9 100644--- a/frontend/src/scenes/models/NodeDetailOverview.tsx+++ b/frontend/src/scenes/models/NodeDetailOverview.tsx@@ -5,7 +5,8 @@ import { LemonTag } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { NODE_TYPE_TAG_SETTINGS, STATUS_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { StatusTag } from 'products/data_modeling/frontend/lineage/StatusTag'import { nodeDetailSceneLogic } from './nodeDetailSceneLogic'@@ -60,9 +61,7 @@ export function NodeDetailOverview({ id }: { id: string }): JSX.Element | null {{effectiveLastRunStatus && (<OverviewItem label="Status">- <LemonTag type={STATUS_TAG_SETTINGS[effectiveLastRunStatus] ?? 'default'}>- {effectiveLastRunStatus}- </LemonTag>+ <StatusTag status={effectiveLastRunStatus} /></OverviewItem>)}diff --git a/frontend/src/scenes/models/modelsLineageLogic.ts b/frontend/src/scenes/models/modelsLineageLogic.tsnew file mode 100644index 000000000000..45d46e859b60--- /dev/null+++ b/frontend/src/scenes/models/modelsLineageLogic.ts@@ -0,0 +1,140 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'++import { DataModelingEdge, DataModelingNode, DataModelingNodeType } from '~/types'++import { lineageDataLogic } from 'products/data_modeling/frontend/lineage/lineageDataLogic'+import {+ ParsedLineageSearch,+ edgesWithinNodes,+ matchNodesByName,+ nodeIdsForLineageSearch,+ parseLineageSearch,+} from 'products/data_modeling/frontend/lineage/lineageSearch'++export const LINEAGE_FILTER_TYPES: DataModelingNodeType[] = ['table', 'view', 'matview', 'endpoint']++export interface modelsLineageLogicValues {+ nodes: DataModelingNode[] // lineageDataLogic+ nodesLoading: boolean // lineageDataLogic+ edges: DataModelingEdge[] // lineageDataLogic+ edgesLoading: boolean // lineageDataLogic+ searchTerm: string+ debouncedSearchTerm: string+ typeFilter: DataModelingNodeType[]+ legendCollapsed: boolean+ parsedSearch: ParsedLineageSearch+ highlightedNodeIds: Set<string>+ visibleNodes: DataModelingNode[]+ visibleEdges: DataModelingEdge[]+ isFiltered: boolean+}++export interface modelsLineageLogicActions {+ setSearchTerm: (searchTerm: string) => { searchTerm: string }+ setDebouncedSearchTerm: (searchTerm: string) => { searchTerm: string }+ setTypeFilter: (typeFilter: DataModelingNodeType[]) => { typeFilter: DataModelingNodeType[] }+ toggleLegendCollapsed: () => Record<string, never>+ resetFilters: () => Record<string, never>+}++export type modelsLineageLogicType = MakeLogicType<modelsLineageLogicValues, modelsLineageLogicActions>++export const modelsLineageLogic = kea<modelsLineageLogicType>([+ path(['scenes', 'models', 'modelsLineageLogic']),+ connect(() => ({+ values: [lineageDataLogic, ['nodes', 'nodesLoading', 'edges', 'edgesLoading']],+ })),+ actions({+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setDebouncedSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setTypeFilter: (typeFilter: DataModelingNodeType[]) => ({ typeFilter }),+ toggleLegendCollapsed: true,+ resetFilters: true,+ }),+ reducers({+ searchTerm: [+ '',+ {+ setSearchTerm: (_, { searchTerm }) => searchTerm,+ resetFilters: () => '',+ },+ ],+ debouncedSearchTerm: [+ '',+ {+ setDebouncedSearchTerm: (_, { searchTerm }) => searchTerm,+ resetFilters: () => '',+ },+ ],+ typeFilter: [+ LINEAGE_FILTER_TYPES,+ {+ setTypeFilter: (_, { typeFilter }) => typeFilter,+ resetFilters: () => LINEAGE_FILTER_TYPES,+ },+ ],+ legendCollapsed: [+ false,+ {+ toggleLegendCollapsed: (collapsed) => !collapsed,+ },+ ],+ }),+ listeners(({ actions }) => ({+ // Every keystroke would otherwise prune the graph and start a fresh ELK layout.+ setSearchTerm: async ({ searchTerm }, breakpoint) => {+ await breakpoint(250)+ actions.setDebouncedSearchTerm(searchTerm)+ },+ })),+ selectors({+ parsedSearch: [(s) => [s.debouncedSearchTerm], (searchTerm: string) => parseLineageSearch(searchTerm)],++ // A plain term highlights matches in place. Only the `+` lineage selectors prune the canvas,+ // so typing a single letter never empties the graph.+ highlightedNodeIds: [+ (s) => [s.nodes, s.parsedSearch],+ (nodes: DataModelingNode[], parsedSearch: ParsedLineageSearch): Set<string> => {+ if (parsedSearch.mode !== 'search') {+ return new Set()+ }+ return new Set(matchNodesByName(nodes, parsedSearch.term).map((node) => node.id))+ },+ ],++ visibleNodes: [+ (s) => [s.nodes, s.edges, s.parsedSearch, s.typeFilter],+ (+ nodes: DataModelingNode[],+ edges: DataModelingEdge[],+ parsedSearch: ParsedLineageSearch,+ typeFilter: DataModelingNodeType[]+ ): DataModelingNode[] => {+ let kept = nodes++ const reached = nodeIdsForLineageSearch(nodes, edges, parsedSearch)+ if (reached) {+ kept = kept.filter((node) => reached.has(node.id))+ }++ if (typeFilter.length !== LINEAGE_FILTER_TYPES.length) {+ kept = kept.filter((node) => typeFilter.includes(node.type))+ }++ return kept+ },+ ],++ visibleEdges: [+ (s) => [s.edges, s.visibleNodes],+ (edges: DataModelingEdge[], visibleNodes: DataModelingNode[]): DataModelingEdge[] =>+ edgesWithinNodes(edges, new Set(visibleNodes.map((node) => node.id))),+ ],++ isFiltered: [+ (s) => [s.nodes, s.visibleNodes],+ (nodes: DataModelingNode[], visibleNodes: DataModelingNode[]): boolean =>+ visibleNodes.length !== nodes.length,+ ],+ }),+])diff --git a/frontend/src/scenes/models/modelsSceneLogic.test.ts b/frontend/src/scenes/models/modelsSceneLogic.test.tsnew file mode 100644index 000000000000..12c593272ebe--- /dev/null+++ b/frontend/src/scenes/models/modelsSceneLogic.test.ts@@ -0,0 +1,213 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { DataModelingNode } from '~/types'++import { lineageDataLogic } from 'products/data_modeling/frontend/lineage/lineageDataLogic'++import { modelsSceneLogic } from './modelsSceneLogic'++function buildNode(id: string, overrides: Partial<DataModelingNode> = {}): DataModelingNode {+ return {+ id,+ name: id,+ type: 'matview',+ dag: 'dag-1',+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ upstream_count: 0,+ downstream_count: 0,+ saved_query_id: `query-${id}`,+ ...overrides,+ }+}++describe('modelsSceneLogic', () => {+ let logic: ReturnType<typeof modelsSceneLogic.build>++ const mount = async (path: string): Promise<void> => {+ router.actions.push(path)+ logic = modelsSceneLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ }++ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/data_modeling_nodes/': {+ count: 7,+ results: [+ buildNode('healthy', {+ last_run_status: 'Completed',+ sync_interval: '1hour',+ last_run_at: '2024-01-01T00:00:00Z',+ }),+ buildNode('broken', {+ last_run_status: 'Failed',+ last_run_error: 'Unknown table foo',+ sync_interval: '1hour',+ last_run_at: '2024-01-01T00:00:00Z',+ }),+ buildNode('child', { last_run_status: 'Skipped' }),+ buildNode('grandchild', { last_run_status: 'Skipped' }),+ buildNode('paused', {+ suspended: { clickhouse: { at: '2024-01-02T00:00:00Z', reason: 'boom', job_id: 'j1' } },+ }),+ buildNode('never-ran'),+ buildNode('shadow-only', {+ suspended: { duckgres: { at: '2024-01-02T00:00:00Z', reason: 'shadow', job_id: 'j2' } },+ }),+ ],+ },+ '/api/environments/:team_id/data_modeling_edges/': {+ count: 2,+ results: [+ { id: 'e1', source_id: 'broken', target_id: 'child', dag: 'dag-1' },+ { id: 'e2', source_id: 'child', target_id: 'grandchild', dag: 'dag-1' },+ ],+ },+ '/api/environments/:team_id/warehouse_saved_queries/': {+ count: 2,+ results: [+ { id: 'query-healthy', name: 'healthy', columns: [], is_materialized: true },+ {+ id: 'query-broken',+ name: 'broken',+ columns: [],+ is_materialized: true,+ latest_error: 'a stale copy nothing should read',+ },+ ],+ },+ },+ })+ initKeaTests()+ })++ /** Flags outlive a test, so each test that cares states the value it needs. */+ const setFlag = (flag: (typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS], value: boolean): void => {+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags(value ? [flag] : [], { [flag]: value })+ }++ afterEach(() => {+ logic?.unmount()+ })++ it.each([+ ['/models', 'overview'],+ ['/models?tab=models', 'models'],+ ['/models?tab=lineage', 'lineage'],+ ['/models?tab=nope', 'overview'],+ ['/models?tab=data-quality', 'overview'],+ ])('%s opens the %s tab', async (path, tab) => {+ await mount(path)+ expect(logic.values.activeTab).toEqual(tab)+ })++ it('opens the data quality tab once its flag is on', async () => {+ setFlag(FEATURE_FLAGS.DATA_QUALITY_CHECKS, true)+ await mount('/models?tab=data-quality')+ expect(logic.values.activeTab).toEqual('data-quality')+ })++ it('opens a data quality deep link after feature flags load', async () => {+ await mount('/models?tab=data-quality')+ expect(logic.values.activeTab).toEqual('overview')++ setFlag(FEATURE_FLAGS.DATA_QUALITY_CHECKS, true)++ expect(logic.values.activeTab).toEqual('data-quality')+ })++ it('counts models whose last run failed and models that are suspended', async () => {+ setFlag(FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES, true)+ await mount('/models')+ await expectLogic(lineageDataLogic).toDispatchActions(['loadNodesSuccess'])+ await expectLogic(dataWarehouseViewsLogic).toDispatchActions(['loadDataWarehouseSavedQueriesSuccess'])++ expect(logic.values.failingNodes.map((node) => node.id)).toEqual(['broken'])+ expect(logic.values.suspendedNodes.map((node) => node.id)).toEqual(['paused'])+ })++ it('ignores a marker on an engine that does not serve queries', async () => {+ setFlag(FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES, true)+ await mount('/models')+ await expectLogic(lineageDataLogic).toDispatchActions(['loadNodesSuccess'])++ // shadow-only carries a duckgres marker. ClickHouse still runs it on schedule.+ expect(logic.values.suspendedNodes.map((node) => node.id)).toEqual(['paused'])+ })++ it('ignores markers on a team that does not enforce suspension', async () => {+ setFlag(FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES, false)+ await mount('/models')+ await expectLogic(lineageDataLogic).toDispatchActions(['loadNodesSuccess'])++ // Detection writes markers for every team, but without enforcement the schedule+ // keeps firing, so the marker records failures rather than a stopped model.+ expect(logic.values.suspendedNodes).toEqual([])+ })++ it('lists broken models with their error and what they hold up', async () => {+ setFlag(FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES, true)+ await mount('/models')+ await expectLogic(lineageDataLogic).toDispatchActions(['loadNodesSuccess', 'loadEdgesSuccess'])+ await expectLogic(dataWarehouseViewsLogic).toDispatchActions(['loadDataWarehouseSavedQueriesSuccess'])++ // Suspended sorts above failed, because a suspended model has stopped running altogether.+ expect(logic.values.attentionModels.map((row) => [row.node.id, row.problem])).toEqual([+ ['paused', 'Suspended'],+ ['broken', 'Failed'],+ ])++ const paused = logic.values.attentionModels[0]+ expect(paused.reason).toEqual('boom')+ expect(paused.downstreamCount).toEqual(0)++ // The whole cone counts, not just direct children, and the anchor is not one of them.+ const broken = logic.values.attentionModels[1]+ expect(broken.reason).toEqual('Unknown table foo')+ expect(broken.reason).not.toEqual('a stale copy nothing should read')+ expect(broken.downstreamCount).toEqual(2)+ expect(broken.skippedCount).toEqual(2)+ })++ it('lists models behind schedule, minus the ones already listed as broken', async () => {+ await mount('/models')+ await expectLogic(lineageDataLogic).toDispatchActions(['loadNodesSuccess', 'loadEdgesSuccess'])++ // Both blew their cadence, but a broken model is already named above, and saying it+ // twice would send the reader to the same place for two different reasons.+ expect(logic.values.behindSchedule.map((row) => row.node.id)).toEqual(['healthy'])+ })++ it('updates models behind schedule when the scene clock advances without reloading nodes', async () => {+ const initialNow = new Date('2026-01-01T12:00:00Z').getTime()+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(initialNow)+ try {+ await mount('/models')+ lineageDataLogic.actions.loadNodesSuccess([+ buildNode('nearly-behind', {+ sync_interval: '1hour',+ last_run_at: '2026-01-01T10:01:00Z',+ }),+ ])+ expect(logic.values.behindSchedule).toEqual([])++ nowSpy.mockReturnValue(initialNow + 2 * 60_000)+ logic.actions.setNow(Date.now())++ expect(logic.values.behindSchedule.map((row) => row.node.id)).toEqual(['nearly-behind'])+ } finally {+ nowSpy.mockRestore()+ }+ })+})diff --git a/frontend/src/scenes/models/modelsSceneLogic.ts b/frontend/src/scenes/models/modelsSceneLogic.tsindex 1f49919d80c2..3e7676489df7 100644--- a/frontend/src/scenes/models/modelsSceneLogic.ts+++ b/frontend/src/scenes/models/modelsSceneLogic.ts@@ -1,46 +1,84 @@-import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'-import { loaders } from 'kea-loaders'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { router, urlToAction } from 'kea-router'-import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'+import { urls } from 'scenes/urls'-import { DataModelingNode } from '~/types'+import { DataModelingEdge, DataModelingNode } from '~/types'+import { BehindScheduleModel, modelsBehindSchedule } from 'products/data_modeling/frontend/freshness'+import { NodeSuspensionApi } from 'products/data_modeling/frontend/generated/api.schemas'+import { lineageDataLogic } from 'products/data_modeling/frontend/lineage/lineageDataLogic'+import { buildAdjacencyMaps, traverseLineage } from 'products/data_modeling/frontend/lineage/lineageSearch'+import { servingSuspension } from 'products/data_modeling/frontend/suspension'++import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'import type { DataWarehouseSavedQuery } from '../../types'-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export type ModelsSceneTab = 'overview' | 'models' | 'lineage' | 'data-quality'++const MODELS_SCENE_TABS: ModelsSceneTab[] = ['overview', 'models', 'lineage', 'data-quality']++function isModelsSceneTab(tab: unknown): tab is ModelsSceneTab {+ return typeof tab === 'string' && (MODELS_SCENE_TABS as string[]).includes(tab)+}++/** One row of the overview's attention table: a broken model, why, and what it holds up. */+export interface AttentionModel {+ node: DataModelingNode+ problem: 'Failed' | 'Suspended'+ reason: string | null+ downstreamCount: number+ skippedCount: number+}+export interface modelsSceneLogicValues {dataWarehouseSavedQueries: DataWarehouseSavedQuery[] // dataWarehouseViewsLogicdataWarehouseSavedQueriesLoading: boolean // dataWarehouseViewsLogic- nodes: DataModelingNode[]- nodesLoading: boolean+ featureFlags: FeatureFlagsSet // featureFlagLogic+ receivedFeatureFlags: boolean // featureFlagLogic+ activeTab: ModelsSceneTab+ dataQualityTabEnabled: boolean+ nodes: DataModelingNode[] // lineageDataLogic+ nodesLoading: boolean // lineageDataLogic+ edges: DataModelingEdge[] // lineageDataLogic+ now: numbersavedQueryIdToNodeId: Record<string, string>+ failingNodes: DataModelingNode[]+ suspendedNodes: DataModelingNode[]+ suspensionBySavedQueryId: Record<string, NodeSuspensionApi | undefined>+ attentionModels: AttentionModel[]+ behindSchedule: BehindScheduleModel[]}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface modelsSceneLogicActions {loadDataWarehouseSavedQueries: () => any // dataWarehouseViewsLogic- loadNodes: () => any- loadNodesFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadNodesSuccess: (- nodes: DataModelingNode[],- payload?: any- ) => {- nodes: DataModelingNode[]- payload?: any- }+ setFeatureFlags: (flags: string[], variants: Record<string, boolean | string>) => any // featureFlagLogic+ setActiveTab: (tab: ModelsSceneTab) => { tab: ModelsSceneTab }+ setNow: (now: number) => { now: number }}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface modelsSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {savedQueryIdToNodeId: (nodes: DataModelingNode[]) => Record<string, string>+ failingNodes: (nodes: DataModelingNode[]) => DataModelingNode[]+ suspendedNodes: (nodes: DataModelingNode[]) => DataModelingNode[]+ suspensionBySavedQueryId: (nodes: DataModelingNode[]) => Record<string, NodeSuspensionApi | undefined>+ dataQualityTabEnabled: (featureFlags: FeatureFlagsSet) => boolean+ attentionModels: (+ failingNodes: DataModelingNode[],+ suspendedNodes: DataModelingNode[],+ edges: DataModelingEdge[],+ nodes: DataModelingNode[],+ savedQueries: DataWarehouseSavedQuery[]+ ) => AttentionModel[]+ behindSchedule: (+ nodes: DataModelingNode[],+ attentionModels: AttentionModel[],+ now: number+ ) => BehindScheduleModel[]}}@@ -54,17 +92,33 @@ export type modelsSceneLogicType = MakeLogicType<export const modelsSceneLogic = kea<modelsSceneLogicType>([path(['scenes', 'models', 'modelsSceneLogic']),connect(() => ({- values: [dataWarehouseViewsLogic, ['dataWarehouseSavedQueries', 'dataWarehouseSavedQueriesLoading']],- actions: [dataWarehouseViewsLogic, ['loadDataWarehouseSavedQueries']],+ values: [+ dataWarehouseViewsLogic,+ ['dataWarehouseSavedQueries', 'dataWarehouseSavedQueriesLoading'],+ featureFlagLogic,+ ['featureFlags', 'receivedFeatureFlags'],+ lineageDataLogic,+ ['nodes', 'nodesLoading', 'edges'],+ ],+ actions: [dataWarehouseViewsLogic, ['loadDataWarehouseSavedQueries'], featureFlagLogic, ['setFeatureFlags']],})),- loaders({- nodes: {- __default: [] as DataModelingNode[],- loadNodes: async () => {- const response = await api.dataModelingNodes.list()- return response.results+ actions({+ setActiveTab: (tab: ModelsSceneTab) => ({ tab }),+ setNow: (now: number) => ({ now }),+ }),+ reducers({+ activeTab: [+ 'overview' as ModelsSceneTab,+ {+ setActiveTab: (_, { tab }) => tab,},- },+ ],+ now: [+ Date.now(),+ {+ setNow: (_, { now }) => now,+ },+ ],}),selectors({savedQueryIdToNodeId: [@@ -79,9 +133,124 @@ export const modelsSceneLogic = kea<modelsSceneLogicType>([return map},],+ failingNodes: [+ (s) => [s.nodes],+ (nodes: DataModelingNode[]): DataModelingNode[] =>+ nodes.filter((node) => node.last_run_status === 'Failed'),+ ],+ // The saved-query list response omits `suspended`, so read it off the nodes.+ /**+ * A marker only means scheduled runs stopped when it is on the serving engine and the team+ * enforces suspension. Detection runs for every team, so an unenforced marker is a record+ * of repeated failures while the schedule keeps firing.+ */+ suspendedNodes: [+ (s) => [s.nodes, s.featureFlags],+ (nodes: DataModelingNode[], featureFlags: FeatureFlagsSet): DataModelingNode[] => {+ if (!featureFlags[FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES]) {+ return []+ }+ return nodes.filter((node) => servingSuspension(node.suspended))+ },+ ],+ suspensionBySavedQueryId: [+ (s) => [s.suspendedNodes],+ (suspendedNodes: DataModelingNode[]): Record<string, NodeSuspensionApi | undefined> => {+ const map: Record<string, NodeSuspensionApi | undefined> = {}+ for (const node of suspendedNodes) {+ if (node.saved_query_id) {+ map[node.saved_query_id] = servingSuspension(node.suspended)+ }+ }+ return map+ },+ ],+ /**+ * What the overview leads with. Suspension outranks a failure because scheduled runs have+ * stopped entirely, and within each the widest blast radius comes first.+ */+ attentionModels: [+ (s) => [s.failingNodes, s.suspendedNodes, s.edges, s.nodes],+ (+ failingNodes: DataModelingNode[],+ suspendedNodes: DataModelingNode[],+ edges: DataModelingEdge[],+ nodes: DataModelingNode[]+ ): AttentionModel[] => {+ const suspendedIds = new Set(suspendedNodes.map((node) => node.id))+ const affected = [...suspendedNodes, ...failingNodes.filter((node) => !suspendedIds.has(node.id))]+ if (affected.length === 0) {+ return []+ }++ const nodeById: Record<string, DataModelingNode> = {}+ for (const node of nodes) {+ nodeById[node.id] = node+ }+ const maps = buildAdjacencyMaps(edges)++ const rows = affected.map((node): AttentionModel => {+ const suspension = servingSuspension(node.suspended)+ // The cone includes the node itself, which is not something it blocks.+ const downstream = [...traverseLineage(node.id, maps, 'downstream')].filter((id) => id !== node.id)+ return {+ node,+ problem: suspension ? 'Suspended' : 'Failed',+ reason: suspension?.reason ?? node.last_run_error ?? null,+ downstreamCount: downstream.length,+ skippedCount: downstream.filter((id) => nodeById[id]?.last_run_status === 'Skipped').length,+ }+ })++ return rows.sort((a, b) => {+ if (a.problem !== b.problem) {+ return a.problem === 'Suspended' ? -1 : 1+ }+ return b.downstreamCount - a.downstreamCount+ })+ },+ ],+ behindSchedule: [+ (s) => [s.nodes, s.attentionModels, s.now],+ (nodes: DataModelingNode[], attentionModels: AttentionModel[], now: number): BehindScheduleModel[] => {+ // A failed or suspended model is behind as a consequence, and its own row+ // already says why, so reporting it here would only repeat the same problem.+ const reported = new Set(attentionModels.map((row) => row.node.id))+ return modelsBehindSchedule(nodes, now).filter((row) => !reported.has(row.node.id))+ },+ ],+ dataQualityTabEnabled: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.DATA_QUALITY_CHECKS],+ ],}),- afterMount(({ actions }) => {+ listeners(({ actions }) => ({+ setFeatureFlags: ({ variants }) => {+ if (router.values.searchParams.tab === 'data-quality') {+ actions.setActiveTab(variants[FEATURE_FLAGS.DATA_QUALITY_CHECKS] ? 'data-quality' : 'overview')+ }+ },+ })),+ urlToAction(({ actions, values }) => ({+ [urls.models()]: (_, searchParams) => {+ let tab: ModelsSceneTab = isModelsSceneTab(searchParams.tab) ? searchParams.tab : 'overview'+ if (tab === 'data-quality' && !values.receivedFeatureFlags) {+ return+ }+ if (tab === 'data-quality' && !values.dataQualityTabEnabled) {+ tab = 'overview'+ }+ if (tab !== values.activeTab) {+ actions.setActiveTab(tab)+ }+ },+ })),+ afterMount(({ actions, cache }) => {actions.loadDataWarehouseSavedQueries()- actions.loadNodes()+ actions.setNow(Date.now())+ cache.disposables.add(() => {+ const intervalId = window.setInterval(() => actions.setNow(Date.now()), 60_000)+ return () => window.clearInterval(intervalId)+ })}),])diff --git a/frontend/src/scenes/models/tabs/ModelsLineageTab.tsx b/frontend/src/scenes/models/tabs/ModelsLineageTab.tsxnew file mode 100644index 000000000000..50af3226da1b--- /dev/null+++ b/frontend/src/scenes/models/tabs/ModelsLineageTab.tsx@@ -0,0 +1,103 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import { IconInfo } from '@posthog/icons'+import { LemonButton, LemonInput, Tooltip } from '@posthog/lemon-ui'++import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { DataModelingNodeType } from '~/types'++import { LineageGraph } from 'products/data_modeling/frontend/lineage/LineageGraph'+import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'+import { NodeTypeLegend } from 'products/data_modeling/frontend/lineage/NodeTypeLegend'+import { SEARCH_SYNTAX_HELP } from 'products/data_modeling/frontend/lineage/SearchSyntaxHelp'++import { LINEAGE_FILTER_TYPES, modelsLineageLogic } from '../modelsLineageLogic'++const TYPE_OPTIONS = LINEAGE_FILTER_TYPES.map((type) => ({+ key: type,+ label: NODE_TYPE_TAG_SETTINGS[type].label,+}))++export function ModelsLineageTab(): JSX.Element {+ const {+ nodes,+ nodesLoading,+ edgesLoading,+ searchTerm,+ typeFilter,+ legendCollapsed,+ highlightedNodeIds,+ visibleNodes,+ visibleEdges,+ isFiltered,+ } = useValues(modelsLineageLogic)+ const { setSearchTerm, setTypeFilter, toggleLegendCollapsed, resetFilters } = useActions(modelsLineageLogic)++ return (+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap gap-2 items-center">+ <LemonInput+ type="search"+ size="small"+ placeholder="Search, or +name for upstream"+ value={searchTerm}+ onChange={setSearchTerm}+ className="w-72"+ data-attr="models-lineage-search"+ />+ <Tooltip title={SEARCH_SYNTAX_HELP}>+ <IconInfo className="text-base text-secondary" />+ </Tooltip>+ <div className="w-44">+ <LemonInputSelect+ mode="multiple"+ size="small"+ placeholder="All types"+ options={TYPE_OPTIONS}+ value={typeFilter}+ onChange={(value) => setTypeFilter(value as DataModelingNodeType[])}+ displayMode="count"+ bulkActions="select-and-clear-all"+ data-attr="models-lineage-type-filter"+ />+ </div>+ {isFiltered && (+ <>+ <span className="text-xs text-secondary">+ Showing {pluralize(visibleNodes.length, 'model')} of {nodes.length}+ </span>+ <LemonButton size="xsmall" onClick={resetFilters} data-attr="models-lineage-reset-filters">+ Clear filters+ </LemonButton>+ </>+ )}+ </div>+ <div className="h-[calc(100vh-20rem)] min-h-[400px] w-full border rounded bg-bg-light overflow-hidden">+ <LineageGraph+ nodes={visibleNodes}+ edges={visibleEdges}+ variant="canvas"+ interactive+ showControls+ showMinimap+ minimapPosition="top-right"+ loading={nodesLoading || edgesLoading}+ emptyMessage={+ isFiltered ? 'No models match these filters.' : 'No models yet. Create a view to see it here.'+ }+ nodeState={(node) => ({+ isHighlighted: highlightedNodeIds.has(node.id),+ isRunning: node.last_run_status === 'Running',+ })}+ onNodeClick={(node) => router.actions.push(urls.nodeDetail(node.id))}+ panelPosition="bottom-left"+ panels={<NodeTypeLegend collapsed={legendCollapsed} onToggleCollapse={toggleLegendCollapsed} />}+ />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/models/tabs/ModelsOverviewTab.tsx b/frontend/src/scenes/models/tabs/ModelsOverviewTab.tsxnew file mode 100644index 000000000000..a24d5cd8da09--- /dev/null+++ b/frontend/src/scenes/models/tabs/ModelsOverviewTab.tsx@@ -0,0 +1,298 @@+import { useActions, useValues } from 'kea'++import { IconCheckCircle } from '@posthog/icons'+import { LemonBanner, LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { pluralize } from 'lib/utils/strings'+import { CADENCE_LABELS } from 'scenes/data-warehouse/saved_queries/SyncFrequencySelect'+import { urls } from 'scenes/urls'++import { BehindScheduleModel } from 'products/data_modeling/frontend/freshness'+import { checkDisplayName } from 'products/data_quality/frontend/checksConstants'+import { CheckStatusCell } from 'products/data_quality/frontend/CheckStatusCell'+import { DataQualityOverviewCheckApi } from 'products/data_quality/frontend/generated/api.schemas'+import { dataQualityOverviewLogic } from 'products/data_quality/frontend/overview/dataQualityOverviewLogic'++import { AttentionModel, modelsSceneLogic } from '../modelsSceneLogic'++function Section({+ title,+ description,+ action,+ children,+}: {+ title: string+ description: string+ action?: JSX.Element+ children: React.ReactNode+}): JSX.Element {+ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-start justify-between gap-4">+ <div>+ <h3 className="mb-0">{title}</h3>+ <p className="mb-0 text-secondary text-sm">{description}</p>+ </div>+ {action}+ </div>+ {children}+ </div>+ )+}++/** What the failure holds up, so a reader can tell a leaf model from one the whole graph waits on. */+function ImpactCell({ row }: { row: AttentionModel }): JSX.Element {+ if (row.downstreamCount === 0) {+ return <span className="text-secondary whitespace-nowrap">Nothing downstream</span>+ }+ return (+ <div className="flex flex-col whitespace-nowrap">+ <span>{pluralize(row.downstreamCount, 'model')} downstream</span>+ {row.skippedCount > 0 && (+ <span className="text-secondary text-xs">{pluralize(row.skippedCount, 'model')} skipped</span>+ )}+ </div>+ )+}++/** Not run statuses: these say whether anything will retry on its own, which is why suspension sorts first. */+const PROBLEM_TOOLTIPS: Record<string, string> = {+ Suspended: 'Scheduled runs have stopped after repeated failures. This model stays behind until you resume it.',+ Failed: 'The last scheduled run failed. The next run will try again.',+}++const ATTENTION_COLUMNS: LemonTableColumns<AttentionModel> = [+ {+ title: 'Model',+ key: 'name',+ render: (_, row) => <LemonTableLink to={urls.nodeDetail(row.node.id)} title={row.node.name} />,+ },+ {+ title: 'Problem',+ key: 'problem',+ width: 0,+ render: (_, row) => (+ <Tooltip title={PROBLEM_TOOLTIPS[row.problem]}>+ <LemonTag type={row.problem === 'Suspended' ? 'warning' : 'danger'}>{row.problem}</LemonTag>+ </Tooltip>+ ),+ },+ {+ title: 'Error',+ key: 'reason',+ render: (_, row) =>+ row.reason ? (+ <Tooltip title={<div className="whitespace-pre-wrap font-mono text-xs">{row.reason}</div>}>+ <span className="line-clamp-2 text-secondary text-xs">{row.reason}</span>+ </Tooltip>+ ) : (+ <span className="text-secondary">-</span>+ ),+ },+ {+ title: 'Impact',+ key: 'impact',+ width: 0,+ render: (_, row) => <ImpactCell row={row} />,+ },+]++const BEHIND_COLUMNS: LemonTableColumns<BehindScheduleModel> = [+ {+ title: 'Model',+ key: 'name',+ render: (_, row) => <LemonTableLink to={urls.nodeDetail(row.node.id)} title={row.node.name} />,+ },+ {+ title: 'Behind by',+ key: 'behind',+ width: 0,+ sorter: (a, b) => a.overdueSeconds - b.overdueSeconds,+ render: (_, row) => (+ <Tooltip title={`This model should be no more than ${CADENCE_LABELS[row.node.sync_interval!]} old.`}>+ <span className="whitespace-nowrap font-medium text-warning">+ {humanFriendlyDuration(row.overdueSeconds, { maxUnits: 2 })}+ </span>+ </Tooltip>+ ),+ },+ {+ title: 'Refreshes every',+ key: 'target',+ width: 0,+ render: (_, row) => (row.node.sync_interval ? CADENCE_LABELS[row.node.sync_interval] : '-'),+ },+ {+ title: 'Last successful run',+ key: 'last_run_at',+ width: 0,+ sorter: (a, b) => b.ageSeconds - a.ageSeconds,+ render: (_, row) =>+ row.node.last_run_at ? (+ <TZLabel time={row.node.last_run_at} />+ ) : (+ <Tooltip title="This model has never finished a run since it was created.">+ <span className="text-secondary">Never</span>+ </Tooltip>+ ),+ },+]++const CHECK_COLUMNS: LemonTableColumns<DataQualityOverviewCheckApi> = [+ {+ title: 'Check',+ key: 'check',+ render: (_, check) => checkDisplayName(check),+ },+ {+ title: 'Subject',+ key: 'subject',+ render: (_, check) =>+ check.subject_node_id ? (+ <Link to={urls.nodeDetail(check.subject_node_id, 'tests')}>{check.subject_name}</Link>+ ) : (+ check.subject_name+ ),+ },+ {+ title: 'Status',+ key: 'status',+ width: 0,+ render: (_, check) => <CheckStatusCell check={check} />,+ },+]++function OverviewBody({+ failingChecks,+ checksLoading,+ checksLoaded,+ checksError,+ onRetryChecks,+}: {+ failingChecks: DataQualityOverviewCheckApi[]+ checksLoading: boolean+ /** False while the checks request is in flight, so an empty list is not yet an answer. */+ checksLoaded: boolean+ checksError: string | null+ onRetryChecks?: () => void+}): JSX.Element {+ const { attentionModels, behindSchedule, nodesLoading, dataQualityTabEnabled } = useValues(modelsSceneLogic)++ const nothingWrong =+ !nodesLoading &&+ checksLoaded &&+ !checksError &&+ attentionModels.length === 0 &&+ behindSchedule.length === 0 &&+ failingChecks.length === 0++ if (nothingWrong) {+ return (+ <div className="flex items-center gap-2" data-attr="models-overview-healthy">+ <IconCheckCircle className="text-success text-xl" />+ <span>+ {dataQualityTabEnabled+ ? 'Every model is up to date and every check passed.'+ : 'Every model is up to date.'}+ </span>+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-6">+ {(nodesLoading || attentionModels.length > 0) && (+ <Section+ title="Models needing attention"+ description="A failed model did not finish its last run. A suspended one has stopped running on its schedule after repeated failures."+ action={+ <Link to={urls.models('models')} data-attr="models-overview-all-models">+ All models+ </Link>+ }+ >+ <LemonTable+ columns={ATTENTION_COLUMNS}+ dataSource={attentionModels}+ loading={nodesLoading}+ rowKey={(row) => row.node.id}+ size="small"+ data-attr="models-overview-attention"+ />+ </Section>+ )}+ {behindSchedule.length > 0 && (+ <Section+ title="Models behind schedule"+ description="Each of these declares how fresh it should be, but has gone more than twice that long without finishing a run. Nothing reported a failure, so they may have stopped quietly."+ >+ <LemonTable+ columns={BEHIND_COLUMNS}+ dataSource={behindSchedule}+ rowKey={(row) => row.node.id}+ size="small"+ data-attr="models-overview-behind"+ />+ </Section>+ )}+ {checksError && (+ <LemonBanner+ type="error"+ action={onRetryChecks ? { children: 'Try again', onClick: onRetryChecks } : undefined}+ data-attr="models-overview-checks-error"+ >+ Data quality checks could not be loaded, so this page cannot say whether any are failing.+ </LemonBanner>+ )}+ {failingChecks.length > 0 && (+ <Section+ title="Failing data quality checks"+ description="Assertions your models did not hold up on their last run."+ action={+ <Link to={urls.models('data-quality')} data-attr="models-overview-all-checks">+ All checks+ </Link>+ }+ >+ <LemonTable+ columns={CHECK_COLUMNS}+ dataSource={failingChecks}+ loading={checksLoading}+ rowKey={(check) => check.id}+ size="small"+ data-attr="models-overview-failing-checks"+ />+ </Section>+ )}+ </div>+ )+}++/** Split out so the checks request is only made where the tab exists. */+function OverviewWithChecks(): JSX.Element {+ const { checks, overviewLoading, snapshotLoaded, overviewError } = useValues(dataQualityOverviewLogic)+ const { loadOverview } = useActions(dataQualityOverviewLogic)++ return (+ <OverviewBody+ failingChecks={checks.filter((check) => check.last_status === 'failed' || check.last_status === 'errored')}+ checksLoading={overviewLoading}+ checksLoaded={snapshotLoaded}+ checksError={overviewError}+ onRetryChecks={loadOverview}+ />+ )+}++export function ModelsOverviewTab(): JSX.Element {+ const { dataQualityTabEnabled } = useValues(modelsSceneLogic)++ return dataQualityTabEnabled ? (+ <OverviewWithChecks />+ ) : (+ <OverviewBody failingChecks={[]} checksLoading={false} checksLoaded checksError={null} />+ )+}diff --git a/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx b/frontend/src/scenes/models/tabs/NodeDetailLineage.tsxindex 56efbd230978..865cfeeedc5d 100644--- a/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx+++ b/frontend/src/scenes/models/tabs/NodeDetailLineage.tsx@@ -83,8 +83,8 @@ export function NodeDetailLineage({ id }: { id: string }): JSX.Element {<LemonButtontype="secondary"size="small"- to={urls.dataOps('modeling')}- tooltip="Open full DAG view"+ to={urls.models('lineage')}+ tooltip="Open the full graph"icon={<IconExternal />}/><LemonButtondiff --git a/frontend/src/scenes/models/tabs/NodeDetailTestsTabLabel.tsx b/frontend/src/scenes/models/tabs/NodeDetailTestsTabLabel.tsxindex 1481ccf56951..48b9bc0fc995 100644--- a/frontend/src/scenes/models/tabs/NodeDetailTestsTabLabel.tsx+++ b/frontend/src/scenes/models/tabs/NodeDetailTestsTabLabel.tsx@@ -1,17 +1,35 @@import { useValues } from 'kea'-import { LemonTag } from '@posthog/lemon-ui'+import { IconWarning } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++import { pluralize } from 'lib/utils/strings'import { dataQualityChecksLogic } from 'products/data_quality/frontend/dataQualityChecksLogic'+/** Erroring means a check could not run at all, so it reports no failure count to speak of. */+const TONES: Record<string, string> = {+ failing: 'text-danger',+ warn: 'text-warning',+ erroring: 'text-warning',+}+export function NodeDetailTestsTabLabel({ subjectId }: { subjectId: string }): JSX.Element {const { health } = useValues(dataQualityChecksLogic({ subjectType: 'view', subjectId }))- const checksFailing = health?.checks_failing ?? 0+ const tone = health ? TONES[health.health] : undefined+ const explanation =+ health?.health === 'erroring'+ ? 'A check could not run'+ : `${pluralize(health?.checks_failing ?? 0, 'check')} failing`return (<span className="flex items-center gap-1">Tests- {checksFailing > 0 && <LemonTag type="danger">{checksFailing} failing</LemonTag>}+ {tone && (+ <Tooltip title={explanation}>+ <IconWarning className={tone} />+ </Tooltip>+ )}</span>)}diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 4ad0931e25cc..e5f38383f35e 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -55,7 +55,6 @@ export const urls = {webScripts: (): string => '/web-scripts',webScriptsNew: (): string => '/web-scripts/new',destinations: (): string => '/data-management/destinations',- models: (): string => '/models',transformations: (): string => '/data-management/transformations',eventFiltering: (): string => '/data-management/event-filtering',activity: (tab: ActivityTab | ':tab' = ActivityTab.ExploreEvents): string => `/activity/${tab}`,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 7389b097abb2..e681f589c7ae 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -82,6 +82,7 @@ import type {import { QueryContext } from '~/queries/types'import { AlertType } from 'products/alerts/frontend/types'+import type { NodeApiSuspended } from 'products/data_modeling/frontend/generated/api.schemas'import type {DataWarehouseSavedQueryApiSuspended,SyncFrequencyBoundsApi,@@ -6284,9 +6285,11 @@ export interface DataModelingNode {upstream_count: numberdownstream_count: numberuser_tag?: string- last_run_at?: string+ last_run_at?: string | nulllast_run_status?: DataModelingJobStatus+ last_run_error?: string | nullsync_interval?: DataModelingSyncInterval+ suspended?: NodeApiSuspended}export interface DataModelingEdge {@@ -6338,8 +6341,7 @@ export interface DataWarehouseSavedQuery {is_incremental?: boolean/** Engine → suspension details. Only included when fetching a single saved query, not in list responses */suspended?: DataWarehouseSavedQueryApiSuspended- upstream_dependency_count?: number- downstream_dependency_count?: number+ created_by?: UserBasicType | nullcreated_at?: stringrun_history?: DataWarehouseSavedQueryRunHistory[]origin?: DataWarehouseSavedQueryOrigindiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8222f492d003..52a9b0e0140c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3055,6 +3055,9 @@ importers:clsx:specifier: '*'version: 1.2.1+ elkjs:+ specifier: '*'+ version: 0.10.0kea:specifier: 'catalog:'version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])@@ -3077,6 +3080,9 @@ importers:'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))products/data_quality:dependencies:diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex f51754780638..fab3e97aa11a 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -6,7 +6,7 @@ from uuid import UUID, uuid4from django.conf import settingsfrom django.db import models-from django.db.models import OuterRef, Subquery+from django.db.models import Exists, OuterRef, Subqueryfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field@@ -27,7 +27,15 @@ from posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputfrom products.access_control.backend.facade.user_access_control import AccessControlLevelfrom products.data_modeling.backend.facade.api import get_declared_target, suspension_state, unsuspend_nodes-from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Edge, Node, NodeType+from products.data_modeling.backend.facade.models import (+ DAG,+ DataModelingJob,+ DataModelingJobEngine,+ DataWarehouseSavedQuery,+ Edge,+ Node,+ NodeType,+)from products.warehouse_sources.backend.facade.models import sync_frequency_interval_to_sync_frequency@@ -47,6 +55,7 @@ class NodeSerializer(serializers.ModelSerializer):downstream_count = serializers.SerializerMethodField(read_only=True)last_run_at = serializers.SerializerMethodField(read_only=True)last_run_status = serializers.SerializerMethodField(read_only=True)+ last_run_error = serializers.SerializerMethodField(read_only=True)user_tag = serializers.SerializerMethodField(read_only=True)sync_interval = serializers.SerializerMethodField(read_only=True)dag_name = serializers.SerializerMethodField(read_only=True)@@ -68,6 +77,7 @@ class NodeSerializer(serializers.ModelSerializer):"downstream_count","last_run_at","last_run_status",+ "last_run_error","user_tag","sync_interval","suspended",@@ -107,10 +117,21 @@ class NodeSerializer(serializers.ModelSerializer):return len(_get_downstream_nodes(node))def get_last_run_at(self, node: Node) -> str | None:- return node.properties.get("system", {}).get("last_run_at") or getattr(node, "_latest_job_run_at", None)+ run_at = getattr(node, "_latest_job_run_at", None)+ if run_at is not None:+ return run_at.isoformat()+ if getattr(node, "_has_serving_job", False):+ return None+ return node.properties.get("system", {}).get("last_run_at")def get_last_run_status(self, node: Node) -> str | None:- return node.properties.get("system", {}).get("last_run_status") or getattr(node, "_latest_job_status", None)+ """Skipped runs are written straight to the job table and never reach the stored status,+ so a blocked model would keep reporting the success before it."""+ return getattr(node, "_latest_job_status", None) or node.properties.get("system", {}).get("last_run_status")++ def get_last_run_error(self, node: Node) -> str | None:+ """Error of the run that last_run_status describes, so the two never disagree."""+ return getattr(node, "_latest_job_error", None) or Nonedef get_user_tag(self, node: Node) -> str | None:return node.properties.get("user", {}).get("tag")@@ -190,27 +211,31 @@ def _get_downstream_nodes(node: Node) -> set[str]:return nodes-def _node_queryset_with_latest_job() -> models.QuerySet:- """Node queryset annotated with the latest DataModelingJob status and last_run_at.+def _annotate_latest_job(queryset: models.QuerySet) -> models.QuerySet:+ """Annotate the run state a reader is asking about: the serving engine's newest job.- This lets the serializer fall back to job data when node.properties["system"] is unpopulated.- - _latest_job_status: status of the most recent job (any status)- - _latest_job_run_at: last_run_at of the most recent *successful* job+ Duckgres jobs shadow a serving run and often finish after it, so a shadow failure would+ otherwise label a model that served fine as failed."""- from products.data_modeling.backend.facade.models import DataModelingJob-- latest_job = DataModelingJob.objects.filter(saved_query_id=OuterRef("saved_query_id")).order_by("-last_run_at")- latest_completed_job = latest_job.filter(status=DataModelingJob.Status.COMPLETED)- return (- Node.objects.select_related("saved_query", "dag")- .annotate(- _latest_job_status=Subquery(latest_job.values("status")[:1]),- _latest_job_run_at=Subquery(latest_completed_job.values("last_run_at")[:1]),- )- .all()+ serving_jobs = (+ DataModelingJob.objects.filter(saved_query_id=OuterRef("saved_query_id"))+ .exclude(engine=DataModelingJobEngine.DUCKGRES)+ .order_by("-last_run_at")+ )+ return queryset.annotate(+ _has_serving_job=Exists(serving_jobs),+ _latest_job_status=Subquery(serving_jobs.values("status")[:1]),+ _latest_job_error=Subquery(serving_jobs.values("error")[:1]),+ _latest_job_run_at=Subquery(+ serving_jobs.filter(status=DataModelingJob.Status.COMPLETED).values("last_run_at")[:1]+ ),)+def _node_queryset_with_latest_job() -> models.QuerySet:+ return _annotate_latest_job(Node.objects.select_related("saved_query", "dag").all())++class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "INTERNAL"queryset = Node.objects.select_related("saved_query", "dag").all()@@ -269,7 +294,7 @@ class NodeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return dag_iddef safely_get_queryset(self, queryset):- qs = queryset.filter(team_id=self.team_id)+ qs = _annotate_latest_job(queryset.filter(team_id=self.team_id))dag_id = self._get_dag_id_param()if dag_id:qs = qs.filter(dag_id=dag_id)diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex 701e6c23b8e7..c07d4ae4d286 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -5,6 +5,8 @@ import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch+from django.utils import timezone+from parameterized import parameterizedfrom rest_framework import statusfrom temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy@@ -18,7 +20,7 @@ from products.data_modeling.backend.logic.node_suspension import (suspension_reset_at,suspension_state,)-from products.data_modeling.backend.models import DAG, Edge, Node, NodeType+from products.data_modeling.backend.models import DAG, DataModelingJob, DataModelingJobEngine, Edge, Node, NodeTypefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom products.warehouse_sources.backend.facade.testing import WarehouseAccessControlTestMixin@@ -65,6 +67,147 @@ class TestNodeViewSet(APIBaseTest):names = {node["name"] for node in response.json()["results"]}self.assertEqual(names, {"events", "test_view"})+ def _node_payload(self) -> dict:+ response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{self.view_node.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return response.json()++ def test_a_duckgres_shadow_failure_does_not_mark_a_served_model_failed(self):+ """The shadow run finishes after the serving one, so reading the newest job of any engine+ would report a model that served fine as failed."""+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.COMPLETED,+ engine=DataModelingJobEngine.CLICKHOUSE,+ last_run_at=timezone.now() - timedelta(minutes=10),+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.FAILED,+ engine=DataModelingJobEngine.DUCKGRES,+ last_run_at=timezone.now(),+ )++ self.assertEqual(self._node_payload()["last_run_status"], "Completed")++ def test_the_reported_error_belongs_to_the_run_that_reported_the_status(self):+ """The saved query's latest_error is a v1 field the DAG path never writes, so the error+ has to come off the job or the attention table shows a failure with no reason."""+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.FAILED,+ error="Code: 241. Memory limit exceeded",+ last_run_at=timezone.now(),+ )++ payload = self._node_payload()++ self.assertEqual(payload["last_run_status"], "Failed")+ self.assertEqual(payload["last_run_error"], "Code: 241. Memory limit exceeded")++ def test_a_model_that_last_succeeded_reports_no_error(self):+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.FAILED,+ error="an old failure",+ last_run_at=timezone.now() - timedelta(hours=2),+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.COMPLETED,+ last_run_at=timezone.now(),+ )++ self.assertIsNone(self._node_payload()["last_run_error"])++ def test_a_skipped_run_is_reported_over_the_stored_status(self):+ """Skipped jobs are written straight to the job table, so the stored status still holds the+ success before them."""+ self.view_node.properties = {"system": {"last_run_status": "Completed"}}+ self.view_node.save(update_fields=["properties"])+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.SKIPPED,+ last_run_at=timezone.now(),+ )++ self.assertEqual(self._node_payload()["last_run_status"], "Skipped")++ def test_last_run_at_reports_the_newest_success_not_a_failed_run(self):+ """The stored stamp is written on failures too, so trusting it would report a broken model+ as freshly refreshed."""+ succeeded_at = timezone.now() - timedelta(hours=3)+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.COMPLETED,+ last_run_at=succeeded_at,+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.FAILED,+ last_run_at=timezone.now(),+ )+ self.view_node.properties = {"system": {"last_run_at": timezone.now().isoformat()}}+ self.view_node.save(update_fields=["properties"])++ payload = self._node_payload()+ self.assertEqual(payload["last_run_status"], "Failed")+ self.assertEqual(payload["last_run_at"][:16], succeeded_at.isoformat()[:16])++ @parameterized.expand([("failed_history", True), ("no_history", False)])+ def test_legacy_last_run_at_is_used_only_without_job_history(self, _name: str, has_failed_job: bool):+ legacy_run_at = timezone.now() - timedelta(days=1)+ self.view_node.properties = {"system": {"last_run_at": legacy_run_at.isoformat()}}+ self.view_node.save(update_fields=["properties"])+ if has_failed_job:+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.FAILED,+ last_run_at=timezone.now(),+ )++ self.assertEqual(self._node_payload()["last_run_at"], None if has_failed_job else legacy_run_at.isoformat())++ @parameterized.expand([("list",), ("retrieve",)])+ def test_nodes_report_status_from_the_latest_job(self, endpoint: str):+ """The node carries no status of its own, so both reads have to take it off the newest job."""+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.COMPLETED,+ last_run_at=timezone.now() - timedelta(hours=2),+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=self.saved_query,+ status=DataModelingJob.Status.FAILED,+ last_run_at=timezone.now(),+ )++ base = f"/api/environments/{self.team.id}/data_modeling_nodes/"+ if endpoint == "list":+ response = self.client.get(base)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ statuses = {node["name"]: node["last_run_status"] for node in response.json()["results"]}+ else:+ statuses = {}+ for node in (self.view_node, self.table_node):+ response = self.client.get(f"{base}{node.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ statuses[response.json()["name"]] = response.json()["last_run_status"]++ self.assertEqual(statuses["test_view"], "Failed")+ self.assertIsNone(statuses["events"])+def test_list_nodes_filters_by_team(self):other_team = Team.objects.create(organization=self.organization)other_dag = DAG.objects.create(team=other_team, name=f"posthog_{other_team.id}")diff --git a/products/data_modeling/frontend/freshness.test.ts b/products/data_modeling/frontend/freshness.test.tsnew file mode 100644index 000000000000..35814c75d064--- /dev/null+++ b/products/data_modeling/frontend/freshness.test.ts@@ -0,0 +1,62 @@+import { DataModelingNode } from '~/types'++import { modelsBehindSchedule } from './freshness'++const NOW = new Date('2026-09-09T12:00:00Z').getTime()+const hoursAgo = (h: number): string => new Date(NOW - h * 3600 * 1000).toISOString()++function node(name: string, overrides: Partial<DataModelingNode> = {}): DataModelingNode {+ return {+ id: name,+ name,+ type: 'matview',+ sync_interval: '1hour',+ last_run_at: hoursAgo(1),+ created_at: hoursAgo(100),+ ...overrides,+ } as DataModelingNode+}++describe('modelsBehindSchedule', () => {+ it('keeps a model that missed more than one scheduled run', () => {+ const behind = modelsBehindSchedule([node('late', { last_run_at: hoursAgo(5) })], NOW)++ expect(behind.map((row) => row.node.name)).toEqual(['late'])+ expect(behind[0].intervalSeconds).toEqual(3600)+ })++ it.each([+ ['a run is merely due', hoursAgo(1.5)],+ ['a run is exactly two intervals old', hoursAgo(2)],+ ])('leaves a model alone when %s', (_label, lastRunAt) => {+ expect(modelsBehindSchedule([node('fresh', { last_run_at: lastRunAt })], NOW)).toEqual([])+ })++ it.each([+ ['it declares no refresh target, which is how a model is paused', { sync_interval: undefined }],+ ['it is a plain view, which stores nothing that can go stale', { type: 'view' as const }],+ ])('leaves a model alone when %s', (_label, overrides) => {+ const stale = node('stale', { last_run_at: hoursAgo(500), ...overrides })++ expect(modelsBehindSchedule([stale], NOW)).toEqual([])+ })++ it('measures a model that has never finished a run from when it was created', () => {+ const never = node('never', { last_run_at: null, created_at: hoursAgo(10) })++ const behind = modelsBehindSchedule([never], NOW)++ expect(behind).toHaveLength(1)+ expect(behind[0].ageSeconds).toEqual(10 * 3600)+ })++ it('orders by how far past the target each model is, matching the column a reader sees', () => {+ const hourly = node('hourly', { sync_interval: '1hour', last_run_at: hoursAgo(20) })+ const daily = node('daily', { sync_interval: '24hour', last_run_at: hoursAgo(96) })++ const behind = modelsBehindSchedule([hourly, daily], NOW)++ expect(behind.map((row) => row.node.name)).toEqual(['daily', 'hourly'])+ expect(behind.map((row) => row.overdueSeconds)).toEqual([72 * 3600, 19 * 3600])+ })+})diff --git a/products/data_modeling/frontend/freshness.ts b/products/data_modeling/frontend/freshness.tsnew file mode 100644index 000000000000..18d7d14c5415--- /dev/null+++ b/products/data_modeling/frontend/freshness.ts@@ -0,0 +1,58 @@+import { DataModelingNode, DataModelingSyncInterval } from '~/types'++export const SYNC_INTERVAL_SECONDS: Record<DataModelingSyncInterval, number> = {+ '15min': 900,+ '30min': 1800,+ '1hour': 3600,+ '6hour': 21600,+ '12hour': 43200,+ '24hour': 86400,+ '7day': 604800,+ '30day': 2592000,+}++/** A plain view runs its query on read, so it stores nothing that can go stale. */+const MATERIALIZING_TYPES = new Set(['matview', 'endpoint'])++/**+ * Age climbs to a full interval between every pair of runs, so a one-interval bar would+ * flag the whole fleet just before each tick. Two means a scheduled run went missing.+ */+export const BEHIND_MULTIPLIER = 2++export interface BehindScheduleModel {+ node: DataModelingNode+ intervalSeconds: number+ /** Seconds since the last successful run, or since creation when it has never finished one. */+ ageSeconds: number+ /** How far past the target the model has drifted. This is the number the table shows. */+ overdueSeconds: number+}++/**+ * Models whose stored data is older than the refresh target they declare. Clearing a+ * target pauses a model on purpose, so a model without one is never behind.+ */+export function modelsBehindSchedule(nodes: DataModelingNode[], now: number): BehindScheduleModel[] {+ const behind: BehindScheduleModel[] = []++ for (const node of nodes) {+ if (!node.sync_interval || !MATERIALIZING_TYPES.has(node.type)) {+ continue+ }+ const intervalSeconds = SYNC_INTERVAL_SECONDS[node.sync_interval]+ if (!intervalSeconds) {+ continue+ }+ // A model that has never run is measured from its creation, so a new one is not+ // reported before its first tick was even due.+ const since = node.last_run_at ?? node.created_at+ const ageSeconds = (now - new Date(since).getTime()) / 1000+ if (ageSeconds <= intervalSeconds * BEHIND_MULTIPLIER) {+ continue+ }+ behind.push({ node, intervalSeconds, ageSeconds, overdueSeconds: ageSeconds - intervalSeconds })+ }++ return behind.sort((a, b) => b.overdueSeconds - a.overdueSeconds)+}diff --git a/products/data_modeling/frontend/generated/api.schemas.ts b/products/data_modeling/frontend/generated/api.schemas.tsindex 4d5998c33ee7..8bc764fe82cc 100644--- a/products/data_modeling/frontend/generated/api.schemas.ts+++ b/products/data_modeling/frontend/generated/api.schemas.ts@@ -136,8 +136,17 @@ export interface NodeApi {readonly downstream_count: number/** @nullable */readonly last_run_at: string | null- /** @nullable */+ /**+ * Skipped runs are written straight to the job table and never reach the stored status,+ * so a blocked model would keep reporting the success before it.+ * @nullable+ */readonly last_run_status: string | null+ /**+ * Error of the run that last_run_status describes, so the two never disagree.+ * @nullable+ */+ readonly last_run_error: string | null/** @nullable */readonly user_tag: string | null/** @nullable */@@ -178,8 +187,17 @@ export interface PatchedNodeApi {readonly downstream_count?: number/** @nullable */readonly last_run_at?: string | null- /** @nullable */+ /**+ * Skipped runs are written straight to the job table and never reach the stored status,+ * so a blocked model would keep reporting the success before it.+ * @nullable+ */readonly last_run_status?: string | null+ /**+ * Error of the run that last_run_status describes, so the two never disagree.+ * @nullable+ */+ readonly last_run_error?: string | null/** @nullable */readonly user_tag?: string | null/** @nullable */diff --git a/products/data_modeling/frontend/lineage/LineageGraph.tsx b/products/data_modeling/frontend/lineage/LineageGraph.tsxindex 20534546793b..8c890f3fa373 100644--- a/products/data_modeling/frontend/lineage/LineageGraph.tsx+++ b/products/data_modeling/frontend/lineage/LineageGraph.tsx@@ -1,17 +1,25 @@import '@xyflow/react/dist/style.css'-import { Background, BackgroundVariant, Controls, MiniMap, Panel, ReactFlow, ReactFlowProvider } from '@xyflow/react'+import {+ Background,+ BackgroundVariant,+ Controls,+ MiniMap,+ Panel,+ PanelPosition,+ ReactFlow,+ ReactFlowProvider,+} from '@xyflow/react'import { useValues } from 'kea'import { ReactNode } from 'react'import { IconArchive } from '@posthog/icons'import { Spinner } from '@posthog/lemon-ui'-import { ElkDirection } from 'scenes/data-warehouse/scene/modeling/types'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { DataModelingEdge, DataModelingNode } from '~/types'+import { ElkDirection } from './autolayout'import { lineageGraphLogic } from './lineageGraphLogic'import { LINEAGE_NODE_TYPES, LineageNodeCallbacks, LineageNodeState, LineageVariant } from './LineageNode'@@ -27,6 +35,7 @@ export interface LineageGraphProps {/** Enable zoom/pan. Off by default for inline previews */interactive?: booleanshowMinimap?: boolean+ minimapPosition?: PanelPositionshowControls?: booleanclassName?: stringloading?: boolean@@ -37,8 +46,9 @@ export interface LineageGraphProps {nodeCallbacks?: (node: DataModelingNode) => LineageNodeCallbacks/** Convenience click handler, used when nodeCallbacks is not provided */onNodeClick?: (node: DataModelingNode) => void- /** Caller-specific chrome (search, legend, layout toggle) rendered over the canvas */+ /** Caller-specific chrome (legend, layout toggle) rendered over the canvas */panels?: ReactNode+ panelPosition?: PanelPosition}function LineageGraphContent(props: LineageGraphProps): JSX.Element {@@ -96,9 +106,15 @@ function LineageGraphContent(props: LineageGraphProps): JSX.Element {<Background variant={BackgroundVariant.Dots} gap={20} size={1} />{props.showControls && <Controls showInteractive={false} position="bottom-right" />}{props.showMinimap && (- <MiniMap zoomable pannable position="bottom-left" nodeStrokeWidth={2} className="hidden lg:block" />+ <MiniMap+ zoomable+ pannable+ position={props.minimapPosition ?? 'bottom-left'}+ nodeStrokeWidth={2}+ className="hidden lg:block border rounded shadow-sm"+ />)}- {props.panels && <Panel position="top-right">{props.panels}</Panel>}+ {props.panels && <Panel position={props.panelPosition ?? 'top-right'}>{props.panels}</Panel>}</ReactFlow>)}diff --git a/products/data_modeling/frontend/lineage/LineageNode.tsx b/products/data_modeling/frontend/lineage/LineageNode.tsxindex b8c449f828db..eef9a56a397e 100644--- a/products/data_modeling/frontend/lineage/LineageNode.tsx+++ b/products/data_modeling/frontend/lineage/LineageNode.tsx@@ -2,17 +2,27 @@ import { Handle, Position } from '@xyflow/react'import clsx from 'clsx'import React, { useCallback, useState } from 'react'-import { IconActivity, IconClockRewind, IconPencil, IconPlay, IconPlayFilled, IconTarget } from '@posthog/icons'+import {+ IconActivity,+ IconClockRewind,+ IconPauseFilled,+ IconPencil,+ IconPlay,+ IconPlayFilled,+ IconTarget,+} from '@posthog/icons'import { LemonButton, Spinner, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { ElkDirection, NodeHandle } from 'scenes/data-warehouse/scene/modeling/types'-import { DataModelingJobStatus, DataModelingNode } from '~/types'+import { DataModelingNode } from '~/types'+import { servingSuspension } from 'products/data_modeling/frontend/suspension'import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'-import { NODE_TYPE_TAG_SETTINGS } from './nodeStyles'+import { ElkDirection, NodeHandle } from './autolayout'+import { NODE_TYPE_TAG_SETTINGS, statusBackgroundClass } from './nodeStyles'+import { NodeTypeTag } from './NodeTypeTag'export type LineageVariant = 'full' | 'canvas'@@ -28,6 +38,7 @@ export type LineageNodeShape = Pick<| 'upstream_count'| 'downstream_count'| 'user_tag'+ | 'suspended'>export interface LineageNodeState {@@ -56,35 +67,29 @@ export interface LineageNodeData extends Record<string, unknown> {handles: NodeHandle[]}-function NodeTypeTag({ type }: { type: DataModelingNode['type'] }): JSX.Element {- const { label, color } = NODE_TYPE_TAG_SETTINGS[type]- return (- <span- className="text-[10px] lowercase tracking-wide px-1 rounded border-1"- // eslint-disable-next-line react/forbid-dom-props- style={{- color,- backgroundColor: `color-mix(in srgb, ${color} 20%, transparent)`,- borderColor: `color-mix(in srgb, ${color} 80%, transparent)`,- }}- >- {label}- </span>- )-}--function StatusDot({ status }: { status?: DataModelingJobStatus }): JSX.Element {+function StatusDot({ node }: { node: LineageNodeShape }): JSX.Element {+ const suspension = servingSuspension(node.suspended)+ if (suspension) {+ return (+ <Tooltip+ title={+ <div className="flex flex-col gap-1">+ <div>Suspended after repeated failures</div>+ <div className="opacity-75">{suspension.reason}</div>+ </div>+ }+ interactive+ >+ <IconPauseFilled className="text-warning text-sm" />+ </Tooltip>+ )+ }return (- <Tooltip title={status ?? 'Not run yet'}>+ <Tooltip title={node.last_run_status ?? 'Not run yet'}><divclassName={clsx('rounded-full w-3 h-3 border-1 border-primary',- status === 'Completed' && 'bg-success',- status === 'Running' && 'bg-warning',- status === 'Failed' && 'bg-danger',- status === 'Cancelled' && 'bg-warning',- status === 'Skipped' && 'bg-muted',- !status && 'bg-surface-primary'+ node.last_run_status ? statusBackgroundClass(node.last_run_status) : 'bg-surface-primary')}/></Tooltip>@@ -144,18 +149,20 @@ function MetadataBar({ node }: { node: LineageNodeShape }): JSX.Element {</Tooltip><IconActivity />{node.last_run_at ? (- <TZLabel- className="text-[10px]"- time={node.last_run_at}- formatDate="MMM D"- formatTime="HH:mm"- showPopover={false}- />+ <Tooltip title="Last successful run. A failed run does not move this.">+ <TZLabel+ className="text-[10px]"+ time={node.last_run_at}+ formatDate="MMM D"+ formatTime="HH:mm"+ showPopover={false}+ />+ </Tooltip>) : (- <Tooltip title="This node has not been run yet">Never</Tooltip>+ <Tooltip title="This model has never finished a run">Never succeeded</Tooltip>)}</div>- <StatusDot status={node.last_run_status} />+ <StatusDot node={node} /></div>)}diff --git a/products/data_modeling/frontend/lineage/NodeTypeLegend.tsx b/products/data_modeling/frontend/lineage/NodeTypeLegend.tsxnew file mode 100644index 000000000000..17370a6184f3--- /dev/null+++ b/products/data_modeling/frontend/lineage/NodeTypeLegend.tsx@@ -0,0 +1,62 @@+import { IconDatabase, IconInfo, IconX } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { DataModelingNodeType } from '~/types'++import { NODE_TYPE_TAG_SETTINGS } from './nodeStyles'++const LEGEND_ENTRIES: { type: DataModelingNodeType; description: string }[] = [+ { type: 'view', description: 'A virtual table based on a SQL query' },+ { type: 'matview', description: 'A persisted view with improved query performance' },+ { type: 'endpoint', description: 'A materialized endpoint for API access' },+]++export interface NodeTypeLegendProps {+ collapsed: boolean+ onToggleCollapse: () => void+}++/** Legend for the node types the canvas draws. Grows upward, so its toggle never moves. */+export function NodeTypeLegend({ collapsed, onToggleCollapse }: NodeTypeLegendProps): JSX.Element {+ if (collapsed) {+ return (+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconInfo />}+ onClick={onToggleCollapse}+ data-attr="lineage-legend-toggle"+ tooltip="Show what each node type means"+ />+ )+ }++ return (+ <div className="flex flex-col gap-2 p-3 w-72 bg-surface-primary border rounded shadow-sm">+ <div className="flex items-center justify-between gap-2">+ <span className="font-semibold text-secondary">Node types</span>+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ onClick={onToggleCollapse}+ data-attr="lineage-legend-toggle"+ tooltip="Hide the legend"+ />+ </div>+ {LEGEND_ENTRIES.map(({ type, description }) => (+ <div key={type} className="flex items-start gap-2">+ <IconDatabase+ className="text-xl shrink-0 mt-0.5"+ // The canvas colors each node type; the legend must use the same hue.+ // eslint-disable-next-line react/forbid-dom-props+ style={{ color: NODE_TYPE_TAG_SETTINGS[type].color }}+ />+ <div className="flex flex-col">+ <span className="font-semibold">{NODE_TYPE_TAG_SETTINGS[type].label}</span>+ <span className="text-xs text-secondary">{description}</span>+ </div>+ </div>+ ))}+ </div>+ )+}diff --git a/products/data_modeling/frontend/lineage/NodeTypeTag.tsx b/products/data_modeling/frontend/lineage/NodeTypeTag.tsxnew file mode 100644index 000000000000..f2d2a969ab7c--- /dev/null+++ b/products/data_modeling/frontend/lineage/NodeTypeTag.tsx@@ -0,0 +1,21 @@+import { DataModelingNodeType } from '~/types'++import { NODE_TYPE_TAG_SETTINGS } from './nodeStyles'++/** The type mark drawn on a lineage node, and repeated in the legend. */+export function NodeTypeTag({ type }: { type: DataModelingNodeType }): JSX.Element {+ const { label, color } = NODE_TYPE_TAG_SETTINGS[type]+ return (+ <span+ className="text-[10px] lowercase tracking-wide px-1 rounded border-1 whitespace-nowrap"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ color,+ backgroundColor: `color-mix(in srgb, ${color} 20%, transparent)`,+ borderColor: `color-mix(in srgb, ${color} 80%, transparent)`,+ }}+ >+ {label}+ </span>+ )+}diff --git a/products/data_modeling/frontend/lineage/SearchSyntaxHelp.tsx b/products/data_modeling/frontend/lineage/SearchSyntaxHelp.tsxnew file mode 100644index 000000000000..01053bb5651d--- /dev/null+++ b/products/data_modeling/frontend/lineage/SearchSyntaxHelp.tsx@@ -0,0 +1,28 @@+import { Fragment } from 'react'++const SEARCH_SYNTAX: { syntax: string; meaning: string }[] = [+ { syntax: '+name', meaning: 'The model and everything it depends on' },+ { syntax: 'name+', meaning: 'The model and everything that depends on it' },+ { syntax: '+name+', meaning: 'Both sides' },+]++/**+ * Tooltip body for the lineage search syntax, shared by every surface that accepts it.+ *+ * Tooltips paint an inverted surface, so the chips borrow the surrounding foreground rather than+ * a themed background token, which would resolve to the tooltip's own color and disappear.+ */+export const SEARCH_SYNTAX_HELP = (+ <div className="flex flex-col gap-2 max-w-72">+ <p className="m-0">Type a name to match models.</p>+ <p className="m-0">Add a plus to follow lineage:</p>+ <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-1 items-baseline">+ {SEARCH_SYNTAX.map(({ syntax, meaning }) => (+ <Fragment key={syntax}>+ <code className="rounded border border-current/40 px-1 text-xs whitespace-nowrap">{syntax}</code>+ <span>{meaning}</span>+ </Fragment>+ ))}+ </div>+ </div>+)diff --git a/products/data_modeling/frontend/lineage/StatusTag.tsx b/products/data_modeling/frontend/lineage/StatusTag.tsxnew file mode 100644index 000000000000..e52525949a38--- /dev/null+++ b/products/data_modeling/frontend/lineage/StatusTag.tsx@@ -0,0 +1,10 @@+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { STATUS_TAG_SETTINGS, STATUS_TOOLTIPS } from './nodeStyles'++/** A run status, with the explanation attached wherever the word alone leaves a reader guessing. */+export function StatusTag({ status }: { status: string }): JSX.Element {+ const tag = <LemonTag type={STATUS_TAG_SETTINGS[status] ?? 'default'}>{status}</LemonTag>+ const explanation = STATUS_TOOLTIPS[status]+ return explanation ? <Tooltip title={explanation}>{tag}</Tooltip> : tag+}diff --git a/frontend/src/scenes/data-warehouse/scene/modeling/autolayout.ts b/products/data_modeling/frontend/lineage/autolayout.tssimilarity index 71%rename from frontend/src/scenes/data-warehouse/scene/modeling/autolayout.tsrename to products/data_modeling/frontend/lineage/autolayout.tsindex 77b62c6cd685..9628fba6a758 100644--- a/frontend/src/scenes/data-warehouse/scene/modeling/autolayout.ts+++ b/products/data_modeling/frontend/lineage/autolayout.ts@@ -1,10 +1,25 @@-import { Edge, Position } from '@xyflow/react'-import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk.bundled.js'+import { Edge, Position, Node as ReactFlowNode } from '@xyflow/react'+import type { ElkExtendedEdge, ElkNode } from 'elkjs'import { getElk } from 'lib/elk'-import { LARGE_GRAPH_NODE_THRESHOLD, NODE_HEIGHT, NODE_WIDTH } from './constants'-import type { ElkDirection, Node } from './types'+export type ElkDirection = 'DOWN' | 'RIGHT'++export interface NodeHandle {+ id?: string+ type: 'source' | 'target'+ position: Position+ x?: number+ y?: number+}++// Above this node count, ELK's NETWORK_SIMPLEX node placement (which scales+// super-linearly and runs on the main thread) becomes the dominant cost of+// showing the graph. We switch to the much cheaper BRANDES_KOEPF placement for+// large graphs; smaller graphs keep NETWORK_SIMPLEX for its tighter layout.+export const LARGE_GRAPH_NODE_THRESHOLD = 150++type LayoutNode = ReactFlowNode<{ handles?: NodeHandle[] } & Record<string, unknown>>const getElkPortSide = (position: Position): string => {switch (position) {@@ -19,15 +34,16 @@ const getElkPortSide = (position: Position): string => {}}-export const getFormattedNodes = async (nodes: Node[], edges: Edge[], direction?: ElkDirection): Promise<Node[]> => {+export const getFormattedNodes = async <T extends LayoutNode>(+ nodes: T[],+ edges: Edge[],+ direction?: ElkDirection+): Promise<T[]> => {if (nodes.length === 0) {return []}direction ??= 'DOWN'- // NETWORK_SIMPLEX node placement gives the tightest layout but scales- // super-linearly; on large graphs it's the main reason the DAG takes- // seconds to appear. BRANDES_KOEPF is ~5x cheaper with a comparable result.const nodePlacementStrategy = nodes.length > LARGE_GRAPH_NODE_THRESHOLD ? 'BRANDES_KOEPF' : 'NETWORK_SIMPLEX'const elkOptions = {'elk.algorithm': 'layered',@@ -62,8 +78,8 @@ export const getFormattedNodes = async (nodes: Node[], edges: Edge[], direction?return {...node,- width: node.width ?? NODE_WIDTH,- height: node.height ?? NODE_HEIGHT,+ width: node.width,+ height: node.height,targetPosition: direction === 'DOWN' ? 'top' : 'left',sourcePosition: direction === 'DOWN' ? 'bottom' : 'right',ports: [...handles],@@ -82,5 +98,5 @@ export const getFormattedNodes = async (nodes: Node[], edges: Edge[], direction?return (laidOutGraph.children?.map((node) => ({...node,position: { x: node.x, y: node.y },- })) ?? []) as Node[]+ })) ?? []) as unknown as T[]}diff --git a/products/data_modeling/frontend/lineage/lineageDataLogic.test.ts b/products/data_modeling/frontend/lineage/lineageDataLogic.test.tsnew file mode 100644index 000000000000..76a757f95330--- /dev/null+++ b/products/data_modeling/frontend/lineage/lineageDataLogic.test.ts@@ -0,0 +1,49 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { DataModelingEdge, DataModelingNode } from '~/types'++import { lineageDataLogic } from './lineageDataLogic'++describe('lineageDataLogic', () => {+ it('loads every page of nodes and edges', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/data_modeling_nodes/': ({ request }) => {+ const page = Number(new URL(request.url).searchParams.get('page') || '1')+ const nextUrl = new URL(request.url)+ nextUrl.searchParams.set('page', '2')+ return [+ 200,+ {+ results: [{ id: `node-${page}` } as DataModelingNode],+ next: page === 1 ? `${nextUrl.pathname}${nextUrl.search}` : null,+ },+ ]+ },+ '/api/environments/:team_id/data_modeling_edges/': ({ request }) => {+ const page = Number(new URL(request.url).searchParams.get('page') || '1')+ const nextUrl = new URL(request.url)+ nextUrl.searchParams.set('page', '2')+ return [+ 200,+ {+ results: [{ id: `edge-${page}` } as DataModelingEdge],+ next: page === 1 ? `${nextUrl.pathname}${nextUrl.search}` : null,+ },+ ]+ },+ },+ })+ initKeaTests()+ const logic = lineageDataLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadNodesSuccess', 'loadEdgesSuccess'])++ expect(logic.values.nodes.map((node) => node.id)).toEqual(['node-1', 'node-2'])+ expect(logic.values.edges.map((edge) => edge.id)).toEqual(['edge-1', 'edge-2'])+ logic.unmount()+ })+})diff --git a/products/data_modeling/frontend/lineage/lineageDataLogic.ts b/products/data_modeling/frontend/lineage/lineageDataLogic.tsnew file mode 100644index 000000000000..21039ef434af--- /dev/null+++ b/products/data_modeling/frontend/lineage/lineageDataLogic.ts@@ -0,0 +1,57 @@+import { MakeLogicType, afterMount, kea, path } from 'kea'+import { loaders } from 'kea-loaders'++import api, { PaginatedResponse } from 'lib/api'++import { DataModelingEdge, DataModelingNode } from '~/types'++export interface lineageDataLogicValues {+ nodes: DataModelingNode[]+ nodesLoading: boolean+ edges: DataModelingEdge[]+ edgesLoading: boolean+}++export interface lineageDataLogicActions {+ loadNodes: () => any+ loadNodesSuccess: (nodes: DataModelingNode[], payload?: any) => { nodes: DataModelingNode[]; payload?: any }+ loadNodesFailure: (error: string, errorObject?: any) => { error: string; errorObject?: any }+ loadEdges: () => any+ loadEdgesSuccess: (edges: DataModelingEdge[], payload?: any) => { edges: DataModelingEdge[]; payload?: any }+ loadEdgesFailure: (error: string, errorObject?: any) => { error: string; errorObject?: any }+}++export type lineageDataLogicType = MakeLogicType<lineageDataLogicValues, lineageDataLogicActions>++async function loadAllPages<T>(loadFirstPage: () => Promise<PaginatedResponse<T>>): Promise<T[]> {+ let response = await loadFirstPage()+ const results = [...response.results]+ while (response.next) {+ // nosemgrep: prefer-codegen-api -- Generated list helpers cannot follow the opaque URL returned by the API.+ response = await api.get<PaginatedResponse<T>>(response.next)+ results.push(...response.results)+ }+ return results+}++/**+ * The team's DAG, loaded once. The models table, the lineage canvas and the models scene all read it,+ * so it cannot live on any one of them: whichever mounts first would then fetch for the others.+ */+export const lineageDataLogic = kea<lineageDataLogicType>([+ path(['products', 'data_modeling', 'frontend', 'lineage', 'lineageDataLogic']),+ loaders({+ nodes: {+ __default: [] as DataModelingNode[],+ loadNodes: async () => loadAllPages(() => api.dataModelingNodes.list()),+ },+ edges: {+ __default: [] as DataModelingEdge[],+ loadEdges: async () => loadAllPages(() => api.dataModelingEdges.list()),+ },+ }),+ afterMount(({ actions }) => {+ actions.loadNodes()+ actions.loadEdges()+ }),+])diff --git a/products/data_modeling/frontend/lineage/lineageGraphLogic.ts b/products/data_modeling/frontend/lineage/lineageGraphLogic.tsindex b6308e4f7cf7..009ecfb3ce46 100644--- a/products/data_modeling/frontend/lineage/lineageGraphLogic.ts+++ b/products/data_modeling/frontend/lineage/lineageGraphLogic.ts@@ -1,11 +1,9 @@import { MarkerType, Position, type Edge as ReactFlowEdge, type Node as ReactFlowNode } from '@xyflow/react'import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, propsChanged, reducers } from 'kea'-import { getFormattedNodes } from 'scenes/data-warehouse/scene/modeling/autolayout'-import { ElkDirection, NodeHandle } from 'scenes/data-warehouse/scene/modeling/types'-import { DataModelingEdge, DataModelingNode } from '~/types'+import { ElkDirection, NodeHandle, getFormattedNodes } from './autolayout'import { LineageNodeData, LineageVariant } from './LineageNode'const NODE_SIZES: Record<LineageVariant, { width: number; height: number }> = {@@ -115,11 +113,14 @@ export const lineageGraphLogic = kea<lineageGraphLogicType>([},],}),- listeners(({ actions, props }) => ({+ listeners((logic) => ({computeLayout: async (_, breakpoint) => {- const layout = await layoutGraph(props.nodes, props.edges, props.variant, props.direction)+ // Read logic.props, not a destructured copy: the copy is frozen at build time, so a+ // relayout after propsChanged would still lay out the original nodes and edges+ const { nodes, edges, variant, direction } = logic.props+ const layout = await layoutGraph(nodes, edges, variant, direction)breakpoint()- actions.layoutComputed(layout)+ logic.actions.layoutComputed(layout)},})),propsChanged(({ actions, props }, oldProps) => {diff --git a/products/data_modeling/frontend/lineage/lineageSearch.test.ts b/products/data_modeling/frontend/lineage/lineageSearch.test.tsnew file mode 100644index 000000000000..28d8a4667187--- /dev/null+++ b/products/data_modeling/frontend/lineage/lineageSearch.test.ts@@ -0,0 +1,74 @@+import { DataModelingEdge, DataModelingNode } from '~/types'++import {+ LineageSearchMode,+ buildAdjacencyMaps,+ edgesWithinNodes,+ matchNodesByName,+ nodeIdsForLineageSearch,+ parseLineageSearch,+ traverseLineage,+} from './lineageSearch'++const node = (id: string, name: string): DataModelingNode => ({ id, name, type: 'view' }) as DataModelingNode+const edge = (source_id: string, target_id: string): DataModelingEdge =>+ ({ id: `${source_id}-${target_id}`, source_id, target_id }) as DataModelingEdge++// events -> orders -> orders_daily -> revenue_endpoint+const EDGES = [edge('events', 'orders'), edge('orders', 'orders_daily'), edge('orders_daily', 'revenue_endpoint')]++describe('lineageSearch', () => {+ it.each([+ ['orders', 'search', 'orders'],+ ['+orders', 'upstream', 'orders'],+ ['orders+', 'downstream', 'orders'],+ ['+orders+', 'both', 'orders'],+ [' +orders ', 'upstream', 'orders'],+ ['+', 'upstream', ''],+ ])('parses %p as %s of %p', (raw, mode, term) => {+ expect(parseLineageSearch(raw)).toEqual({ mode, term })+ })++ it.each([+ ['upstream', 'orders_daily', ['orders_daily', 'orders', 'events']],+ ['downstream', 'orders', ['orders', 'orders_daily', 'revenue_endpoint']],+ ['both', 'orders', ['orders', 'events', 'orders_daily', 'revenue_endpoint']],+ ])('walks %s from %s', (mode, start, expected) => {+ const reached = traverseLineage(start, buildAdjacencyMaps(EDGES), mode as LineageSearchMode)+ expect([...reached].sort()).toEqual([...expected].sort())+ })++ it('does not reach a sibling through a shared parent', () => {+ // events feeds both orders and a sibling. From orders, `both` must never reach the sibling.+ const maps = buildAdjacencyMaps([...EDGES, edge('events', 'sessions')])++ expect(traverseLineage('orders', maps, 'both').has('sessions')).toBe(false)+ })++ it('anchors on the exact name over a longer one that contains it', () => {+ const nodes = [node('1', 'orders_daily'), node('2', 'orders'), node('3', 'stripe_orders_raw')]+ expect(matchNodesByName(nodes, 'orders')[0].name).toEqual('orders')+ })++ describe('nodeIdsForLineageSearch', () => {+ // EDGES is keyed by name, so the fixture names each node after its id.+ const nodes = ['events', 'orders', 'orders_daily', 'revenue_endpoint'].map((name) => node(name, name))++ it('returns null for a plain term, so a name search highlights instead of pruning', () => {+ expect(nodeIdsForLineageSearch(nodes, EDGES, parseLineageSearch('orders'))).toBeNull()+ })++ it('prunes to nothing when the anchor names no model', () => {+ expect(nodeIdsForLineageSearch(nodes, EDGES, parseLineageSearch('+nope'))?.size).toEqual(0)+ })++ it('prunes to the cone of an anchored term', () => {+ const reached = nodeIdsForLineageSearch(nodes, EDGES, parseLineageSearch('+orders_daily'))+ expect([...(reached ?? [])].sort()).toEqual(['events', 'orders', 'orders_daily'])+ })+ })++ it('drops edges that lost an endpoint to filtering', () => {+ expect(edgesWithinNodes(EDGES, new Set(['events', 'orders']))).toEqual([edge('events', 'orders')])+ })+})diff --git a/products/data_modeling/frontend/lineage/lineageSearch.ts b/products/data_modeling/frontend/lineage/lineageSearch.tsnew file mode 100644index 000000000000..c5c62dc312ae--- /dev/null+++ b/products/data_modeling/frontend/lineage/lineageSearch.ts@@ -0,0 +1,115 @@+import { DataModelingEdge, DataModelingNode } from '~/types'++export type LineageSearchMode = 'search' | 'upstream' | 'downstream' | 'both'++export interface ParsedLineageSearch {+ mode: LineageSearchMode+ /** The name to anchor lineage traversal on, or the term to match for plain search */+ term: string+}++/**+ * dbt-style selectors: `+model` walks upstream, `model+` downstream, `+model+` both.+ * A bare term is a plain name match, which highlights rather than filters.+ */+export function parseLineageSearch(rawTerm: string): ParsedLineageSearch {+ const trimmed = rawTerm.trim()+ const leading = trimmed.startsWith('+')+ const trailing = trimmed.endsWith('+') && trimmed.length > 1+ const term = trimmed.slice(leading ? 1 : 0, trailing ? -1 : undefined).trim()++ if (leading && trailing) {+ return { mode: 'both', term }+ }+ if (leading) {+ return { mode: 'upstream', term }+ }+ if (trailing) {+ return { mode: 'downstream', term }+ }+ return { mode: 'search', term }+}++export interface AdjacencyMaps {+ upstream: Map<string, string[]>+ downstream: Map<string, string[]>+}++export function buildAdjacencyMaps(edges: DataModelingEdge[]): AdjacencyMaps {+ const upstream = new Map<string, string[]>()+ const downstream = new Map<string, string[]>()++ for (const edge of edges) {+ upstream.set(edge.target_id, [...(upstream.get(edge.target_id) ?? []), edge.source_id])+ downstream.set(edge.source_id, [...(downstream.get(edge.source_id) ?? []), edge.target_id])+ }++ return { upstream, downstream }+}++function walk(startId: string, adjacency: Map<string, string[]>, reached: Set<string>): void {+ const queue = [startId]+ while (queue.length > 0) {+ const current = queue.shift() as string+ for (const neighbor of adjacency.get(current) ?? []) {+ if (!reached.has(neighbor)) {+ reached.add(neighbor)+ queue.push(neighbor)+ }+ }+ }+}++/**+ * The nodes a selector reaches from an anchor.+ *+ * `both` unions two one-way walks rather than walking both ways at each hop. Alternating direction+ * would reach siblings through a shared parent, which is the whole connected component, not lineage.+ */+export function traverseLineage(startId: string, maps: AdjacencyMaps, mode: LineageSearchMode): Set<string> {+ const reached = new Set<string>([startId])+ if (mode === 'upstream' || mode === 'both') {+ walk(startId, maps.upstream, reached)+ }+ if (mode === 'downstream' || mode === 'both') {+ walk(startId, maps.downstream, reached)+ }+ return reached+}++/** Nodes whose name contains the term, best match first so lineage anchors on the closest name. */+export function matchNodesByName(nodes: DataModelingNode[], term: string): DataModelingNode[] {+ const needle = term.toLowerCase()+ if (!needle) {+ return []+ }+ return nodes+ .filter((node) => node.name.toLowerCase().includes(needle))+ .sort((a, b) => {+ const exact = Number(b.name.toLowerCase() === needle) - Number(a.name.toLowerCase() === needle)+ return exact !== 0 ? exact : a.name.length - b.name.length+ })+}++/**+ * The node ids a lineage selector keeps, or null when the term prunes nothing.+ *+ * Null means "no lineage restriction" — a plain term matches names in place, so a single letter+ * never empties the result. An unmatched anchor returns an empty set, since the term names nothing.+ */+export function nodeIdsForLineageSearch(+ nodes: DataModelingNode[],+ edges: DataModelingEdge[],+ parsed: ParsedLineageSearch+): Set<string> | null {+ if (parsed.mode === 'search' || !parsed.term) {+ return null+ }+ const anchor = matchNodesByName(nodes, parsed.term)[0]+ return anchor ? traverseLineage(anchor.id, buildAdjacencyMaps(edges), parsed.mode) : new Set<string>()+}++/** Keeps only edges whose endpoints both survived filtering, so no edge dangles. */+export function edgesWithinNodes(edges: DataModelingEdge[], nodeIds: Set<string>): DataModelingEdge[] {+ return edges.filter((edge) => nodeIds.has(edge.source_id) && nodeIds.has(edge.target_id))+}diff --git a/products/data_modeling/frontend/lineage/nodeStyles.test.ts b/products/data_modeling/frontend/lineage/nodeStyles.test.tsnew file mode 100644index 000000000000..a077bcb972d4--- /dev/null+++ b/products/data_modeling/frontend/lineage/nodeStyles.test.ts@@ -0,0 +1,31 @@+import { STATUS_MARK_BACKGROUNDS, STATUS_TAG_SETTINGS, statusBackgroundClass } from './nodeStyles'++describe('nodeStyles', () => {+ describe('statusBackgroundClass', () => {+ it.each([+ ['Completed', 'bg-success'],+ ['Failed', 'bg-danger'],+ ['Running', 'bg-warning'],+ ['Cancelled', 'bg-muted'],+ ['Skipped', 'bg-muted'],+ ['Modified', 'bg-warning'],+ ])('gives %s a %s background', (status, expected) => {+ expect(statusBackgroundClass(status)).toEqual(expected)+ })++ it('only marks a failure as a failure', () => {+ const failing = Object.keys(STATUS_TAG_SETTINGS).filter(+ (status) => statusBackgroundClass(status) === 'bg-danger'+ )+ expect(failing).toEqual(['Failed'])+ })++ it('covers every status the tags know about', () => {+ expect(Object.keys(STATUS_MARK_BACKGROUNDS).sort()).toEqual(Object.keys(STATUS_TAG_SETTINGS).sort())+ })++ it('falls back to muted for a status it does not know', () => {+ expect(statusBackgroundClass('SomethingNew')).toEqual('bg-muted')+ })+ })+})diff --git a/products/data_modeling/frontend/lineage/nodeStyles.ts b/products/data_modeling/frontend/lineage/nodeStyles.tsindex dc806506d24b..ded9427a60a3 100644--- a/products/data_modeling/frontend/lineage/nodeStyles.ts+++ b/products/data_modeling/frontend/lineage/nodeStyles.ts@@ -20,3 +20,31 @@ export const STATUS_TAG_SETTINGS: Record<string, LemonTagType> = {Skipped: 'muted',Modified: 'warning',}++/**+ * Statuses a reader cannot act on from the word alone. `Skipped` is the one that gets asked about:+ * nothing about the model itself went wrong, so the tag has to say where to look instead.+ */+export const STATUS_TOOLTIPS: Record<string, string> = {+ Skipped: 'Skipped in the last scheduled run because a model it depends on failed.',+ Cancelled: 'The run was stopped before it finished.',+ Modified: 'The query changed after the last run, so the stored data is behind it.',+}++/**+ * Tag colors cannot fill a solid mark: LemonTag tints its background, so its `primary` becomes raw+ * brand orange when filled, one hue off danger red. A mark with no text needs its own palette.+ */+export const STATUS_MARK_BACKGROUNDS: Record<string, string> = {+ Running: 'bg-warning',+ Completed: 'bg-success',+ Failed: 'bg-danger',+ Cancelled: 'bg-muted',+ Skipped: 'bg-muted',+ Modified: 'bg-warning',+}++/** Background for a status mark that carries no text of its own, such as a run-history square. */+export function statusBackgroundClass(status: string): string {+ return STATUS_MARK_BACKGROUNDS[status] ?? 'bg-muted'+}diff --git a/products/data_modeling/frontend/suspension.ts b/products/data_modeling/frontend/suspension.tsnew file mode 100644index 000000000000..f3c452fa3404--- /dev/null+++ b/products/data_modeling/frontend/suspension.ts@@ -0,0 +1,11 @@+import { NodeApiSuspended, NodeSuspensionApi } from './generated/api.schemas'++/**+ * Markers are written per engine, but only ClickHouse serves queries. A marker on the duckgres+ * shadow means the comparison run stopped, not that the model stopped refreshing.+ */+export const SERVING_ENGINE = 'clickhouse'++export function servingSuspension(suspended: NodeApiSuspended | undefined | null): NodeSuspensionApi | undefined {+ return suspended?.[SERVING_ENGINE]+}diff --git a/products/data_modeling/package.json b/products/data_modeling/package.jsonindex a37ea2018f52..5fc5b9445aaa 100644--- a/products/data_modeling/package.json+++ b/products/data_modeling/package.json@@ -11,13 +11,15 @@"kea-router": "catalog:"},"devDependencies": {- "@storybook/react": "catalog:"+ "@storybook/react": "catalog:",+ "kea-test-utils": "catalog:"},"peerDependencies": {"@posthog/icons": "catalog:","@types/react": "*","@xyflow/react": "*","clsx": "*",+ "elkjs": "*","react": "*","react-dom": "*"}diff --git a/products/data_warehouse/backend/presentation/views/data_modeling_job.py b/products/data_warehouse/backend/presentation/views/data_modeling_job.pyindex 443e5a06b680..48f8d950a471 100644--- a/products/data_warehouse/backend/presentation/views/data_modeling_job.py+++ b/products/data_warehouse/backend/presentation/views/data_modeling_job.py@@ -69,7 +69,7 @@ class DataModelingJobViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSpagination_class = DataModelingJobPaginationqueryset = DataModelingJob.objects.all()filter_backends = [DjangoFilterBackend]- filterset_fields = ["saved_query_id"]+ filterset_fields = ["saved_query_id", "status"]search_fields = ["saved_query_id"]ordering_fields = ["created_at"]ordering = "-created_at"diff --git a/products/data_warehouse/backend/tests/api/test_datamodelingjob.py b/products/data_warehouse/backend/tests/api/test_datamodelingjob.pyindex 3206e63d7c8a..4a9c39e323ba 100644--- a/products/data_warehouse/backend/tests/api/test_datamodelingjob.py+++ b/products/data_warehouse/backend/tests/api/test_datamodelingjob.py@@ -111,6 +111,13 @@ class TestDataModelingJob(APIBaseTest):self.assertEqual(len(results), 1)self.assertEqual(results[0]["id"], str(other_job.id))+ def test_filters_by_status(self):+ response = self.client.get(+ f"/api/environments/{self.team.pk}/data_modeling_jobs/?status={DataModelingJob.Status.FAILED}"+ )+ self.assertEqual(response.status_code, 200)+ self.assertEqual([job["id"] for job in response.json()["results"]], [str(self.job3.id)])+def test_pagination_honors_offset_and_returns_count(self):paged_query = DataWarehouseSavedQuery.objects.create(team=self.team, name="Paged saved query")for _ in range(12):diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 6c5cafb62bb4..afec21637eed 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -4968,8 +4968,26 @@ export type DataModelingJobsListParams = {*/offset?: numbersaved_query_id?: string+ /**+ * * `Cancelled` - Cancelled+ * * `Completed` - Completed+ * * `Failed` - Failed+ * * `Running` - Running+ * * `Skipped` - Skipped+ */+ status?: DataModelingJobsListStatus}+export type DataModelingJobsListStatus = (typeof DataModelingJobsListStatus)[keyof typeof DataModelingJobsListStatus]++export const DataModelingJobsListStatus = {+ Cancelled: 'Cancelled',+ Completed: 'Completed',+ Failed: 'Failed',+ Running: 'Running',+ Skipped: 'Skipped',+} as const+export type DataWarehouseCheckDatabaseNameRetrieveParams = {/*** Database name to checkdiff --git a/products/data_warehouse/manifest.tsx b/products/data_warehouse/manifest.tsxindex c154947540ac..20656460b82c 100644--- a/products/data_warehouse/manifest.tsx+++ b/products/data_warehouse/manifest.tsx@@ -4,6 +4,7 @@ import { urls } from 'scenes/urls'import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'import { ActivityScope, ProductManifest } from '~/types'+import type { ModelsSceneTab } from '../../frontend/src/scenes/models/modelsSceneLogic'import type { NodeDetailSceneTab } from '../../frontend/src/scenes/models/nodeDetailSceneLogic'import type { SchemaConfigurationSection, SchemaSceneTab } from './frontend/scenes/SchemaScene/SchemaScene'import type { SourceSceneTab } from './frontend/scenes/SourceScene/SourceScene'@@ -112,7 +113,7 @@ export const manifest: ProductManifest = {const query = params.toString()return query ? `/data-ops?${query}` : '/data-ops'},- models: (): string => '/models',+ models: (tab?: ModelsSceneTab): string => (tab && tab !== 'overview' ? `/models?tab=${tab}` : '/models'),nodeDetail: (id: string, tab?: NodeDetailSceneTab): string => `/models/${id}${tab ? `/${tab}` : ''}`,sources: (): string => '/data-management/sources',dataWarehouseSource: (id: string, tab?: SourceSceneTab): string =>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 450f48fd9326..65ebb9259fbc 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53888,8 +53888,17 @@ export namespace Schemas {readonly downstream_count: number;/** @nullable */readonly last_run_at: string | null;- /** @nullable */+ /**+ * Skipped runs are written straight to the job table and never reach the stored status,+ * so a blocked model would keep reporting the success before it.+ * @nullable+ */readonly last_run_status: string | null;+ /**+ * Error of the run that last_run_status describes, so the two never disagree.+ * @nullable+ */+ readonly last_run_error: string | null;/** @nullable */readonly user_tag: string | null;/** @nullable */@@ -66865,8 +66874,17 @@ export namespace Schemas {readonly downstream_count?: number;/** @nullable */readonly last_run_at?: string | null;- /** @nullable */+ /**+ * Skipped runs are written straight to the job table and never reach the stored status,+ * so a blocked model would keep reporting the success before it.+ * @nullable+ */readonly last_run_status?: string | null;+ /**+ * Error of the run that last_run_status describes, so the two never disagree.+ * @nullable+ */+ readonly last_run_error?: string | null;/** @nullable */readonly user_tag?: string | null;/** @nullable */@@ -96212,8 +96230,27 @@ export namespace Schemas {*/offset?: number;saved_query_id?: string;+ /**+ * * `Cancelled` - Cancelled+ * * `Completed` - Completed+ * * `Failed` - Failed+ * * `Running` - Running+ * * `Skipped` - Skipped+ */+ status?: DataModelingJobsListStatus;};+ export type DataModelingJobsListStatus = typeof DataModelingJobsListStatus[keyof typeof DataModelingJobsListStatus];+++ export const DataModelingJobsListStatus = {+ Cancelled: 'Cancelled',+ Completed: 'Completed',+ Failed: 'Failed',+ Running: 'Running',+ Skipped: 'Skipped',+ } as const;+export type DataModelingNodesListParams = {/*** A page number within the paginated result set.