: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): refresh materialization status when a run ends (#114225)
posthog[bot]9a918e1a10b4
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.tsindex 7ead28b16893..6c88508c5136 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts@@ -37,6 +37,11 @@ describe('materializationJobsLogic', () => {return button as HTMLElement}+ const setDocumentHidden = (hidden: boolean): void => {+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })+ document.dispatchEvent(new Event('visibilitychange'))+ }+let logic: ReturnType<typeof materializationJobsLogic.build>let checkCalls = 0// Read on every saved-query fetch, so a test can move the saved cadence between reloads.@@ -94,6 +99,7 @@ describe('materializationJobsLogic', () => {logic?.unmount()featureFlagLogic.unmount()jest.useRealTimers()+ delete (document as { hidden?: boolean }).hidden})it.each([@@ -305,8 +311,9 @@ describe('materializationJobsLogic', () => {// 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 () => {+ // window leaves a run writing to a view that is gone. A run started there has no earlier job to+ // tell its own job apart from, so it would stop waiting on the first job it sees.+ it('blocks deletion and runs until the run state is known and re-enables them when runs cannot load', async () => {let fail = falseconst mocks = apiMocks({ isMaterialized: true })let releaseJobs!: () => void@@ -324,11 +331,13 @@ describe('materializationJobsLogic', () => {render(createElement(MaterializationRunActions, { viewId: 'view-1' }))fireEvent.click(buttonByAttr('node-detail-materialization-actions'))expect(buttonByAttr('node-detail-delete-view').getAttribute('aria-disabled')).toBe('true')+ expect(buttonByAttr('node-detail-sync-now').getAttribute('aria-disabled')).toBe('true')fail = truereleaseJobs()await expectLogic(logic).toDispatchActions(['loadDataModelingJobsFailure']).toFinishAllListeners()expect(buttonByAttr('node-detail-delete-view').getAttribute('aria-disabled')).not.toBe('true')+ expect(buttonByAttr('node-detail-sync-now').getAttribute('aria-disabled')).not.toBe('true')})// Regression: the saved query reloads on every jobs poll. Without the once-per-mount guard the@@ -577,7 +586,7 @@ describe('materializationJobsLogic', () => {logic = materializationJobsLogic({ viewId: 'view-1' })logic.mount()await jest.advanceTimersByTimeAsync(0)- const interval = status === 'Running' ? 10000 : 60000+ const interval = status === 'Running' ? 5000 : 60000await jest.advanceTimersByTimeAsync(interval - 1)expect(jobsCalls).toBe(1)fail = true@@ -628,6 +637,49 @@ describe('materializationJobsLogic', () => {expect(logic.values.savedQuery?.is_materialized).toBe(false)expect(logic.values.savedQueryError).toBe(false)})+ it('keeps a started run pending until its job appears or the wait times out, and reloads on tab return', async () => {+ jest.useFakeTimers()+ let jobs = [{ id: 'run-1', status: 'Completed' }]+ let jobsCalls = 0+ const mocks = apiMocks({ isMaterialized: true })+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = () => {+ jobsCalls += 1+ return [200, { count: jobs.length, results: jobs }]+ }+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ logic.actions.setStartingMaterialization(true)+ dataWarehouseViewsLogic.actions.runDataWarehouseSavedQueryFailure('other-view')+ logic.actions.loadDataModelingJobs()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.startingMaterialization).toBe(true)++ jobs = [{ id: 'run-2', status: 'Running' }, ...jobs]+ await jest.advanceTimersByTimeAsync(5000)+ expect(logic.values.startingMaterialization).toBe(false)++ jobs = [+ { id: 'run-2', status: 'Completed' },+ { id: 'run-1', status: 'Completed' },+ ]+ setDocumentHidden(true)+ await jest.advanceTimersByTimeAsync(60000)+ const callsWhileHidden = jobsCalls+ setDocumentHidden(false)+ await jest.advanceTimersByTimeAsync(0)+ expect(jobsCalls).toBe(callsWhileHidden + 1)+ expect(logic.values.dataModelingJobs?.results[0].status).toBe('Completed')++ logic.actions.setStartingMaterialization(true)+ await jest.advanceTimersByTimeAsync(119999)+ expect(logic.values.startingMaterialization).toBe(true)+ await jest.advanceTimersByTimeAsync(1)+ expect(logic.values.startingMaterialization).toBe(false)+ })+it('ignores a saved query response started before a materialization action', async () => {useMocks(apiMocks({ isMaterialized: true }))logic = materializationJobsLogic({ viewId: 'view-1' })diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.tsindex 9030d65861be..0d6206e82e0e 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts@@ -33,8 +33,11 @@ import { DEFAULT_MATERIALIZE_SYNC_FREQUENCY, dataWarehouseViewsLogic } from './dimport { latestSuccessfulSyncAt } from './materializationJobUtils'import { SyncFrequencyValue } from './SyncFrequencySelect'-const ACTIVE_REFRESH_INTERVAL_MS = 10000+const ACTIVE_REFRESH_INTERVAL_MS = 5000const IDLE_REFRESH_INTERVAL_MS = 60000+// The run request returns before the workflow writes the job row, so a run can take a while to show up.+// Give up waiting after this long so the controls do not stay blocked when no job ever appears.+const STARTING_TIMEOUT_MS = 120000export const DEFAULT_JOBS_PAGE_SIZE = 10export interface MaterializationJobsLogicProps {@@ -401,7 +404,7 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([},],})),- reducers({+ reducers(({ props }) => ({jobsPage: [1, { setJobsPage: (_, { page }) => page }],olderJobsPageError: [false, { loadOlderJobsPage: () => false, loadOlderJobsPageFailure: () => true }],deletingView: [false, { deleteView: () => true, finishDeletingView: () => false }],@@ -498,25 +501,13 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([false,{setStartingMaterialization: (_, { starting }: { starting: boolean }) => starting,- // No job exists when the request itself failed, so the job-status reset below never- // fires and the controls would stay disabled until the panel remounts.- runDataWarehouseSavedQueryFailure: () => false,- loadDataModelingJobsSuccess: (- state: boolean,- { dataModelingJobs }: { dataModelingJobs: PaginatedDataModelingJobListApi | null }- ) => {- const currentJobStatus = dataModelingJobs?.results?.[0]?.status- if (- currentJobStatus &&- ['Running', 'Completed', 'Failed', 'Cancelled', 'Skipped'].includes(currentJobStatus)- ) {- return false- }- return state- },+ // No job exists when the request itself failed, so the reset on job arrival never+ // fires and the controls would stay disabled until the starting timeout.+ runDataWarehouseSavedQueryFailure: (state: boolean, { viewId }: { viewId: string }) =>+ viewId === props.viewId ? false : state,},],- }),+ })),selectors({materializationRefreshPending: [(s) => [s.savedQueryRefreshPending, s.jobsRefreshPending],@@ -564,11 +555,26 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([) => latestSuccessfulSyncAt([...(dataModelingJobs?.results ?? []), ...(latestCompletedJob?.results ?? [])]),],}),- afterMount(({ actions, props }) => {+ afterMount(({ actions, cache, props }) => {if (props.viewId) {actions.loadDataModelingJobs()actions.loadSavedQuery()}+ // Background tabs pause the poll timer, and it restarts with its full delay. Reload at once+ // when the user comes back, so the panel does not show a finished run as still running.+ cache.disposables.add(+ () => {+ const onVisibilityChange = (): void => {+ if (!document.hidden && props.viewId) {+ actions.loadDataModelingJobs()+ }+ }+ document.addEventListener('visibilitychange', onVisibilityChange)+ return () => document.removeEventListener('visibilitychange', onVisibilityChange)+ },+ 'visibilityRefresh',+ { pauseOnPageHidden: false }+ )}),propsChanged(({ actions, props }, oldProps) => {if (props.viewId && props.viewId !== oldProps.viewId) {@@ -614,6 +620,26 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([return () => clearTimeout(timeoutId)}, 'dataModelingJobsRefreshTimeout')},+ setStartingMaterialization: ({ starting }) => {+ if (!starting) {+ cache.disposables.dispose('startingMaterializationTimeout')+ return+ }+ cache.newestJobIdBeforeStart = values.dataModelingJobs?.results[0]?.id ?? null+ cache.disposables.add(+ () => {+ const timeoutId = setTimeout(() => actions.setStartingMaterialization(false), STARTING_TIMEOUT_MS)+ return () => clearTimeout(timeoutId)+ },+ 'startingMaterializationTimeout',+ { pauseOnPageHidden: false }+ )+ },+ runDataWarehouseSavedQueryFailure: ({ viewId }) => {+ if (viewId === props.viewId) {+ cache.disposables.dispose('startingMaterializationTimeout')+ }+ },loadDataModelingJobsFailure: () => {actions.scheduleJobsRefresh(IDLE_REFRESH_INTERVAL_MS)},@@ -740,6 +766,10 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([actions.loadDataWarehouseSavedQueries()}cache.newestJobState = newestJobState+ // Until the new run's job row exists, the newest job is the run before the click.+ if (values.startingMaterialization && newestJob && newestJob.id !== cache.newestJobIdBeforeStart) {+ actions.setStartingMaterialization(false)+ }const active = values.startingMaterialization || runningactions.scheduleJobsRefresh(active ? ACTIVE_REFRESH_INTERVAL_MS : IDLE_REFRESH_INTERVAL_MS)},diff --git a/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsx b/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsxindex 2d4a8c21277b..4516028e4492 100644--- a/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsx+++ b/products/data_warehouse/frontend/shared/components/MaterializationRunActions.tsx@@ -87,6 +87,13 @@ export function MaterializationRunActions({savedQuery.user_access_level)const refreshReason = materializationRefreshPending ? 'Refreshing materialization status' : 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 run started in that+ // window has no earlier job to compare against, so it stops waiting on the first job it sees. A+ // failed request re-enables the actions rather than stranding the user, since nothing else+ // retries it on mount.+ const runStateReason = !dataModelingJobs && !dataModelingJobsError ? 'Checking for a running refresh' : 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.@@ -105,11 +112,7 @@ export function MaterializationRunActions({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) ||+ runStateReason ||(running || startingMaterialization ? 'Materialization is currently running' : undefined) ||(updatingDataWarehouseSavedQuery || materializationActionLoading ? 'Updating materialization' : undefined),onClick: () =>@@ -184,6 +187,7 @@ export function MaterializationRunActions({const busyReason =refreshReason ||(deletingView ? 'Deleting view' : undefined) ||+ runStateReason ||(updatingDataWarehouseSavedQuery? 'Saving materialization settings': materializationActionLoading