: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
fix(data-modeling): add view deletion and paginate run history (#100648)
Jovan Sakovica4b303dd4b10
diff --git a/docs/internal/models.md b/docs/internal/models.mdnew file mode 100644index 000000000000..74a70289cf7c--- /dev/null+++ b/docs/internal/models.md@@ -0,0 +1,17 @@+# Managing models++Open a saved view from Models to inspect its query, refresh schedule, and run history.+The actions menu offers **Delete view** for a saved view and **Delete materialized view** for a materialized view.+Deletion asks for confirmation, removes the saved view and its materialized data, and returns to Models after success.+Queries that depend on the deleted view will stop working.+**Revert materialization** removes the materialized data and stops scheduled refreshes while keeping the saved view.+Endpoint-backed models use the endpoint page to manage their lifecycle.++Run history shows ten runs per page with previous and next controls.+Refreshing the history reloads the current page.+The latest run continues to update independently while you browse older pages, so the model status and run controls reflect the current run.+**Last synced** reports the newest completed run, even when it is older than the ten runs on the first page.++When suspension enforcement is enabled, a model suspended on the serving engine shows **Suspended** in both the attention list and its detail summary.+The summary includes the reason and the stopped schedule; past runs retain their recorded outcomes.+A marker on a shadow engine, or a marker while enforcement is disabled, does not mean scheduled refreshes have stopped.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex af0ba6cb642b..c7c875508a7c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5712,10 +5712,18 @@ snapshots:hash: v1.k794b7964.d434bef909772810035f7365e0708f55638dbd6b9b067f8103ae5fc44bdeee86.B6D2vcrTN4lAr9wyJhdppEe8pxfhv5BBdg-yMIKOGCsproducts-data-modeling-node-detail-scene--narrow-materialized-view--light:hash: v1.k794b7964.3dd7a8488d960144bef5a3cd7473c9337bd4881ed62e5f4559b66f22b52610e6.e_43r1kxIPrLb6ZQA6oQHHh23lYQrIfOqTwMJwKfIWE+ products-data-modeling-node-detail-scene--narrow-suspended-with-run-history--dark:+ hash: v1.k794b7964.61e9fdf103d31a89474fce6c238e7daf727a23734c93113d0ce6beda8bd6bde8.5xne6j1ft6cwHmCVvkk8XTwAJvjmbjYu0H_viJzPrws+ products-data-modeling-node-detail-scene--narrow-suspended-with-run-history--light:+ hash: v1.k794b7964.bb01b3a50bc5b002f1cf7c9cbd6dc8ddca449d37abbdc6750623d2873630879e.AsQNacWMvT8ZkkMBKJH0Ux0tO2oE_Afzh9Y-qdCzTqcproducts-data-modeling-node-detail-scene--narrow-view--dark:hash: v1.k794b7964.9110aa72356c45ec91a7ac3ac712904e28cf6b51a2b4ae6b032d60b524327427.6x6APOu5hbFc9JZVJBA1YQNgrxqszt3X2PfHorWYzrwproducts-data-modeling-node-detail-scene--narrow-view--light:hash: v1.k794b7964.42808291c239b90849edc8df8dfc10a69b0d73974de964412492325fdca5cb01.YfMvngDzfur4xRvb7O6msDlyuLsJkv7gcunSWAhNG5g+ products-data-modeling-node-detail-scene--suspended-with-run-history--dark:+ hash: v1.k794b7964.8777021fae0861f86ccd00ee197d14fcacf12d0ae1ba8a8fe7b38f20591cbc41.r_GyHK2h2ozRGIYXoZ3N4CAlJMClpccnfeC5TEgiDOo+ products-data-modeling-node-detail-scene--suspended-with-run-history--light:+ hash: v1.k794b7964.8e3a299698deffd2d09cc49fcef1f040cf40d0ec3be8fddf52ca34551c8f7e0a.uq9M5UbnFlUTEOem2aXKGYcYItgfYjMxhBk7AG-UvyQproducts-data-modeling-node-detail-scene--view--dark:hash: v1.k794b7964.c3a0122ed3c944fd0036bf07405b2e09e14f7f218660863779a3587da606f3aa.HS-n7WOMbDZm10kaWIku0Y01udvSaEeEdFoDzUBLlrkproducts-data-modeling-node-detail-scene--view--light:diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsxindex c4a5d6287287..26dc8c879e37 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx@@ -192,7 +192,7 @@ export const MaterializationSettings: StoryObj = {mswDecorator({get: {'/api/environments/:team_id/warehouse_saved_queries/:id/': [200, SETTINGS_VIEW],- '/api/environments/:team_id/data_modeling_jobs': [200, { results: [], count: 0 }],+ '/api/projects/:team_id/data_modeling_jobs/': [200, { results: [], count: 0, next: null }],'/api/environments/:team_id/data_modeling_nodes/lineage/': [200,{diff --git a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsxindex 9736614abe36..02120a94ae34 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx+++ b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx@@ -17,16 +17,17 @@ import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'-import { AccessControlLevel, AccessControlResourceType, DataModelingJob, LogEntryLevel } from '~/types'+import { AccessControlLevel, AccessControlResourceType, LogEntryLevel } from '~/types'import { SERVING_ENGINE } from 'products/data_modeling/frontend/suspension'+import type { DataModelingJobApi } from 'products/data_warehouse/frontend/generated/api.schemas'import { MaterializationLoading } from 'products/data_warehouse/frontend/shared/components/MaterializationLoading'import { MaterializationRunActions } from 'products/data_warehouse/frontend/shared/components/MaterializationRunActions'import { MaterializationRunError } from 'products/data_warehouse/frontend/shared/components/MaterializationRunError'import { IncrementalConfigOptions } from '../editor/IncrementalConfigFields'import { dataWarehouseViewsLogic } from './dataWarehouseViewsLogic'-import { materializationJobsLogic } from './materializationJobsLogic'+import { DEFAULT_JOBS_PAGE_SIZE, materializationJobsLogic } from './materializationJobsLogic'import { computeJobDuration, jobLogsWindow } from './materializationJobUtils'import {SyncFrequencySelect,@@ -131,7 +132,11 @@ export function MaterializationStatusPanel({const {dataModelingJobs,dataModelingJobsLoading,- hasMoreJobsToLoad,+ jobsPage,+ jobsPageResults,+ olderJobsPageLoading,+ olderJobsPageError,+ dataModelingJobsError,lastSuccessfulSyncAt,startingMaterialization,savedQuery,@@ -144,7 +149,8 @@ export function MaterializationStatusPanel({} = useValues(jobsLogic)const {loadDataModelingJobs,- loadOlderDataModelingJobs,+ setJobsPage,+ loadOlderJobsPage,setInitialSyncFrequency,setIncrementalDraft,setSyncFrequencyDraft,@@ -389,21 +395,46 @@ export function MaterializationStatusPanel({icon={<IconRefresh />}size="small"type="secondary"- onClick={() => loadDataModelingJobs()}- loading={dataModelingJobsLoading}+ onClick={() => (jobsPage === 1 ? loadDataModelingJobs() : loadOlderJobsPage())}+ loading={jobsPage === 1 ? dataModelingJobsLoading : olderJobsPageLoading}disabledReason={startingMaterialization ? 'Materialization is starting' : undefined}tooltip="Refresh runs"+ aria-label="Refresh runs"/></div>+ {(jobsPage === 1 ? dataModelingJobsError : olderJobsPageError) && (+ <LemonBanner type="error">Couldn't load runs. Use Refresh runs to try again.</LemonBanner>+ )}<LemonTable+ rowKey="id"+ pagination={{+ controlled: true,+ useUrl: false,+ pageSize: DEFAULT_JOBS_PAGE_SIZE,+ currentPage: jobsPage,+ entryCount: jobsPageResults?.count,+ // PaginationControl decides whether an arrow is enabled from the entry count, not+ // from these handlers, so withholding one while a page loads would leave a live+ // arrow that does nothing. Let the click through: the page loader breakpoints, so+ // the superseded response is discarded.+ onBackward: jobsPage > 1 ? () => setJobsPage(jobsPage - 1) : undefined,+ onForward: jobsPageResults?.next ? () => setJobsPage(jobsPage + 1) : undefined,+ }}size="small"- loading={dataModelingJobsLoading && !dataModelingJobs?.results?.length}- dataSource={dataModelingJobs?.results || []}+ // A timer reloads page 1 in the background, and LemonTable's loading overlay blocks+ // pointer events over the rows and the pager, so page 1 shows the loader only before it+ // has rows. Only a user action loads an older page, so that loader always shows.+ loading={+ jobsPage === 1+ ? dataModelingJobsLoading && !jobsPageResults?.results?.length+ : olderJobsPageLoading+ }+ dataSource={jobsPage > 1 && olderJobsPageError ? [] : jobsPageResults?.results || []}columns={[{title: 'Status',dataIndex: 'status',- render: (_, job: DataModelingJob) => {+ render: (_, job: DataModelingJobApi) => {const { status, rows_materialized, rows_expected } = jobconst type = STATUS_TAG_TYPES[status] || 'warning'@@ -436,8 +467,8 @@ export function MaterializationStatusPanel({title: 'Refresh mode',dataIndex: 'run_mode',isHidden:- !showIncremental || !savedQuery.is_materialized || !dataModelingJobs?.results?.length,- render: (_, { run_mode }: DataModelingJob) =>+ !showIncremental || !savedQuery.is_materialized || !jobsPageResults?.results?.length,+ render: (_, { run_mode }: DataModelingJobApi) =>run_mode === 'incremental'? 'Incremental': run_mode === 'full_refresh'@@ -447,7 +478,7 @@ export function MaterializationStatusPanel({{title: 'Error',dataIndex: 'error',- render: (_, { error, status }: DataModelingJob) => (+ render: (_, { error, status }: DataModelingJobApi) => (<div className="max-w-28 @min-[48rem]/materialization:max-w-60"><spanclassName={`block truncate ${status === 'Failed' ? 'text-danger' : 'text-secondary'}`}@@ -460,7 +491,7 @@ export function MaterializationStatusPanel({{title: 'Rows',dataIndex: 'rows_materialized',- render: (_, { rows_materialized, status, run_mode }: DataModelingJob) => {+ render: (_, { rows_materialized, status, run_mode }: DataModelingJobApi) => {if ((status === 'Running' || status === 'Cancelled' || status === 'Skipped') &&rows_materialized === 0@@ -487,18 +518,18 @@ export function MaterializationStatusPanel({{title: 'Updated',dataIndex: 'last_run_at',- render: (_, { last_run_at }: DataModelingJob) =>+ render: (_, { last_run_at }: DataModelingJobApi) =>last_run_at ? <TZLabel time={last_run_at} /> : '-',},{title: 'Duration',- render: (_, job: DataModelingJob) => computeJobDuration(job),+ render: (_, job: DataModelingJobApi) => computeJobDuration(job),},]}expandable={- dataModelingJobs?.results?.length+ jobsPageResults?.results?.length? {- expandedRowRender: (job: DataModelingJob) => (+ expandedRowRender: (job: DataModelingJobApi) => (<div className="p-4 min-w-0"><MaterializationRunError error={job.error} status={job.status} /><LogsViewer@@ -524,20 +555,6 @@ export function MaterializationStatusPanel({}nouns={['run', 'runs']}emptyState="No runs available"- footer={- hasMoreJobsToLoad && (- <div className="flex items-center m-2">- <LemonButton- center- fullWidth- onClick={() => loadOlderDataModelingJobs()}- loading={dataModelingJobsLoading}- >- Load older runs- </LemonButton>- </div>- )- }/></div></div>diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.tsindex 5128cc2ae5da..a3f78328e5b1 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobUtils.ts@@ -52,13 +52,13 @@ export function computeJobDuration(job: JobTiming): string {/** When the data the view currently serves was synced. A run that failed, was cancelled, was* skipped, or was blocked by failing data quality checks leaves the previous version in place.* Only a completed run answers this. The newest run does not. */-export function latestSuccessfulSyncAt(jobs: DataModelingJob[] | undefined): string | null {+export function latestSuccessfulSyncAt(jobs: JobTiming[] | undefined): string | null {return latestOf(...(jobs ?? []).filter((job) => job.status === 'Completed').map((job) => job.last_run_at))}/** Time window for the run's log search. An open `dateTo` (still running, or no usable end* timestamp) lets the LogsViewer default to "now" instead of silently cutting off logs. */-export function jobLogsWindow(job: DataModelingJob, timezone: string): { dateFrom?: string; dateTo?: string } {+export function jobLogsWindow(job: JobTiming, timezone: string): { dateFrom?: string; dateTo?: string } {const end = jobEndTimestamp(job)return {dateFrom: isParseableDate(job.created_at)diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.tsindex 86892315add4..64b9d03c348e 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts@@ -1,4 +1,5 @@import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import { createElement } from 'react'@@ -8,6 +9,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useMocks } from '~/mocks/jest'+import { DataWarehouseSavedQueryOrigin } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { MaterializationRunActions } from 'products/data_warehouse/frontend/shared/components/MaterializationRunActions'@@ -44,9 +46,11 @@ describe('materializationJobsLogic', () => {function apiMocks({isMaterialized,incremental = null,+ savedQueryExtras,}: {isMaterialized: booleanincremental?: Record<string, any> | null+ savedQueryExtras?: Record<string, any>}): Parameters<typeof useMocks>[0] {return {get: {@@ -60,9 +64,10 @@ describe('materializationJobsLogic', () => {sync_frequency: savedSyncFrequency,incremental,query: { kind: 'HogQLQuery', query: 'SELECT timestamp, id FROM events' },+ ...savedQueryExtras,},],- '/api/environments/:team_id/data_modeling_jobs': { results: [], count: 0 },+ '/api/projects/:team_id/data_modeling_jobs/': { results: [], count: 0 },},post: {'/api/environments/:team_id/warehouse_saved_queries/check_incremental/': () => {@@ -90,6 +95,149 @@ describe('materializationJobsLogic', () => {jest.useRealTimers()})+ it('pages through older runs without changing the latest run or growing polling requests', async () => {+ const mocks = apiMocks({ isMaterialized: true })+ const requests: string[] = []+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = (req) => {+ const params = new URL(req.request.url).searchParams+ const offset = Number(params.get('offset'))+ // The last-successful-sync lookup is a separate, status-filtered request; this test is about+ // the history pages, so only those are recorded.+ if (!params.get('status')) {+ requests.push(`${params.get('limit')}:${offset}`)+ }+ return [+ 200,+ {+ count: 21,+ next: offset < 20 ? '/next' : null,+ results: [{ id: `run-${offset}`, status: offset === 0 ? 'Running' : 'Failed' }],+ },+ ]+ }+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadDataModelingJobsSuccess'])+ await expectLogic(logic, () => logic.actions.setJobsPage(2)).toDispatchActions(['loadOlderJobsPageSuccess'])+ expect(logic.values.jobsPageResults?.results.map((job) => job.id)).toEqual(['run-10'])+ expect(logic.values.dataModelingJobs?.results[0].status).toBe('Running')+ await expectLogic(logic, () => logic.actions.loadDataModelingJobs()).toDispatchActions([+ 'loadDataModelingJobsSuccess',+ ])+ expect(logic.values.jobsPage).toBe(2)+ expect(logic.values.jobsPageResults?.results.map((job) => job.id)).toEqual(['run-10'])+ await expectLogic(logic, () => logic.actions.setJobsPage(1)).toDispatchActions(['loadDataModelingJobsSuccess'])+ expect(logic.values.jobsPageResults?.results.map((job) => job.id)).toEqual(['run-0'])+ expect(requests).toEqual(['10:0', '10:10', '10:0', '10:0'])+ })++ // Regression: the run history only holds the ten newest runs, so a view whose recent runs all+ // failed still serves the data an older completed run built. That timestamp must survive.+ it.each([+ ['every recent run failed', 'Failed', '2026-09-01T10:00:00Z', 1],+ ['a recent run completed', 'Completed', '2026-09-10T10:00:00Z', 0],+ ])('reports the last successful sync when %s', async (_name, status, expected, expectedLookups) => {+ let lookups = 0+ const mocks = apiMocks({ isMaterialized: true })+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = (req) => {+ if (new URL(req.request.url).searchParams.get('status') === 'Completed') {+ lookups += 1+ return [200, { count: 1, results: [{ id: 'old', status: 'Completed', last_run_at: expected }] }]+ }+ return [200, { count: 1, results: [{ id: 'recent', status, last_run_at: '2026-09-10T10:00:00Z' }] }]+ }+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadDataModelingJobsSuccess']).toFinishAllListeners()+ expect(logic.values.lastSuccessfulSyncAt).toBe(expected)+ expect(lookups).toBe(expectedLookups)+ })++ it.each([false, true])(+ 'offers deletion for a materialized=%s view and clears the pending state after success',+ async (isMaterialized) => {+ const mocks = apiMocks({ isMaterialized })+ mocks.delete = { '/api/environments/:team_id/warehouse_saved_queries/:id/': [204] }+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSavedQuerySuccess', 'loadDataModelingJobsSuccess'])+ render(createElement(MaterializationRunActions, { viewId: 'view-1' }))+ fireEvent.click(+ buttonByAttr(isMaterialized ? 'node-detail-materialization-actions' : 'node-detail-view-actions')+ )+ const label = isMaterialized ? 'Delete materialized view' : 'Delete view'+ fireEvent.click(screen.getByText(label))+ await expectLogic(logic, () => {+ fireEvent.click(screen.getAllByText(label).at(-1)!)+ }).toDispatchActions(['deleteDataWarehouseSavedQuerySuccess'])+ expect(logic.values.deletingView).toBe(false)+ }+ )++ it('keeps a view open and allows retry when deletion fails', async () => {+ const mocks = apiMocks({ isMaterialized: true })+ mocks.delete = {+ '/api/environments/:team_id/warehouse_saved_queries/:id/': [500, { detail: 'Could not delete view' }],+ }+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSavedQuerySuccess'])+ const path = router.values.location.pathname+ await expectLogic(logic, () => logic.actions.deleteView()).toDispatchActions([+ 'deleteDataWarehouseSavedQueryFailure',+ ])+ expect(logic.values.deletingView).toBe(false)+ expect(router.values.location.pathname).toBe(path)+ })++ // Another product owns these views: a managed viewset refuses the delete outright, and deleting+ // an endpoint-origin view breaks the endpoint it serves. The SQL editor renders the actions+ // without the endpoint `kind`, so the saved query has to carry the signal.+ it.each([+ ['a managed viewset', { managed_viewset_kind: 'revenue_analytics' }],+ ['an endpoint', { origin: DataWarehouseSavedQueryOrigin.ENDPOINT }],+ ])('blocks deletion for a view owned by %s', async (_name, savedQueryExtras) => {+ useMocks(apiMocks({ isMaterialized: true, savedQueryExtras }))+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSavedQuerySuccess', 'loadDataModelingJobsSuccess'])+ render(createElement(MaterializationRunActions, { viewId: 'view-1' }))+ fireEvent.click(buttonByAttr('node-detail-materialization-actions'))+ expect(buttonByAttr('node-detail-delete-view').getAttribute('aria-disabled')).toBe('true')+ })++ // Regression: the run check reads the loaded run list, which is empty both when nothing runs and+ // when the runs have not arrived. The saved query can arrive first, and deleting through that+ // window leaves a run writing to a view that is gone.+ it('blocks deletion until the run state is known and re-enables it when runs cannot load', async () => {+ let fail = false+ const mocks = apiMocks({ isMaterialized: true })+ let releaseJobs!: () => void+ const held = new Promise<void>((resolve) => {+ releaseJobs = resolve+ })+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = async () => {+ await held+ return fail ? [500, { detail: 'Unavailable' }] : [200, { results: [], count: 0 }]+ }+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSavedQuerySuccess'])+ render(createElement(MaterializationRunActions, { viewId: 'view-1' }))+ fireEvent.click(buttonByAttr('node-detail-materialization-actions'))+ expect(buttonByAttr('node-detail-delete-view').getAttribute('aria-disabled')).toBe('true')++ fail = true+ releaseJobs()+ await expectLogic(logic).toDispatchActions(['loadDataModelingJobsFailure']).toFinishAllListeners()+ expect(buttonByAttr('node-detail-delete-view').getAttribute('aria-disabled')).not.toBe('true')+ })+// Regression: the saved query reloads on every jobs poll. Without the once-per-mount guard the// eligibility check fires on each poll, hammering a parse-heavy endpoint. And without the key// default, enabling incremental starts from an empty picker.@@ -258,7 +406,7 @@ describe('materializationJobsLogic', () => {fetches += 1return [200, { id: 'view-1' }]},- '/api/environments/:team_id/data_modeling_jobs': () => {+ '/api/projects/:team_id/data_modeling_jobs/': () => {fetches += 1return [200, { results: [], count: 0 }]},@@ -324,7 +472,11 @@ describe('materializationJobsLogic', () => {let jobsCalls = 0let fail = falseconst mocks = apiMocks({ isMaterialized: true })- mocks.get!['/api/environments/:team_id/data_modeling_jobs'] = () => {+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = (req) => {+ // Only the unfiltered history request is on the polling schedule.+ if (new URL(req.request.url).searchParams.get('status')) {+ return [200, { results: [], count: 0 }]+ }jobsCalls += 1return fail ? [500, { detail: 'Unavailable' }] : [200, { results: [{ id: 'job-1', status }], count: 1 }]}diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.tsindex 6e039d5b3d3b..ad7dada32839 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts@@ -17,20 +17,15 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'-import api, { ApiConfig, ApiError, PaginatedResponse } from 'lib/api'+import api, { ApiConfig, ApiError } from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import {- DataModelingJob,- DataModelingSyncInterval,- DataWarehouseSavedQuery,- DataWarehouseSavedQueryIncrementalCheck,-} from '~/types'+import { DataModelingSyncInterval, DataWarehouseSavedQuery, DataWarehouseSavedQueryIncrementalCheck } from '~/types'-import { warehouseSavedQueriesResumeCreate } from 'products/data_warehouse/frontend/generated/api'+import { dataModelingJobsList, warehouseSavedQueriesResumeCreate } from 'products/data_warehouse/frontend/generated/api'+import type { PaginatedDataModelingJobListApi } from 'products/data_warehouse/frontend/generated/api.schemas'-import type { CountedPaginatedResponse } from '../../../lib/api'import { EMPTY_INCREMENTAL_DRAFT, IncrementalConfigDraft } from '../editor/IncrementalConfigFields'import { DEFAULT_MATERIALIZE_SYNC_FREQUENCY, dataWarehouseViewsLogic } from './dataWarehouseViewsLogic'import { latestSuccessfulSyncAt } from './materializationJobUtils'@@ -38,7 +33,7 @@ import { SyncFrequencyValue } from './SyncFrequencySelect'const ACTIVE_REFRESH_INTERVAL_MS = 10000const IDLE_REFRESH_INTERVAL_MS = 60000-const DEFAULT_JOBS_PAGE_SIZE = 10+export const DEFAULT_JOBS_PAGE_SIZE = 10export interface MaterializationJobsLogicProps {viewId: string@@ -48,19 +43,26 @@ export interface MaterializationJobsLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface materializationJobsLogicValues {- dataModelingJobs: PaginatedResponse<DataModelingJob> | null+ dataModelingJobs: PaginatedDataModelingJobListApi | nulldataModelingJobsError: booleandataModelingJobsLoading: boolean+ deletingView: booleanhasMaterializationChanges: boolean- hasMoreJobsToLoad: booleanincrementalCheck: DataWarehouseSavedQueryIncrementalCheck | nullincrementalCheckLoading: booleanincrementalDraft: IncrementalConfigDraftincrementalDraftTouched: booleaninitialSyncFrequency: DataModelingSyncInterval+ jobsPage: number+ jobsPageResults: PaginatedDataModelingJobListApi | nulljobsRefreshPending: booleanlastSuccessfulSyncAt: string | null+ latestCompletedJob: PaginatedDataModelingJobListApi | null+ latestCompletedJobLoading: booleanmaterializationRefreshPending: boolean+ olderJobsPage: PaginatedDataModelingJobListApi | null+ olderJobsPageError: boolean+ olderJobsPageLoading: booleanrefreshModeChanged: booleanresumingMaterialization: booleansavedQuery: DataWarehouseSavedQuery | null@@ -74,6 +76,21 @@ export interface materializationJobsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface materializationJobsLogicActions {+ deleteDataWarehouseSavedQuery: (viewId: string) => string // dataWarehouseViewsLogic+ deleteDataWarehouseSavedQueryFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ } // dataWarehouseViewsLogic+ deleteDataWarehouseSavedQuerySuccess: (+ dataWarehouseSavedQueries: DataWarehouseSavedQuery[],+ payload?: string | undefined+ ) => {+ dataWarehouseSavedQueries: DataWarehouseSavedQuery[]+ payload?: string+ } // dataWarehouseViewsLogicmaterializationChanged: (viewId: string) => {viewId: string} // dataWarehouseViewsLogic@@ -99,9 +116,15 @@ export interface materializationJobsLogicActions {clearSyncFrequencyDraft: () => {value: true}+ deleteView: () => {+ value: true+ }discardMaterializationChanges: () => {value: true}+ finishDeletingView: () => {+ value: true+ }finishSavingMaterialization: () => {value: true}@@ -114,10 +137,10 @@ export interface materializationJobsLogicActions {errorObject?: any}loadDataModelingJobsSuccess: (- dataModelingJobs: CountedPaginatedResponse<DataModelingJob>,+ dataModelingJobs: PaginatedDataModelingJobListApi,payload?: void) => {- dataModelingJobs: CountedPaginatedResponse<DataModelingJob>+ dataModelingJobs: PaginatedDataModelingJobListApipayload?: void}loadIncrementalCheck: () => any@@ -135,20 +158,35 @@ export interface materializationJobsLogicActions {incrementalCheck: DataWarehouseSavedQueryIncrementalCheck | nullpayload?: any}- loadOlderDataModelingJobs: () => any- loadOlderDataModelingJobsFailure: (+ loadLatestCompletedJob: (_: void) => void+ loadLatestCompletedJobFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- loadOlderDataModelingJobsSuccess: (- dataModelingJobs: PaginatedResponse<DataModelingJob> | null,- payload?: any+ loadLatestCompletedJobSuccess: (+ latestCompletedJob: PaginatedDataModelingJobListApi,+ payload?: void) => {- dataModelingJobs: PaginatedResponse<DataModelingJob> | null- payload?: any+ latestCompletedJob: PaginatedDataModelingJobListApi+ payload?: void+ }+ loadOlderJobsPage: (_: void) => void+ loadOlderJobsPageFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOlderJobsPageSuccess: (+ olderJobsPage: PaginatedDataModelingJobListApi,+ payload?: void+ ) => {+ olderJobsPage: PaginatedDataModelingJobListApi+ payload?: void}loadSavedQuery: (_: void) => voidloadSavedQueryFailure: (@@ -186,6 +224,9 @@ export interface materializationJobsLogicActions {setInitialSyncFrequency: (syncFrequency: DataModelingSyncInterval) => {syncFrequency: DataModelingSyncInterval}+ setJobsPage: (page: number) => {+ page: number+ }setResumingMaterialization: (resuming: boolean) => {resuming: boolean}@@ -212,8 +253,15 @@ export interface materializationJobsLogicMeta {syncFrequencyDraft: SyncFrequencyValue | null,refreshModeChanged: boolean) => boolean- hasMoreJobsToLoad: (dataModelingJobs: PaginatedResponse<DataModelingJob> | null) => boolean- lastSuccessfulSyncAt: (dataModelingJobs: PaginatedResponse<DataModelingJob> | null) => string | null+ jobsPageResults: (+ jobsPage: number,+ dataModelingJobs: PaginatedDataModelingJobListApi | null,+ olderJobsPage: PaginatedDataModelingJobListApi | null+ ) => PaginatedDataModelingJobListApi | null+ lastSuccessfulSyncAt: (+ dataModelingJobs: PaginatedDataModelingJobListApi | null,+ latestCompletedJob: PaginatedDataModelingJobListApi | null+ ) => string | null}}@@ -238,11 +286,17 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>(['runDataWarehouseSavedQueryFailure','runDataWarehouseSavedQuerySuccess','materializationChanged',+ 'deleteDataWarehouseSavedQuery',+ 'deleteDataWarehouseSavedQuerySuccess',+ 'deleteDataWarehouseSavedQueryFailure',],],})),actions({refreshMaterialization: true,+ setJobsPage: (page: number) => ({ page }),+ deleteView: true,+ finishDeletingView: true,scheduleJobsRefresh: (delay: number) => ({ delay }),setStartingMaterialization: (starting: boolean) => ({ starting }),resumeMaterialization: true,@@ -296,35 +350,55 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([},],dataModelingJobs: [- null as PaginatedResponse<DataModelingJob> | null,+ null as PaginatedDataModelingJobListApi | null,{loadDataModelingJobs: async (_: void, breakpoint) => {- const jobs = await api.dataWarehouseSavedQueries.dataWarehouseDataModelingJobs.list(- props.viewId,- values.dataModelingJobs?.results.length- ? Math.max(values.dataModelingJobs.results.length, DEFAULT_JOBS_PAGE_SIZE)- : DEFAULT_JOBS_PAGE_SIZE,- 0- )+ const jobs = await dataModelingJobsList(String(ApiConfig.getCurrentTeamId()), {+ saved_query_id: props.viewId,+ limit: DEFAULT_JOBS_PAGE_SIZE,+ offset: 0,+ })breakpoint()return jobs},- loadOlderDataModelingJobs: async () => {- const nextUrl = values.dataModelingJobs?.next-- if (!nextUrl) {- return values.dataModelingJobs- }-- const res = await api.get<PaginatedResponse<DataModelingJob>>(nextUrl)- res.results = [...(values.dataModelingJobs?.results ?? []), ...res.results]-- return res+ },+ ],+ // The newest completed run when the first page holds none. The panel reports when the data the+ // view serves was built, and a view whose last ten runs all failed still serves an older build.+ latestCompletedJob: [+ null as PaginatedDataModelingJobListApi | null,+ {+ loadLatestCompletedJob: async (_: void, breakpoint) => {+ const jobs = await dataModelingJobsList(String(ApiConfig.getCurrentTeamId()), {+ saved_query_id: props.viewId,+ status: 'Completed',+ limit: 1,+ offset: 0,+ })+ breakpoint()+ return jobs+ },+ },+ ],+ olderJobsPage: [+ null as PaginatedDataModelingJobListApi | null,+ {+ loadOlderJobsPage: async (_: void, breakpoint) => {+ const jobs = await dataModelingJobsList(String(ApiConfig.getCurrentTeamId()), {+ saved_query_id: props.viewId,+ limit: DEFAULT_JOBS_PAGE_SIZE,+ offset: (values.jobsPage - 1) * DEFAULT_JOBS_PAGE_SIZE,+ })+ breakpoint()+ return jobs},},],})),reducers({+ jobsPage: [1, { setJobsPage: (_, { page }) => page }],+ olderJobsPageError: [false, { loadOlderJobsPage: () => false, loadOlderJobsPageFailure: () => true }],+ deletingView: [false, { deleteView: () => true, finishDeletingView: () => false }],savedQueryError: [false,{@@ -423,7 +497,7 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([runDataWarehouseSavedQueryFailure: () => false,loadDataModelingJobsSuccess: (state: boolean,- { dataModelingJobs }: { dataModelingJobs: PaginatedResponse<DataModelingJob> | null }+ { dataModelingJobs }: { dataModelingJobs: PaginatedDataModelingJobListApi | null }) => {const currentJobStatus = dataModelingJobs?.results?.[0]?.statusif (@@ -468,14 +542,20 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([!!savedQuery?.is_materialized &&(modeChanged || (frequency !== null && frequency !== (savedQuery.sync_frequency || 'never'))),],- hasMoreJobsToLoad: [- (s) => [s.dataModelingJobs],- (dataModelingJobs: PaginatedResponse<DataModelingJob> | null) => !!dataModelingJobs?.next,+ jobsPageResults: [+ (s) => [s.jobsPage, s.dataModelingJobs, s.olderJobsPage],+ (+ page: number,+ latest: PaginatedDataModelingJobListApi | null,+ older: PaginatedDataModelingJobListApi | null+ ): PaginatedDataModelingJobListApi | null => (page === 1 ? latest : older),],lastSuccessfulSyncAt: [- (s) => [s.dataModelingJobs],- (dataModelingJobs: PaginatedResponse<DataModelingJob> | null) =>- latestSuccessfulSyncAt(dataModelingJobs?.results),+ (s) => [s.dataModelingJobs, s.latestCompletedJob],+ (+ dataModelingJobs: PaginatedDataModelingJobListApi | null,+ latestCompletedJob: PaginatedDataModelingJobListApi | null+ ) => latestSuccessfulSyncAt([...(dataModelingJobs?.results ?? []), ...(latestCompletedJob?.results ?? [])]),],}),afterMount(({ actions, props }) => {@@ -491,6 +571,20 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([}}),listeners(({ actions, cache, props, values }) => ({+ setJobsPage: () => {+ if (values.jobsPage === 1) {+ actions.loadDataModelingJobs()+ } else {+ actions.loadOlderJobsPage()+ }+ },+ deleteView: () => actions.deleteDataWarehouseSavedQuery(props.viewId),+ deleteDataWarehouseSavedQuerySuccess: ({ payload }) => {+ if (payload === props.viewId && values.deletingView) {+ actions.finishDeletingView()+ }+ },+ deleteDataWarehouseSavedQueryFailure: () => actions.finishDeletingView(),materializationChanged: ({ viewId }) => {if (viewId === props.viewId) {actions.refreshMaterialization()@@ -623,9 +717,12 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([actions.loadSavedQuery()}},- loadDataModelingJobsSuccess: () => {+ loadDataModelingJobsSuccess: ({ dataModelingJobs }) => {// Refresh saved query alongside jobs so latest_error / status / sync_frequency stay in sync.actions.loadSavedQuery()+ if (!dataModelingJobs.results.some((job) => job.status === 'Completed')) {+ actions.loadLatestCompletedJob()+ }const active = values.startingMaterialization || values.dataModelingJobs?.results[0]?.status === 'Running'actions.scheduleJobsRefresh(active ? ACTIVE_REFRESH_INTERVAL_MS : IDLE_REFRESH_INTERVAL_MS)},diff --git a/frontend/src/scenes/models/NodeDetailOverview.tsx b/frontend/src/scenes/models/NodeDetailOverview.tsxindex d1d1cc024282..444db50578a3 100644--- a/frontend/src/scenes/models/NodeDetailOverview.tsx+++ b/frontend/src/scenes/models/NodeDetailOverview.tsx@@ -65,7 +65,7 @@ export function NodeDetailOverview({ id, metadata }: { id: string; metadata?: Re}// Only ClickHouse serves queries, so a marker on a shadow engine means the comparison// run stopped, not that this model stopped refreshing.- const suspension = savedQuery?.suspended?.[SERVING_ENGINE]+ const suspension = (savedQuery?.suspended ?? node.suspended)?.[SERVING_ENGINE]const suspended = !!featureFlags[FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES] && !!suspensionconst cadence = savedQuery?.sync_frequencyconst schedule = suspendeddiff --git a/frontend/src/scenes/models/modelsSceneLogic.test.ts b/frontend/src/scenes/models/modelsSceneLogic.test.tsindex 12c593272ebe..a33a15cf7905 100644--- a/frontend/src/scenes/models/modelsSceneLogic.test.ts+++ b/frontend/src/scenes/models/modelsSceneLogic.test.ts@@ -58,6 +58,7 @@ describe('modelsSceneLogic', () => {buildNode('child', { last_run_status: 'Skipped' }),buildNode('grandchild', { last_run_status: 'Skipped' }),buildNode('paused', {+ last_run_status: 'Failed',suspended: { clickhouse: { at: '2024-01-02T00:00:00Z', reason: 'boom', job_id: 'j1' } },}),buildNode('never-ran'),@@ -133,7 +134,7 @@ describe('modelsSceneLogic', () => {await expectLogic(lineageDataLogic).toDispatchActions(['loadNodesSuccess'])await expectLogic(dataWarehouseViewsLogic).toDispatchActions(['loadDataWarehouseSavedQueriesSuccess'])- expect(logic.values.failingNodes.map((node) => node.id)).toEqual(['broken'])+ expect(logic.values.failingNodes.map((node) => node.id)).toEqual(['broken', 'paused'])expect(logic.values.suspendedNodes.map((node) => node.id)).toEqual(['paused'])})@@ -154,6 +155,7 @@ describe('modelsSceneLogic', () => {// 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([])+ expect(logic.values.attentionModels.find((row) => row.node.id === 'paused')?.problem).toBe('Failed')})it('lists broken models with their error and what they hold up', async () => {diff --git a/frontend/src/scenes/models/modelsSceneLogic.ts b/frontend/src/scenes/models/modelsSceneLogic.tsindex 3e7676489df7..6b5f02cd89a3 100644--- a/frontend/src/scenes/models/modelsSceneLogic.ts+++ b/frontend/src/scenes/models/modelsSceneLogic.ts@@ -190,7 +190,7 @@ export const modelsSceneLogic = kea<modelsSceneLogicType>([const maps = buildAdjacencyMaps(edges)const rows = affected.map((node): AttentionModel => {- const suspension = servingSuspension(node.suspended)+ const suspension = suspendedIds.has(node.id) ? servingSuspension(node.suspended) : undefined// 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 {diff --git a/frontend/src/scenes/models/nodeDetailSceneLogic.test.ts b/frontend/src/scenes/models/nodeDetailSceneLogic.test.tsindex 2c2e69fcb60f..988b1f0e822d 100644--- a/frontend/src/scenes/models/nodeDetailSceneLogic.test.ts+++ b/frontend/src/scenes/models/nodeDetailSceneLogic.test.ts@@ -1,14 +1,19 @@+import { cleanup, render, screen } from '@testing-library/react'import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { createElement } from 'react'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'+import { materializationJobsLogic } from 'scenes/data-warehouse/saved_queries/materializationJobsLogic'import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { DataModelingNode, DataModelingNodeType, DataWarehouseSavedQuery } from '~/types'+import { NodeDetailOverview } from './NodeDetailOverview'import { NodeDetailSceneTab, nodeDetailSceneLogic } from './nodeDetailSceneLogic'const NODE_ID = 'node-1'@@ -61,10 +66,36 @@ describe('nodeDetailSceneLogic', () => {})afterEach(() => {+ cleanup()logic?.unmount()flagsLogic.unmount()})+ it.each([undefined, {}])(+ 'uses node suspension only until saved-query suspension is available (%s)',+ async (savedSuspension) => {+ node = buildNode('matview', {+ suspended: {+ clickhouse: { at: '2026-09-13T12:00:00Z', reason: 'Source unavailable', job_id: 'job-1' },+ },+ })+ savedQuery = { ...savedQuery, is_materialized: true, status: 'Failed', suspended: savedSuspension }+ flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES], {+ [FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES]: true,+ })+ await mountScene(urls.nodeDetail(NODE_ID))+ const jobs = materializationJobsLogic({ viewId: SAVED_QUERY_ID })+ jobs.mount()+ try {+ await expectLogic(jobs).toDispatchActions(['loadSavedQuerySuccess'])+ render(createElement(NodeDetailOverview, { id: NODE_ID }))+ expect(screen.queryByText('Suspended') !== null).toBe(savedSuspension === undefined)+ } finally {+ jobs.unmount()+ }+ }+ )+// A model with no tab in the URL has to land somewhere useful for its kind, and the URL has to// say where it landed — otherwise a refresh or a shared link reopens a different tab.it.each<[string, DataModelingNodeType, boolean, NodeDetailSceneTab]>([@@ -166,6 +197,19 @@ describe('nodeDetailSceneLogic', () => {expect(logic.values.effectiveLastRunStatus).toEqual('Completed')})+ // The delete runs from a shared component that also renders in the SQL editor, so the page the+ // deleted view owns is the one that has to leave — and only for its own view.+ it.each([+ ['its own view', SAVED_QUERY_ID, '/project/997/models'],+ ['another view', 'saved-query-2', `/project/997${urls.nodeDetail(NODE_ID, 'query')}`],+ ])('leaves for Models when %s is deleted', async (_name, deletedId, expectedPath) => {+ await mountScene(urls.nodeDetail(NODE_ID))++ dataWarehouseViewsLogic.actions.deleteDataWarehouseSavedQuerySuccess([], deletedId)++ expect(router.values.location.pathname).toEqual(expectedPath)+ })+it('keeps a tab mounted once it has been visited', async () => {await mountScene(urls.nodeDetail(NODE_ID))diff --git a/frontend/src/scenes/models/nodeDetailSceneLogic.ts b/frontend/src/scenes/models/nodeDetailSceneLogic.tsindex ad03ea738a1a..d52195dab916 100644--- a/frontend/src/scenes/models/nodeDetailSceneLogic.ts+++ b/frontend/src/scenes/models/nodeDetailSceneLogic.ts@@ -60,6 +60,13 @@ export interface nodeDetailSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface nodeDetailSceneLogicActions {+ deleteDataWarehouseSavedQuerySuccess: (+ dataWarehouseSavedQueries: DataWarehouseSavedQuery[],+ payload?: string | undefined+ ) => {+ dataWarehouseSavedQueries: DataWarehouseSavedQuery[]+ payload?: string+ } // dataWarehouseViewsLogicupdateDataWarehouseSavedQuerySuccess: (dataWarehouseSavedQueries: DataWarehouseSavedQuery[],payload?:@@ -197,7 +204,10 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([path((key) => ['scenes', 'models', 'nodeDetailSceneLogic', key]),connect(() => ({values: [featureFlagLogic, ['featureFlags']],- actions: [dataWarehouseViewsLogic, ['updateDataWarehouseSavedQuerySuccess']],+ actions: [+ dataWarehouseViewsLogic,+ ['updateDataWarehouseSavedQuerySuccess', 'deleteDataWarehouseSavedQuerySuccess'],+ ],})),actions({updateNodeDescription: (description: string) => ({ description }),@@ -421,6 +431,14 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([actions.loadSavedQuery()}},+ // This page is about the deleted view, so it has nowhere left to stand. The same delete runs+ // from the SQL editor, which keeps its own tab, so the navigation belongs here and not in the+ // shared materialization logic.+ deleteDataWarehouseSavedQuerySuccess: ({ payload }) => {+ if (payload && payload === values.node?.saved_query_id) {+ router.actions.push(urls.models())+ }+ },})),urlToAction(({ actions, props }) => {// Clicking a node in the lineage graph navigates model to model. The outgoing model's logicdiff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsxindex 4c5a7a23014b..b530197751c0 100644--- a/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsx+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailScene.stories.tsx@@ -1,6 +1,7 @@import type { Decorator, Meta, StoryObj } from '@storybook/react'import { useEffect, useRef } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'import { NodeDetailScene } from 'scenes/models/NodeDetailScene'import { urls } from 'scenes/urls'@@ -113,10 +114,7 @@ export const MaterializedView: Story = {sync_frequency: '1hour',},],- '/api/environments/:team_id/data_modeling_jobs/': () => [- 200,- { results: [], count: 0, next: null },- ],+ '/api/projects/:team_id/data_modeling_jobs/': () => [200, { results: [], count: 0, next: null }],},},},@@ -127,3 +125,64 @@ export const NarrowMaterializedView: Story = {...MaterializedView,decorators: NarrowView.decorators,}++const suspension = {+ clickhouse: { at: '2026-09-13T12:00:00Z', reason: 'The source table orders is unavailable.', job_id: 'run-0' },+}++export const SuspendedWithRunHistory: Story = {+ parameters: {+ pageUrl: urls.nodeDetail(node.id, 'materialization'),+ featureFlags: [FEATURE_FLAGS.DATA_MODELING_SUSPEND_FAILING_NODES],+ msw: {+ mocks: {+ get: {+ '/api/environments/:team_id/data_modeling_nodes/:id/': () => [+ 200,+ { ...node, type: 'matview', suspended: suspension, last_run_status: 'Failed' },+ ],+ '/api/environments/:team_id/warehouse_saved_queries/:id/': () => [+ 200,+ {+ ...savedQuery,+ is_materialized: true,+ status: 'Failed',+ sync_frequency: '1hour',+ suspended: suspension,+ },+ ],+ '/api/projects/:team_id/data_modeling_jobs/': ({ request }: { request: Request }) => {+ const params = new URL(request.url).searchParams+ // Every run this model has failed, so the last-successful-sync lookup finds nothing.+ if (params.get('status') === 'Completed') {+ return [200, { count: 0, next: null, results: [] }]+ }+ const offset = Number(params.get('offset') ?? 0)+ return [+ 200,+ {+ count: 25,+ next: offset < 20 ? '/next' : null,+ results: Array.from({ length: Math.min(10, 25 - offset) }, (_, index) => ({+ id: `run-${offset + index}`,+ status: 'Failed',+ rows_materialized: 0,+ rows_expected: null,+ error: 'The source table orders is unavailable.',+ created_at: '2026-09-13T12:00:00Z',+ last_run_at: '2026-09-13T12:00:00Z',+ updated_at: '2026-09-13T12:00:03Z',+ })),+ },+ ]+ },+ },+ },+ },+ },+}++export const NarrowSuspendedWithRunHistory: Story = {+ ...SuspendedWithRunHistory,+ decorators: NarrowView.decorators,+}diff --git a/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsx b/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsxindex f205737359d4..d06f3661aa8c 100644--- a/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsx+++ b/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsx@@ -14,6 +14,7 @@ import {modeDisabledReason,} from 'scenes/data-warehouse/saved_queries/SyncFrequencySelect'+import { DataWarehouseSavedQueryOrigin } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { SERVING_ENGINE } from 'products/data_modeling/frontend/suspension'@@ -27,6 +28,7 @@ export function MaterializationRunActions({}): JSX.Element | null {const {savedQuery,+ deletingView,dataModelingJobs,startingMaterialization,resumingMaterialization,@@ -43,6 +45,7 @@ export function MaterializationRunActions({} = useValues(materializationJobsLogic({ viewId, kind }))const {refreshMaterialization,+ deleteView,setStartingMaterialization,resumeMaterialization,saveMaterializationChanges,@@ -84,52 +87,103 @@ export function MaterializationRunActions({savedQuery.user_access_level)const refreshReason = materializationRefreshPending ? 'Refreshing materialization status' : undefined+ // Another product owns these views, so the `kind` prop cannot decide on its own: the SQL editor+ // renders this component without it, and an endpoint-origin view then looks like a plain one.+ // The saved query names its owner, and deleting through it either fails or breaks that product.+ const ownerReason = savedQuery.managed_viewset_kind+ ? 'PostHog manages this view. Turn the managed viewset off to delete it.'+ : savedQuery.origin === DataWarehouseSavedQueryOrigin.ENDPOINT+ ? 'This view belongs to an endpoint. Delete the endpoint instead.'+ : undefined+ const deleteLabel = savedQuery.is_materialized ? 'Delete materialized view' : 'Delete view'+ const deleteItem = {+ label: deleteLabel,+ 'data-attr': 'node-detail-delete-view',+ status: 'danger' as const,+ disabledReason:+ accessReason ||+ ownerReason ||+ refreshReason ||+ (deletingView ? 'Deleting view' : undefined) ||+ // The saved query and the runs load independently, so the saved query can arrive first and+ // `running` then reads false because the run list is still empty, not because nothing runs.+ // Deleting through that window leaves a run writing to a view that is gone. A failed request+ // re-enables the item rather than stranding the user, since nothing else retries it on mount.+ (!dataModelingJobs && !dataModelingJobsError ? 'Checking for a running refresh' : undefined) ||+ (running || startingMaterialization ? 'Materialization is currently running' : undefined) ||+ (updatingDataWarehouseSavedQuery || materializationActionLoading ? 'Updating materialization' : undefined),+ onClick: () =>+ LemonDialog.open({+ title: `${deleteLabel} "${savedQuery.name}"?`,+ description: savedQuery.is_materialized+ ? 'This deletes the saved view and its materialized data and stops scheduled refreshes. Queries that use this view will stop working. This cannot be undone.'+ : 'Queries that use this view will stop working. This cannot be undone.',+ primaryButton: { children: deleteLabel, status: 'danger', onClick: deleteView },+ secondaryButton: { children: 'Cancel' },+ }),+ }if (!savedQuery.is_materialized) {const draftError =incrementalDraft.enabled && (!incrementalDraft.incrementalKey || !incrementalDraft.uniqueKey.length)? 'Select the incremental column and unique key columns': undefinedreturn (- <LemonButton- type="primary"- size="small"- loading={materializationActionLoading || materializationRefreshPending}- disabledReason={- accessReason ||- refreshReason ||- (updatingDataWarehouseSavedQuery ? 'Saving materialization settings' : undefined) ||- // Modes with a reason cannot be materialized at all: the endpoint refuses a- // managed viewset, and a view with no node has nothing to schedule through.- modeDisabledReason(savedQuery.sync_frequency_bounds) ||- unsatisfiableReason(savedQuery.sync_frequency_bounds) ||- draftError- }- data-attr="node-detail-materialize"- onClick={() =>- materializeDataWarehouseSavedQuery(- viewId,- defaultCadenceWithin(savedQuery.sync_frequency_bounds, initialSyncFrequency),- !incrementalDraftTouched ||- kind === 'endpoint' ||- !featureFlags[FEATURE_FLAGS.DATA_MODELING_INCREMENTAL_VIEWS]- ? undefined- : incrementalDraft.enabled && incrementalDraft.incrementalKey- ? {- enabled: true,- incremental_key: incrementalDraft.incrementalKey,- unique_key: incrementalDraft.uniqueKey,- lookback_seconds: incrementalDraft.lookbackSeconds,- }- : null- )- }- >- Materialize- </LemonButton>+ <>+ <LemonButton+ type="primary"+ size="small"+ loading={materializationActionLoading || materializationRefreshPending || deletingView}+ disabledReason={+ accessReason ||+ refreshReason ||+ (deletingView ? 'Deleting view' : undefined) ||+ (updatingDataWarehouseSavedQuery ? 'Saving materialization settings' : undefined) ||+ // Modes with a reason cannot be materialized at all: the endpoint refuses a+ // managed viewset, and a view with no node has nothing to schedule through.+ modeDisabledReason(savedQuery.sync_frequency_bounds) ||+ unsatisfiableReason(savedQuery.sync_frequency_bounds) ||+ draftError+ }+ data-attr="node-detail-materialize"+ onClick={() =>+ materializeDataWarehouseSavedQuery(+ viewId,+ defaultCadenceWithin(savedQuery.sync_frequency_bounds, initialSyncFrequency),+ !incrementalDraftTouched ||+ kind === 'endpoint' ||+ !featureFlags[FEATURE_FLAGS.DATA_MODELING_INCREMENTAL_VIEWS]+ ? undefined+ : incrementalDraft.enabled && incrementalDraft.incrementalKey+ ? {+ enabled: true,+ incremental_key: incrementalDraft.incrementalKey,+ unique_key: incrementalDraft.uniqueKey,+ lookback_seconds: incrementalDraft.lookbackSeconds,+ }+ : null+ )+ }+ >+ Materialize+ </LemonButton>+ {kind !== 'endpoint' && (+ <LemonMenu items={[deleteItem]}>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconEllipsis />}+ loading={deletingView}+ aria-label="View actions"+ data-attr="node-detail-view-actions"+ />+ </LemonMenu>+ )}+ </>)}const busyReason =refreshReason ||+ (deletingView ? 'Deleting view' : undefined) ||(updatingDataWarehouseSavedQuery? 'Saving materialization settings': materializationActionLoading@@ -295,6 +349,7 @@ export function MaterializationRunActions({secondaryButton: { children: 'Cancel' },}),},+ deleteItem,]: []),]}@@ -303,6 +358,7 @@ export function MaterializationRunActions({type="secondary"size="small"icon={<IconEllipsis />}+ loading={deletingView}aria-label="Materialization actions"data-attr="node-detail-materialization-actions"/>