: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): add model status and Trino job details (#123087)
Jovan Sakovic1a4af3f45439
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9af5e5c99360..37eac1dcdb81 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7469,25 +7469,33 @@ snapshots:products-data-modeling-models-overview--partial-last-page--light:hash: v1.k794b7964.0a510efc77afae6a02c52831583c4c38870a6e9c1a1dcd78c2905ff05933c085.KSDQ61iPt91mJjAozciHJ7_p5ed-dd3IkN5KPYxR204products-data-modeling-models-usage--empty--dark:- hash: v1.k794b7964.18c0ad26660aeabfe409a49668ee77318007a883e8edde9ba4d80338355160c4.9cENDLqBNgbWBwcwOed_5UaQz1HyRlVLupZTqDfYfbE+ hash: v1.k794b7964.794122ef01e1cbdf612c6e898d2746c0edd22f4091d653e611ff9463eec1ab1e.NMB-O3Bzpz-wX1Ehg0HAAq22qfuQtYFyTYRMXj9uCqYproducts-data-modeling-models-usage--empty--light:- hash: v1.k794b7964.be096ff4381492e09c3da8d54206c609c72befd5618a1d3e0c551cb6d0f1e576.qc5ZeMyVOmZZiMW5_TgNNVHznvY3HEW8-dQf-XLxrWQ+ hash: v1.k794b7964.e91d706e4e23e5b8ec059dc94300929628fac3a137f830a3a02ef67bcbc31dbb.auXv2VU9dH-CQxT69mWnchYzq1xq-Txos1Kx60Lmadkproducts-data-modeling-models-usage--error--dark:- hash: v1.k794b7964.fc525bf84886def1051de338491e76c5204dd7ece56dc2b8b322c3e64692e44c.tziVJb9cJG7vFYcFUJbs6uHsNcm4KHJ7idyHWmgu_8A+ hash: v1.k794b7964.96dbec9b2bcade9227cc8d76aefe4eca59e4a3d70fd843d71bcb4904617c28b2.YaVrujmHytJbsK2PROn6O4DgNh9oKLL8YPbf8ymqZ5sproducts-data-modeling-models-usage--error--light:- hash: v1.k794b7964.3eb45cfc31a92bf216e2cac9f1b2afae561ebcbee9212c8c2bb8d262314aef3f.fEKQiIHOXqxZukkfbGgbNuiWFTUjtR7CyNM3WU13p80+ hash: v1.k794b7964.7ad357a4263212e6a943643e84f1b1c4a8fba5688aa88fab825e7c5fea86786c.OgmCM-dKcZI9B2a3jdciMu9KgNFrOJ2YvEYPdzyK9Yc+ products-data-modeling-models-usage--filtered-by-failed-models--dark:+ hash: v1.k794b7964.5227230e2c87030d8ab6d9eb085e338c0559d0519a97df50ee5289465eed6bd1.OpRh3Oj0Tgpq2rgK1mggpK97nNK-3acxpsrAijWCjE0+ products-data-modeling-models-usage--filtered-by-failed-models--light:+ hash: v1.k794b7964.a911a34c17d14853b0fcf2d4c5ca123ce67e6a0eceaebe49b4091f47476f2b95.NAguVEpH6uFZkqvaN67N6T30hy_GwLEB_UaqZGlipnsproducts-data-modeling-models-usage--narrow--dark:- hash: v1.k794b7964.4fad717b5fe2b7729caf0623577cb140fb5566b14137897c7f123a6fa0322489.efpSZxHEV4137a0YaX0t5ZGZm3bvNGQUhgTQ2E3PuCY+ hash: v1.k794b7964.d45bc3ec3b99d69f263bea5e240b82fb8b7558a004a1a1d7960c094397070c1e.mn8t0WeIeeFY6hXdVeIF1cdEqBVfEIF3eRDX719qk-Uproducts-data-modeling-models-usage--narrow--light:- hash: v1.k794b7964.3ac8e20a35a9b3dc80eebecaac95e33b09650194596d6d3c1f8bca5bfdf93269.09Su4MCXEdjI5TNoKQcYkbw67_-PHOJ6F4F7xzWoVWE+ hash: v1.k794b7964.41825b5b570acc1e3a06f7f9a7fc9f2aac5395a537b78334d80f346c47212b45.CXoYoaKXkuVxOZ_wQpXOzXeHtBnJ-uQ1C1ELununJiEproducts-data-modeling-models-usage--populated--dark:- hash: v1.k794b7964.13bc4856822b1758befe9e138af9e5ccb9a5d0626f67884eaa0e28f0f9b45fc9.-FIl8e5Fei8C-XZp3Fmo8Vz7BVAo1N7Iq1hlbJlDWgg+ hash: v1.k794b7964.7347905329382de9904c8dd27995860efae5d121e98ec972b8984a9f71a23f61.W6L5AajpwdhVrG2yMbsOqa_Fh35v2Uezh77MD-ATLUYproducts-data-modeling-models-usage--populated--light:- hash: v1.k794b7964.513c49058b973329230d944342af41d17332f9ec88f6f807f7e7c0184cc233b3.TVTVGPxsNKr7BIIJi--ZCC6rK5bLHiX-FjCWOzef5i0+ hash: v1.k794b7964.8db475e78d40495f09a63dd5eed350a48e57c2d00706b11b6f70c65f19dbed91.bCgqP3mABo0Sm5euLM96_RFSHs7Xpb-ZbX2rsT7ZYmU+ products-data-modeling-models-usage--status-only--dark:+ hash: v1.k794b7964.843b703ee6891ee34efe1197bb6ebd590ea566cba1132f20ae2443ab60799419.MNAGtHUc7xtCMLOn1s_pcXnukRUTHHQCINhQ2rh_foM+ products-data-modeling-models-usage--status-only--light:+ hash: v1.k794b7964.867c9559e44d0e09c4917c577ba9dc1e9e3187ac9a42a34bc6395682e67166f1.F1qdz52LZQrOMsDI-Hbfy-oOd5I9E7Lwgn7NsJFy9x4products-data-modeling-models-usage--unmeasured--dark:- hash: v1.k794b7964.fbccec9254c34a6b3a3141c465e6e794f7c0c4b51b15ab3910619da0e1d61df3.gJtdNulD3Zvx-D5KZ2R-YFrfvlCrRMDpPSkZZ0-Gfgo+ hash: v1.k794b7964.83cfe7f1b96aab125b156e2d22e59b15dc18da9dbf19e7f151fe8b8e8b1527e3.c4MIrGF6GxHQlbYm9Vr7Sq_ZTsTFUCZvxPN9CrDbtu0products-data-modeling-models-usage--unmeasured--light:- hash: v1.k794b7964.c53a65db17e9cbb7c5a8c97d200376ecf2be864f797b7c658195f2a2d515e67d.LKM9CH0fIBA1V4aYUqn28Odwukzp6OW04kJUtuLnY-I+ hash: v1.k794b7964.1943fb020a1510601a2a451da4dd9056e1cf1c27eb08758aee880b5656e03c4e.73PZaJDXWHgo-t9_cM3F4c0Gwpjs9wV11V0dM1_iEogproducts-data-modeling-node-detail-scene--deleted-model--dark:hash: v1.k794b7964.bf008eaa19295f4131e58d639e52c574e724973ac897a20d95c905206ccfe333.8CL_nCzrTvLfheyYXNeMHjX8MI8t_lazxmw_8FtPLu4products-data-modeling-node-detail-scene--deleted-model--light:diff --git a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsxindex 0fa4cb886581..438c5f697943 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx+++ b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx@@ -1,13 +1,15 @@import { useActions, useValues } from 'kea'import { IconRefresh } from '@posthog/icons'-import { LemonBanner, LemonCard, LemonSkeleton, LemonTable, Link } from '@posthog/lemon-ui'+import { LemonBanner, LemonCard, LemonSelect, LemonSkeleton, LemonTable, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'import { humanFriendlyNumber } from 'lib/utils/numbers'@@ -18,7 +20,10 @@ import { userLogic } from 'scenes/userLogic'import { AccessControlLevel, AccessControlResourceType, LogEntryLevel } from '~/types'import { SERVING_ENGINE, suspendedScheduleMessage } from 'products/data_modeling/frontend/suspension'-import type { DataModelingJobApi } from 'products/data_warehouse/frontend/generated/api.schemas'+import {+ DataModelingJobsListEngine,+ 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'@@ -132,9 +137,9 @@ export function MaterializationStatusPanel({dataModelingJobsLoading,jobsPage,jobsPageResults,- olderJobsPageLoading,- olderJobsPageError,- dataModelingJobsError,+ runHistoryLoading,+ runHistoryError,+ selectedRunHistoryEngine,lastSuccessfulSyncAt,startingMaterialization,savedQuery,@@ -147,14 +152,18 @@ export function MaterializationStatusPanel({} = useValues(jobsLogic)const {loadDataModelingJobs,+ loadRunHistoryJobs,setJobsPage,loadOlderJobsPage,+ setSelectedRunHistoryEngine,setInitialSyncFrequency,setIncrementalDraft,setSyncFrequencyDraft,} = useActions(jobsLogic)const { updatingDataWarehouseSavedQuery, materializationActionLoading } = useValues(dataWarehouseViewsLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const managedWarehouseEnabled = !!featureFlags[FEATURE_FLAGS.MANAGED_TRINO_QUERY]const { timezone } = useValues(teamLogic)const { user } = useValues(userLogic)@@ -372,18 +381,41 @@ export function MaterializationStatusPanel({<div><h3 className="mb-0">Run history</h3></div>- <LemonButton- icon={<IconRefresh />}- size="small"- type="secondary"- onClick={() => (jobsPage === 1 ? loadDataModelingJobs() : loadOlderJobsPage())}- loading={jobsPage === 1 ? dataModelingJobsLoading : olderJobsPageLoading}- disabledReason={startingMaterialization ? 'Materialization is starting' : undefined}- tooltip="Refresh runs"- aria-label="Refresh runs"- />+ <div className="flex items-center gap-2">+ {managedWarehouseEnabled ? (+ <LemonSelect+ value={selectedRunHistoryEngine}+ onChange={setSelectedRunHistoryEngine}+ options={[+ { value: DataModelingJobsListEngine.Clickhouse, label: 'ClickHouse' },+ {+ value: DataModelingJobsListEngine.ManagedWarehouse,+ label: 'Managed warehouse',+ },+ ]}+ size="small"+ data-attr="materialization-run-history-engine-filter"+ />+ ) : null}+ <LemonButton+ icon={<IconRefresh />}+ size="small"+ type="secondary"+ onClick={() =>+ jobsPage > 1+ ? loadOlderJobsPage()+ : selectedRunHistoryEngine === DataModelingJobsListEngine.Clickhouse+ ? loadDataModelingJobs()+ : loadRunHistoryJobs()+ }+ loading={runHistoryLoading}+ disabledReason={startingMaterialization ? 'Materialization is starting' : undefined}+ tooltip="Refresh runs"+ aria-label="Refresh runs"+ />+ </div></div>- {(jobsPage === 1 ? dataModelingJobsError : olderJobsPageError) && (+ {runHistoryError && (<LemonBanner type="error">Couldn't load runs. Use Refresh runs to try again.</LemonBanner>)}<LemonTable@@ -405,12 +437,8 @@ export function MaterializationStatusPanel({// 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 || []}+ loading={runHistoryLoading && (jobsPage > 1 || !jobsPageResults?.results?.length)}+ dataSource={jobsPage > 1 && runHistoryError ? [] : jobsPageResults?.results || []}columns={[{title: 'Status',@@ -441,7 +469,21 @@ export function MaterializationStatusPanel({)}- return <LemonTag type={type}>{status}</LemonTag>+ const tag = (+ <LemonTag type={type}>{status === 'Cancelled' ? 'Canceled' : status}</LemonTag>+ )+ return job.error ? (+ <Tooltip+ title={<div className="whitespace-pre-wrap font-mono text-xs">{job.error}</div>}+ interactive+ >+ <span tabIndex={0} aria-label={`${status}. ${job.error}`}>+ {tag}+ </span>+ </Tooltip>+ ) : (+ tag+ )},},{diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.tsindex cc85cc0d887e..9853ad79f25d 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts@@ -1,15 +1,18 @@-import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { act, 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'import api from 'lib/api'+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 { DataModelingJobsListEngine } from 'products/data_warehouse/frontend/generated/api.schemas'import { MaterializationRunActions } from 'products/data_warehouse/frontend/shared/components/MaterializationRunActions'import { dataWarehouseViewsLogic } from './dataWarehouseViewsLogic'@@ -171,9 +174,67 @@ describe('materializationJobsLogic', () => {expect(screen.getByText('Last run')).toBeTruthy()expect(screen.getAllByText('Failed').length).toBeGreaterThan(0)+ expect(screen.getByLabelText('Failed. Query failed')).toBeTruthy()expect(screen.getByText('Materialization').parentElement?.children).toHaveLength(1)})+ it('loads managed warehouse run history without changing the ClickHouse status data', async () => {+ const requests: URLSearchParams[] = []+ const mocks = apiMocks({ isMaterialized: true })+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = (req) => {+ const params = new URL(req.request.url).searchParams+ requests.push(params)+ return [200, { count: 0, results: [] }]+ }+ useMocks(mocks)+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MANAGED_TRINO_QUERY], {+ [FEATURE_FLAGS.MANAGED_TRINO_QUERY]: true,+ })+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadDataModelingJobsSuccess'])++ render(createElement(MaterializationStatusPanel, { viewId: 'view-1', showRunActions: false }))+ expect(document.querySelector('[data-attr="materialization-run-history-engine-filter"]')).toBeTruthy()++ await expectLogic(logic, () =>+ logic.actions.setSelectedRunHistoryEngine(DataModelingJobsListEngine.ManagedWarehouse)+ ).toDispatchActions(['loadRunHistoryJobsSuccess'])++ expect(requests.at(-1)?.get('all_engines')).toBe('true')+ expect(requests.at(-1)?.get('engine')).toBe('managed_warehouse')+ expect(logic.values.dataModelingJobs).toEqual({ count: 0, results: [] })+ })++ it('refreshes the selected managed warehouse history during status refreshes and polling', async () => {+ jest.useFakeTimers()+ const managedRequests: URLSearchParams[] = []+ const mocks = apiMocks({ isMaterialized: true })+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = (req) => {+ const params = new URL(req.request.url).searchParams+ if (params.get('engine') === 'managed_warehouse') {+ managedRequests.push(params)+ }+ return [200, { count: 0, results: [] }]+ }+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ logic.actions.setSelectedRunHistoryEngine(DataModelingJobsListEngine.ManagedWarehouse)+ await jest.advanceTimersByTimeAsync(0)+ const requestsAfterSelection = managedRequests.length++ logic.actions.refreshMaterialization()+ await jest.advanceTimersByTimeAsync(0)+ expect(managedRequests).toHaveLength(requestsAfterSelection + 1)++ logic.actions.scheduleJobsRefresh(100)+ await jest.advanceTimersByTimeAsync(100)+ expect(managedRequests).toHaveLength(requestsAfterSelection + 2)+ })+it('pages through older runs without changing the latest run or growing polling requests', async () => {const mocks = apiMocks({ isMaterialized: true })const requests: string[] = []@@ -211,6 +272,56 @@ describe('materializationJobsLogic', () => {expect(requests).toEqual(['10:0', '10:10', '10:0', '10:0'])})+ it('does not show a cached older page for another engine', async () => {+ const mocks = apiMocks({ isMaterialized: true })+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = (req) => {+ const params = new URL(req.request.url).searchParams+ const engine = params.get('engine') ?? 'clickhouse'+ const offset = Number(params.get('offset'))+ return [+ 200,+ {+ count: 20,+ next: null,+ results: [{ id: `${engine}-${offset}`, status: 'Completed', engine }],+ },+ ]+ }+ 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[0].id).toBe('clickhouse-10')++ await expectLogic(logic, () => {+ logic.actions.setSelectedRunHistoryEngine(DataModelingJobsListEngine.ManagedWarehouse)+ logic.actions.setJobsPage(2)+ expect(logic.values.jobsPageResults).toBeNull()+ expect(logic.values.runHistoryLoading).toBe(true)+ }).toDispatchActions(['loadOlderJobsPageSuccess'])++ expect(logic.values.jobsPageResults?.results[0].id).toBe('managed_warehouse-10')+ })++ it('keeps cached page-one history visible after a refresh error', async () => {+ const mocks = apiMocks({ isMaterialized: true })+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = [+ 200,+ { count: 1, results: [{ id: 'run-1', status: 'Completed' }] },+ ]+ useMocks(mocks)+ logic = materializationJobsLogic({ viewId: 'view-1' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSavedQuerySuccess', 'loadDataModelingJobsSuccess'])+ render(createElement(MaterializationStatusPanel, { viewId: 'view-1', showRunActions: false }))++ act(() => logic.actions.loadDataModelingJobsFailure('Refresh failed'))++ expect(screen.getByText("Couldn't load runs. Use Refresh runs to try again.")).toBeTruthy()+ expect(screen.getAllByText('Completed').length).toBeGreaterThan(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([diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.tsindex 8899dc802896..f8c6c2b16010 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.ts@@ -24,6 +24,7 @@ import type { DataWarehouseSavedQuery } from '~/types'import { DataModelingSyncInterval, DataWarehouseSavedQueryIncrementalCheck } from '~/types'import { dataModelingJobsList, warehouseSavedQueriesResumeCreate } from 'products/data_warehouse/frontend/generated/api'+import { DataModelingJobsListEngine } from 'products/data_warehouse/frontend/generated/api.schemas'import type {DataModelingJobApi,PaginatedDataModelingJobListApi,@@ -45,6 +46,19 @@ const IDLE_REFRESH_INTERVAL_MS = 60000const STARTING_TIMEOUT_MS = 120000export const DEFAULT_JOBS_PAGE_SIZE = 10+interface OlderJobsPageResult {+ engine: DataModelingJobsListEngine+ page: number+ jobs: PaginatedDataModelingJobListApi+}++function runHistoryEngineParams(engine: DataModelingJobsListEngine): {+ all_engines?: boolean+ engine?: DataModelingJobsListEngine+} {+ return engine === DataModelingJobsListEngine.ManagedWarehouse ? { all_engines: true, engine } : {}+}+function isNewRunVisible(newestJob: DataModelingJobApi | undefined, previousJobId: string | null | undefined): boolean {return !!newestJob && newestJob.id !== previousJobId}@@ -74,16 +88,22 @@ export interface materializationJobsLogicValues {latestCompletedJob: PaginatedDataModelingJobListApi | nulllatestCompletedJobLoading: booleanmaterializationRefreshPending: boolean- olderJobsPage: PaginatedDataModelingJobListApi | null+ olderJobsPage: OlderJobsPageResult | nullolderJobsPageError: booleanolderJobsPageLoading: booleanrefreshModeChanged: booleanresumingMaterialization: boolean+ runHistoryError: boolean+ runHistoryJobs: PaginatedDataModelingJobListApi | null+ runHistoryJobsError: boolean+ runHistoryJobsLoading: boolean+ runHistoryLoading: booleansavedQuery: DataWarehouseSavedQuery | nullsavedQueryError: booleansavedQueryLoading: booleansavedQueryRefreshPending: booleansavingMaterialization: boolean+ selectedRunHistoryEngine: DataModelingJobsListEnginestartingMaterialization: booleansyncFrequencyDraft: SyncFrequencyValue | null}@@ -199,10 +219,33 @@ export interface materializationJobsLogicActions {errorObject?: any}loadOlderJobsPageSuccess: (- olderJobsPage: PaginatedDataModelingJobListApi,+ olderJobsPage: {+ engine: DataModelingJobsListEngine+ jobs: PaginatedDataModelingJobListApi+ page: number+ },+ payload?: void+ ) => {+ olderJobsPage: {+ engine: DataModelingJobsListEngine+ jobs: PaginatedDataModelingJobListApi+ page: number+ }+ payload?: void+ }+ loadRunHistoryJobs: (_: void) => void+ loadRunHistoryJobsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRunHistoryJobsSuccess: (+ runHistoryJobs: PaginatedDataModelingJobListApi,payload?: void) => {- olderJobsPage: PaginatedDataModelingJobListApi+ runHistoryJobs: PaginatedDataModelingJobListApipayload?: void}loadSavedQuery: (_: void) => void@@ -247,6 +290,9 @@ export interface materializationJobsLogicActions {setResumingMaterialization: (resuming: boolean) => {resuming: boolean}+ setSelectedRunHistoryEngine: (engine: DataModelingJobsListEngine) => {+ engine: DataModelingJobsListEngine+ }setStartingMaterialization: (starting: boolean) => {starting: boolean}@@ -272,9 +318,25 @@ export interface materializationJobsLogicMeta {) => booleanjobsPageResults: (jobsPage: number,+ selectedRunHistoryEngine: DataModelingJobsListEngine,dataModelingJobs: PaginatedDataModelingJobListApi | null,- olderJobsPage: PaginatedDataModelingJobListApi | null+ runHistoryJobs: PaginatedDataModelingJobListApi | null,+ olderJobsPage: OlderJobsPageResult | null) => PaginatedDataModelingJobListApi | null+ runHistoryError: (+ selectedRunHistoryEngine: DataModelingJobsListEngine,+ dataModelingJobsError: boolean,+ runHistoryJobsError: boolean,+ olderJobsPageError: boolean,+ jobsPage: number+ ) => boolean+ runHistoryLoading: (+ selectedRunHistoryEngine: DataModelingJobsListEngine,+ dataModelingJobsLoading: boolean,+ runHistoryJobsLoading: boolean,+ olderJobsPageLoading: boolean,+ jobsPage: number+ ) => booleanlastSuccessfulSyncAt: (dataModelingJobs: PaginatedDataModelingJobListApi | null,latestCompletedJob: PaginatedDataModelingJobListApi | null@@ -313,6 +375,7 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([actions({refreshMaterialization: true,setJobsPage: (page: number) => ({ page }),+ setSelectedRunHistoryEngine: (engine: DataModelingJobsListEngine) => ({ engine }),deleteView: true,finishDeletingView: true,scheduleJobsRefresh: (delay: number) => ({ delay }),@@ -381,6 +444,21 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([},},],+ runHistoryJobs: [+ null as PaginatedDataModelingJobListApi | null,+ {+ loadRunHistoryJobs: async (_: void, breakpoint) => {+ const jobs = await dataModelingJobsList(String(ApiConfig.getCurrentTeamId()), {+ saved_query_id: props.viewId,+ limit: DEFAULT_JOBS_PAGE_SIZE,+ offset: 0,+ ...runHistoryEngineParams(values.selectedRunHistoryEngine),+ })+ breakpoint()+ return jobs+ },+ },+ ],// 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: [@@ -399,22 +477,30 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([},],olderJobsPage: [- null as PaginatedDataModelingJobListApi | null,+ null as OlderJobsPageResult | null,{loadOlderJobsPage: async (_: void, breakpoint) => {+ const engine = values.selectedRunHistoryEngine+ const page = values.jobsPageconst jobs = await dataModelingJobsList(String(ApiConfig.getCurrentTeamId()), {saved_query_id: props.viewId,limit: DEFAULT_JOBS_PAGE_SIZE,- offset: (values.jobsPage - 1) * DEFAULT_JOBS_PAGE_SIZE,+ offset: (page - 1) * DEFAULT_JOBS_PAGE_SIZE,+ ...runHistoryEngineParams(engine),})breakpoint()- return jobs+ return { engine, page, jobs }},},],})),reducers(({ props }) => ({- jobsPage: [1, { setJobsPage: (_, { page }) => page }],+ jobsPage: [1, { setJobsPage: (_, { page }) => page, setSelectedRunHistoryEngine: () => 1 }],+ selectedRunHistoryEngine: [+ DataModelingJobsListEngine.Clickhouse as DataModelingJobsListEngine,+ { setSelectedRunHistoryEngine: (_, { engine }) => engine },+ ],+ runHistoryJobsError: [false, { loadRunHistoryJobs: () => false, loadRunHistoryJobsFailure: () => true }],olderJobsPageError: [false, { loadOlderJobsPage: () => false, loadOlderJobsPageFailure: () => true }],deletingView: [false, { deleteView: () => true, finishDeletingView: () => false }],savedQueryError: [@@ -549,12 +635,61 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([(modeChanged || (frequency !== null && frequency !== (savedQuery.sync_frequency || 'never'))),],jobsPageResults: [- (s) => [s.jobsPage, s.dataModelingJobs, s.olderJobsPage],+ (s) => [s.jobsPage, s.selectedRunHistoryEngine, s.dataModelingJobs, s.runHistoryJobs, s.olderJobsPage],(page: number,+ engine: DataModelingJobsListEngine,latest: PaginatedDataModelingJobListApi | null,- older: PaginatedDataModelingJobListApi | null- ): PaginatedDataModelingJobListApi | null => (page === 1 ? latest : older),+ filtered: PaginatedDataModelingJobListApi | null,+ older: OlderJobsPageResult | null+ ): PaginatedDataModelingJobListApi | null => {+ if (page === 1) {+ return engine === DataModelingJobsListEngine.Clickhouse ? latest : filtered+ }+ return older?.engine === engine && older.page === page ? older.jobs : null+ },+ ],+ runHistoryError: [+ (s) => [+ s.selectedRunHistoryEngine,+ s.dataModelingJobsError,+ s.runHistoryJobsError,+ s.olderJobsPageError,+ s.jobsPage,+ ],+ (+ engine: DataModelingJobsListEngine,+ clickhouseError: boolean,+ managedError: boolean,+ olderError: boolean,+ page: number+ ): boolean =>+ page > 1+ ? olderError+ : engine === DataModelingJobsListEngine.Clickhouse+ ? clickhouseError+ : managedError,+ ],+ runHistoryLoading: [+ (s) => [+ s.selectedRunHistoryEngine,+ s.dataModelingJobsLoading,+ s.runHistoryJobsLoading,+ s.olderJobsPageLoading,+ s.jobsPage,+ ],+ (+ engine: DataModelingJobsListEngine,+ clickhouseLoading: boolean,+ managedLoading: boolean,+ olderLoading: boolean,+ page: number+ ): boolean =>+ page > 1+ ? olderLoading+ : engine === DataModelingJobsListEngine.Clickhouse+ ? clickhouseLoading+ : managedLoading,],lastSuccessfulSyncAt: [(s) => [s.dataModelingJobs, s.latestCompletedJob],@@ -564,7 +699,7 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([) => latestSuccessfulSyncAt([...(dataModelingJobs?.results ?? []), ...(latestCompletedJob?.results ?? [])]),],}),- afterMount(({ actions, cache, props }) => {+ afterMount(({ actions, cache, props, values }) => {if (props.viewId) {actions.loadDataModelingJobs()actions.loadSavedQuery()@@ -576,6 +711,12 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([const onVisibilityChange = (): void => {if (!document.hidden && props.viewId) {actions.loadDataModelingJobs()+ if (+ values.jobsPage === 1 &&+ values.selectedRunHistoryEngine === DataModelingJobsListEngine.ManagedWarehouse+ ) {+ actions.loadRunHistoryJobs()+ }}}document.addEventListener('visibilitychange', onVisibilityChange)@@ -593,12 +734,21 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([}),listeners(({ actions, cache, props, values }) => ({setJobsPage: () => {- if (values.jobsPage === 1) {+ if (values.jobsPage === 1 && values.selectedRunHistoryEngine === DataModelingJobsListEngine.Clickhouse) {actions.loadDataModelingJobs()+ } else if (values.jobsPage === 1) {+ actions.loadRunHistoryJobs()} else {actions.loadOlderJobsPage()}},+ setSelectedRunHistoryEngine: () => {+ if (values.selectedRunHistoryEngine === DataModelingJobsListEngine.Clickhouse) {+ actions.loadDataModelingJobs()+ } else {+ actions.loadRunHistoryJobs()+ }+ },deleteView: () => actions.deleteDataWarehouseSavedQuery(props.viewId),deleteDataWarehouseSavedQuerySuccess: ({ payload }) => {if (payload === props.viewId && values.deletingView) {@@ -619,13 +769,27 @@ export const materializationJobsLogic = kea<materializationJobsLogicType>([refreshMaterialization: () => {actions.loadSavedQuery()actions.loadDataModelingJobs()+ if (+ values.jobsPage === 1 &&+ values.selectedRunHistoryEngine === DataModelingJobsListEngine.ManagedWarehouse+ ) {+ actions.loadRunHistoryJobs()+ }},loadDataModelingJobs: () => {cache.disposables.dispose('dataModelingJobsRefreshTimeout')},scheduleJobsRefresh: ({ delay }) => {cache.disposables.add(() => {- const timeoutId = setTimeout(() => actions.loadDataModelingJobs(), delay)+ const timeoutId = setTimeout(() => {+ actions.loadDataModelingJobs()+ if (+ values.jobsPage === 1 &&+ values.selectedRunHistoryEngine === DataModelingJobsListEngine.ManagedWarehouse+ ) {+ actions.loadRunHistoryJobs()+ }+ }, delay)return () => clearTimeout(timeoutId)}, 'dataModelingJobsRefreshTimeout')},diff --git a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.pyindex a66aae92124e..224422ac6e65 100644--- a/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py+++ b/posthog/temporal/data_modeling/activities/materialize_view_managed_warehouse.py@@ -107,6 +107,7 @@ class ManagedWarehouseShadowResult:file_size_delta_bytes: int = 0run_mode: str = UNKNOWN_RUN_MODEread_bytes: int | None = None+ cpu_microseconds: int | None = Nonedef _failed_run_mode(plan: WritePlan | None, use_trino: bool) -> str:@@ -246,7 +247,10 @@ def _resolve_managed_warehouse_job(job_id: str, result: "ManagedWarehouseShadowRjob.error = result.errorcompleted_at = dt.datetime.now(dt.UTC)job.read_bytes = result.read_bytes- job.usage_updated_at = completed_at if result.read_bytes is not None else None+ job.cpu_microseconds = result.cpu_microseconds+ job.usage_updated_at = (+ completed_at if result.read_bytes is not None or result.cpu_microseconds is not None else None+ )job.last_run_at = completed_atjob.save()return job.engine@@ -278,6 +282,7 @@ async def _materialize_view_managed_warehouse(s3_secrets: tuple[DuckLakeS3Secret, ...] = ()plan: WritePlan | None = Noneprocessed_bytes: list[int] = []+ cpu_milliseconds: list[int] = []try:from products.managed_warehouse.backend.facade.client import execute_ducklake_create_table, execute_trino_model@@ -301,6 +306,7 @@ async def _materialize_view_managed_warehouse(source_query=saved_query.query,incremental=_trino_incremental_write(plan),on_processed_bytes=processed_bytes.append,+ on_cpu_milliseconds=cpu_milliseconds.append,)if plan.config is not None:# A quiet window writes nothing, so it records the run without moving the watermark.@@ -354,6 +360,7 @@ async def _materialize_view_managed_warehouse(file_size_delta_bytes=result.file_size_delta_bytes,run_mode=INCREMENTAL_RUN_MODE if inputs.use_trino and result.merged else FULL_REFRESH_RUN_MODE,read_bytes=_total_read_bytes(processed_bytes),+ cpu_microseconds=_total_cpu_microseconds(cpu_milliseconds),)job_engine = await _resolve_managed_warehouse_job(inputs.job_id, shadow_result)await clear_node_suspension_for_engine(@@ -403,6 +410,7 @@ async def _materialize_view_managed_warehouse(error=str(e),run_mode=_failed_run_mode(plan, inputs.use_trino),read_bytes=_total_read_bytes(processed_bytes),+ cpu_microseconds=_total_cpu_microseconds(cpu_milliseconds),)if plan is not None and plan.incremental:# The merge may have stopped partway or failed on a schema change. Rebuilding next run@@ -434,6 +442,10 @@ def _total_read_bytes(processed_bytes: list[int]) -> int | None:return sum(processed_bytes) if processed_bytes else None+def _total_cpu_microseconds(cpu_milliseconds: list[int]) -> int | None:+ return sum(cpu_milliseconds) * 1_000 if cpu_milliseconds else None++def _trino_incremental_write(plan: WritePlan) -> TrinoIncrementalWrite | None:if plan.config is None:return Nonediff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 8daf14bf2b1a..f2c721eab764 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -200,6 +200,8 @@ class TestMaterializeViewManagedWarehouseActivity:def execute_trino_model(**kwargs: Any) -> DuckLakeTableResult:kwargs["on_processed_bytes"](300)kwargs["on_processed_bytes"](45)+ kwargs["on_cpu_milliseconds"](20)+ kwargs["on_cpu_milliseconds"](5)if compile_error is not None:raise compile_errorreturn DuckLakeTableResult(schema_name="shadow_models", table_name="test_model", row_count=12)@@ -233,11 +235,12 @@ class TestMaterializeViewManagedWarehouseActivity:source_query=executable_query,incremental=None,on_processed_bytes=unittest.mock.ANY,+ on_cpu_milliseconds=unittest.mock.ANY,)legacy_execute.assert_not_called()await database_sync_to_async(ajob.refresh_from_db)()assert ajob.read_bytes == 345- assert ajob.read_bytes == 345+ assert ajob.cpu_microseconds == 25_000assert ajob.usage_updated_at is not Noneassert capture.called is error_trackedif compile_error is not None:diff --git a/products/data_modeling/backend/logic/usage.py b/products/data_modeling/backend/logic/usage.pyindex 08dbdd9d7dbb..bbbbe0446a31 100644--- a/products/data_modeling/backend/logic/usage.py+++ b/products/data_modeling/backend/logic/usage.py@@ -22,22 +22,42 @@ class EngineUsage(TypedDict):query_count: int | None+class ModelStatusModel(TypedDict):+ saved_query_id: UUID+ name: str+ deleted: bool+++class ModelStatusBreakdown(TypedDict):+ engine: DataModelingJobEngine+ status: DataModelingJobStatus+ count: int+ models: list[ModelStatusModel]++class ModelUsage:USAGE_FIELDS = ("runs", "measured_runs", "read_bytes", "read_rows", "cpu_microseconds", "query_count")COUNT_USAGE_FIELDS = ("runs", "measured_runs")@staticmethod- def jobs(+ def all_jobs(team_id: int, start: datetime, end: datetime, engines: tuple[DataModelingJobEngine, ...]) -> QuerySet[DataModelingJob]:return DataModelingJob.objects.filter(team_id=team_id,engine__in=engines,- status__in=[DataModelingJobStatus.COMPLETED, DataModelingJobStatus.FAILED, DataModelingJobStatus.CANCELLED],last_run_at__gte=start,last_run_at__lt=end,)+ @classmethod+ def jobs(+ cls, team_id: int, start: datetime, end: datetime, engines: tuple[DataModelingJobEngine, ...]+ ) -> QuerySet[DataModelingJob]:+ return cls.all_jobs(team_id, start, end, engines).filter(+ status__in=[DataModelingJobStatus.COMPLETED, DataModelingJobStatus.FAILED, DataModelingJobStatus.CANCELLED]+ )+@staticmethoddef aggregates(*, prefix: str = "", engine: DataModelingJobEngine | None = None) -> dict[str, Count | Sum]:engine_filter = Q(engine=engine) if engine else Q()@@ -78,6 +98,36 @@ class ModelUsage:def empty_usage(cls, prefix: str = "") -> dict[str, int | None]:return {f"{prefix}{field}": 0 if field in cls.COUNT_USAGE_FIELDS else None for field in cls.USAGE_FIELDS}+ @staticmethod+ def status_breakdown(jobs: QuerySet[DataModelingJob]) -> list[ModelStatusBreakdown]:+ latest_jobs = (+ jobs.filter(saved_query_id__isnull=False)+ .select_related("saved_query")+ .only("saved_query_id", "engine", "status", "saved_query__name", "saved_query__deleted")+ .order_by("saved_query_id", "engine", "-last_run_at", "-created_at")+ .distinct("saved_query_id", "engine")+ )+ groups: dict[tuple[DataModelingJobEngine, DataModelingJobStatus], list[ModelStatusModel]] = {}+ for job in latest_jobs:+ if job.saved_query is None or job.saved_query_id is None:+ continue+ key = (DataModelingJobEngine(job.engine), DataModelingJobStatus(job.status))+ groups.setdefault(key, []).append(+ ModelStatusModel(+ saved_query_id=job.saved_query_id,+ name=job.saved_query.name or "Untitled model",+ deleted=job.saved_query.deleted is not False,+ )+ )++ for models in groups.values():+ models.sort(key=lambda model: (model["name"].lower(), str(model["saved_query_id"])))++ return [+ ModelStatusBreakdown(engine=engine, status=status, count=len(models), models=models)+ for (engine, status), models in sorted(groups.items())+ ]+@classmethoddef get(cls,@@ -93,6 +143,7 @@ class ModelUsage:end = datetime.combine(end_date, time.min, tzinfo=UTC)range_days = (end_date - start_date).daysjobs = cls.jobs(team_id, start, end, engines).filter(saved_query_id__in=saved_query_ids)+ status_jobs = cls.all_jobs(team_id, start, end, engines).filter(saved_query_id__in=saved_query_ids)overview = jobs.aggregate(**cls.aggregates())usage_updated_at = jobs.aggregate(latest=Max("usage_updated_at"))["latest"]daily = {@@ -147,6 +198,7 @@ class ModelUsage:for row in rows],"count": count,+ "status_breakdown": cls.status_breakdown(status_jobs),"usage_updated_at": usage_updated_at,}diff --git a/products/data_modeling/backend/presentation/views/usage.py b/products/data_modeling/backend/presentation/views/usage.pyindex 6cce7099459c..457763f519d5 100644--- a/products/data_modeling/backend/presentation/views/usage.py+++ b/products/data_modeling/backend/presentation/views/usage.py@@ -1,4 +1,5 @@from datetime import UTC, datetime, timedelta+from uuid import UUIDfrom django.db import models@@ -38,11 +39,28 @@ class ModelUsageQuerySerializer(serializers.Serializer):default=ModelUsageEngine.CLICKHOUSE,help_text="Materialization engine. All combines ClickHouse and managed warehouse usage.",)- saved_query_id = serializers.UUIDField(- required=False, allow_null=True, help_text="Limit usage to one accessible materialized view."+ saved_query_ids = serializers.CharField(+ required=False, help_text="Comma-separated materialized view IDs. Usage is limited to accessible views.")+ saved_query_id = serializers.UUIDField(required=False, help_text="Limit usage to one accessible materialized view.")++ def validate_saved_query_ids(self, value: str) -> list[UUID]:+ values = [item.strip() for item in value.split(",") if item.strip()]+ if not values:+ raise serializers.ValidationError("Select at least one materialized view.")+ try:+ return [UUID(item) for item in values]+ except ValueError as error:+ raise serializers.ValidationError("Enter valid materialized view IDs.") from errordef validate(self, attrs: dict) -> dict:+ saved_query_id = attrs.get("saved_query_id")+ if saved_query_id is not None:+ if "saved_query_ids" in attrs:+ raise serializers.ValidationError(+ {"saved_query_id": "Use saved_query_id or saved_query_ids, not both."}+ )+ attrs["saved_query_ids"] = [saved_query_id]days = attrs.get("days")date_from = attrs.get("date_from")date_to = attrs.get("date_to")@@ -98,6 +116,19 @@ class ModelUsageRowSerializer(ModelUsageTotalsSerializer):engines = ModelUsageEngineSerializer(many=True, help_text="Usage totals for each selected engine.")+class ModelStatusModelSerializer(serializers.Serializer):+ saved_query_id = serializers.UUIDField(help_text="Model ID.")+ name = serializers.CharField(help_text="Model name.")+ deleted = serializers.BooleanField(help_text="Whether this model has been deleted.")+++class ModelStatusBreakdownSerializer(serializers.Serializer):+ engine = serializers.CharField(help_text="Materialization engine: clickhouse or managed_warehouse.")+ status = serializers.CharField(help_text="Status of the latest run for the model and engine in this range.")+ count = serializers.IntegerField(help_text="Number of models whose latest run has this status.")+ models = ModelStatusModelSerializer(many=True, help_text="Models whose latest run has this status.")++class ModelUsageSerializer(serializers.Serializer):date_from = serializers.DateField(help_text="Inclusive UTC start date.")date_to = serializers.DateField(help_text="Exclusive UTC end date. Today's incomplete usage is excluded.")@@ -105,6 +136,9 @@ class ModelUsageSerializer(serializers.Serializer):trends = ModelUsageDaySerializer(many=True, help_text="Daily usage, attributed to when each run finished.")models = ModelUsageRowSerializer(many=True, help_text="Model breakdown, highest measured bytes first.")count = serializers.IntegerField(help_text="Total number of models in the breakdown.")+ status_breakdown = ModelStatusBreakdownSerializer(+ many=True, help_text="Latest run status for each model and engine in the selected complete-day range."+ )usage_updated_at = serializers.DateTimeField(allow_null=True, help_text="Latest usage collection timestamp in this range.")@@ -123,8 +157,8 @@ class ModelUsageViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def list(self, request: ValidatedRequest, **kwargs: object) -> response.Response:query_data = request.validated_query_datasaved_queries = self.get_queryset()- if saved_query_id := query_data.get("saved_query_id"):- saved_queries = saved_queries.filter(id=saved_query_id)+ if saved_query_ids := query_data.get("saved_query_ids"):+ saved_queries = saved_queries.filter(id__in=saved_query_ids)selected_engine = query_data["engine"]engines = ((DataModelingJobEngine.CLICKHOUSE, DataModelingJobEngine.MANAGED_WAREHOUSE)diff --git a/products/data_modeling/backend/tests/api/test_usage.py b/products/data_modeling/backend/tests/api/test_usage.pyindex df5083fb2513..6625f9b28f03 100644--- a/products/data_modeling/backend/tests/api/test_usage.py+++ b/products/data_modeling/backend/tests/api/test_usage.py@@ -59,6 +59,22 @@ class TestModelUsageValidation(SimpleTestCase):serializer = ModelUsageQuerySerializer(data={"date_from": "2026-10-01", "date_to": "9999-12-31"})self.assertTrue(serializer.is_valid(), serializer.errors)+ def test_normalizes_legacy_saved_query_id(self) -> None:+ saved_query_id = UUID(int=1)+ serializer = ModelUsageQuerySerializer(data={"saved_query_id": str(saved_query_id)})++ self.assertTrue(serializer.is_valid(), serializer.errors)+ self.assertEqual(serializer.validated_data["saved_query_ids"], [saved_query_id])++ def test_rejects_single_and_multiple_saved_query_filters(self) -> None:+ saved_query_id = UUID(int=1)+ serializer = ModelUsageQuerySerializer(+ data={"saved_query_id": str(saved_query_id), "saved_query_ids": str(saved_query_id)}+ )++ self.assertFalse(serializer.is_valid())+ self.assertIn("saved_query_id", serializer.errors)+@time_machine.travel("2026-10-16T12:00:00Z", tick=False)class TestModelUsage(WarehouseAccessControlTestMixin):@@ -78,7 +94,9 @@ class TestModelUsage(WarehouseAccessControlTestMixin):}base = {"team": self.team, "saved_query": model, "status": "Completed", "last_run_at": finished}DataModelingJob.objects.create(**base, **measured)- DataModelingJob.objects.create(**{**base, "status": "Failed"})+ DataModelingJob.objects.create(+ **{**base, "status": "Failed", "last_run_at": finished + timedelta(seconds=1)}, error="Query failed"+ )DataModelingJob.objects.create(**{**base, "status": "Running"}, **measured)managed = DataModelingJob.objects.create(**{**base, "engine": "managed_warehouse"}, read_bytes=4096, usage_updated_at=finished@@ -106,6 +124,23 @@ class TestModelUsage(WarehouseAccessControlTestMixin):self.assertEqual(data["trends"][-1]["engines"][0]["engine"], "clickhouse")self.assertEqual(data["models"][0]["name"], "daily_orders")self.assertEqual(data["count"], 1)+ self.assertEqual(+ data["status_breakdown"],+ [+ {+ "engine": "clickhouse",+ "status": "Failed",+ "count": 1,+ "models": [+ {+ "saved_query_id": str(model.id),+ "name": "daily_orders",+ "deleted": False,+ }+ ],+ }+ ],+ )combined = self.client.get(f"/api/projects/{self.team.id}/data_modeling_usage/", {"days": 7, "engine": "all"}@@ -121,6 +156,35 @@ class TestModelUsage(WarehouseAccessControlTestMixin):[(item["engine"], item["read_bytes"]) for item in combined["models"][0]["engines"]],[("clickhouse", 1024), ("managed_warehouse", managed.read_bytes)],)+ self.assertEqual(+ combined["status_breakdown"],+ [+ {+ "engine": "clickhouse",+ "status": "Failed",+ "count": 1,+ "models": [+ {+ "saved_query_id": str(model.id),+ "name": "daily_orders",+ "deleted": False,+ }+ ],+ },+ {+ "engine": "managed_warehouse",+ "status": "Completed",+ "count": 1,+ "models": [+ {+ "saved_query_id": str(model.id),+ "name": "daily_orders",+ "deleted": False,+ }+ ],+ },+ ],+ )managed_only = self.client.get(f"/api/projects/{self.team.id}/data_modeling_usage/", {"days": 7, "engine": "managed_warehouse"}@@ -129,14 +193,53 @@ class TestModelUsage(WarehouseAccessControlTestMixin):self.assertEqual(managed_only["overview"]["read_bytes"], 4096)self.assertEqual([item["engine"] for item in managed_only["models"][0]["engines"]], ["managed_warehouse"])+ second_model = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="weekly_orders", query={"kind": "HogQLQuery", "query": "SELECT 1"}+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=second_model,+ status="Completed",+ last_run_at=finished,+ read_bytes=2048,+ usage_updated_at=finished,+ )filtered = self.client.get(f"/api/projects/{self.team.id}/data_modeling_usage/",- {"days": 7, "engine": "all", "saved_query_id": model.id},+ {"days": 7, "engine": "all", "saved_query_ids": f"{model.id},{second_model.id}"},).json()- self.assertEqual(filtered["count"], 1)+ self.assertEqual(filtered["count"], 2)+ self.assertEqual(+ {row["saved_query_id"] for row in filtered["models"]},+ {str(model.id), str(second_model.id)},+ )+ legacy_filtered = self.client.get(+ f"/api/projects/{self.team.id}/data_modeling_usage/",+ {"days": 7, "engine": "all", "saved_query_id": str(second_model.id)},+ ).json()+ self.assertEqual(legacy_filtered["count"], 1)+ self.assertEqual(legacy_filtered["models"][0]["saved_query_id"], str(second_model.id))invalid = self.client.get(f"/api/projects/{self.team.id}/data_modeling_usage/", {"days": 91})self.assertEqual(invalid.status_code, 400)+ def test_status_breakdown_includes_a_model_without_finished_runs(self) -> None:+ model = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="running_model", query={"kind": "HogQLQuery", "query": "SELECT 1"}+ )+ DataModelingJob.objects.create(+ team=self.team,+ saved_query=model,+ status="Running",+ last_run_at=datetime(2026, 10, 15, 20, tzinfo=UTC),+ )++ data = self.client.get(f"/api/projects/{self.team.id}/data_modeling_usage/", {"days": 7}).json()++ self.assertEqual(data["overview"]["runs"], 0)+ self.assertEqual(data["status_breakdown"][0]["status"], "Running")+ self.assertEqual(data["status_breakdown"][0]["count"], 1)+ self.assertEqual(data["status_breakdown"][0]["models"][0]["name"], "running_model")+def test_model_breakdown_paginates_without_changing_totals(self) -> None:finished = datetime(2026, 10, 15, 20, tzinfo=UTC)model_ids = []@@ -228,4 +331,11 @@ class TestModelUsage(WarehouseAccessControlTestMixin):self.assertEqual(data["overview"]["runs"], 1)self.assertEqual(data["trends"][-1]["read_bytes"], 100)self.assertEqual(data["count"], 1)+ self.assertEqual(+ [(group["engine"], group["status"], group["count"]) for group in data["status_breakdown"]],+ [("clickhouse", "Completed", 1)],+ )+ self.assertEqual(+ [model["saved_query_id"] for model in data["status_breakdown"][0]["models"]], [str(visible.id)]+ )self.assertEqual([row["saved_query_id"] for row in data["models"]], [str(visible.id)])diff --git a/products/data_modeling/frontend/MaterializationJobsTable.tsx b/products/data_modeling/frontend/MaterializationJobsTable.tsxindex a63606e22681..e0dd817ae672 100644--- a/products/data_modeling/frontend/MaterializationJobsTable.tsx+++ b/products/data_modeling/frontend/MaterializationJobsTable.tsx@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'import { TZLabel } from 'lib/components/TZLabel'import { LinkPrimitive } from 'lib/lemon-ui/Link/Link'+import { Tooltip } from 'lib/lemon-ui/Tooltip'import {Badge,Button,@@ -42,6 +43,7 @@ import { urls } from 'scenes/urls'import { DataModelingJobsListStatus } from 'products/data_warehouse/frontend/generated/api.schemas'import { MATERIALIZATION_ENGINE_LABELS, MATERIALIZATION_JOBS_PAGE_SIZE, modelsUsageLogic } from './modelsUsageLogic'+import { UsageNotAvailable } from './UsageNotAvailable'const STATUS_VARIANTS: Record<string, 'success' | 'destructive' | 'warning' | 'default'> = {Completed: 'success',@@ -51,6 +53,22 @@ const STATUS_VARIANTS: Record<string, 'success' | 'destructive' | 'warning' | 'dSkipped: 'default',}+function JobStatus({ status, error }: { status: string; error: string | null }): JSX.Element {+ const badge = (+ <Badge variant={STATUS_VARIANTS[status] ?? 'default'}>{status === 'Cancelled' ? 'Canceled' : status}</Badge>+ )++ return error ? (+ <Tooltip title={<span className="whitespace-pre-wrap">{error}</span>} interactive>+ <span tabIndex={0} aria-label={`${status}. ${error}`}>+ {badge}+ </span>+ </Tooltip>+ ) : (+ badge+ )+}+export function MaterializationJobsTable({savedQueryIdToNodeId,}: {@@ -156,9 +174,7 @@ export function MaterializationJobsTable({)}</TableCell><TableCell>- <Badge variant={STATUS_VARIANTS[job.status] ?? 'default'}>- {job.status === 'Cancelled' ? 'Canceled' : job.status}- </Badge>+ <JobStatus status={job.status} error={job.error} /></TableCell>{managedWarehouseEnabled ? (<TableCell className="whitespace-nowrap">@@ -181,9 +197,11 @@ export function MaterializationJobsTable({align="right"className="hidden whitespace-nowrap tabular-nums @min-[48rem]/main-content:table-cell">- {job.read_bytes === null- ? 'Not measured'- : humanizeBytes(job.read_bytes)}+ {job.read_bytes === null ? (+ <UsageNotAvailable context="job" />+ ) : (+ humanizeBytes(job.read_bytes)+ )}</TableCell></TableRow>)diff --git a/products/data_modeling/frontend/ModelsUsageByModelTable.tsx b/products/data_modeling/frontend/ModelsUsageByModelTable.tsxindex 1ad558142697..e3ed5804d2c5 100644--- a/products/data_modeling/frontend/ModelsUsageByModelTable.tsx+++ b/products/data_modeling/frontend/ModelsUsageByModelTable.tsx@@ -31,6 +31,7 @@ import { urls } from 'scenes/urls'import { DataModelingUsageListEngine, type ModelUsageRowApi } from './generated/api.schemas'import { modelsUsageLogic } from './modelsUsageLogic'+import { UsageNotAvailable } from './UsageNotAvailable'const PAGE_SIZE = 20@@ -121,9 +122,7 @@ export function ModelsUsageByModelTable({className="whitespace-nowrap tabular-nums">{readBytes === null ? (- <Text variant="muted" render={<span />}>- Not measured- </Text>+ <UsageNotAvailable context="model" />) : (humanizeBytes(readBytes))}@@ -133,9 +132,7 @@ export function ModelsUsageByModelTable({) : (<TableCell align="right" className="whitespace-nowrap tabular-nums">{row.read_bytes === null ? (- <Text variant="muted" render={<span />}>- Not measured- </Text>+ <UsageNotAvailable context="model" />) : (humanizeBytes(row.read_bytes))}@@ -146,9 +143,7 @@ export function ModelsUsageByModelTable({className="hidden whitespace-nowrap tabular-nums @min-[48rem]/main-content:table-cell">{row.cpu_microseconds === null ? (- <Text variant="muted" render={<span />}>- Not measured- </Text>+ <UsageNotAvailable context="model" />) : (humanFriendlyDuration(row.cpu_microseconds / 1_000_000))}diff --git a/products/data_modeling/frontend/ModelsUsageTab.stories.tsx b/products/data_modeling/frontend/ModelsUsageTab.stories.tsxindex 0ff2870b6e54..0890b6b68133 100644--- a/products/data_modeling/frontend/ModelsUsageTab.stories.tsx+++ b/products/data_modeling/frontend/ModelsUsageTab.stories.tsx@@ -1,4 +1,5 @@import type { Decorator, Meta, StoryObj } from '@storybook/react'+import { waitFor } from '@testing-library/dom'import { FEATURE_FLAGS } from 'lib/constants'@@ -7,7 +8,8 @@ import type { MockResolverInfo } from '~/mocks/utils'import type { DataModelingJobApi } from 'products/data_warehouse/frontend/generated/api.schemas'-import type { ModelUsageApi, ModelUsageRowApi, ModelUsageTotalsApi } from './generated/api.schemas'+import type { ModelStatusModelApi, ModelUsageApi, ModelUsageRowApi, ModelUsageTotalsApi } from './generated/api.schemas'+import { modelsUsageLogic } from './modelsUsageLogic'import { ModelsUsageTab } from './ModelsUsageTab'const totals: ModelUsageTotalsApi = {@@ -68,12 +70,34 @@ const models: ModelUsageRowApi[] = [],},]+const statusModel = (index: number): ModelStatusModelApi => ({+ saved_query_id: models[index].saved_query_id!,+ name: models[index].name,+ deleted: models[index].deleted,+})const populated: ModelUsageApi = {date_from: '2026-09-16',date_to: '2026-10-16',overview: totals,models,count: 3,+ status_breakdown: [+ { engine: 'clickhouse', status: 'Completed', count: 2, models: [statusModel(0), statusModel(1)] },+ {+ engine: 'clickhouse',+ status: 'Failed',+ count: 1,+ models: [statusModel(2)],+ },+ { engine: 'managed_warehouse', status: 'Completed', count: 1, models: [statusModel(0)] },+ { engine: 'managed_warehouse', status: 'Running', count: 1, models: [statusModel(1)] },+ {+ engine: 'managed_warehouse',+ status: 'Failed',+ count: 1,+ models: [statusModel(2)],+ },+ ],usage_updated_at: '2026-10-16T03:00:00Z',trends: Array.from({ length: 30 }, (_, index) => {const readBytes = (150 + ((index * 71) % 300)) * 1024 ** 3@@ -88,6 +112,37 @@ const populated: ModelUsageApi = {}}),}++const getUsage = ({ request }: MockResolverInfo): [number, ModelUsageApi] => {+ const savedQueryIds = new Set(+ (new URL(request.url).searchParams.get('saved_query_ids') ?? '').split(',').filter(Boolean)+ )+ if (savedQueryIds.size === 0) {+ return [200, populated]+ }++ const selectedModels = populated.models.filter(+ (model) => model.saved_query_id && savedQueryIds.has(model.saved_query_id)+ )+ const statusBreakdown = populated.status_breakdown+ .map((breakdown) => {+ const selectedStatusModels = breakdown.models.filter((model) => savedQueryIds.has(model.saved_query_id))+ return { ...breakdown, count: selectedStatusModels.length, models: selectedStatusModels }+ })+ .filter((breakdown) => breakdown.count > 0)++ return [+ 200,+ {+ ...populated,+ overview: selectedModels.length === 1 ? selectedModels[0] : populated.overview,+ models: selectedModels,+ count: selectedModels.length,+ status_breakdown: statusBreakdown,+ trends: [],+ },+ ]+}const unknown: ModelUsageTotalsApi = {runs: 8,measured_runs: 0,@@ -206,12 +261,12 @@ const meta: Meta<typeof ModelsUsageTab> = {msw: {mocks: {get: {- '/api/projects/:team_id/data_modeling_usage/': populated,+ '/api/projects/:team_id/data_modeling_usage/': getUsage,'/api/projects/:team_id/data_modeling_jobs/': ({ request }: MockResolverInfo) => {const params = new URL(request.url).searchParamsconst offset = Number(params.get('offset') ?? 0)const limit = Number(params.get('limit') ?? 20)- const savedQueryId = params.get('saved_query_id')+ const savedQueryIds = new Set((params.get('saved_query_ids') ?? '').split(',').filter(Boolean))const engine = params.get('engine')const status = params.get('status')const after = params.get('after')@@ -219,7 +274,8 @@ const meta: Meta<typeof ModelsUsageTab> = {const filteredJobs = jobs.filter((job) => {const startedAt = new Date(job.created_at)return (- (!savedQueryId || job.saved_query_id === savedQueryId) &&+ (savedQueryIds.size === 0 ||+ (job.saved_query_id && savedQueryIds.has(job.saved_query_id))) &&(!engine || job.engine === engine) &&(!status || job.status === status) &&(!after || startedAt >= new Date(after)) &&@@ -296,6 +352,7 @@ export const Empty: Story = {models: [],trends: [],count: 0,+ status_breakdown: [],usage_updated_at: null,},},@@ -303,6 +360,44 @@ export const Empty: Story = {},},}+export const StatusOnly: Story = {+ decorators: [inMainContent('w-256')],+ parameters: {+ msw: {+ mocks: {+ get: {+ '/api/projects/:team_id/data_modeling_usage/': {+ ...populated,+ overview: { ...unknown, runs: 0 },+ models: [],+ trends: [],+ count: 0,+ status_breakdown: [+ {+ engine: 'managed_warehouse',+ status: 'Running',+ count: 1,+ models: [statusModel(1)],+ },+ ],+ usage_updated_at: null,+ },+ },+ },+ },+ },+}+export const FilteredByFailedModels: Story = {+ decorators: [inMainContent('w-256')],+ play: async () => {+ await waitFor(() => {+ if (!modelsUsageLogic.findMounted()?.values.usage) {+ throw new globalThis.Error('Models usage must finish loading')+ }+ })+ modelsUsageLogic.findMounted()!.actions.setSelectedSavedQueryIds([models[2].saved_query_id!])+ },+}export const Error: Story = {decorators: [inMainContent('w-256')],parameters: {diff --git a/products/data_modeling/frontend/ModelsUsageTab.tsx b/products/data_modeling/frontend/ModelsUsageTab.tsxindex b4bf344ed149..12114bedfdf5 100644--- a/products/data_modeling/frontend/ModelsUsageTab.tsx+++ b/products/data_modeling/frontend/ModelsUsageTab.tsx@@ -1,8 +1,8 @@import { useActions, useValues } from 'kea'-import { useMemo, useRef } from 'react'+import { useRef } from 'react'import { IconRefresh } from '@posthog/icons'-import { TimeSeriesBarChart } from '@posthog/quill-charts'+import { BarChart, TimeSeriesBarChart, type BarChartConfig } from '@posthog/quill-charts'import { useChartConfig, useChartTheme } from 'lib/charts/hooks'import { DateFilter } from 'lib/components/DateFilter/DateFilter'@@ -38,7 +38,12 @@ import type { DateMappingOption } from '~/types'import { DataModelingUsageListEngine } from './generated/api.schemas'import { MaterializationJobsTable } from './MaterializationJobsTable'import { ModelsUsageByModelTable } from './ModelsUsageByModelTable'-import { MATERIALIZATION_ENGINE_LABELS, MaterializedViewOption, modelsUsageLogic } from './modelsUsageLogic'+import {+ MATERIALIZATION_ENGINE_LABELS,+ MaterializedViewOption,+ modelStatusLabel,+ modelsUsageLogic,+} from './modelsUsageLogic'const DATE_OPTIONS: DateMappingOption[] = [7, 30, 90].map((days) => ({key: `Last ${days} complete days`,@@ -48,8 +53,6 @@ const DATE_OPTIONS: DateMappingOption[] = [7, 30, 90].map((days) => ({defaultInterval: 'day',}))-const ALL_VIEWS: MaterializedViewOption = { id: 'all', name: 'All materialized views' }-function MetricTile({ title, value }: { title: string; value: string }): JSX.Element {return (<Card size="sm" className="min-w-0">@@ -76,17 +79,26 @@ export function ModelsUsageTab({dateTo,chartLabels,chartSeries,+ statusChartLabels,+ statusChartSeries,jobsLoading,managedWarehouseEnabled,- materializedViewOptions,selectedEngine,- selectedSavedQueryId,+ selectedMaterializedViewOptions,+ selectedSavedQueryIds,+ viewFilterOptions,} = useValues(modelsUsageLogic)- const { refresh, setDateRange, loadUsage, setSelectedEngine, setSelectedSavedQueryId } =+ const { refresh, setDateRange, loadUsage, setSelectedEngine, setSelectedSavedQueryIds } =useActions(modelsUsageLogic)const viewFilterRef = useRef<HTMLButtonElement>(null)- const viewOptions = useMemo(() => [ALL_VIEWS, ...materializedViewOptions], [materializedViewOptions])- const selectedView = viewOptions.find((option) => option.id === (selectedSavedQueryId ?? ALL_VIEWS.id)) ?? ALL_VIEWS+ const selectedViewsLabel =+ selectedSavedQueryIds.length === 0+ ? 'All materialized views'+ : selectedSavedQueryIds.length === 1+ ? (selectedMaterializedViewOptions[0]?.name ?? '1 materialized view')+ : `${selectedSavedQueryIds.length} materialized views`+ const chartSeriesKey = chartSeries.map((series) => series.key).join('|')+ const statusChartSeriesKey = statusChartSeries.map((series) => series.key).join('|')const theme = useChartTheme()const chartConfig = useChartConfig(() => ({@@ -98,6 +110,18 @@ export function ModelsUsageTab({}),[chartSeries.length])+ const statusChartConfig = useChartConfig<BarChartConfig>(+ () => ({+ barLayout: 'stacked',+ showGrid: true,+ showAxisLines: true,+ showTickMarks: true,+ yTickFormatter: (value: number) => humanFriendlyNumber(value),+ tooltip: { valueFormatter: (value: number) => humanFriendlyNumber(value) },+ legend: { show: statusChartSeries.length > 1, position: 'top', interactive: true },+ }),+ [statusChartSeries.length]+ )return (<div className="space-y-4" data-attr="models-usage" data-quill>@@ -110,12 +134,13 @@ export function ModelsUsageTab({</div><div className="flex flex-wrap gap-2"><Combobox- items={viewOptions}- value={selectedView}+ multiple+ items={viewFilterOptions}+ value={selectedMaterializedViewOptions}itemToStringValue={(option: MaterializedViewOption) => option.name}isItemEqualToValue={(option, value) => option.id === value.id}- onValueChange={(option: MaterializedViewOption | null) =>- setSelectedSavedQueryId(!option || option.id === ALL_VIEWS.id ? null : option.id)+ onValueChange={(options: MaterializedViewOption[]) =>+ setSelectedSavedQueryIds(options.map((option) => option.id))}><ComboboxTrigger@@ -124,10 +149,22 @@ export function ModelsUsageTab({data-attr="models-usage-view-filter"disabled={usageLoading || jobsLoading}>- <span className="truncate">{selectedView.name}</span>+ <span className="truncate">{selectedViewsLabel}</span></ComboboxTrigger><ComboboxContent anchor={viewFilterRef} align="end" className="w-80 max-w-[calc(100vw-2rem)]"><ComboboxInput placeholder="Search materialized views" showTrigger={false} />+ {selectedSavedQueryIds.length > 0 ? (+ <div className="px-1 pt-1">+ <Button+ variant="link-muted"+ size="xs"+ onClick={() => setSelectedSavedQueryIds([])}+ data-attr="models-usage-view-filter-clear"+ >+ Clear selection+ </Button>+ </div>+ ) : null}<ComboboxEmpty>No materialized views found.</ComboboxEmpty><ComboboxList>{(option: MaterializedViewOption) => (@@ -198,11 +235,11 @@ export function ModelsUsageTab({</Button></CardContent></Card>- ) : !usage || usageLoading ? (+ ) : !usage ? (<div className="flex justify-center py-16"><Spinner /></div>- ) : usage.overview.runs === 0 ? (+ ) : usage.overview.runs === 0 && statusChartLabels.length === 0 ? (<Card size="sm"><CardContent><Text variant="muted">@@ -211,8 +248,17 @@ export function ModelsUsageTab({</CardContent></Card>) : (- <>- {usage.overview.measured_runs < usage.overview.runs ? (+ <div className="relative space-y-4" aria-busy={usageLoading}>+ {usage.overview.runs === 0 ? (+ <Card size="sm">+ <CardContent>+ <Text variant="muted">+ No finished materialization runs match these filters. The status chart includes+ current and skipped runs.+ </Text>+ </CardContent>+ </Card>+ ) : usage.overview.measured_runs < usage.overview.runs ? (<Card size="sm"><CardContent><Text variant="muted">@@ -224,50 +270,97 @@ export function ModelsUsageTab({</CardContent></Card>) : null}- <div className="grid grid-cols-1 gap-4 @min-[36rem]/main-content:grid-cols-3">- <MetricTile- title="Bytes read"- value={- usage.overview.read_bytes === null- ? 'Not measured'- : humanizeBytes(usage.overview.read_bytes)- }- />- <MetricTile- title="CPU time"- value={- usage.overview.cpu_microseconds === null- ? 'Not measured'- : humanFriendlyDuration(usage.overview.cpu_microseconds / 1_000_000)- }- />- <MetricTile title="Runs" value={humanFriendlyNumber(usage.overview.runs)} />- </div>- {usage.overview.measured_runs > 0 ? (- <Card size="sm" className="min-w-0">- <CardHeader>- <CardTitle role="heading" aria-level={3}>- Bytes read by day- </CardTitle>- <CardDescription>- Usage is attributed to the day each run finished. Gaps have no measured usage.- {chartSeries.length > 1 ? ' Bars are stacked by engine.' : ''}- </CardDescription>- </CardHeader>- <CardContent>- <div className="h-64 flex flex-col">- <TimeSeriesBarChart- series={chartSeries}- labels={chartLabels}- theme={theme}- config={chartConfig}- />- </div>- </CardContent>- </Card>+ {usage.overview.runs > 0 ? (+ <div className="grid grid-cols-1 gap-4 @min-[36rem]/main-content:grid-cols-3">+ <MetricTile+ title="Bytes read"+ value={+ usage.overview.read_bytes === null+ ? 'Not measured'+ : humanizeBytes(usage.overview.read_bytes)+ }+ />+ <MetricTile+ title="CPU time"+ value={+ usage.overview.cpu_microseconds === null+ ? 'Not measured'+ : humanFriendlyDuration(usage.overview.cpu_microseconds / 1_000_000)+ }+ />+ <MetricTile title="Runs" value={humanFriendlyNumber(usage.overview.runs)} />+ </div>) : null}+ <div className="grid grid-cols-1 gap-4 @min-[64rem]/main-content:grid-cols-2">+ {usage.overview.measured_runs > 0 ? (+ <Card size="sm" className="min-w-0">+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ Bytes read by day+ </CardTitle>+ <CardDescription>+ Usage is attributed to the day each run finished. Gaps have no measured usage.+ {chartSeries.length > 1 ? ' Bars are stacked by engine.' : ''}+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="h-64 flex flex-col">+ <TimeSeriesBarChart+ key={chartSeriesKey}+ series={chartSeries}+ labels={chartLabels}+ theme={theme}+ config={chartConfig}+ />+ </div>+ </CardContent>+ </Card>+ ) : null}+ {statusChartLabels.length > 0 ? (+ <Card size="sm" className="min-w-0">+ <CardHeader>+ <CardTitle role="heading" aria-level={3}>+ Models by latest run status+ </CardTitle>+ <CardDescription>+ Latest run for each model and engine in the selected complete-day range.+ {statusChartSeries.length > 1 ? ' Bars are stacked by engine.' : ''}+ {' Select a bar to filter this tab to its models.'}+ </CardDescription>+ </CardHeader>+ <CardContent>+ <div className="flex h-64 flex-col">+ <BarChart+ key={statusChartSeriesKey}+ series={statusChartSeries}+ labels={statusChartLabels}+ theme={theme}+ config={statusChartConfig}+ onPointClick={({ series, label }) => {+ const breakdown = usage.status_breakdown.find(+ (item) =>+ item.engine === series.key &&+ modelStatusLabel(item.status) === label+ )+ if (breakdown) {+ setSelectedSavedQueryIds(+ breakdown.models.map((model) => model.saved_query_id)+ )+ }+ }}+ />+ </div>+ </CardContent>+ </Card>+ ) : null}+ </div><ModelsUsageByModelTable savedQueryIdToNodeId={savedQueryIdToNodeId} />- </>+ {usageLoading ? (+ <div className="absolute inset-0 z-10 flex items-center justify-center rounded bg-background/60">+ <Spinner />+ </div>+ ) : null}+ </div>)}<MaterializationJobsTable savedQueryIdToNodeId={savedQueryIdToNodeId} />diff --git a/products/data_modeling/frontend/UsageNotAvailable.tsx b/products/data_modeling/frontend/UsageNotAvailable.tsxnew file mode 100644index 000000000000..dd6aba5b4c3a--- /dev/null+++ b/products/data_modeling/frontend/UsageNotAvailable.tsx@@ -0,0 +1,22 @@+import { Tooltip } from 'lib/lemon-ui/Tooltip'++const EXPLANATIONS = {+ model: 'No usage measurement is available for this model and date range.',+ job: 'Usage is measured once a day. Recent jobs update after the next daily measurement. Older measurements may be unavailable.',+}++export function UsageNotAvailable({ context }: { context: keyof typeof EXPLANATIONS }): JSX.Element {+ const explanation = EXPLANATIONS[context]++ return (+ <Tooltip title={explanation}>+ <span+ className="cursor-help border-b border-dotted text-secondary"+ tabIndex={0}+ aria-label={`N/A. ${explanation}`}+ >+ N/A+ </span>+ </Tooltip>+ )+}diff --git a/products/data_modeling/frontend/generated/api.schemas.ts b/products/data_modeling/frontend/generated/api.schemas.tsindex d4cb5b9a800f..f3905643805f 100644--- a/products/data_modeling/frontend/generated/api.schemas.ts+++ b/products/data_modeling/frontend/generated/api.schemas.ts@@ -391,6 +391,26 @@ export interface ModelUsageRowApi {engines: ModelUsageEngineApi[]}+export interface ModelStatusModelApi {+ /** Model ID. */+ saved_query_id: string+ /** Model name. */+ name: string+ /** Whether this model has been deleted. */+ deleted: boolean+}++export interface ModelStatusBreakdownApi {+ /** Materialization engine: clickhouse or managed_warehouse. */+ engine: string+ /** Status of the latest run for the model and engine in this range. */+ status: string+ /** Number of models whose latest run has this status. */+ count: number+ /** Models whose latest run has this status. */+ models: ModelStatusModelApi[]+}+export interface ModelUsageApi {/** Inclusive UTC start date. */date_from: string@@ -404,6 +424,8 @@ export interface ModelUsageApi {models: ModelUsageRowApi[]/** Total number of models in the breakdown. */count: number+ /** Latest run status for each model and engine in the selected complete-day range. */+ status_breakdown: ModelStatusBreakdownApi[]/*** Latest usage collection timestamp in this range.* @nullable@@ -498,9 +520,13 @@ export type DataModelingUsageListParams = {page_size?: number/*** Limit usage to one accessible materialized view.- * @nullable*/- saved_query_id?: string | null+ saved_query_id?: string+ /**+ * Comma-separated materialized view IDs. Usage is limited to accessible views.+ * @minLength 1+ */+ saved_query_ids?: string}export type DataModelingUsageListEngine = (typeof DataModelingUsageListEngine)[keyof typeof DataModelingUsageListEngine]diff --git a/products/data_modeling/frontend/modelsUsageLogic.test.ts b/products/data_modeling/frontend/modelsUsageLogic.test.tsindex 65534a61a7a3..075ad77f4341 100644--- a/products/data_modeling/frontend/modelsUsageLogic.test.ts+++ b/products/data_modeling/frontend/modelsUsageLogic.test.ts@@ -24,6 +24,7 @@ const emptyUsage = {},models: [],count: 0,+ status_breakdown: [],usage_updated_at: null,trends: [],}@@ -73,27 +74,83 @@ describe('modelsUsageLogic', () => {expect(usageRequests[0].get('engine')).toBe('all')expect(jobRequests[0].get('all_engines')).toBe('true')expect(jobRequests[0].get('engine')).toBeNull()- expect(jobRequests[0].get('saved_query_id')).toBeNull()+ expect(jobRequests[0].get('saved_query_ids')).toBeNull()expect(jobRequests[0].get('after')).not.toBeNull()expect(jobRequests[0].get('before')).toBeNull()expect(logic.values.materializedViewOptions.map((option) => option.name)).toEqual(['Alpha view', 'Beta view'])- await expectLogic(logic, () => logic.actions.setSelectedSavedQueryId('view-a')).toDispatchActions([+ await expectLogic(logic, () => logic.actions.setSelectedSavedQueryIds(['view-a', 'view-b'])).toDispatchActions(['loadUsageSuccess','loadMaterializationJobsSuccess',])- expect(usageRequests.at(-1)?.get('saved_query_id')).toBe('view-a')- expect(jobRequests.at(-1)?.get('saved_query_id')).toBe('view-a')+ expect(usageRequests.at(-1)?.get('saved_query_ids')).toBe('view-a,view-b')+ expect(jobRequests.at(-1)?.get('saved_query_ids')).toBe('view-a,view-b')expect(jobRequests.at(-1)?.get('offset')).toBe('0')await expectLogic(logic, () => logic.actions.setJobsPage(2)).toDispatchActions(['loadMaterializationJobsSuccess',])- expect(jobRequests.at(-1)?.get('saved_query_id')).toBe('view-a')+ expect(jobRequests.at(-1)?.get('saved_query_ids')).toBe('view-a,view-b')expect(jobRequests.at(-1)?.get('offset')).toBe('20')expect(logic.values.page).toBe(1)})+ it('builds a status breakdown by engine', async () => {+ await expectLogic(logic).toDispatchActions(['loadUsageSuccess'])++ logic.actions.loadUsageSuccess({+ ...emptyUsage,+ status_breakdown: [+ { engine: 'clickhouse', status: 'Completed', count: 3, models: [] },+ { engine: 'clickhouse', status: 'Failed', count: 1, models: [] },+ { engine: 'managed_warehouse', status: 'Failed', count: 2, models: [] },+ ],+ })++ expect(logic.values.statusChartLabels).toEqual(['Completed', 'Failed'])+ expect(logic.values.statusChartSeries).toEqual([+ { key: 'clickhouse', label: 'ClickHouse', data: [3, 1] },+ { key: 'managed_warehouse', label: 'Managed warehouse', data: [0, 2] },+ ])++ expect(logic.values.selectedSavedQueryIds).toEqual([])+ })++ it('keeps selected status models that are absent from the materialized view options', async () => {+ await expectLogic(logic).toDispatchActions(['loadUsageSuccess', 'loadMaterializationJobsSuccess'])+ await expectLogic(logic, () => logic.actions.setSelectedSavedQueryIds(['deleted-view'])).toDispatchActions([+ 'loadUsageSuccess',+ 'loadMaterializationJobsSuccess',+ ])++ logic.actions.loadUsageSuccess({+ ...emptyUsage,+ status_breakdown: [+ {+ engine: 'clickhouse',+ status: 'Failed',+ count: 1,+ models: [+ {+ saved_query_id: 'deleted-view',+ name: 'Deleted view',+ deleted: true,+ },+ ],+ },+ ],+ })++ expect(logic.values.viewFilterOptions).toContainEqual({ id: 'deleted-view', name: 'Deleted view' })+ expect(logic.values.selectedMaterializedViewOptions).toEqual([{ id: 'deleted-view', name: 'Deleted view' }])++ logic.actions.setSelectedSavedQueryIds(['deleted-view', 'view-a'])+ expect(logic.values.selectedMaterializedViewOptions).toEqual([+ { id: 'deleted-view', name: 'Deleted view' },+ { id: 'view-a', name: 'Alpha view' },+ ])+ })+it('filters all tab requests by engine', async () => {await expectLogic(logic).toDispatchActions(['loadUsageSuccess', 'loadMaterializationJobsSuccess'])diff --git a/products/data_modeling/frontend/modelsUsageLogic.ts b/products/data_modeling/frontend/modelsUsageLogic.tsindex 1436ff169206..34f9c0f9448a 100644--- a/products/data_modeling/frontend/modelsUsageLogic.ts+++ b/products/data_modeling/frontend/modelsUsageLogic.ts@@ -32,6 +32,14 @@ export const MATERIALIZATION_ENGINE_LABELS: Record<string, string> = {managed_warehouse: 'Managed warehouse',}+const MODEL_STATUS_ORDER = [+ DataModelingJobsListStatus.Completed,+ DataModelingJobsListStatus.Running,+ DataModelingJobsListStatus.Failed,+ DataModelingJobsListStatus.Cancelled,+ DataModelingJobsListStatus.Skipped,+]+const JOB_ENGINE_BY_USAGE_ENGINE: Partial<Record<DataModelingUsageListEngine, DataModelingJobsListEngine>> = {[DataModelingUsageListEngine.Clickhouse]: DataModelingJobsListEngine.Clickhouse,[DataModelingUsageListEngine.ManagedWarehouse]: DataModelingJobsListEngine.ManagedWarehouse,@@ -104,6 +112,10 @@ export interface MaterializedViewOption {name: string}+export function modelStatusLabel(status: string): string {+ return status === DataModelingJobsListStatus.Cancelled ? 'Canceled' : status+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface modelsUsageLogicValues {dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[] // dataWarehouseViewsLogic@@ -126,9 +138,13 @@ export interface modelsUsageLogicValues {page: numberselectedEngine: DataModelingUsageListEngineselectedJobStatus: DataModelingJobsListStatus | null- selectedSavedQueryId: string | null+ selectedMaterializedViewOptions: MaterializedViewOption[]+ selectedSavedQueryIds: string[]+ statusChartLabels: string[]+ statusChartSeries: Series[]usage: ModelUsageApi | nullusageLoading: boolean+ viewFilterOptions: MaterializedViewOption[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -192,8 +208,8 @@ export interface modelsUsageLogicActions {setSelectedJobStatus: (status: DataModelingJobsListStatus | null) => {status: DataModelingJobsListStatus | null}- setSelectedSavedQueryId: (savedQueryId: string | null) => {- savedQueryId: string | null+ setSelectedSavedQueryIds: (savedQueryIds: string[]) => {+ savedQueryIds: string[]}}@@ -204,10 +220,21 @@ export interface modelsUsageLogicMeta {materializedViewOptions: (dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]) => MaterializedViewOption[]+ viewFilterOptions: (+ materializedViewOptions: MaterializedViewOption[],+ selectedSavedQueryIds: string[],+ usage: ModelUsageApi | null+ ) => MaterializedViewOption[]+ selectedMaterializedViewOptions: (+ viewFilterOptions: MaterializedViewOption[],+ selectedSavedQueryIds: string[]+ ) => MaterializedViewOption[]jobsFailed: (materializationJobsFailed: boolean, dataWarehouseSavedQueriesFailed: boolean) => booleanjobsLoading: (materializationJobsLoading: boolean, dataWarehouseSavedQueriesLoading: boolean) => booleanchartLabels: (usage: ModelUsageApi | null) => string[]chartSeries: (usage: ModelUsageApi | null) => Series[]+ statusChartLabels: (usage: ModelUsageApi | null) => string[]+ statusChartSeries: (usage: ModelUsageApi | null) => Series[]}}@@ -236,7 +263,7 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([setJobsPage: (page: number) => ({ page }),setSelectedEngine: (engine: DataModelingUsageListEngine) => ({ engine }),setSelectedJobStatus: (status: DataModelingJobsListStatus | null) => ({ status }),- setSelectedSavedQueryId: (savedQueryId: string | null) => ({ savedQueryId }),+ setSelectedSavedQueryIds: (savedQueryIds: string[]) => ({ savedQueryIds }),openModel: true,refresh: true,refreshJobs: true,@@ -253,7 +280,7 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([setPage: (_, { page }) => page,setDateRange: () => 1,setSelectedEngine: () => 1,- setSelectedSavedQueryId: () => 1,+ setSelectedSavedQueryIds: () => 1,},],jobsPage: [@@ -263,7 +290,7 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([setDateRange: () => 1,setSelectedEngine: () => 1,setSelectedJobStatus: () => 1,- setSelectedSavedQueryId: () => 1,+ setSelectedSavedQueryIds: () => 1,},],selectedEngine: [@@ -274,10 +301,7 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([null as DataModelingJobsListStatus | null,{ setSelectedJobStatus: (_, { status }) => status },],- selectedSavedQueryId: [- null as string | null,- { setSelectedSavedQueryId: (_, { savedQueryId }) => savedQueryId },- ],+ selectedSavedQueryIds: [[] as string[], { setSelectedSavedQueryIds: (_, { savedQueryIds }) => savedQueryIds }],failed: [false, { loadUsage: () => false, loadUsageFailure: () => true }],materializationJobsFailed: [false,@@ -299,7 +323,7 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([: DataModelingUsageListEngine.Clickhouse,page: values.page,page_size: 20,- saved_query_id: values.selectedSavedQueryId ?? undefined,+ saved_query_ids: values.selectedSavedQueryIds.join(',') || undefined,})breakpoint()return result@@ -314,7 +338,8 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([after: materializationJobsDateFrom(values.dateFrom, values.dateTo),limit: MATERIALIZATION_JOBS_PAGE_SIZE,offset: (values.jobsPage - 1) * MATERIALIZATION_JOBS_PAGE_SIZE,- saved_query_id: values.selectedSavedQueryId ?? undefined,+ saved_query_ids:+ values.selectedSavedQueryIds.length > 0 ? values.selectedSavedQueryIds : undefined,all_engines: values.managedWarehouseEnabled || undefined,engine:values.managedWarehouseEnabled && values.selectedEngine !== DataModelingUsageListEngine.All@@ -341,6 +366,37 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([.map((view) => ({ id: view.id, name: view.name ?? 'Untitled view' })).sort((a, b) => a.name.localeCompare(b.name)),],+ viewFilterOptions: [+ (s) => [s.materializedViewOptions, s.selectedSavedQueryIds, s.usage],+ (+ materializedViewOptions: MaterializedViewOption[],+ selectedSavedQueryIds: string[],+ usage: ModelUsageApi | null+ ): MaterializedViewOption[] => {+ const optionsById = new Map(materializedViewOptions.map((option) => [option.id, option]))+ const selectedIds = new Set(selectedSavedQueryIds)+ for (const breakdown of usage?.status_breakdown ?? []) {+ for (const model of breakdown.models) {+ if (selectedIds.has(model.saved_query_id) && !optionsById.has(model.saved_query_id)) {+ optionsById.set(model.saved_query_id, { id: model.saved_query_id, name: model.name })+ }+ }+ }+ for (const id of selectedSavedQueryIds) {+ if (!optionsById.has(id)) {+ optionsById.set(id, { id, name: 'Unavailable model' })+ }+ }+ return [...optionsById.values()]+ },+ ],+ selectedMaterializedViewOptions: [+ (s) => [s.viewFilterOptions, s.selectedSavedQueryIds],+ (viewFilterOptions: MaterializedViewOption[], selectedSavedQueryIds: string[]) => {+ const optionsById = new Map(viewFilterOptions.map((option) => [option.id, option]))+ return selectedSavedQueryIds.map((id) => optionsById.get(id)!)+ },+ ],jobsFailed: [(s) => [s.materializationJobsFailed, s.dataWarehouseSavedQueriesFailed],(materializationJobsFailed: boolean, dataWarehouseSavedQueriesFailed: boolean): boolean =>@@ -367,6 +423,31 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([) ?? [],})),],+ statusChartLabels: [+ (s) => [s.usage],+ (usage: ModelUsageApi | null): string[] =>+ MODEL_STATUS_ORDER.filter((status) =>+ usage?.status_breakdown.some((item) => item.status === status)+ ).map(modelStatusLabel),+ ],+ statusChartSeries: [+ (s) => [s.usage],+ (usage: ModelUsageApi | null): Series[] => {+ const engines = [...new Set(usage?.status_breakdown.map((item) => item.engine) ?? [])]+ const statuses = MODEL_STATUS_ORDER.filter((status) =>+ usage?.status_breakdown.some((item) => item.status === status)+ )+ return engines.map((engine) => ({+ key: engine,+ label: MATERIALIZATION_ENGINE_LABELS[engine] ?? engine,+ data: statuses.map(+ (status) =>+ usage?.status_breakdown.find((item) => item.engine === engine && item.status === status)+ ?.count ?? 0+ ),+ }))+ },+ ],}),listeners(({ actions, values }) => ({setDateRange: () => {@@ -384,7 +465,7 @@ export const modelsUsageLogic = kea<modelsUsageLogicType>([actions.loadMaterializationJobs()},setSelectedJobStatus: () => actions.loadMaterializationJobs(),- setSelectedSavedQueryId: () => {+ setSelectedSavedQueryIds: () => {actions.loadUsage()actions.loadMaterializationJobs()},diff --git a/products/data_warehouse/backend/presentation/views/data_modeling_job.py b/products/data_warehouse/backend/presentation/views/data_modeling_job.pyindex 8bdf37edb9ed..f479cf8131e2 100644--- a/products/data_warehouse/backend/presentation/views/data_modeling_job.py+++ b/products/data_warehouse/backend/presentation/views/data_modeling_job.py@@ -86,6 +86,10 @@ class DataModelingJobPagination(pagination.LimitOffsetPagination):max_limit = 100+class UUIDInFilter(django_filters.BaseInFilter, django_filters.UUIDFilter):+ pass++DATA_MODELING_JOB_LIST_FIELDS = ("id","saved_query_id",@@ -110,6 +114,11 @@ DATA_MODELING_JOB_LIST_FIELDS = (class DataModelingJobFilterSet(django_filters.FilterSet):+ saved_query_ids = UUIDInFilter(+ field_name="saved_query_id",+ lookup_expr="in",+ help_text="Comma-separated materialized view IDs.",+ )after = django_filters.IsoDateTimeFilter(field_name="last_run_at", lookup_expr="gte", help_text="Include jobs finished at or after this time.")@@ -119,7 +128,7 @@ class DataModelingJobFilterSet(django_filters.FilterSet):class Meta:model = DataModelingJob- fields = ["saved_query_id", "status", "engine"]+ fields = ["saved_query_id", "saved_query_ids", "status", "engine"]@extend_schema_view(diff --git a/products/data_warehouse/backend/tests/api/test_datamodelingjob.py b/products/data_warehouse/backend/tests/api/test_datamodelingjob.pyindex ba20aeabb1e0..bde4951708ed 100644--- a/products/data_warehouse/backend/tests/api/test_datamodelingjob.py+++ b/products/data_warehouse/backend/tests/api/test_datamodelingjob.py@@ -122,6 +122,32 @@ class TestDataModelingJob(APIBaseTest):self.assertEqual(response.status_code, 200)self.assertEqual([job["id"] for job in response.json()["results"]], [str(self.job3.id)])+ def test_filters_by_saved_query_ids(self):+ included_query = DataWarehouseSavedQuery.objects.create(team=self.team, name="Included query")+ included_job = DataModelingJob.objects.create(+ team=self.team,+ saved_query=included_query,+ status=DataModelingJob.Status.COMPLETED,+ last_run_at=timezone.now(),+ )+ excluded_query = DataWarehouseSavedQuery.objects.create(team=self.team, name="Excluded query")+ excluded_job = DataModelingJob.objects.create(+ team=self.team,+ saved_query=excluded_query,+ status=DataModelingJob.Status.COMPLETED,+ last_run_at=timezone.now(),+ )++ response = self.client.get(+ f"/api/environments/{self.team.pk}/data_modeling_jobs/",+ {"saved_query_ids": f"{self.saved_query.id},{included_query.id}"},+ )++ self.assertEqual(response.status_code, 200)+ job_ids = {job["id"] for job in response.json()["results"]}+ self.assertEqual(job_ids, {str(self.job1.id), str(self.job2.id), str(self.job3.id), str(included_job.id)})+ self.assertNotIn(str(excluded_job.id), job_ids)+def test_filters_by_finished_date_range(self):DataModelingJob.objects.filter(id=self.job1.id).update(last_run_at=datetime(2026, 10, 10, tzinfo=UTC))DataModelingJob.objects.filter(id=self.job2.id).update(last_run_at=datetime(2026, 10, 11, tzinfo=UTC))diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 15168506f3cd..0d026e2e692a 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -5636,6 +5636,10 @@ export type DataModelingJobsListParams = {*/offset?: numbersaved_query_id?: string+ /**+ * Comma-separated materialized view IDs.+ */+ saved_query_ids?: string[]/*** * `Cancelled` - Cancelled* * `Completed` - Completeddiff --git a/products/managed_warehouse/backend/facade/client.py b/products/managed_warehouse/backend/facade/client.pyindex a9145384f8cf..d53be5fdc18e 100644--- a/products/managed_warehouse/backend/facade/client.py+++ b/products/managed_warehouse/backend/facade/client.py@@ -252,9 +252,9 @@ async def execute_trino_model(source_query: object,incremental: TrinoIncrementalWrite | None = None,on_processed_bytes: Callable[[int], None] | None = None,+ on_cpu_milliseconds: Callable[[int], None] | None = None,) -> DuckLakeTableResult:- """Build the model on Trino. ``on_processed_bytes`` receives the bytes each statement processed,- including statements of attempts that fail."""+ """Build the model on Trino and report the final statement usage, including failed attempts."""from products.managed_warehouse.backend.trino_execution import ( # noqa: PLC0415 -- keeps executor creation off startup pathsrun_trino_model_with_retries,)@@ -272,4 +272,5 @@ async def execute_trino_model(control=control,),on_processed_bytes=on_processed_bytes,+ on_cpu_milliseconds=on_cpu_milliseconds,)diff --git a/products/managed_warehouse/backend/tests/test_trino_execution.py b/products/managed_warehouse/backend/tests/test_trino_execution.pyindex f63580ebf321..aa061a1e3e9f 100644--- a/products/managed_warehouse/backend/tests/test_trino_execution.py+++ b/products/managed_warehouse/backend/tests/test_trino_execution.py@@ -63,6 +63,18 @@ async def test_success_preserves_result() -> None:assert await execution.run_trino_model(lambda control: 42, query_seconds=60) == 42+async def test_reports_cpu_time() -> None:+ cpu_milliseconds: list[int] = []++ def execute(control: execution.TrinoQueryControl) -> int:+ control.record_cpu_milliseconds(25)+ return 42++ assert await execution.run_trino_model(execute, query_seconds=60, on_cpu_milliseconds=cpu_milliseconds.append) == 42+ assert cpu_milliseconds == [25]++@pytest.mark.asyncio@pytest.mark.parametrize("error_name,expected_attempts",diff --git a/products/managed_warehouse/backend/tests/test_trino_materialization.py b/products/managed_warehouse/backend/tests/test_trino_materialization.pyindex c273a3f3f3e8..ee88d00e817f 100644--- a/products/managed_warehouse/backend/tests/test_trino_materialization.py+++ b/products/managed_warehouse/backend/tests/test_trino_materialization.py@@ -391,6 +391,7 @@ class _ScriptedCursor:duplicate: bool = False,max_key: Any = None,processed_bytes: int = 0,+ cpu_milliseconds: int = 0,unreachable_from: str | None = None,) -> None:self.table_exists = table_exists@@ -401,6 +402,7 @@ class _ScriptedCursor:self.rowcount = -1self.description: list[tuple[str]] | None = Noneself.processed_bytes = processed_bytes+ self.cpu_milliseconds = cpu_millisecondsself.unreachable_from = unreachable_fromself.stats: dict[str, Any] | None = Noneself._rows: list[tuple[Any, ...]] = []@@ -410,7 +412,7 @@ class _ScriptedCursor:raise ConnectionError("coordinator unreachable")self.statements.append((statement, parameters))self.rowcount, self._rows = -1, []- self.stats = {"processedBytes": self.processed_bytes}+ self.stats = {"processedBytes": self.processed_bytes, "cpuTimeMillis": self.cpu_milliseconds}if "information_schema.tables" in statement:self._rows = [(1,)] if self.table_exists else []elif statement.startswith("CREATE OR REPLACE TABLE"):@@ -528,13 +530,21 @@ class TestTrinoIncrementalMaterialization(BaseTest):("duplicate_keys_fail_the_merge", True, 4),])- def test_reports_bytes_processed_by_every_statement(self, _name: str, duplicate: bool, statements: int) -> None:+ def test_reports_usage_by_every_statement(self, _name: str, duplicate: bool, statements: int) -> None:processed: list[int] = []- cursor = _ScriptedCursor(table_exists=True, staged=3, duplicate=duplicate, processed_bytes=100)+ cpu: list[int] = []+ cursor = _ScriptedCursor(+ table_exists=True, staged=3, duplicate=duplicate, processed_bytes=100, cpu_milliseconds=25+ )- self.run_build(cursor, self.since, TrinoQueryControl(on_processed_bytes=processed.append))+ self.run_build(+ cursor,+ self.since,+ TrinoQueryControl(on_processed_bytes=processed.append, on_cpu_milliseconds=cpu.append),+ )assert processed == [100] * statements+ assert cpu == [25] * statementsdef test_a_statement_that_never_starts_does_not_recount_the_previous_one(self) -> None:processed: list[int] = []diff --git a/products/managed_warehouse/backend/trino_execution.py b/products/managed_warehouse/backend/trino_execution.pyindex 337dff3c73d9..3ef43be75790 100644--- a/products/managed_warehouse/backend/trino_execution.py+++ b/products/managed_warehouse/backend/trino_execution.py@@ -34,12 +34,14 @@ class TrinoQueryControl:self,query_seconds: float = TRINO_QUERY_SECONDS,on_processed_bytes: Callable[[int], None] | None = None,+ on_cpu_milliseconds: Callable[[int], None] | None = None,) -> None:self.cancelled = threading.Event()self.finished = threading.Event()self.cursor: Cursor | None = Noneself.deadline = monotonic() + query_secondsself.on_processed_bytes = on_processed_bytes+ self.on_cpu_milliseconds = on_cpu_millisecondsdef checkpoint(self) -> None:if self.cancelled.is_set() or monotonic() >= self.deadline:@@ -52,6 +54,10 @@ class TrinoQueryControl:if self.on_processed_bytes is not None and isinstance(processed_bytes, int):self.on_processed_bytes(processed_bytes)+ def record_cpu_milliseconds(self, cpu_milliseconds: object) -> None:+ if self.on_cpu_milliseconds is not None and isinstance(cpu_milliseconds, int):+ self.on_cpu_milliseconds(cpu_milliseconds)+def _cancel_until_finished(self) -> None:# execute() can still be waiting for its first nextUri when cancellation arrives.while not self.finished.is_set():@@ -73,8 +79,9 @@ async def run_trino_model(*,query_seconds: float = TRINO_QUERY_SECONDS,on_processed_bytes: Callable[[int], None] | None = None,+ on_cpu_milliseconds: Callable[[int], None] | None = None,) -> _Result:- control = TrinoQueryControl(query_seconds, on_processed_bytes)+ control = TrinoQueryControl(query_seconds, on_processed_bytes, on_cpu_milliseconds)task = asyncio.create_task(database_sync_to_async_pool(execute, executor=_executor)(control))timeout = asyncio.timeout(query_seconds)try:@@ -106,16 +113,20 @@ async def run_trino_model_with_retries(query_seconds: float = TRINO_QUERY_SECONDS,retry_delays: tuple[float, ...] = TRANSIENT_TRINO_ERROR_RETRY_DELAYS_SECONDS,on_processed_bytes: Callable[[int], None] | None = None,+ on_cpu_milliseconds: Callable[[int], None] | None = None,) -> _Result:"""Run ``execute`` again after a transient Trino cluster fault. All attempts share one deadline.- ``on_processed_bytes`` receives the bytes each statement processed, in every attempt.+ The usage callbacks receive each statement's final counters, in every attempt."""deadline = monotonic() + query_secondsfor delay in retry_delays:try:return await run_trino_model(- execute, query_seconds=deadline - monotonic(), on_processed_bytes=on_processed_bytes+ execute,+ query_seconds=deadline - monotonic(),+ on_processed_bytes=on_processed_bytes,+ on_cpu_milliseconds=on_cpu_milliseconds,)except Exception as error:if not is_transient_trino_error(error) or monotonic() + delay >= deadline:@@ -126,4 +137,9 @@ async def run_trino_model_with_retries(retry_in_seconds=delay,)await asyncio.sleep(delay)- return await run_trino_model(execute, query_seconds=deadline - monotonic(), on_processed_bytes=on_processed_bytes)+ return await run_trino_model(+ execute,+ query_seconds=deadline - monotonic(),+ on_processed_bytes=on_processed_bytes,+ on_cpu_milliseconds=on_cpu_milliseconds,+ )diff --git a/products/managed_warehouse/backend/trino_materialization.py b/products/managed_warehouse/backend/trino_materialization.pyindex b9f0f2231d35..bc4371748c21 100644--- a/products/managed_warehouse/backend/trino_materialization.py+++ b/products/managed_warehouse/backend/trino_materialization.py@@ -209,7 +209,7 @@ def _fetch(statement: str,parameters: list[object] | None = None,) -> list[Any]:- """Run one statement, read all of its rows, and report the bytes it processed to ``control``."""+ """Run one statement, read all of its rows, and report its final usage to ``control``."""if control:control.checkpoint()stats_before = cursor.stats@@ -228,3 +228,4 @@ def _fetch(stats = cursor.statsif control is not None and stats is not None and stats is not stats_before:control.record_processed_bytes(stats.get("processedBytes"))+ control.record_cpu_milliseconds(stats.get("cpuTimeMillis"))diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0aa632ddd42a..8f27af6a449f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -71258,6 +71258,26 @@ export namespace Schemas {models: ModelChoice[];}+ export interface ModelStatusModel {+ /** Model ID. */+ saved_query_id: string;+ /** Model name. */+ name: string;+ /** Whether this model has been deleted. */+ deleted: boolean;+ }++ export interface ModelStatusBreakdown {+ /** Materialization engine: clickhouse or managed_warehouse. */+ engine: string;+ /** Status of the latest run for the model and engine in this range. */+ status: string;+ /** Number of models whose latest run has this status. */+ count: number;+ /** Models whose latest run has this status. */+ models: ModelStatusModel[];+ }+export interface ModelUsageTotals {/** Finished materialization runs, including failures and cancellations. */runs: number;@@ -71396,6 +71416,8 @@ export namespace Schemas {models: ModelUsageRow[];/** Total number of models in the breakdown. */count: number;+ /** Latest run status for each model and engine in the selected complete-day range. */+ status_breakdown: ModelStatusBreakdown[];/*** Latest usage collection timestamp in this range.* @nullable@@ -128907,6 +128929,10 @@ export namespace Schemas {*/offset?: number;saved_query_id?: string;+ /**+ * Comma-separated materialized view IDs.+ */+ saved_query_ids?: string[];/*** * `Cancelled` - Cancelled* * `Completed` - Completed@@ -129017,9 +129043,13 @@ export namespace Schemas {page_size?: number;/*** Limit usage to one accessible materialized view.- * @nullable*/- saved_query_id?: string | null;+ saved_query_id?: string;+ /**+ * Comma-separated materialized view IDs. Usage is limited to accessible views.+ * @minLength 1+ */+ saved_query_ids?: string;};export type DataModelingUsageListEngine = typeof DataModelingUsageListEngine[keyof typeof DataModelingUsageListEngine];