: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-ops): add warehouse monitoring dashboard (#82885)
Eric Duong8321b562ec3f
diff --git a/docs/internal/managed-warehouse-monitoring.md b/docs/internal/managed-warehouse-monitoring.mdnew file mode 100644index 000000000000..341cb807df14--- /dev/null+++ b/docs/internal/managed-warehouse-monitoring.md@@ -0,0 +1,69 @@+# Managed warehouse monitoring++The **Monitoring** tab in Data ops gives every project in an organization the same operational view of its managed warehouse.+It combines a current fleet snapshot with allowlisted historical metrics from Duckgres.++## Request path and tenant boundary++The browser calls project-scoped PostHog endpoints:++- `GET /api/projects/{team_id}/data_warehouse/managed-warehouse-monitoring/`+- `GET /api/projects/{team_id}/data_warehouse/managed-warehouse-monitoring-timeseries/?metric=...&window=...`++PostHog derives the organization ID from the authenticated project and forwards the request to the corresponding organization-scoped Duckgres endpoint.+The browser never supplies an organization ID and never calls Duckgres directly.+Both PostHog actions require `warehouse_view:read`.++Duckgres only returns sanitized worker data.+The response excludes SQL text, usernames, client addresses, pod names, images, credentials, trace IDs, and control-plane ownership details.++### MCP access++Authenticated MCP clients can request the same organization-scoped data through these tools:++- `managed-warehouse-monitoring-get` for the current worker and workload snapshot+- `managed-warehouse-metric-history-get` for one operational metric over a trailing time window++Both tools require `warehouse_view:read` and are available when the `data-warehouse-scene` feature is enabled.+They use the active project to derive the organization and do not accept an organization ID from the caller.+The returned values describe operational activity and capacity, not invoiced usage.++## Snapshot++The snapshot contains:++- Warehouse state and configured worker limits+- Current worker, allocated CPU, allocated memory, session, running-query, and queued-connection totals+- One sanitized row per non-terminal worker, with its allocation, heartbeat, and optional live session progress+- Control-plane response coverage++Allocated CPU and memory describe the configured worker size, not measured CPU or memory utilization.+The `max_vcpus` setting limits active admitted session vCPUs; it is not a ceiling on the total CPU allocated to warm and active workers.+The UI must keep that distinction in labels and help text.++Legacy and default-profile workers persist empty resource sentinels.+Duckgres resolves those workers against the deployment defaults that provision their pods, rather than guessing from current organization defaults.+Query progress is returned as unavailable when DuckDB cannot estimate it, instead of failing the full snapshot.++Live sessions are held in memory by individual control-plane replicas.+Duckgres fans out the live portion of the snapshot and returns `cp_responders`, `cp_total`, and `partial`.+When coverage is partial, the UI labels live totals as incomplete instead of presenting missing replicas as zero activity.++## Historical metrics++The time-series endpoint accepts only named metrics and validated windows.+Duckgres maps each name to server-owned PromQL and applies the organization selector before querying Prometheus.+It is not an arbitrary PromQL proxy.++The dashboard displays query rate and outcomes, query latency, active sessions, worker acquisition latency and source, storage size, and worker crashes.+Each response includes a unit and labeled series so the UI can format values without guessing.++The dashboard loads historical data when the selected range changes or the user refreshes it.+The current snapshot polls more frequently while work is active and less frequently while the warehouse is idle.+If a refresh fails, the UI preserves the last successful data and shows how to retry.++## Usage scope++This first version reports operational activity and allocated capacity.+It does not calculate invoice totals or read Duckgres's billing delivery buffer, because acknowledged billing buckets are deleted after delivery.+Historical billable compute and storage belong in a billing-backed API rather than this monitoring path.diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 4e6c89741495..34abc4ac5b43 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -52,6 +52,8 @@ const ERROR_FILTER_ALLOW_LIST = ['loadToolDataEvents','loadPrChecks', // Polled in the Inbox report detail; the CI checks section renders its own error state'loadPrComments', // The Inbox report detail's PR comments section renders its own error state+ 'loadMonitoringSnapshot', // The managed warehouse Monitoring tab renders its own retry state+ 'loadMonitoringSeries', // The managed warehouse Monitoring tab renders its own partial/error state]/*diff --git a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsxindex d15398a67f22..31f318191113 100644--- a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx+++ b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx@@ -14,6 +14,7 @@ import { ProductKey } from '~/queries/schema/schema-general'import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'import { DataModelingTab } from './scene/DataModelingTab'+import { MonitoringTab } from './scene/MonitoringTab'import { OverviewTab } from './scene/OverviewTab'import { SettingsTab } from './scene/SettingsTab'@@ -25,6 +26,7 @@ export const scene: SceneExport = {const TAB_LABELS: Record<DataWarehouseTab, string> = {[DataWarehouseTab.OVERVIEW]: 'Overview',+ [DataWarehouseTab.MONITORING]: 'Monitoring',[DataWarehouseTab.SETTINGS]: 'Settings',[DataWarehouseTab.MODELING]: 'Modeling',}@@ -33,6 +35,8 @@ function tabContent(tab: DataWarehouseTab): JSX.Element {switch (tab) {case DataWarehouseTab.OVERVIEW:return <OverviewTab />+ case DataWarehouseTab.MONITORING:+ return <MonitoringTab />case DataWarehouseTab.SETTINGS:return <SettingsTab />case DataWarehouseTab.MODELING:diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.tsindex e319ea2afe34..a2136d40b399 100644--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts@@ -56,7 +56,7 @@ describe('dataWarehouseSceneLogic', () => {{name: 'warehouse ready',status: { state: 'ready' },- expectedTabs: [DataWarehouseTab.OVERVIEW, DataWarehouseTab.SETTINGS],+ expectedTabs: [DataWarehouseTab.OVERVIEW, DataWarehouseTab.MONITORING, DataWarehouseTab.SETTINGS],},])('$name', async ({ status, expectedTabs }) => {warehouseStatusResponse = status ? [200, status] : [404, {}]@@ -76,7 +76,7 @@ describe('dataWarehouseSceneLogic', () => {// The URL is parsed before the warehouse status arrives, so a requested tab has to survive the// wait — clamping it against a tab list that doesn't include Overview yet would drop it.- it.each([[DataWarehouseTab.OVERVIEW], [DataWarehouseTab.SETTINGS]])(+ it.each([[DataWarehouseTab.OVERVIEW], [DataWarehouseTab.MONITORING], [DataWarehouseTab.SETTINGS]])('honors a tab requested before the warehouse status resolves (%s)',async (tab) => {warehouseStatusResponse = [200, { state: 'ready' }]diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.tsindex 209b79d4ae6e..47569c148109 100644--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts@@ -13,6 +13,7 @@ import { warehouseProvisioningLogic } from './scene/warehouseProvisioningLogic'export enum DataWarehouseTab {OVERVIEW = 'overview',+ MONITORING = 'monitoring',SETTINGS = 'settings',MODELING = 'modeling',}@@ -119,6 +120,7 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([const tabs: DataWarehouseTab[] = []if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE] && warehouseReady) {tabs.push(DataWarehouseTab.OVERVIEW)+ tabs.push(DataWarehouseTab.MONITORING)}if (featureFlags[FEATURE_FLAGS.DATA_MODELING_TAB]) {tabs.push(DataWarehouseTab.MODELING)diff --git a/frontend/src/scenes/data-warehouse/scene/MonitoringTab.test.tsx b/frontend/src/scenes/data-warehouse/scene/MonitoringTab.test.tsxnew file mode 100644index 000000000000..b8f12b4e7cb5--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/MonitoringTab.test.tsx@@ -0,0 +1,179 @@+import '@testing-library/jest-dom'++import { act, cleanup, render, screen, waitFor } from '@testing-library/react'+import { Provider } from 'kea'++import { TimeSeriesLineChart } from '@posthog/quill-charts'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'++import {+ dataWarehouseManagedWarehouseMonitoringRetrieve,+ dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve,+} from 'products/data_warehouse/frontend/generated/api'+import type {+ ManagedWarehouseMonitoringSeriesResponseApi,+ ManagedWarehouseMonitoringSnapshotResponseApi,+} from 'products/data_warehouse/frontend/generated/api.schemas'++import { managedWarehouseMonitoringLogic } from './managedWarehouseMonitoringLogic'+import { MonitoringTab } from './MonitoringTab'++jest.mock('@posthog/quill-charts', () => ({+ ...jest.requireActual('@posthog/quill-charts'),+ TimeSeriesLineChart: jest.fn(({ series }: { series: Array<{ key: string }> }) => (+ <div data-testid="monitoring-chart">{series.map(({ key }) => key).join(',')}</div>+ )),+}))++jest.mock('products/data_warehouse/frontend/generated/api', () => ({+ dataWarehouseManagedWarehouseMonitoringRetrieve: jest.fn(),+ dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve: jest.fn(),+}))++const mockSnapshotRetrieve = dataWarehouseManagedWarehouseMonitoringRetrieve as jest.MockedFunction<+ typeof dataWarehouseManagedWarehouseMonitoringRetrieve+>+const mockSeriesRetrieve = dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve as jest.MockedFunction<+ typeof dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve+>+const mockTimeSeriesLineChart = jest.mocked(TimeSeriesLineChart)++const monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi = {+ schema_version: 1,+ org_id: 'org-1',+ as_of: '2026-08-12T10:00:00Z',+ warehouse: { state: 'ready' },+ limits: {+ max_workers: 10,+ max_vcpus: 20,+ default_worker_cpu: '2',+ default_worker_memory: '8Gi',+ default_worker_ttl_seconds: 300,+ default_worker_min_hot_idle: 1,+ },+ totals: {+ workers: 0,+ allocated_cpu_cores: 0,+ allocated_memory_bytes: 0,+ active_sessions: 0,+ running_queries: 0,+ queued_connections: 0,+ },+ workers: [],+ coverage: { cp_responders: 1, cp_total: 1, partial: false },+}++function seriesResponse(+ metric: ManagedWarehouseMonitoringSeriesResponseApi['metric']+): ManagedWarehouseMonitoringSeriesResponseApi {+ return {+ schema_version: 1,+ org_id: 'org-1',+ metric,+ unit: 'count',+ start: '2026-08-12T09:59:00Z',+ end: '2026-08-12T10:00:00Z',+ step_seconds: 60,+ series: [+ {+ labels: {},+ points: [+ { timestamp: '2026-08-12T09:59:00Z', value: 1 },+ { timestamp: '2026-08-12T10:00:00Z', value: 2 },+ ],+ },+ ],+ }+}++describe('MonitoringTab', () => {+ let logic: ReturnType<typeof managedWarehouseMonitoringLogic.build>++ beforeEach(() => {+ initKeaTests()+ silenceKeaLoadersErrors()+ mockSnapshotRetrieve.mockReset()+ mockSeriesRetrieve.mockReset()+ mockTimeSeriesLineChart.mockClear()+ mockSnapshotRetrieve.mockResolvedValue(monitoringSnapshot)+ mockSeriesRetrieve.mockRejectedValue(new Error('series unavailable'))+ logic = managedWarehouseMonitoringLogic()+ })++ afterEach(() => {+ cleanup()+ resumeKeaLoadersErrors()+ })++ it('keeps settled empty charts mounted while another time range loads', async () => {+ render(+ <Provider>+ <MonitoringTab />+ </Provider>+ )++ await screen.findByText("Historical metrics couldn't be loaded. Refresh to try again.")+ expect(screen.queryByText('Data read rate')).not.toBeInTheDocument()+ expect(screen.getByText('Tracked storage')).toBeInTheDocument()+ const settledEmptyCharts = screen.getAllByText('No data in this time range.')+ expect(settledEmptyCharts).toHaveLength(7)++ const resolveRequests: Array<() => void> = []+ mockSeriesRetrieve.mockImplementation(+ async (_teamId, { metric }) =>+ await new Promise<ManagedWarehouseMonitoringSeriesResponseApi>((resolve) => {+ resolveRequests.push(() => resolve({ ...seriesResponse(metric), series: [] }))+ })+ )++ act(() => logic.actions.setMonitoringWindow('7d'))+ await waitFor(() => expect(logic.values.monitoringSeriesLoading).toBe(true))++ const emptyChartsWhileLoading = screen.getAllByText('No data in this time range.')+ expect(emptyChartsWhileLoading).toHaveLength(settledEmptyCharts.length)+ emptyChartsWhileLoading.forEach((chart, index) => expect(chart).toBe(settledEmptyCharts[index]))+ expect(screen.getByText("Historical metrics couldn't be loaded. Refresh to try again.")).toBeInTheDocument()++ await act(async () => {+ for (const resolveRequest of resolveRequests) {+ resolveRequest()+ }+ })+ await waitFor(() => expect(logic.values.monitoringSeriesLoading).toBe(false))+ })++ it('does not redraw populated charts for an in-flight time range', async () => {+ mockSeriesRetrieve.mockImplementation(async (_teamId, { metric }) => seriesResponse(metric))+ render(+ <Provider>+ <MonitoringTab />+ </Provider>+ )++ await waitFor(() => expect(mockTimeSeriesLineChart).toHaveBeenCalledTimes(7))+ mockTimeSeriesLineChart.mockClear()++ const resolveRequests: Array<() => void> = []+ mockSeriesRetrieve.mockImplementation(+ async (_teamId, { metric }) =>+ await new Promise<ManagedWarehouseMonitoringSeriesResponseApi>((resolve) => {+ resolveRequests.push(() => resolve(seriesResponse(metric)))+ })+ )++ act(() => logic.actions.setMonitoringWindow('7d'))+ await waitFor(() => expect(logic.values.monitoringSeriesLoading).toBe(true))++ expect(mockTimeSeriesLineChart).not.toHaveBeenCalled()++ await act(async () => {+ for (const resolveRequest of resolveRequests) {+ resolveRequest()+ }+ })+ await waitFor(() => expect(logic.values.monitoringSeriesLoading).toBe(false))+ expect(mockTimeSeriesLineChart).toHaveBeenCalledTimes(7)+ })+})diff --git a/frontend/src/scenes/data-warehouse/scene/MonitoringTab.tsx b/frontend/src/scenes/data-warehouse/scene/MonitoringTab.tsxnew file mode 100644index 000000000000..2c796aca675d--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/MonitoringTab.tsx@@ -0,0 +1,493 @@+import { useActions, useValues } from 'kea'+import { memo, useMemo } from 'react'+import type { ReactNode } from 'react'++import { IconRefresh } from '@posthog/icons'+import { TimeSeriesLineChart, createXAxisTickCallback } from '@posthog/quill-charts'+import type { TimeSeriesLineChartConfig } from '@posthog/quill-charts'++import { useChartConfig, useChartTheme } from 'lib/charts/hooks'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonCard } from 'lib/lemon-ui/LemonCard'+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { humanFriendlyNumber, humanizeBytes, percentage } from 'lib/utils/numbers'++import type {+ ManagedWarehouseMonitoringSeriesResponseApi,+ ManagedWarehouseMonitoringSnapshotResponseApi,+} from 'products/data_warehouse/frontend/generated/api.schemas'++import { MONITORING_WINDOW_OPTIONS, managedWarehouseMonitoringLogic } from './managedWarehouseMonitoringLogic'+import type { MonitoringWorker } from './managedWarehouseMonitoringLogic'+import { buildMonitoringChartData } from './monitoringChartData'+import type { MonitoringChartMetricConfig } from './monitoringChartData'++const WORKER_STATE_TAGS: Record<string, LemonTagType> = {+ hot: 'success',+ hot_idle: 'success',+ idle: 'muted',+ reserved: 'primary',+ activating: 'warning',+ spawning: 'warning',+ draining: 'caution',+ lost: 'danger',+}++const WAREHOUSE_STATE_TAGS: Record<string, LemonTagType> = {+ ready: 'success',+ provisioning: 'warning',+ resharding: 'warning',+ deleting: 'caution',+ failed: 'danger',+}++function sentenceCase(value: string): string {+ const normalized = value.replaceAll('_', ' ')+ return normalized.charAt(0).toUpperCase() + normalized.slice(1)+}++function MonitoringMetricCard({+ label,+ value,+ description,+ loading,+}: {+ label: string+ value: string+ description: string+ loading: boolean+}): JSX.Element {+ return (+ <LemonCard hoverEffect={false} className="min-h-32 p-4">+ <div className="text-sm font-semibold text-muted-alt">{label}</div>+ {loading ? (+ <LemonSkeleton className="my-3 h-8 w-24" />+ ) : (+ <div className="my-2 truncate text-3xl font-bold tabular-nums">{value}</div>+ )}+ <div className="text-xs text-muted">{description}</div>+ </LemonCard>+ )+}++function MonitoringChart({+ title,+ description,+ responses,+ metrics,+ yAxis,+ valueFormatter,+ loading,+}: {+ title: string+ description: string+ responses: ManagedWarehouseMonitoringSeriesResponseApi[]+ metrics: MonitoringChartMetricConfig[]+ yAxis?: TimeSeriesLineChartConfig['yAxis']+ valueFormatter?: (value: number) => string+ loading: boolean+}): JSX.Element {+ const theme = useChartTheme()+ const data = useMemo(() => buildMonitoringChartData(responses, metrics), [responses, metrics])+ const config = useChartConfig<TimeSeriesLineChartConfig>(+ () => ({+ xAxis: {+ timezone: 'UTC',+ tickFormatter: createXAxisTickCallback({ allDays: data.labels, timezone: 'UTC' }),+ },+ yAxis,+ legend: { show: data.series.length > 1, interactive: true, position: 'bottom' },+ tooltip: { placement: 'cursor', sortedByValue: true, valueFormatter },+ }),+ [data.labels, data.series.length, valueFormatter, yAxis]+ )++ return (+ <LemonCard hoverEffect={false} className="flex min-h-80 flex-col p-4">+ <div className="mb-4">+ <h3 className="mb-1">{title}</h3>+ <p className="mb-0 text-xs text-muted">{description}</p>+ </div>+ {loading && !data.labels.length ? (+ <LemonSkeleton className="h-64 w-full" />+ ) : data.labels.length && data.series.length ? (+ <div className="flex h-64 flex-col">+ <TimeSeriesLineChart series={data.series} labels={data.labels} theme={theme} config={config} />+ </div>+ ) : (+ <div className="flex h-64 items-center justify-center text-muted">No data in this time range.</div>+ )}+ </LemonCard>+ )+}++function WorkerState({ worker }: { worker: MonitoringWorker }): JSX.Element {+ if (worker.session?.stalled) {+ return <LemonTag type="danger">Stalled</LemonTag>+ }+ return <LemonTag type={WORKER_STATE_TAGS[worker.state] ?? 'default'}>{sentenceCase(worker.state)}</LemonTag>+}++function SessionProgress({ worker }: { worker: MonitoringWorker }): JSX.Element {+ if (!worker.session) {+ return <span className="text-muted">No active session</span>+ }++ const progress = worker.session.percentage+ const rows = `${humanFriendlyNumber(worker.session.rows)} / ${humanFriendlyNumber(worker.session.total_rows)} rows`++ return (+ <div className="min-w-48 space-y-1">+ <div className="flex items-center justify-between gap-2 text-xs">+ <span>+ {sentenceCase(worker.session.state)} via {worker.session.protocol}+ </span>+ <span className="text-muted">{humanFriendlyDuration(worker.session.elapsed_ms / 1000)}</span>+ </div>+ {progress !== null && progress >= 0 && <LemonProgress percent={Math.min(100, progress)} />}+ <div className="text-xs text-muted">{rows}</div>+ </div>+ )+}++const workerColumns: LemonTableColumns<MonitoringWorker> = [+ {+ title: 'Worker',+ dataIndex: 'id',+ render: (id) => (+ <code className="block max-w-48 truncate" title={String(id)}>+ {String(id)}+ </code>+ ),+ },+ {+ title: 'State',+ key: 'state',+ render: (_, worker) => <WorkerState worker={worker} />,+ },+ {+ title: 'Allocated resources',+ key: 'resources',+ render: (_, worker) => (+ <div>+ <div>{worker.cpu ? `${worker.cpu} CPU` : 'CPU unavailable'}</div>+ <div className="text-xs text-muted">+ {worker.memory ? `${worker.memory} memory` : 'Memory unavailable'}+ </div>+ </div>+ ),+ },+ {+ title: 'Session',+ key: 'session',+ render: (_, worker) => <SessionProgress worker={worker} />,+ },+ {+ title: 'Created',+ dataIndex: 'created_at',+ render: (createdAt) => humanFriendlyDetailedTime(String(createdAt)),+ },+ {+ title: 'Last heartbeat',+ dataIndex: 'last_heartbeat_at',+ render: (lastHeartbeatAt) => humanFriendlyDetailedTime(lastHeartbeatAt ? String(lastHeartbeatAt) : null),+ },+]++function SummaryCards({+ snapshot,+ loading,+}: {+ snapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null+ loading: boolean+}): JSX.Element {+ const workerValue = snapshot+ ? snapshot.limits.max_workers > 0+ ? `${snapshot.totals.workers} / ${snapshot.limits.max_workers}`+ : humanFriendlyNumber(snapshot.totals.workers)+ : '-'+ return (+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-6">+ <MonitoringMetricCard+ label="Workers"+ value={workerValue}+ description={+ snapshot?.limits.max_workers === 0+ ? 'Current workers. No organization-specific limit.'+ : 'Current workers and organization limit'+ }+ loading={loading}+ />+ <MonitoringMetricCard+ label="Active sessions"+ value={snapshot ? humanFriendlyNumber(snapshot.totals.active_sessions) : '-'}+ description={+ snapshot?.limits.max_vcpus === 0+ ? 'Open sessions. No organization-specific vCPU admission limit.'+ : `Open sessions. Admission limit: ${humanFriendlyNumber(snapshot?.limits.max_vcpus ?? 0)} active vCPUs.`+ }+ loading={loading}+ />+ <MonitoringMetricCard+ label="Running queries"+ value={snapshot ? humanFriendlyNumber(snapshot.totals.running_queries) : '-'}+ description="Queries currently running"+ loading={loading}+ />+ <MonitoringMetricCard+ label="Queued connections"+ value={snapshot ? humanFriendlyNumber(snapshot.totals.queued_connections) : '-'}+ description="Connections waiting for a worker"+ loading={loading}+ />+ <MonitoringMetricCard+ label="Allocated CPU"+ value={snapshot ? humanFriendlyNumber(snapshot.totals.allocated_cpu_cores) : '-'}+ description="Worker CPU cores currently allocated"+ loading={loading}+ />+ <MonitoringMetricCard+ label="Allocated memory"+ value={snapshot ? humanizeBytes(snapshot.totals.allocated_memory_bytes) : '-'}+ description="Worker memory currently allocated"+ loading={loading}+ />+ </div>+ )+}++function MonitoringSection({+ title,+ description,+ children,+}: {+ title: string+ description: string+ children: ReactNode+}): JSX.Element {+ return (+ <section className="space-y-3">+ <div>+ <h2 className="mb-1">{title}</h2>+ <p className="mb-0 text-muted">{description}</p>+ </div>+ {children}+ </section>+ )+}++interface HistoricalMonitoringChartsProps {+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[]+ initialLoading: boolean+}++const HistoricalMonitoringCharts = memo(function HistoricalMonitoringCharts({+ monitoringSeries,+ initialLoading,+}: HistoricalMonitoringChartsProps): JSX.Element {+ return (+ <>+ <MonitoringSection+ title="Query health"+ description="Query volume, failures, and duration for the selected time range."+ >+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">+ <MonitoringChart+ title="Query rate"+ description="Queries per second, split by status and reason"+ responses={monitoringSeries}+ metrics={[{ metric: 'query_rate', fallbackLabel: 'Queries' }]}+ valueFormatter={(value) => `${humanFriendlyNumber(value)}/s`}+ loading={initialLoading}+ />+ <MonitoringChart+ title="Query error ratio"+ description="Share of queries that returned an error"+ responses={monitoringSeries}+ metrics={[{ metric: 'error_ratio', fallbackLabel: 'Errors' }]}+ yAxis={{ format: 'percentage' }}+ valueFormatter={(value) => percentage(value)}+ loading={initialLoading}+ />+ <MonitoringChart+ title="Query duration"+ description="Median and p95 query duration"+ responses={monitoringSeries}+ metrics={[+ { metric: 'duration_p50', fallbackLabel: 'p50' },+ { metric: 'duration_p95', fallbackLabel: 'p95' },+ ]}+ yAxis={{ format: 'duration' }}+ valueFormatter={(value) => humanFriendlyDuration(value, { secondsPrecision: 2 })}+ loading={initialLoading}+ />+ </div>+ </MonitoringSection>++ <MonitoringSection+ title="Capacity"+ description="Worker demand, connection wait time, and unexpected worker exits."+ >+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">+ <MonitoringChart+ title="Active sessions"+ description="Open sessions using warehouse capacity"+ responses={monitoringSeries}+ metrics={[{ metric: 'sessions_active', fallbackLabel: 'Sessions' }]}+ valueFormatter={(value) => humanFriendlyNumber(value)}+ loading={initialLoading}+ />+ <MonitoringChart+ title="Worker acquisition time"+ description="p95 time to assign a worker, split by source"+ responses={monitoringSeries}+ metrics={[{ metric: 'acquire_p95', fallbackLabel: 'Acquire p95' }]}+ yAxis={{ format: 'duration' }}+ valueFormatter={(value) => humanFriendlyDuration(value, { secondsPrecision: 2 })}+ loading={initialLoading}+ />+ <MonitoringChart+ title="Worker crash rate"+ description="Unexpected worker exits per second"+ responses={monitoringSeries}+ metrics={[{ metric: 'worker_crash_rate', fallbackLabel: 'Crashes' }]}+ valueFormatter={(value) => `${humanFriendlyNumber(value)}/s`}+ loading={initialLoading}+ />+ </div>+ </MonitoringSection>++ <MonitoringSection title="Storage" description="Tracked warehouse storage over time.">+ <div className="grid grid-cols-1 gap-4">+ <MonitoringChart+ title="Tracked storage"+ description="Current warehouse data stored in object storage"+ responses={monitoringSeries}+ metrics={[{ metric: 'storage_bytes', fallbackLabel: 'Storage' }]}+ yAxis={{ tickFormatter: (value: number) => humanizeBytes(value) }}+ valueFormatter={humanizeBytes}+ loading={initialLoading}+ />+ </div>+ </MonitoringSection>+ </>+ )+})++export function MonitoringTab(): JSX.Element {+ const {+ monitoringSnapshot,+ monitoringSnapshotLoading,+ monitoringSnapshotError,+ monitoringSeries,+ initialMonitoringSeriesLoading,+ monitoringSeriesLoading,+ monitoringSeriesError,+ monitoringWindow,+ sortedWorkers,+ } = useValues(managedWarehouseMonitoringLogic)+ const { refreshMonitoring, setMonitoringWindow } = useActions(managedWarehouseMonitoringLogic)+ const initialLoading = monitoringSnapshotLoading && !monitoringSnapshot++ if (!monitoringSnapshot && monitoringSnapshotError) {+ return (+ <LemonBanner+ type="error"+ className="mt-4"+ action={{+ children: 'Try again',+ onClick: refreshMonitoring,+ loading: monitoringSnapshotLoading || monitoringSeriesLoading,+ }}+ >+ Couldn't load warehouse monitoring. Refresh to try again.+ </LemonBanner>+ )+ }++ return (+ <div className="mt-4 space-y-6">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <div className="mb-1 flex items-center gap-2">+ <h2 className="mb-0">Warehouse monitoring</h2>+ {monitoringSnapshot && (+ <LemonTag type={WAREHOUSE_STATE_TAGS[monitoringSnapshot.warehouse.state] ?? 'default'}>+ {sentenceCase(monitoringSnapshot.warehouse.state)}+ </LemonTag>+ )}+ </div>+ <p className="mb-0 text-muted">+ View workers, query health, and resource usage across this organization.+ </p>+ {monitoringSnapshot && (+ <p className="mb-0 mt-1 text-xs text-muted">+ Updated {humanFriendlyDetailedTime(monitoringSnapshot.as_of)}+ </p>+ )}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <LemonSegmentedButton+ value={monitoringWindow}+ onChange={setMonitoringWindow}+ options={MONITORING_WINDOW_OPTIONS}+ size="small"+ />+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ onClick={refreshMonitoring}+ loading={monitoringSnapshotLoading || monitoringSeriesLoading}+ >+ Refresh+ </LemonButton>+ </div>+ </div>++ {monitoringSnapshot && monitoringSnapshotError && (+ <LemonBanner type="warning">+ Live worker data couldn't be refreshed. Showing the most recent available data.+ </LemonBanner>+ )}+ {monitoringSnapshot?.coverage.partial && (+ <LemonBanner type="warning">+ Worker data is incomplete. {monitoringSnapshot.coverage.cp_responders} of{' '}+ {monitoringSnapshot.coverage.cp_total} known control planes responded. Refresh to try again.+ </LemonBanner>+ )}+ {monitoringSeriesError && (+ <LemonBanner type="warning">+ {monitoringSeries.length > 0+ ? "Some historical metrics couldn't be refreshed. Available charts show the most recent data."+ : "Historical metrics couldn't be loaded. Refresh to try again."}+ </LemonBanner>+ )}++ <SummaryCards snapshot={monitoringSnapshot} loading={initialLoading} />++ <HistoricalMonitoringCharts+ monitoringSeries={monitoringSeries}+ initialLoading={initialMonitoringSeriesLoading}+ />++ <MonitoringSection title="Workers" description="Current workers and their allocated resources.">+ <LemonTable+ columns={workerColumns}+ dataSource={sortedWorkers}+ rowKey="id"+ loading={initialLoading}+ loadingSkeletonRows={3}+ pagination={{ pageSize: 20 }}+ emptyState="No workers are currently allocated. Run a query to start one."+ />+ </MonitoringSection>+ </div>+ )+}diff --git a/frontend/src/scenes/data-warehouse/scene/managedWarehouseMonitoringLogic.test.ts b/frontend/src/scenes/data-warehouse/scene/managedWarehouseMonitoringLogic.test.tsnew file mode 100644index 000000000000..a8ea1c7bd362--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/managedWarehouseMonitoringLogic.test.ts@@ -0,0 +1,357 @@+import { MOCK_DEFAULT_TEAM, MOCK_TEAM_ID } from 'lib/api.mock'++import { teamLogic } from 'scenes/teamLogic'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'++import {+ dataWarehouseManagedWarehouseMonitoringRetrieve,+ dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve,+} from 'products/data_warehouse/frontend/generated/api'+import type {+ DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams,+ ManagedWarehouseMonitoringSeriesResponseApi,+ ManagedWarehouseMonitoringSnapshotResponseApi,+} from 'products/data_warehouse/frontend/generated/api.schemas'++import { managedWarehouseMonitoringLogic } from './managedWarehouseMonitoringLogic'++jest.mock('products/data_warehouse/frontend/generated/api', () => ({+ dataWarehouseManagedWarehouseMonitoringRetrieve: jest.fn(),+ dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve: jest.fn(),+}))++const mockSnapshotRetrieve = dataWarehouseManagedWarehouseMonitoringRetrieve as jest.MockedFunction<+ typeof dataWarehouseManagedWarehouseMonitoringRetrieve+>+const mockSeriesRetrieve = dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve as jest.MockedFunction<+ typeof dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve+>++function snapshot({+ organizationId = 'org-1',+ runningQueries = 0,+}: {+ organizationId?: string+ runningQueries?: number+} = {}): ManagedWarehouseMonitoringSnapshotResponseApi {+ return {+ schema_version: 1,+ org_id: organizationId,+ as_of: '2026-08-12T10:00:00Z',+ warehouse: { state: 'ready' },+ limits: {+ max_workers: 10,+ max_vcpus: 20,+ default_worker_cpu: '2',+ default_worker_memory: '8Gi',+ default_worker_ttl_seconds: 300,+ default_worker_min_hot_idle: 1,+ },+ totals: {+ workers: 1,+ allocated_cpu_cores: 2,+ allocated_memory_bytes: 8 * 1024 ** 3,+ active_sessions: runningQueries,+ running_queries: runningQueries,+ queued_connections: 0,+ },+ workers: [+ {+ id: `worker-${organizationId}`,+ state: 'hot',+ cpu: '2',+ memory: '8Gi',+ ttl_seconds: 300,+ created_at: '2026-08-12T09:55:00Z',+ last_heartbeat_at: '2026-08-12T10:00:00Z',+ session: null,+ },+ ],+ coverage: { cp_responders: 2, cp_total: 2, partial: false },+ }+}++function seriesResponse(+ metric: DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams['metric'],+ organizationId = 'org-1'+): ManagedWarehouseMonitoringSeriesResponseApi {+ return {+ schema_version: 1,+ org_id: organizationId,+ metric,+ unit: 'count',+ start: '2026-08-12T09:59:00Z',+ end: '2026-08-12T10:00:00Z',+ step_seconds: 60,+ series: [+ {+ labels: {},+ points: [+ { timestamp: '2026-08-12T09:59:00Z', value: 1 },+ { timestamp: '2026-08-12T10:00:00Z', value: 2 },+ ],+ },+ ],+ }+}++describe('managedWarehouseMonitoringLogic', () => {+ let logic: ReturnType<typeof managedWarehouseMonitoringLogic.build>++ const mountLogic = (): void => {+ logic = managedWarehouseMonitoringLogic()+ logic.mount()+ }++ beforeEach(() => {+ jest.useFakeTimers()+ initKeaTests()+ mockSnapshotRetrieve.mockReset()+ mockSeriesRetrieve.mockReset()+ mockSnapshotRetrieve.mockImplementation(async (teamId) => snapshot({ organizationId: `org-${teamId}` }))+ mockSeriesRetrieve.mockImplementation(async (teamId, { metric }) => seriesResponse(metric, `org-${teamId}`))+ })++ afterEach(() => {+ logic?.unmount()+ resumeKeaLoadersErrors()+ jest.useRealTimers()+ })++ it('loads the live snapshot and every displayed series on mount', async () => {+ mountLogic()++ expect(logic.values.monitoringSnapshotLoading).toBe(true)+ expect(logic.values.monitoringSeriesLoading).toBe(true)++ await jest.advanceTimersByTimeAsync(0)++ expect(mockSnapshotRetrieve).toHaveBeenCalledWith(String(MOCK_TEAM_ID))+ expect(mockSeriesRetrieve).toHaveBeenCalledTimes(8)+ expect(mockSeriesRetrieve.mock.calls.map(([, { metric }]) => metric)).toEqual([+ 'query_rate',+ 'error_ratio',+ 'duration_p50',+ 'duration_p95',+ 'sessions_active',+ 'acquire_p95',+ 'storage_bytes',+ 'worker_crash_rate',+ ])+ expect(logic.values.monitoringSnapshot?.org_id).toBe(`org-${MOCK_TEAM_ID}`)+ expect(logic.values.monitoringSeries).toHaveLength(8)+ })++ it.each([+ { name: 'active work', runningQueries: 1, intervalMs: 15_000 },+ { name: 'stable warehouse', runningQueries: 0, intervalMs: 60_000 },+ ])('polls the snapshot at the expected interval for $name', async ({ runningQueries, intervalMs }) => {+ mockSnapshotRetrieve.mockResolvedValue(snapshot({ runningQueries }))+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)++ await jest.advanceTimersByTimeAsync(intervalMs - 1)+ expect(mockSnapshotRetrieve).toHaveBeenCalledTimes(1)++ await jest.advanceTimersByTimeAsync(1)+ expect(mockSnapshotRetrieve).toHaveBeenCalledTimes(2)+ })++ it('reloads every series when the time window changes', async () => {+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)+ const previousSeries = logic.values.monitoringSeries+ mockSeriesRetrieve.mockClear()+ mockSeriesRetrieve.mockImplementation(async (teamId, { metric }) => {+ if (metric === 'error_ratio') {+ throw new Error('metric unavailable')+ }+ return seriesResponse(metric, `org-${teamId}`)+ })++ logic.actions.setMonitoringWindow('7d')+ expect(logic.values.monitoringSeries).toBe(previousSeries)+ expect(logic.values.monitoringSeriesLoading).toBe(true)+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.monitoringWindow).toBe('7d')+ expect(logic.values.monitoringSeriesWindow).toBe('7d')+ expect(mockSeriesRetrieve).toHaveBeenCalledTimes(8)+ expect(mockSeriesRetrieve.mock.calls.every(([, params]) => params.window === '7d')).toBe(true)+ expect(logic.values.monitoringSeries).toHaveLength(7)+ expect(logic.values.monitoringSeries.some((response) => response.metric === 'error_ratio')).toBe(false)+ })++ it('keeps settled empty charts stable while retrying after a series error', async () => {+ silenceKeaLoadersErrors()+ mockSeriesRetrieve.mockRejectedValue(new Error('series unavailable'))+ mountLogic()++ expect(logic.values.initialMonitoringSeriesLoading).toBe(true)+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.monitoringSeries).toEqual([])+ expect(logic.values.monitoringSeriesError).toBe(true)+ expect(logic.values.monitoringSeriesResolved).toBe(true)+ expect(logic.values.initialMonitoringSeriesLoading).toBe(false)++ logic.actions.setMonitoringWindow('7d')++ expect(logic.values.monitoringSeriesLoading).toBe(true)+ expect(logic.values.monitoringSeriesError).toBe(true)+ expect(logic.values.initialMonitoringSeriesLoading).toBe(false)+ await jest.advanceTimersByTimeAsync(0)+ })++ it('keeps the previous value for a metric when other metrics refresh successfully', async () => {+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)+ const previousErrorRatio = logic.values.monitoringSeries.find((response) => response.metric === 'error_ratio')+ mockSeriesRetrieve.mockImplementation(async (teamId, { metric }) => {+ if (metric === 'error_ratio') {+ throw new Error('metric unavailable')+ }+ return seriesResponse(metric, `org-${teamId}`)+ })++ logic.actions.refreshMonitoring()+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.monitoringSeries).toHaveLength(8)+ expect(logic.values.monitoringSeries.find((response) => response.metric === 'error_ratio')).toBe(+ previousErrorRatio+ )+ expect(logic.values.monitoringSeriesError).toBe(true)+ })++ it('keeps the last good data and marks each section when refreshes fail', async () => {+ silenceKeaLoadersErrors()+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)+ const previousSnapshot = logic.values.monitoringSnapshot+ const previousSeries = logic.values.monitoringSeries+ mockSnapshotRetrieve.mockRejectedValueOnce(new Error('snapshot unavailable'))+ mockSeriesRetrieve.mockRejectedValue(new Error('series unavailable'))++ logic.actions.refreshMonitoring()+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.monitoringSnapshot).toBe(previousSnapshot)+ expect(logic.values.monitoringSeries).toBe(previousSeries)+ expect(logic.values.monitoringSnapshotError).toBe(true)+ expect(logic.values.monitoringSeriesError).toBe(true)+ })++ it('stops polling after unmount', async () => {+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)+ const snapshotCalls = mockSnapshotRetrieve.mock.calls.length+ const seriesCalls = mockSeriesRetrieve.mock.calls.length++ logic.unmount()+ await jest.advanceTimersByTimeAsync(120_000)++ expect(mockSnapshotRetrieve).toHaveBeenCalledTimes(snapshotCalls)+ expect(mockSeriesRetrieve).toHaveBeenCalledTimes(seriesCalls)+ })++ it('clears organization data before loading it for a new team', async () => {+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.monitoringSnapshot?.org_id).toBe(`org-${MOCK_TEAM_ID}`)++ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ id: 1234,+ project_id: 1234,+ organization: 'org-2',+ })++ expect(logic.values.monitoringSnapshot).toBeNull()+ expect(logic.values.monitoringSeries).toEqual([])++ await jest.advanceTimersByTimeAsync(0)+ expect(mockSnapshotRetrieve).toHaveBeenLastCalledWith('1234')+ expect(logic.values.monitoringSnapshot?.org_id).toBe('org-1234')+ expect(logic.values.monitoringSeries.every((response) => response.org_id === 'org-1234')).toBe(true)+ })++ it('ignores responses from requests superseded by a team change', async () => {+ let resolveOldSnapshot: ((value: ManagedWarehouseMonitoringSnapshotResponseApi) => void) | undefined+ const oldSeriesResolvers = new Map<+ DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams['metric'],+ (value: ManagedWarehouseMonitoringSeriesResponseApi) => void+ >()+ mockSnapshotRetrieve.mockImplementation(+ async (teamId) =>+ await (teamId === String(MOCK_TEAM_ID)+ ? new Promise<ManagedWarehouseMonitoringSnapshotResponseApi>((resolve) => {+ resolveOldSnapshot = resolve+ })+ : Promise.resolve(snapshot({ organizationId: `org-${teamId}` })))+ )+ mockSeriesRetrieve.mockImplementation(+ async (teamId, { metric }) =>+ await (teamId === String(MOCK_TEAM_ID)+ ? new Promise<ManagedWarehouseMonitoringSeriesResponseApi>((resolve) => {+ oldSeriesResolvers.set(metric, resolve)+ })+ : Promise.resolve(seriesResponse(metric, `org-${teamId}`)))+ )+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)++ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ id: 1234,+ project_id: 1234,+ organization: 'org-2',+ })+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.monitoringSnapshot?.org_id).toBe('org-1234')++ resolveOldSnapshot?.(snapshot({ organizationId: `org-${MOCK_TEAM_ID}` }))+ for (const [metric, resolve] of oldSeriesResolvers) {+ resolve(seriesResponse(metric, `org-${MOCK_TEAM_ID}`))+ }+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.monitoringSnapshot?.org_id).toBe('org-1234')+ expect(logic.values.monitoringSeries).toHaveLength(8)+ expect(logic.values.monitoringSeries.every((response) => response.org_id === 'org-1234')).toBe(true)+ })++ it('ignores failures from requests superseded by a team change', async () => {+ silenceKeaLoadersErrors()+ let rejectOldSnapshot: ((reason: Error) => void) | undefined+ mockSnapshotRetrieve.mockImplementation(+ async (teamId) =>+ await (teamId === String(MOCK_TEAM_ID)+ ? new Promise<ManagedWarehouseMonitoringSnapshotResponseApi>((_, reject) => {+ rejectOldSnapshot = reject+ })+ : Promise.resolve(snapshot({ organizationId: `org-${teamId}` })))+ )+ mountLogic()+ await jest.advanceTimersByTimeAsync(0)++ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ id: 1234,+ project_id: 1234,+ organization: 'org-2',+ })+ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.monitoringSnapshot?.org_id).toBe('org-1234')+ expect(logic.values.monitoringSnapshotError).toBe(false)++ rejectOldSnapshot?.(new Error('old organization unavailable'))+ await jest.advanceTimersByTimeAsync(0)++ expect(logic.values.monitoringSnapshot?.org_id).toBe('org-1234')+ expect(logic.values.monitoringSnapshotError).toBe(false)+ expect(logic.values.monitoringSnapshotLoading).toBe(false)+ })+})diff --git a/frontend/src/scenes/data-warehouse/scene/managedWarehouseMonitoringLogic.ts b/frontend/src/scenes/data-warehouse/scene/managedWarehouseMonitoringLogic.tsnew file mode 100644index 000000000000..c95e565c9f95--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/managedWarehouseMonitoringLogic.ts@@ -0,0 +1,368 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { teamLogic } from 'scenes/teamLogic'++import {+ dataWarehouseManagedWarehouseMonitoringRetrieve,+ dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve,+} from 'products/data_warehouse/frontend/generated/api'+import type {+ DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams,+ ManagedWarehouseMonitoringSeriesResponseApi,+ ManagedWarehouseMonitoringSnapshotResponseApi,+} from 'products/data_warehouse/frontend/generated/api.schemas'++const ACTIVE_REFRESH_INTERVAL_MS = 15_000+const STABLE_REFRESH_INTERVAL_MS = 60_000+const SERIES_REFRESH_INTERVAL_MS = 60_000++export type MonitoringWindow = NonNullable<DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams['window']>+export type MonitoringMetric = NonNullable<DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams['metric']>+export type MonitoringWorker = ManagedWarehouseMonitoringSnapshotResponseApi['workers'][number]++export const MONITORING_WINDOW_OPTIONS: { label: string; value: MonitoringWindow }[] = [+ { label: '1h', value: '1h' },+ { label: '6h', value: '6h' },+ { label: '24h', value: '24h' },+ { label: '7d', value: '7d' },+ { label: '30d', value: '30d' },+]++const MONITORING_METRICS: MonitoringMetric[] = [+ 'query_rate',+ 'error_ratio',+ 'duration_p50',+ 'duration_p95',+ 'sessions_active',+ 'acquire_p95',+ 'storage_bytes',+ 'worker_crash_rate',+]++const WORKER_STATE_SEVERITY: Record<string, number> = {+ lost: 0,+ draining: 1,+ spawning: 2,+ activating: 3,+ reserved: 4,+ hot: 5,+ hot_idle: 6,+ idle: 7,+}++function workerSeverity(worker: MonitoringWorker): number {+ if (worker.session?.stalled) {+ return -1+ }+ return WORKER_STATE_SEVERITY[worker.state] ?? 100+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface managedWarehouseMonitoringLogicValues {+ currentTeamId: number | null // teamLogic+ hasLiveActivity: boolean+ initialMonitoringSeriesLoading: boolean+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[]+ monitoringSeriesError: boolean+ monitoringSeriesLoading: boolean+ monitoringSeriesResolved: boolean+ monitoringSeriesWindow: MonitoringWindow | null+ monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null+ monitoringSnapshotError: boolean+ monitoringSnapshotLoading: boolean+ monitoringWindow: MonitoringWindow+ sortedWorkers: MonitoringWorker[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface managedWarehouseMonitoringLogicActions {+ loadMonitoringSeries: (requestedWindow: MonitoringWindow | undefined) => MonitoringWindow | undefined+ loadMonitoringSeriesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMonitoringSeriesSuccess: (+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[],+ payload?: MonitoringWindow | undefined+ ) => {+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[]+ payload?: MonitoringWindow | undefined+ }+ loadMonitoringSnapshot: (_: void) => void+ loadMonitoringSnapshotFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadMonitoringSnapshotSuccess: (+ monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null,+ payload?: void+ ) => {+ monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null+ payload?: void+ }+ refreshMonitoring: () => {+ value: true+ }+ resetMonitoringData: () => {+ value: true+ }+ setMonitoringSeriesError: (hasError: boolean) => {+ hasError: boolean+ }+ setMonitoringSnapshotError: (hasError: boolean) => {+ hasError: boolean+ }+ setMonitoringWindow: (monitoringWindow: MonitoringWindow) => {+ monitoringWindow: MonitoringWindow+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface managedWarehouseMonitoringLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ initialMonitoringSeriesLoading: (+ monitoringSeriesLoading: boolean,+ monitoringSeriesResolved: boolean,+ monitoringSeriesError: boolean+ ) => boolean+ hasLiveActivity: (monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null) => boolean+ sortedWorkers: (monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null) => MonitoringWorker[]+ }+}++export type managedWarehouseMonitoringLogicType = MakeLogicType<+ managedWarehouseMonitoringLogicValues,+ managedWarehouseMonitoringLogicActions,+ Record<string, any>,+ managedWarehouseMonitoringLogicMeta+>++export const managedWarehouseMonitoringLogic = kea<managedWarehouseMonitoringLogicType>([+ path(['scenes', 'data-warehouse', 'scene', 'managedWarehouseMonitoringLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),+ actions({+ refreshMonitoring: true,+ resetMonitoringData: true,+ setMonitoringSeriesError: (hasError: boolean) => ({ hasError }),+ setMonitoringSnapshotError: (hasError: boolean) => ({ hasError }),+ setMonitoringWindow: (monitoringWindow: MonitoringWindow) => ({ monitoringWindow }),+ }),+ loaders(({ values, actions }) => ({+ monitoringSnapshot: [+ null as ManagedWarehouseMonitoringSnapshotResponseApi | null,+ {+ loadMonitoringSnapshot: async (_: void, breakpoint) => {+ const requestedTeamId = values.currentTeamId+ if (!requestedTeamId) {+ return null+ }+ let response: ManagedWarehouseMonitoringSnapshotResponseApi+ try {+ response = await dataWarehouseManagedWarehouseMonitoringRetrieve(String(requestedTeamId))+ } catch (error) {+ breakpoint()+ throw error+ }+ breakpoint()+ return response+ },+ },+ ],+ monitoringSeries: [+ [] as ManagedWarehouseMonitoringSeriesResponseApi[],+ {+ loadMonitoringSeries: async (requestedWindow: MonitoringWindow | undefined, breakpoint) => {+ const requestedTeamId = values.currentTeamId+ if (!requestedTeamId) {+ return []+ }+ const monitoringWindow = requestedWindow ?? values.monitoringWindow+ const results = await Promise.allSettled(+ MONITORING_METRICS.map((metric) =>+ dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve(String(requestedTeamId), {+ metric,+ window: monitoringWindow,+ })+ )+ )+ breakpoint()++ const successfulResponses = results.flatMap((result) =>+ result.status === 'fulfilled' ? [result.value] : []+ )+ if (!successfulResponses.length) {+ const firstFailure = results.find((result) => result.status === 'rejected')+ throw firstFailure?.reason ?? new Error('No warehouse monitoring metrics were returned')+ }++ const previousResponses =+ values.monitoringSeriesWindow === monitoringWindow ? values.monitoringSeries : []+ const responsesByMetric = new Map(previousResponses.map((response) => [response.metric, response]))+ for (const response of successfulResponses) {+ responsesByMetric.set(response.metric, response)+ }+ actions.setMonitoringSeriesError(successfulResponses.length !== results.length)++ return MONITORING_METRICS.flatMap((metric) => {+ const response = responsesByMetric.get(metric)+ return response ? [response] : []+ })+ },+ },+ ],+ })),+ reducers({+ monitoringWindow: [+ '24h' as MonitoringWindow,+ {+ setMonitoringWindow: (_, { monitoringWindow }) => monitoringWindow,+ },+ ],+ monitoringSnapshot: {+ resetMonitoringData: () => null,+ },+ monitoringSeries: {+ resetMonitoringData: () => [],+ },+ monitoringSeriesResolved: [+ false,+ {+ loadMonitoringSeriesSuccess: () => true,+ loadMonitoringSeriesFailure: () => true,+ resetMonitoringData: () => false,+ },+ ],+ monitoringSeriesWindow: [+ null as MonitoringWindow | null,+ {+ loadMonitoringSeriesSuccess: (state, { payload }) => payload ?? state,+ resetMonitoringData: () => null,+ },+ ],+ monitoringSnapshotError: [+ false,+ {+ loadMonitoringSnapshot: () => false,+ setMonitoringSnapshotError: (_, { hasError }) => hasError,+ resetMonitoringData: () => false,+ },+ ],+ monitoringSeriesError: [+ false,+ {+ setMonitoringSeriesError: (_, { hasError }) => hasError,+ resetMonitoringData: () => false,+ },+ ],+ }),+ selectors({+ initialMonitoringSeriesLoading: [+ (s) => [s.monitoringSeriesLoading, s.monitoringSeriesResolved, s.monitoringSeriesError],+ (+ monitoringSeriesLoading: boolean,+ monitoringSeriesResolved: boolean,+ monitoringSeriesError: boolean+ ): boolean => monitoringSeriesLoading && !monitoringSeriesResolved && !monitoringSeriesError,+ ],+ hasLiveActivity: [+ (s) => [s.monitoringSnapshot],+ (monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null): boolean =>+ !!monitoringSnapshot &&+ (monitoringSnapshot.totals.running_queries > 0 || monitoringSnapshot.totals.queued_connections > 0),+ ],+ sortedWorkers: [+ (s) => [s.monitoringSnapshot],+ (monitoringSnapshot: ManagedWarehouseMonitoringSnapshotResponseApi | null): MonitoringWorker[] =>+ [...(monitoringSnapshot?.workers ?? [])].sort((a, b) => workerSeverity(a) - workerSeverity(b)),+ ],+ }),+ listeners(({ actions, values, cache }) => ({+ refreshMonitoring: () => {+ if (!values.monitoringSnapshotLoading) {+ actions.loadMonitoringSnapshot()+ }+ if (!values.monitoringSeriesLoading) {+ actions.loadMonitoringSeries(values.monitoringWindow)+ }+ },+ setMonitoringWindow: ({ monitoringWindow }) => {+ actions.loadMonitoringSeries(monitoringWindow)+ },+ loadMonitoringSnapshotSuccess: () => {+ if (!values.currentTeamId) {+ return+ }+ actions.setMonitoringSnapshotError(false)+ cache.disposables.add(() => {+ const timeoutId = window.setTimeout(+ () => {+ if (!values.monitoringSnapshotLoading) {+ actions.loadMonitoringSnapshot()+ }+ },+ values.hasLiveActivity ? ACTIVE_REFRESH_INTERVAL_MS : STABLE_REFRESH_INTERVAL_MS+ )+ return () => window.clearTimeout(timeoutId)+ }, 'monitoringSnapshotPoll')+ },+ loadMonitoringSnapshotFailure: () => {+ actions.setMonitoringSnapshotError(true)+ cache.disposables.add(() => {+ const timeoutId = window.setTimeout(() => {+ if (!values.monitoringSnapshotLoading) {+ actions.loadMonitoringSnapshot()+ }+ }, STABLE_REFRESH_INTERVAL_MS)+ return () => window.clearTimeout(timeoutId)+ }, 'monitoringSnapshotPoll')+ },+ loadMonitoringSeriesSuccess: () => {+ if (!values.currentTeamId) {+ return+ }+ cache.disposables.add(() => {+ const timeoutId = window.setTimeout(() => {+ if (!values.monitoringSeriesLoading) {+ actions.loadMonitoringSeries(values.monitoringWindow)+ }+ }, SERIES_REFRESH_INTERVAL_MS)+ return () => window.clearTimeout(timeoutId)+ }, 'monitoringSeriesPoll')+ },+ loadMonitoringSeriesFailure: () => {+ actions.setMonitoringSeriesError(true)+ cache.disposables.add(() => {+ const timeoutId = window.setTimeout(() => {+ if (!values.monitoringSeriesLoading) {+ actions.loadMonitoringSeries(values.monitoringWindow)+ }+ }, SERIES_REFRESH_INTERVAL_MS)+ return () => window.clearTimeout(timeoutId)+ }, 'monitoringSeriesPoll')+ },+ })),+ subscriptions(({ actions, values, cache }) => ({+ currentTeamId: (teamId: number | null, previousTeamId: number | null | undefined) => {+ if (previousTeamId !== undefined && teamId !== previousTeamId) {+ cache.disposables.dispose('monitoringSnapshotPoll')+ cache.disposables.dispose('monitoringSeriesPoll')+ actions.resetMonitoringData()+ actions.loadMonitoringSnapshot()+ actions.loadMonitoringSeries(values.monitoringWindow)+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.refreshMonitoring()+ }),+])diff --git a/frontend/src/scenes/data-warehouse/scene/monitoringChartData.test.ts b/frontend/src/scenes/data-warehouse/scene/monitoringChartData.test.tsnew file mode 100644index 000000000000..67de367fe174--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/monitoringChartData.test.ts@@ -0,0 +1,93 @@+import type { ManagedWarehouseMonitoringSeriesResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'++import { buildMonitoringChartData } from './monitoringChartData'++describe('buildMonitoringChartData', () => {+ it('normalizes independently fetched series to a shared time grid', () => {+ const response = (+ metric: string,+ timestamps: string[],+ values: number[]+ ): ManagedWarehouseMonitoringSeriesResponseApi => ({+ schema_version: 1,+ org_id: 'org-1',+ metric,+ unit: 'seconds',+ start: timestamps[0] ?? '',+ end: timestamps[timestamps.length - 1] ?? '',+ step_seconds: 60,+ series: [+ {+ labels: {},+ points: timestamps.map((timestamp, index) => ({ timestamp, value: values[index] })),+ },+ ],+ })++ const chartData = buildMonitoringChartData(+ [+ response('duration_p50', ['2026-08-12T10:00:01Z', '2026-08-12T10:01:01Z'], [1, 2]),+ response('duration_p95', ['2026-08-12T10:00:03Z', '2026-08-12T10:01:03Z'], [10, 20]),+ ],+ [+ { metric: 'duration_p50', fallbackLabel: 'p50' },+ { metric: 'duration_p95', fallbackLabel: 'p95' },+ ]+ )++ expect(chartData.labels).toEqual(['2026-08-12T10:00:00.000Z', '2026-08-12T10:01:00.000Z'])+ expect(chartData.series).toEqual([+ { key: 'duration_p50:[]', label: 'p50', data: [1, 2] },+ { key: 'duration_p95:[]', label: 'p95', data: [10, 20] },+ ])+ })++ it('preserves timestamps that are missing from one series', () => {+ const chartData = buildMonitoringChartData(+ [+ {+ schema_version: 1,+ org_id: 'org-1',+ metric: 'query_rate',+ unit: 'queries_per_second',+ start: '2026-08-12T10:00:00Z',+ end: '2026-08-12T10:02:00Z',+ step_seconds: 60,+ series: [+ {+ labels: { status: 'success' },+ points: [+ { timestamp: '2026-08-12T10:00:00Z', value: 10 },+ { timestamp: '2026-08-12T10:01:00Z', value: 11 },+ { timestamp: '2026-08-12T10:02:00Z', value: 12 },+ ],+ },+ {+ labels: { status: 'error' },+ points: [{ timestamp: '2026-08-12T10:01:00Z', value: 1 }],+ },+ ],+ },+ ],+ [{ metric: 'query_rate', fallbackLabel: 'Queries' }]+ )++ expect(chartData.labels).toEqual([+ '2026-08-12T10:00:00.000Z',+ '2026-08-12T10:01:00.000Z',+ '2026-08-12T10:02:00.000Z',+ ])+ expect(chartData.series).toEqual([+ {+ key: 'query_rate:[["status","error"]]',+ label: 'Error',+ data: [Number.NaN, 1, Number.NaN],+ },+ {+ key: 'query_rate:[["status","success"]]',+ label: 'Success',+ data: [10, 11, 12],+ },+ ])+ })+})diff --git a/frontend/src/scenes/data-warehouse/scene/monitoringChartData.ts b/frontend/src/scenes/data-warehouse/scene/monitoringChartData.tsnew file mode 100644index 000000000000..28538e7a3540--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/monitoringChartData.ts@@ -0,0 +1,79 @@+import type { Series } from '@posthog/quill-charts'++import type {+ DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams,+ ManagedWarehouseMonitoringSeriesResponseApi,+} from 'products/data_warehouse/frontend/generated/api.schemas'++export type MonitoringChartMetric = NonNullable<+ DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams['metric']+>+type MonitoringSeries = ManagedWarehouseMonitoringSeriesResponseApi['series'][number]++export interface MonitoringChartMetricConfig {+ metric: MonitoringChartMetric+ fallbackLabel: string+}++function sentenceCase(value: string): string {+ const normalized = value.replaceAll('_', ' ')+ return normalized.charAt(0).toUpperCase() + normalized.slice(1)+}++function sortedLabels(series: MonitoringSeries): [string, string][] {+ return Object.entries(series.labels).sort(([left], [right]) => left.localeCompare(right))+}++function seriesLabel(series: MonitoringSeries, fallback: string): string {+ const labels = sortedLabels(series)+ if (!labels.length) {+ return fallback+ }+ if (labels.length === 1) {+ return sentenceCase(labels[0][1])+ }+ return labels.map(([key, value]) => `${sentenceCase(key)}: ${value}`).join(', ')+}++export function buildMonitoringChartData(+ responses: ManagedWarehouseMonitoringSeriesResponseApi[],+ metrics: MonitoringChartMetricConfig[]+): { labels: string[]; series: Series[] } {+ const chartResponses = metrics.flatMap(({ metric }) => {+ const response = responses.find((candidate) => candidate.metric === metric)+ return response ? [response] : []+ })+ const stepMilliseconds = Math.max(1, ...chartResponses.map((response) => response.step_seconds)) * 1000+ const configuredSeries = metrics+ .flatMap(({ metric, fallbackLabel }) => {+ const response = chartResponses.find((candidate) => candidate.metric === metric)+ return (response?.series ?? []).map((series) => ({+ key: `${metric}:${JSON.stringify(sortedLabels(series))}`,+ label: seriesLabel(series, fallbackLabel),+ points: new Map(+ series.points.map((point) => [+ new Date(+ Math.round(new Date(point.timestamp).getTime() / stepMilliseconds) * stepMilliseconds+ ).toISOString(),+ point.value,+ ])+ ),+ }))+ })+ .sort((left, right) => left.key.localeCompare(right.key))++ if (!configuredSeries.length) {+ return { labels: [], series: [] }+ }++ const labels = [...new Set(configuredSeries.flatMap(({ points }) => [...points.keys()]))].sort()++ return {+ labels,+ series: configuredSeries.map(({ key, label, points }) => ({+ key,+ label,+ data: labels.map((timestamp) => points.get(timestamp) ?? Number.NaN),+ })),+ }+}diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex e003b8ed6f6b..c528d5f5f7d0 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -723,6 +723,19 @@ SPECTACULAR_SETTINGS = {"needs_attention","sync_paused",],+ "ManagedWarehouseMonitoringMetricEnum": [+ "query_rate",+ "error_ratio",+ "duration_p50",+ "duration_p95",+ "sessions_active",+ "s3_bytes_rate",+ "acquire_p95",+ "acquire_by_source",+ "storage_bytes",+ "worker_crash_rate",+ ],+ "ManagedWarehouseMonitoringWindowEnum": ["1h", "6h", "24h", "7d", "30d"],# Full signal taxonomy on the report `signals` endpoint; the source-config serializer's# subset enums keep their own auto-resolved names."SignalSourceProduct": "products.signals.backend.enums.SIGNAL_SOURCE_PRODUCT_VALUES",diff --git a/products/data_warehouse/backend/presentation/managed_warehouse_monitoring.py b/products/data_warehouse/backend/presentation/managed_warehouse_monitoring.pynew file mode 100644index 000000000000..b08099fd1264--- /dev/null+++ b/products/data_warehouse/backend/presentation/managed_warehouse_monitoring.py@@ -0,0 +1,273 @@+from collections.abc import Mapping+from typing import cast++from rest_framework import serializers++MANAGED_WAREHOUSE_MONITORING_METRICS = (+ "query_rate",+ "error_ratio",+ "duration_p50",+ "duration_p95",+ "sessions_active",+ "acquire_p95",+ "acquire_by_source",+ "storage_bytes",+ "worker_crash_rate",+)+MANAGED_WAREHOUSE_MONITORING_WINDOWS = ("1h", "6h", "24h", "7d", "30d")+MANAGED_WAREHOUSE_MONITORING_LABELS = {+ "query_rate": frozenset({"status", "reason"}),+ "error_ratio": frozenset(),+ "duration_p50": frozenset(),+ "duration_p95": frozenset(),+ "sessions_active": frozenset(),+ "acquire_p95": frozenset({"source"}),+ "acquire_by_source": frozenset({"source"}),+ "storage_bytes": frozenset(),+ "worker_crash_rate": frozenset(),+}+++class ManagedWarehouseMonitoringUpstreamError(Exception):+ pass+++class ManagedWarehouseMonitoringErrorResponseSerializer(serializers.Serializer):+ error = serializers.CharField(required=False, help_text="Human-readable managed warehouse monitoring error.")+ type = serializers.CharField(required=False, help_text="Machine-readable validation error type.")+ code = serializers.CharField(required=False, help_text="Machine-readable validation error code.")+ detail = serializers.CharField(required=False, help_text="Human-readable validation error detail.")+ attr = serializers.CharField(required=False, allow_null=True, help_text="Query parameter associated with an error.")+++class ManagedWarehouseMonitoringWarehouseSerializer(serializers.Serializer):+ state = serializers.CharField(+ help_text="Current managed warehouse lifecycle state, such as ready, provisioning, or resharding."+ )+++class ManagedWarehouseMonitoringLimitsSerializer(serializers.Serializer):+ max_workers = serializers.IntegerField(+ min_value=0,+ help_text="Maximum concurrent workers for the organization. Zero means no organization-specific limit.",+ )+ max_vcpus = serializers.IntegerField(+ min_value=0,+ help_text="Maximum active session vCPUs admitted for the organization. Zero means no organization-specific limit.",+ )+ default_worker_cpu = serializers.CharField(+ allow_blank=True,+ help_text="Default worker CPU as a Kubernetes resource quantity, such as 2 or 500m.",+ )+ default_worker_memory = serializers.CharField(+ allow_blank=True,+ help_text="Default worker memory as a Kubernetes resource quantity, such as 8Gi.",+ )+ default_worker_ttl_seconds = serializers.IntegerField(+ min_value=0,+ help_text="Default number of seconds an idle worker remains available for reuse.",+ )+ default_worker_min_hot_idle = serializers.IntegerField(+ min_value=0,+ help_text="Minimum number of idle workers the organization keeps warm.",+ )+++class ManagedWarehouseMonitoringTotalsSerializer(serializers.Serializer):+ workers = serializers.IntegerField(min_value=0, help_text="Number of current non-terminal workers.")+ allocated_cpu_cores = serializers.FloatField(+ min_value=0,+ help_text="Total CPU cores allocated to current workers.",+ )+ allocated_memory_bytes = serializers.IntegerField(+ min_value=0,+ help_text="Total memory bytes allocated to current workers.",+ )+ active_sessions = serializers.IntegerField(+ min_value=0,+ help_text="Number of active database sessions across the organization's control planes.",+ )+ running_queries = serializers.IntegerField(+ min_value=0,+ help_text="Number of sessions currently executing a query.",+ )+ queued_connections = serializers.IntegerField(+ min_value=0,+ help_text="Number of connections waiting for worker capacity.",+ )+++class ManagedWarehouseMonitoringWorkerSessionSerializer(serializers.Serializer):+ protocol = serializers.CharField(help_text="Connection protocol, such as pg or flight.")+ state = serializers.CharField(help_text="Current database session state.")+ elapsed_ms = serializers.IntegerField(+ min_value=0,+ help_text="Milliseconds elapsed for the current query, or zero when the session is idle.",+ )+ percentage = serializers.FloatField(+ min_value=0,+ allow_null=True,+ help_text="Best-effort query progress percentage, or null when DuckDB cannot estimate progress.",+ )+ rows = serializers.IntegerField(min_value=0, help_text="Rows processed by the current query.")+ total_rows = serializers.IntegerField(+ min_value=0,+ help_text="Estimated total rows for the current query when available.",+ )+ stalled = serializers.BooleanField(help_text="Whether the current query appears stalled.")+++class ManagedWarehouseMonitoringWorkerSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="Opaque identifier for the worker.")+ state = serializers.CharField(help_text="Current worker lifecycle state.")+ cpu = serializers.CharField(+ allow_blank=True,+ help_text="Worker CPU as a Kubernetes resource quantity, such as 2 or 500m. Blank when unavailable.",+ )+ memory = serializers.CharField(+ allow_blank=True,+ help_text="Worker memory as a Kubernetes resource quantity, such as 8Gi. Blank when unavailable.",+ )+ ttl_seconds = serializers.IntegerField(+ min_value=0,+ help_text="Number of seconds the worker remains available while idle.",+ )+ created_at = serializers.DateTimeField(help_text="UTC timestamp when the worker was created.")+ last_heartbeat_at = serializers.DateTimeField(help_text="UTC timestamp of the worker's latest heartbeat.")+ session = ManagedWarehouseMonitoringWorkerSessionSerializer(+ required=False,+ allow_null=True,+ help_text="Sanitized live session assigned to the worker, when one exists.",+ )+++class ManagedWarehouseMonitoringCoverageSerializer(serializers.Serializer):+ cp_responders = serializers.IntegerField(+ min_value=0,+ help_text="Number of control planes that contributed live data.",+ )+ cp_total = serializers.IntegerField(+ min_value=0,+ help_text="Number of control planes queried for live data.",+ )+ partial = serializers.BooleanField( # type: ignore[assignment] # Response field shadows DRF's partial option.+ help_text="Whether one or more control planes failed to contribute live data."+ )+++class ManagedWarehouseMonitoringSnapshotResponseSerializer(serializers.Serializer):+ schema_version = serializers.IntegerField(+ min_value=1,+ max_value=1,+ help_text="Version of the managed warehouse monitoring response schema.",+ )+ org_id = serializers.CharField(help_text="Organization whose managed warehouse is represented.")+ as_of = serializers.DateTimeField(help_text="UTC timestamp when this snapshot was assembled.")+ warehouse = ManagedWarehouseMonitoringWarehouseSerializer(help_text="Managed warehouse lifecycle details.")+ limits = ManagedWarehouseMonitoringLimitsSerializer(help_text="Organization-level worker limits and defaults.")+ totals = ManagedWarehouseMonitoringTotalsSerializer(help_text="Current organization-level activity totals.")+ workers = ManagedWarehouseMonitoringWorkerSerializer(+ many=True,+ help_text="Current non-terminal workers with tenant-safe runtime details.",+ )+ coverage = ManagedWarehouseMonitoringCoverageSerializer(+ help_text="Completeness of the cross-control-plane live data."+ )+++class ManagedWarehouseMonitoringSeriesQuerySerializer(serializers.Serializer):+ metric = serializers.ChoiceField(+ choices=MANAGED_WAREHOUSE_MONITORING_METRICS,+ help_text="Allow-listed managed warehouse metric to retrieve.",+ )+ window = serializers.ChoiceField(+ choices=MANAGED_WAREHOUSE_MONITORING_WINDOWS,+ default="24h",+ help_text="Trailing time window to retrieve. Defaults to 24h.",+ )+++class ManagedWarehouseMonitoringPointSerializer(serializers.Serializer):+ timestamp = serializers.DateTimeField(help_text="UTC timestamp of the sample.")+ value = serializers.FloatField(help_text="Metric value at the sample timestamp.")+++class ManagedWarehouseMonitoringSeriesSerializer(serializers.Serializer):+ labels = serializers.DictField(+ child=serializers.CharField(),+ help_text="Allow-listed labels distinguishing this series, such as query outcome or acquisition source.",+ )+ points = ManagedWarehouseMonitoringPointSerializer(+ many=True,+ help_text="Chronologically ordered metric samples.",+ )+++class ManagedWarehouseMonitoringSeriesResponseSerializer(serializers.Serializer):+ schema_version = serializers.IntegerField(+ min_value=1,+ max_value=1,+ help_text="Version of the managed warehouse monitoring response schema.",+ )+ org_id = serializers.CharField(help_text="Organization whose managed warehouse is represented.")+ metric = serializers.CharField(help_text="Allow-listed metric returned by this response.")+ unit = serializers.CharField(help_text="Unit for every value in the response.")+ start = serializers.DateTimeField(help_text="Inclusive UTC start of the returned time window.")+ end = serializers.DateTimeField(help_text="Inclusive UTC end of the returned time window.")+ step_seconds = serializers.IntegerField(+ min_value=1,+ help_text="Number of seconds between requested samples.",+ )+ series = ManagedWarehouseMonitoringSeriesSerializer(+ many=True,+ help_text="Metric series grouped by their allow-listed labels.",+ )+++def serialize_monitoring_snapshot(raw: object, *, expected_organization_id: str) -> dict[str, object]:+ return _serialize_monitoring_response(+ raw,+ serializer_class=ManagedWarehouseMonitoringSnapshotResponseSerializer,+ expected_organization_id=expected_organization_id,+ )+++def serialize_monitoring_series(+ raw: object,+ *,+ expected_organization_id: str,+ expected_metric: str,+) -> dict[str, object]:+ data = _serialize_monitoring_response(+ raw,+ serializer_class=ManagedWarehouseMonitoringSeriesResponseSerializer,+ expected_organization_id=expected_organization_id,+ )+ if data["metric"] != expected_metric:+ raise ManagedWarehouseMonitoringUpstreamError("Monitoring service returned a different metric")+ allowed_labels = MANAGED_WAREHOUSE_MONITORING_LABELS[expected_metric]+ for series in cast(list[object], data["series"]):+ if not isinstance(series, Mapping) or not isinstance(series.get("labels"), Mapping):+ raise ManagedWarehouseMonitoringUpstreamError("Monitoring service returned invalid series labels")+ if not set(series["labels"]).issubset(allowed_labels):+ raise ManagedWarehouseMonitoringUpstreamError("Monitoring service returned unexpected series labels")+ return data+++def _serialize_monitoring_response(+ raw: object,+ *,+ serializer_class: type[serializers.Serializer],+ expected_organization_id: str,+) -> dict[str, object]:+ if not isinstance(raw, Mapping):+ raise ManagedWarehouseMonitoringUpstreamError("Monitoring service returned an invalid response")++ serializer = serializer_class(data=raw)+ if not serializer.is_valid():+ raise ManagedWarehouseMonitoringUpstreamError("Monitoring service returned an invalid response")++ data = dict(serializer.data)+ if str(data["org_id"]) != expected_organization_id:+ raise ManagedWarehouseMonitoringUpstreamError("Monitoring service returned data for a different organization")+ return datadiff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.pyindex 48c65aa8fcf0..36cb109ad60b 100644--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py@@ -39,6 +39,15 @@ from products.data_warehouse.backend.presentation.managed_warehouse_data_statusManagedWarehouseSourceSchemasQuerySerializer,ManagedWarehouseSourceSchemasResponseSerializer,)+from products.data_warehouse.backend.presentation.managed_warehouse_monitoring import (+ ManagedWarehouseMonitoringErrorResponseSerializer,+ ManagedWarehouseMonitoringSeriesQuerySerializer,+ ManagedWarehouseMonitoringSeriesResponseSerializer,+ ManagedWarehouseMonitoringSnapshotResponseSerializer,+ ManagedWarehouseMonitoringUpstreamError,+ serialize_monitoring_series,+ serialize_monitoring_snapshot,+)from products.managed_warehouse.backend.presentation import views as managed_warehousefrom products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_namefrom products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource@@ -49,6 +58,68 @@ logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)+_MONITORING_ERROR_RESPONSES = {+ status.HTTP_400_BAD_REQUEST: OpenApiResponse(+ response=ManagedWarehouseMonitoringErrorResponseSerializer,+ description="The monitoring query parameters are invalid.",+ ),+ status.HTTP_403_FORBIDDEN: OpenApiResponse(+ response=ManagedWarehouseMonitoringErrorResponseSerializer,+ description="Managed warehouse monitoring is not available to the caller.",+ ),+ status.HTTP_404_NOT_FOUND: OpenApiResponse(+ response=ManagedWarehouseMonitoringErrorResponseSerializer,+ description="The organization does not have a managed warehouse.",+ ),+ status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(+ response=ManagedWarehouseMonitoringErrorResponseSerializer,+ description="Managed warehouse monitoring is not configured.",+ ),+ status.HTTP_502_BAD_GATEWAY: OpenApiResponse(+ response=ManagedWarehouseMonitoringErrorResponseSerializer,+ description="The managed warehouse monitoring service returned an invalid response or was unreachable.",+ ),+ status.HTTP_504_GATEWAY_TIMEOUT: OpenApiResponse(+ response=ManagedWarehouseMonitoringErrorResponseSerializer,+ description="The managed warehouse monitoring service timed out.",+ ),+}+++def _managed_warehouse_monitoring_error_response(upstream_response: Response) -> Response:+ upstream_status = upstream_response.status_code+ if upstream_status == status.HTTP_403_FORBIDDEN:+ return Response(+ {"error": "Warehouse monitoring isn't available for this organization."},+ status=status.HTTP_403_FORBIDDEN,+ )+ if (+ upstream_status == status.HTTP_404_NOT_FOUND+ and isinstance(upstream_response.data, dict)+ and upstream_response.data.get("code") == "managed_warehouse_not_found"+ ):+ return Response(+ {"error": "Couldn't find a managed warehouse for this organization. Set one up in Data ops and try again."},+ status=status.HTTP_404_NOT_FOUND,+ )+ if upstream_status == status.HTTP_501_NOT_IMPLEMENTED:+ return Response(+ {"error": "Warehouse monitoring isn't configured. Contact support."},+ status=status.HTTP_501_NOT_IMPLEMENTED,+ )+ if upstream_status == status.HTTP_504_GATEWAY_TIMEOUT:+ return Response(+ {"error": "Warehouse monitoring took too long to respond. Try again."},+ status=status.HTTP_504_GATEWAY_TIMEOUT,+ )+ return Response(+ {+ "error": "Couldn't load warehouse monitoring data. Refresh the page, and contact support if it keeps happening."+ },+ status=status.HTTP_502_BAD_GATEWAY,+ )++class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"""API endpoints for data warehouse aggregate statistics and operations.@@ -57,6 +128,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# warehouse_view inherits from warehouse_objects; reads require viewer access,# write actions (see required_scopes below) require editor access.scope_object = "warehouse_view"+ requires_resource_level_access = Falseserializer_class = _FallbackSerializerdef _require_organization_admin(self, request: Request, action: str) -> Response | None:@@ -1019,6 +1091,91 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):managed_warehouse.ensure_direct_connection_tables(self.team_id, self.team.organization_id)return resp+ @extend_schema(+ responses={+ status.HTTP_200_OK: OpenApiResponse(+ response=ManagedWarehouseMonitoringSnapshotResponseSerializer,+ description="Current organization-scoped worker and query activity.",+ ),+ **_MONITORING_ERROR_RESPONSES,+ },+ summary="Get managed warehouse monitoring snapshot",+ description="Get tenant-safe live worker, session, queue, and capacity data for the current organization.",+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path="managed-warehouse-monitoring",+ required_scopes=["warehouse_view:read"],+ requires_resource_level_access=True,+ )+ def managed_warehouse_monitoring(self, request: Request, **kwargs) -> Response:+ organization_id = str(self.team.organization_id)+ upstream_response = managed_warehouse.monitoring_snapshot_for(organization_id)+ if upstream_response.status_code != status.HTTP_200_OK:+ return _managed_warehouse_monitoring_error_response(upstream_response)++ try:+ data = serialize_monitoring_snapshot(+ upstream_response.data,+ expected_organization_id=organization_id,+ )+ except ManagedWarehouseMonitoringUpstreamError:+ logger.warning(+ "Managed warehouse monitoring snapshot response failed validation",+ organization_id=organization_id,+ )+ return _managed_warehouse_monitoring_error_response(Response(status=status.HTTP_502_BAD_GATEWAY))+ return Response(data)++ @validated_request(+ query_serializer=ManagedWarehouseMonitoringSeriesQuerySerializer,+ responses={+ status.HTTP_200_OK: OpenApiResponse(+ response=ManagedWarehouseMonitoringSeriesResponseSerializer,+ description="One organization-scoped monitoring metric over time.",+ ),+ **_MONITORING_ERROR_RESPONSES,+ },+ summary="Get managed warehouse monitoring time series",+ description="Get one allow-listed monitoring metric for the current organization and trailing time window.",+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path="managed-warehouse-monitoring-timeseries",+ required_scopes=["warehouse_view:read"],+ requires_resource_level_access=True,+ )+ def managed_warehouse_monitoring_timeseries(self, request: Request, **kwargs) -> Response:+ organization_id = str(self.team.organization_id)+ metric = cast(+ managed_warehouse.ManagedWarehouseMonitoringMetric,+ request.validated_query_data["metric"],+ )+ window = cast(+ managed_warehouse.ManagedWarehouseMonitoringWindow,+ request.validated_query_data["window"],+ )+ upstream_response = managed_warehouse.monitoring_series_for(organization_id, metric, window)+ if upstream_response.status_code != status.HTTP_200_OK:+ return _managed_warehouse_monitoring_error_response(upstream_response)++ try:+ data = serialize_monitoring_series(+ upstream_response.data,+ expected_organization_id=organization_id,+ expected_metric=metric,+ )+ except ManagedWarehouseMonitoringUpstreamError:+ logger.warning(+ "Managed warehouse monitoring series response failed validation",+ organization_id=organization_id,+ metric=metric,+ )+ return _managed_warehouse_monitoring_error_response(Response(status=status.HTTP_502_BAD_GATEWAY))+ return Response(data)+@extend_schema(responses={200: ManagedWarehouseDataStatusResponseSerializer})@action(methods=["GET"],diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse_monitoring.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse_monitoring.pynew file mode 100644index 000000000000..ae6c2ad358cb--- /dev/null+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse_monitoring.py@@ -0,0 +1,366 @@+import json+from typing import cast++import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import status+from rest_framework.response import Response++from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.data_warehouse.backend.presentation.managed_warehouse_monitoring import (+ ManagedWarehouseMonitoringSeriesQuerySerializer,+)+from products.warehouse_sources.backend.tests.api._access_control_base import WarehouseAccessControlTestMixin+++def _snapshot(organization_id: object) -> dict[str, object]:+ return {+ "schema_version": 1,+ "org_id": str(organization_id),+ "as_of": "2026-08-12T17:00:00Z",+ "warehouse": {"state": "ready"},+ "limits": {+ "max_workers": 4,+ "max_vcpus": 8,+ "default_worker_cpu": "2",+ "default_worker_memory": "8Gi",+ "default_worker_ttl_seconds": 1800,+ "default_worker_min_hot_idle": 1,+ },+ "totals": {+ "workers": 1,+ "allocated_cpu_cores": 2,+ "allocated_memory_bytes": 8_589_934_592,+ "active_sessions": 1,+ "running_queries": 1,+ "queued_connections": 0,+ },+ "workers": [+ {+ "id": 7,+ "state": "hot",+ "cpu": "2",+ "memory": "8Gi",+ "ttl_seconds": 900,+ "created_at": "2026-08-12T16:00:00Z",+ "last_heartbeat_at": "2026-08-12T16:59:59Z",+ "session": {+ "protocol": "pg",+ "state": "active",+ "elapsed_ms": 1200,+ "percentage": 42.5,+ "rows": 100,+ "total_rows": 1000,+ "stalled": False,+ },+ }+ ],+ "coverage": {"cp_responders": 2, "cp_total": 2, "partial": False},+ }+++def _series(organization_id: object, metric: str = "query_rate") -> dict[str, object]:+ return {+ "schema_version": 1,+ "org_id": str(organization_id),+ "metric": metric,+ "unit": "queries_per_second",+ "start": "2026-08-11T17:00:00Z",+ "end": "2026-08-12T17:00:00Z",+ "step_seconds": 60,+ "series": [+ {+ "labels": {"status": "success", "reason": "none"},+ "points": [{"timestamp": "2026-08-12T16:59:00Z", "value": 2.5}],+ }+ ],+ }+++class TestManagedWarehouseMonitoringSeriesQuerySerializer(SimpleTestCase):+ @parameterized.expand(+ [+ ("unknown_metric", {"metric": "worker_states", "window": "1h"}, "metric"),+ ("removed_data_read_metric", {"metric": "s3_bytes_rate", "window": "1h"}, "metric"),+ ("unknown_window", {"metric": "query_rate", "window": "2h"}, "window"),+ ("missing_metric", {"window": "24h"}, "metric"),+ ]+ )+ def test_rejects_values_outside_the_allow_list(+ self,+ _name: str,+ query: dict[str, str],+ error_field: str,+ ) -> None:+ serializer = ManagedWarehouseMonitoringSeriesQuerySerializer(data=query)++ assert not serializer.is_valid()+ assert error_field in serializer.errors+++class TestManagedWarehouseMonitoringAPI(APIBaseTest):+ def _snapshot_url(self) -> str:+ return f"/api/projects/{self.team.id}/data_warehouse/managed-warehouse-monitoring/"++ def _series_url(self, query: str = "metric=query_rate&window=6h") -> str:+ return f"/api/projects/{self.team.id}/data_warehouse/managed-warehouse-monitoring-timeseries/?{query}"++ @patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"+ )+ def test_snapshot_derives_the_organization_and_removes_unknown_fields(self, mock_snapshot: MagicMock) -> None:+ upstream = _snapshot(self.organization.id)+ upstream["bucket"] = "sensitive-bucket"+ worker = cast(dict[str, object], cast(list[object], upstream["workers"])[0])+ worker["pod_name"] = "sensitive-pod"+ worker["image"] = "sensitive-image"+ worker["owner_cp_instance_id"] = "sensitive-control-plane"+ session = cast(dict[str, object], worker["session"])+ session["user"] = "sensitive-user"+ mock_snapshot.return_value = Response(upstream, status=status.HTTP_200_OK)++ response = self.client.get(self._snapshot_url())++ assert response.status_code == status.HTTP_200_OK+ mock_snapshot.assert_called_once_with(str(self.organization.id))+ body = response.json()+ assert set(body) == {+ "schema_version",+ "org_id",+ "as_of",+ "warehouse",+ "limits",+ "totals",+ "workers",+ "coverage",+ }+ assert body["workers"][0]["id"] == "7"+ serialized = json.dumps(body)+ for forbidden in (+ "bucket",+ "sensitive-bucket",+ "pod_name",+ "sensitive-pod",+ "image",+ "sensitive-image",+ "owner_cp_instance_id",+ "sensitive-control-plane",+ "user",+ "sensitive-user",+ ):+ assert forbidden not in serialized++ @patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"+ )+ def test_snapshot_rejects_an_upstream_organization_mismatch(self, mock_snapshot: MagicMock) -> None:+ upstream = _snapshot("different-organization")+ upstream["secret"] = "must-not-leak"+ mock_snapshot.return_value = Response(upstream, status=status.HTTP_200_OK)++ response = self.client.get(self._snapshot_url())++ assert response.status_code == status.HTTP_502_BAD_GATEWAY+ assert "different-organization" not in response.content.decode()+ assert "must-not-leak" not in response.content.decode()++ @patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"+ )+ def test_snapshot_accepts_workers_with_unavailable_resource_profiles(self, mock_snapshot: MagicMock) -> None:+ upstream = _snapshot(self.organization.id)+ worker = cast(dict[str, object], cast(list[object], upstream["workers"])[0])+ worker["cpu"] = ""+ worker["memory"] = ""+ mock_snapshot.return_value = Response(upstream, status=status.HTTP_200_OK)++ response = self.client.get(self._snapshot_url())++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["workers"][0]["cpu"] == ""+ assert response.json()["workers"][0]["memory"] == ""++ @patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"+ )+ def test_snapshot_accepts_unavailable_query_progress(self, mock_snapshot: MagicMock) -> None:+ upstream = _snapshot(self.organization.id)+ worker = cast(dict[str, object], cast(list[object], upstream["workers"])[0])+ session = cast(dict[str, object], worker["session"])+ session["percentage"] = None+ mock_snapshot.return_value = Response(upstream, status=status.HTTP_200_OK)++ response = self.client.get(self._snapshot_url())++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["workers"][0]["session"]["percentage"] is None++ @patch("products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_series_for")+ def test_timeseries_validates_and_forwards_the_allow_listed_query(self, mock_series: MagicMock) -> None:+ mock_series.return_value = Response(_series(self.organization.id), status=status.HTTP_200_OK)++ response = self.client.get(self._series_url())++ assert response.status_code == status.HTTP_200_OK+ mock_series.assert_called_once_with(str(self.organization.id), "query_rate", "6h")+ assert response.json()["series"][0]["labels"] == {"status": "success", "reason": "none"}++ @patch("products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_series_for")+ def test_timeseries_rejects_invalid_query_before_calling_upstream(self, mock_series: MagicMock) -> None:+ response = self.client.get(self._series_url("metric=worker_states&window=2h"))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_series.assert_not_called()++ @patch("products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_series_for")+ def test_timeseries_rejects_an_unexpected_upstream_label(self, mock_series: MagicMock) -> None:+ upstream = _series(self.organization.id)+ upstream_series = cast(list[object], upstream["series"])+ labels = cast(dict[str, str], cast(dict[str, object], upstream_series[0])["labels"])+ labels["pod"] = "sensitive-pod"+ mock_series.return_value = Response(upstream, status=status.HTTP_200_OK)++ response = self.client.get(self._series_url())++ assert response.status_code == status.HTTP_502_BAD_GATEWAY+ assert "pod" not in response.content.decode()+ assert "sensitive-pod" not in response.content.decode()++ @parameterized.expand(+ [+ ("timeout", status.HTTP_504_GATEWAY_TIMEOUT, status.HTTP_504_GATEWAY_TIMEOUT),+ ("upstream_error", status.HTTP_503_SERVICE_UNAVAILABLE, status.HTTP_502_BAD_GATEWAY),+ ]+ )+ @patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"+ )+ def test_snapshot_maps_upstream_failures_without_forwarding_details(+ self,+ _name: str,+ upstream_status: int,+ expected_status: int,+ mock_snapshot: MagicMock,+ ) -> None:+ mock_snapshot.return_value = Response(+ {"error": "private control-plane detail"},+ status=upstream_status,+ )++ response = self.client.get(self._snapshot_url())++ assert response.status_code == expected_status+ assert "private control-plane detail" not in response.content.decode()++ @parameterized.expand(+ [+ ("explicit_missing_warehouse", {"code": "managed_warehouse_not_found"}, status.HTTP_404_NOT_FOUND),+ ("old_control_plane_route", {"error": "404 page not found"}, status.HTTP_502_BAD_GATEWAY),+ ]+ )+ @patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"+ )+ def test_snapshot_distinguishes_missing_warehouse_from_an_old_control_plane_route(+ self,+ _name: str,+ upstream_body: dict[str, str],+ expected_status: int,+ mock_snapshot: MagicMock,+ ) -> None:+ mock_snapshot.return_value = Response(upstream_body, status=status.HTTP_404_NOT_FOUND)++ response = self.client.get(self._snapshot_url())++ assert response.status_code == expected_status+++class TestManagedWarehouseMonitoringAccessControl(WarehouseAccessControlTestMixin):+ resource = "warehouse_objects"++ def setUp(self) -> None:+ super().setUp()+ saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="restricted_view",+ query={"kind": "HogQLQuery", "query": "select 1"},+ created_by=self.user,+ )+ self._create_project_default(access_level="none")+ self._create_access_control(+ self.viewer_user,+ resource="warehouse_view",+ resource_id=str(saved_query.id),+ access_level="viewer",+ )+ self.client.force_login(self.viewer_user)++ @parameterized.expand(+ [+ (+ "snapshot",+ "monitoring_snapshot_for",+ "managed-warehouse-monitoring/",+ ),+ (+ "timeseries",+ "monitoring_series_for",+ "managed-warehouse-monitoring-timeseries/?metric=query_rate&window=6h",+ ),+ ]+ )+ def test_org_wide_monitoring_requires_resource_level_warehouse_access(+ self,+ _name: str,+ upstream_method: str,+ endpoint: str,+ ) -> None:+ upstream_path = (+ f"products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.{upstream_method}"+ )+ with patch(upstream_path) as mock_upstream:+ upstream_body = (+ _snapshot(self.organization.id)+ if upstream_method == "monitoring_snapshot_for"+ else _series(self.organization.id)+ )+ mock_upstream.return_value = Response(+ upstream_body,+ status=status.HTTP_200_OK,+ )++ response = self.client.get(f"/api/projects/{self.team.id}/data_warehouse/{endpoint}")++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mock_upstream.assert_not_called()+++class TestManagedWarehouseMonitoringPersonalAPIKey(APIBaseTest):+ CONFIG_AUTO_LOGIN = False++ def _get_snapshot(self, token: str) -> Response:+ return self.client.get(+ f"/api/projects/{self.team.id}/data_warehouse/managed-warehouse-monitoring/",+ headers={"authorization": f"Bearer {token}"},+ )++ @patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"+ )+ def test_snapshot_requires_the_warehouse_view_read_scope(self, mock_snapshot: MagicMock) -> None:+ mock_snapshot.return_value = Response(_snapshot(self.organization.id), status=status.HTTP_200_OK)+ allowed_token = self.create_personal_api_key_with_scopes(["warehouse_view:read"])+ denied_token = self.create_personal_api_key_with_scopes(["query:read"])++ allowed_response = self._get_snapshot(allowed_token)+ denied_response = self._get_snapshot(denied_token)++ assert allowed_response.status_code == status.HTTP_200_OK+ assert denied_response.status_code == status.HTTP_403_FORBIDDEN+ assert mock_snapshot.call_count == 1diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex f9a29d6c3044..6b6649bba4b4 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -237,6 +237,222 @@ export interface ManagedWarehouseDataStatusResponseApi {generated_at: string}+export interface ManagedWarehouseMonitoringWarehouseApi {+ /** Current managed warehouse lifecycle state, such as ready, provisioning, or resharding. */+ state: string+}++export interface ManagedWarehouseMonitoringLimitsApi {+ /**+ * Maximum concurrent workers for the organization. Zero means no organization-specific limit.+ * @minimum 0+ */+ max_workers: number+ /**+ * Maximum active session vCPUs admitted for the organization. Zero means no organization-specific limit.+ * @minimum 0+ */+ max_vcpus: number+ /** Default worker CPU as a Kubernetes resource quantity, such as 2 or 500m. */+ default_worker_cpu: string+ /** Default worker memory as a Kubernetes resource quantity, such as 8Gi. */+ default_worker_memory: string+ /**+ * Default number of seconds an idle worker remains available for reuse.+ * @minimum 0+ */+ default_worker_ttl_seconds: number+ /**+ * Minimum number of idle workers the organization keeps warm.+ * @minimum 0+ */+ default_worker_min_hot_idle: number+}++export interface ManagedWarehouseMonitoringTotalsApi {+ /**+ * Number of current non-terminal workers.+ * @minimum 0+ */+ workers: number+ /**+ * Total CPU cores allocated to current workers.+ * @minimum 0+ */+ allocated_cpu_cores: number+ /**+ * Total memory bytes allocated to current workers.+ * @minimum 0+ */+ allocated_memory_bytes: number+ /**+ * Number of active database sessions across the organization's control planes.+ * @minimum 0+ */+ active_sessions: number+ /**+ * Number of sessions currently executing a query.+ * @minimum 0+ */+ running_queries: number+ /**+ * Number of connections waiting for worker capacity.+ * @minimum 0+ */+ queued_connections: number+}++export interface ManagedWarehouseMonitoringWorkerSessionApi {+ /** Connection protocol, such as pg or flight. */+ protocol: string+ /** Current database session state. */+ state: string+ /**+ * Milliseconds elapsed for the current query, or zero when the session is idle.+ * @minimum 0+ */+ elapsed_ms: number+ /**+ * Best-effort query progress percentage, or null when DuckDB cannot estimate progress.+ * @minimum 0+ * @nullable+ */+ percentage: number | null+ /**+ * Rows processed by the current query.+ * @minimum 0+ */+ rows: number+ /**+ * Estimated total rows for the current query when available.+ * @minimum 0+ */+ total_rows: number+ /** Whether the current query appears stalled. */+ stalled: boolean+}++export interface ManagedWarehouseMonitoringWorkerApi {+ /** Opaque identifier for the worker. */+ id: string+ /** Current worker lifecycle state. */+ state: string+ /** Worker CPU as a Kubernetes resource quantity, such as 2 or 500m. Blank when unavailable. */+ cpu: string+ /** Worker memory as a Kubernetes resource quantity, such as 8Gi. Blank when unavailable. */+ memory: string+ /**+ * Number of seconds the worker remains available while idle.+ * @minimum 0+ */+ ttl_seconds: number+ /** UTC timestamp when the worker was created. */+ created_at: string+ /** UTC timestamp of the worker's latest heartbeat. */+ last_heartbeat_at: string+ /** Sanitized live session assigned to the worker, when one exists. */+ session?: ManagedWarehouseMonitoringWorkerSessionApi | null+}++export interface ManagedWarehouseMonitoringCoverageApi {+ /**+ * Number of control planes that contributed live data.+ * @minimum 0+ */+ cp_responders: number+ /**+ * Number of control planes queried for live data.+ * @minimum 0+ */+ cp_total: number+ /** Whether one or more control planes failed to contribute live data. */+ partial: boolean+}++export interface ManagedWarehouseMonitoringSnapshotResponseApi {+ /**+ * Version of the managed warehouse monitoring response schema.+ * @minimum 1+ * @maximum 1+ */+ schema_version: number+ /** Organization whose managed warehouse is represented. */+ org_id: string+ /** UTC timestamp when this snapshot was assembled. */+ as_of: string+ /** Managed warehouse lifecycle details. */+ warehouse: ManagedWarehouseMonitoringWarehouseApi+ /** Organization-level worker limits and defaults. */+ limits: ManagedWarehouseMonitoringLimitsApi+ /** Current organization-level activity totals. */+ totals: ManagedWarehouseMonitoringTotalsApi+ /** Current non-terminal workers with tenant-safe runtime details. */+ workers: ManagedWarehouseMonitoringWorkerApi[]+ /** Completeness of the cross-control-plane live data. */+ coverage: ManagedWarehouseMonitoringCoverageApi+}++export interface ManagedWarehouseMonitoringErrorResponseApi {+ /** Human-readable managed warehouse monitoring error. */+ error?: string+ /** Machine-readable validation error type. */+ type?: string+ /** Machine-readable validation error code. */+ code?: string+ /** Human-readable validation error detail. */+ detail?: string+ /**+ * Query parameter associated with an error.+ * @nullable+ */+ attr?: string | null+}++export interface ManagedWarehouseMonitoringPointApi {+ /** UTC timestamp of the sample. */+ timestamp: string+ /** Metric value at the sample timestamp. */+ value: number+}++/**+ * Allow-listed labels distinguishing this series, such as query outcome or acquisition source.+ */+export type ManagedWarehouseMonitoringSeriesApiLabels = { [key: string]: string }++export interface ManagedWarehouseMonitoringSeriesApi {+ /** Allow-listed labels distinguishing this series, such as query outcome or acquisition source. */+ labels: ManagedWarehouseMonitoringSeriesApiLabels+ /** Chronologically ordered metric samples. */+ points: ManagedWarehouseMonitoringPointApi[]+}++export interface ManagedWarehouseMonitoringSeriesResponseApi {+ /**+ * Version of the managed warehouse monitoring response schema.+ * @minimum 1+ * @maximum 1+ */+ schema_version: number+ /** Organization whose managed warehouse is represented. */+ org_id: string+ /** Allow-listed metric returned by this response. */+ metric: string+ /** Unit for every value in the response. */+ unit: string+ /** Inclusive UTC start of the returned time window. */+ start: string+ /** Inclusive UTC end of the returned time window. */+ end: string+ /**+ * Number of seconds between requested samples.+ * @minimum 1+ */+ step_seconds: number+ /** Metric series grouped by their allow-listed labels. */+ series: ManagedWarehouseMonitoringSeriesApi[]+}+/*** * `copy` - copy* * `register` - register@@ -4621,6 +4837,61 @@ export type DataWarehouseCheckSchemaNameRetrieveParams = {name: string}+export type DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams = {+ /**+ * Allow-listed managed warehouse metric to retrieve.+ *+ * * `query_rate` - query_rate+ * * `error_ratio` - error_ratio+ * * `duration_p50` - duration_p50+ * * `duration_p95` - duration_p95+ * * `sessions_active` - sessions_active+ * * `acquire_p95` - acquire_p95+ * * `acquire_by_source` - acquire_by_source+ * * `storage_bytes` - storage_bytes+ * * `worker_crash_rate` - worker_crash_rate+ * @minLength 1+ */+ metric: DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric+ /**+ * Trailing time window to retrieve. Defaults to 24h.+ *+ * * `1h` - 1h+ * * `6h` - 6h+ * * `24h` - 24h+ * * `7d` - 7d+ * * `30d` - 30d+ * @minLength 1+ */+ window?: DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow+}++export type DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric =+ (typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric)[keyof typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric]++export const DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric = {+ QueryRate: 'query_rate',+ ErrorRatio: 'error_ratio',+ DurationP50: 'duration_p50',+ DurationP95: 'duration_p95',+ SessionsActive: 'sessions_active',+ AcquireP95: 'acquire_p95',+ AcquireBySource: 'acquire_by_source',+ StorageBytes: 'storage_bytes',+ WorkerCrashRate: 'worker_crash_rate',+} as const++export type DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow =+ (typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow)[keyof typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow]++export const DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow = {+ '1h': '1h',+ '6h': '6h',+ '24h': '24h',+ '7d': '7d',+ '30d': '30d',+} as const+export type DataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {/*** Imported source connection to fetch per-schema detail for.diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex e3dc2afcf25f..3ce312070e22 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -18,6 +18,7 @@ import type {DataWarehouseCheckDatabaseNameRetrieveParams,DataWarehouseCheckSchemaNameRetrieveParams,DataWarehouseExpressionApi,+ DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams,DataWarehouseManagedWarehouseSourceSchemasRetrieveParams,DataWarehouseModelPathApi,DataWarehouseSavedQueryApi,@@ -32,6 +33,8 @@ import type {InsightVariableApi,InsightVariablesListParams,ManagedWarehouseDataStatusResponseApi,+ ManagedWarehouseMonitoringSeriesResponseApi,+ ManagedWarehouseMonitoringSnapshotResponseApi,ManagedWarehouseSourceSchemasResponseApi,OnboardWarehouseTeamRequestApi,OnboardWarehouseTeamResponseApi,@@ -376,6 +379,64 @@ export const dataWarehouseManagedWarehouseDataStatusRetrieve = async ()}+export const getDataWarehouseManagedWarehouseMonitoringRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_warehouse/managed-warehouse-monitoring/`+}++/**+ * Get tenant-safe live worker, session, queue, and capacity data for the current organization.+ * @summary Get managed warehouse monitoring snapshot+ */+export const dataWarehouseManagedWarehouseMonitoringRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<ManagedWarehouseMonitoringSnapshotResponseApi> => {+ return apiMutator<ManagedWarehouseMonitoringSnapshotResponseApi>(+ getDataWarehouseManagedWarehouseMonitoringRetrieveUrl(projectId),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getDataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveUrl = (+ projectId: string,+ params: DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/data_warehouse/managed-warehouse-monitoring-timeseries/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_warehouse/managed-warehouse-monitoring-timeseries/`+}++/**+ * Get one allow-listed monitoring metric for the current organization and trailing time window.+ * @summary Get managed warehouse monitoring time series+ */+export const dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieve = async (+ projectId: string,+ params: DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams,+ options?: RequestInit+): Promise<ManagedWarehouseMonitoringSeriesResponseApi> => {+ return apiMutator<ManagedWarehouseMonitoringSeriesResponseApi>(+ getDataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getDataWarehouseManagedWarehouseSourceSchemasRetrieveUrl = (projectId: string,params: DataWarehouseManagedWarehouseSourceSchemasRetrieveParamsdiff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex 831185ab0a83..31736bfe5296 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -105,6 +105,36 @@ tools:managed-viewsets-update:operation: managed_viewsets_updateenabled: false+ managed-warehouse-metric-history-get:+ operation: data_warehouse_managed_warehouse_monitoring_timeseries_retrieve+ enabled: true+ scopes:+ - warehouse_view:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get managed warehouse metric history+ description: >+ Get one operational metric over a trailing time window for the active project's managed warehouse. Available+ metrics cover query rate and errors, query duration, active sessions, worker acquisition, storage size, and+ worker crashes. The response includes units and labeled series. These values are not billing totals.+ feature_flag: data-warehouse-scene+ managed-warehouse-monitoring-get:+ operation: data_warehouse_managed_warehouse_monitoring_retrieve+ enabled: true+ scopes:+ - warehouse_view:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get managed warehouse monitoring+ description: >+ Get current workers, allocated resources, active sessions, running queries, queued connections, capacity+ limits, and response coverage for the active project's managed warehouse. Use this to inspect current+ capacity and workload. These values describe operational activity, not invoiced usage.+ feature_flag: data-warehouse-scenequery-tab-state-create:operation: query_tab_state_createenabled: falsediff --git a/products/managed_warehouse/backend/presentation/views.py b/products/managed_warehouse/backend/presentation/views.pyindex e8b7bdedf0a5..675444ec19d8 100644--- a/products/managed_warehouse/backend/presentation/views.py+++ b/products/managed_warehouse/backend/presentation/views.py@@ -12,7 +12,7 @@ per organization (not per team).import refrom datetime import date-from typing import TypedDict+from typing import Literal, TypedDictfrom uuid import UUIDfrom django.conf import settings@@ -54,6 +54,21 @@ class PresentedConnection(TypedDict):username: str+ManagedWarehouseMonitoringMetric = Literal[+ "query_rate",+ "error_ratio",+ "duration_p50",+ "duration_p95",+ "sessions_active",+ "s3_bytes_rate",+ "acquire_p95",+ "acquire_by_source",+ "storage_bytes",+ "worker_crash_rate",+]+ManagedWarehouseMonitoringWindow = Literal["1h", "6h", "24h", "7d", "30d"]++def managed_warehouse_domain() -> str:deployment = (getattr(settings, "CLOUD_DEPLOYMENT", None) or "").upper()return _MANAGED_WAREHOUSE_DOMAINS.get(deployment, "test.local")@@ -896,6 +911,26 @@ def status_for(organization_id: UUID | str) -> Response:return resp+def monitoring_snapshot_for(organization_id: UUID | str) -> Response:+ """Fetch tenant-safe live monitoring data for one organization."""+ return _request("GET", organization_id, "/monitoring/snapshot", timeout=10)+++def monitoring_series_for(+ organization_id: UUID | str,+ metric: ManagedWarehouseMonitoringMetric,+ window: ManagedWarehouseMonitoringWindow,+) -> Response:+ """Fetch one allow-listed monitoring series for one organization."""+ return _request(+ "GET",+ organization_id,+ "/monitoring/series",+ params={"metric": metric, "window": window},+ timeout=10,+ )++def cp_bucket_for(organization_id: UUID | str) -> str | None:"""Authoritative S3 bucket for the org's duckling, straight from the control plane.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex efd7cdf06e4c..6ba5a9706151 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6689,6 +6689,36 @@"readOnlyHint": true}},+ "managed-warehouse-metric-history-get": {+ "description": "Get one operational metric over a trailing time window for the active project's managed warehouse. Available metrics cover query rate and errors, query duration, active sessions, worker acquisition, storage size, and worker crashes. The response includes units and labeled series. These values are not billing totals.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Get managed warehouse metric history",+ "title": "Get managed warehouse metric history",+ "required_scopes": ["warehouse_view:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-warehouse-scene"+ },+ "managed-warehouse-monitoring-get": {+ "description": "Get current workers, allocated resources, active sessions, running queries, queued connections, capacity limits, and response coverage for the active project's managed warehouse. Use this to inspect current capacity and workload. These values describe operational activity, not invoiced usage.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Get managed warehouse monitoring",+ "title": "Get managed warehouse monitoring",+ "required_scopes": ["warehouse_view:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-warehouse-scene"+ },"marketing-analytics-conversion-goals": {"description": "List the configured marketing conversion goals for the current project. Each goal returns its conversion_goal_id — the value the explain, update and delete tools take — plus its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.","category": "Marketing analytics",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 28b199dfbf02..cf13dd2a93b1 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7069,6 +7069,36 @@"readOnlyHint": true}},+ "managed-warehouse-metric-history-get": {+ "description": "Get one operational metric over a trailing time window for the active project's managed warehouse. Available metrics cover query rate and errors, query duration, active sessions, worker acquisition, storage size, and worker crashes. The response includes units and labeled series. These values are not billing totals.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Get managed warehouse metric history",+ "title": "Get managed warehouse metric history",+ "required_scopes": ["warehouse_view:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-warehouse-scene"+ },+ "managed-warehouse-monitoring-get": {+ "description": "Get current workers, allocated resources, active sessions, running queries, queued connections, capacity limits, and response coverage for the active project's managed warehouse. Use this to inspect current capacity and workload. These values describe operational activity, not invoiced usage.",+ "category": "Data warehouse",+ "feature": "data_warehouse",+ "summary": "Get managed warehouse monitoring",+ "title": "Get managed warehouse monitoring",+ "required_scopes": ["warehouse_view:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "data-warehouse-scene"+ },"marketing-analytics-conversion-goals": {"description": "List the configured marketing conversion goals for the current project. Each goal returns its conversion_goal_id — the value the explain, update and delete tools take — plus its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.","category": "Marketing analytics",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cfd9e854c8e1..2619ad1272f3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46282,6 +46282,222 @@ export namespace Schemas {generated_at: string;}+ export interface ManagedWarehouseMonitoringCoverage {+ /**+ * Number of control planes that contributed live data.+ * @minimum 0+ */+ cp_responders: number;+ /**+ * Number of control planes queried for live data.+ * @minimum 0+ */+ cp_total: number;+ /** Whether one or more control planes failed to contribute live data. */+ partial: boolean;+ }++ export interface ManagedWarehouseMonitoringErrorResponse {+ /** Human-readable managed warehouse monitoring error. */+ error?: string;+ /** Machine-readable validation error type. */+ type?: string;+ /** Machine-readable validation error code. */+ code?: string;+ /** Human-readable validation error detail. */+ detail?: string;+ /**+ * Query parameter associated with an error.+ * @nullable+ */+ attr?: string | null;+ }++ export interface ManagedWarehouseMonitoringLimits {+ /**+ * Maximum concurrent workers for the organization. Zero means no organization-specific limit.+ * @minimum 0+ */+ max_workers: number;+ /**+ * Maximum active session vCPUs admitted for the organization. Zero means no organization-specific limit.+ * @minimum 0+ */+ max_vcpus: number;+ /** Default worker CPU as a Kubernetes resource quantity, such as 2 or 500m. */+ default_worker_cpu: string;+ /** Default worker memory as a Kubernetes resource quantity, such as 8Gi. */+ default_worker_memory: string;+ /**+ * Default number of seconds an idle worker remains available for reuse.+ * @minimum 0+ */+ default_worker_ttl_seconds: number;+ /**+ * Minimum number of idle workers the organization keeps warm.+ * @minimum 0+ */+ default_worker_min_hot_idle: number;+ }++ export interface ManagedWarehouseMonitoringPoint {+ /** UTC timestamp of the sample. */+ timestamp: string;+ /** Metric value at the sample timestamp. */+ value: number;+ }++ /**+ * Allow-listed labels distinguishing this series, such as query outcome or acquisition source.+ */+ export type ManagedWarehouseMonitoringSeriesLabels = {[key: string]: string};++ export interface ManagedWarehouseMonitoringSeries {+ /** Allow-listed labels distinguishing this series, such as query outcome or acquisition source. */+ labels: ManagedWarehouseMonitoringSeriesLabels;+ /** Chronologically ordered metric samples. */+ points: ManagedWarehouseMonitoringPoint[];+ }++ export interface ManagedWarehouseMonitoringSeriesResponse {+ /**+ * Version of the managed warehouse monitoring response schema.+ * @minimum 1+ * @maximum 1+ */+ schema_version: number;+ /** Organization whose managed warehouse is represented. */+ org_id: string;+ /** Allow-listed metric returned by this response. */+ metric: string;+ /** Unit for every value in the response. */+ unit: string;+ /** Inclusive UTC start of the returned time window. */+ start: string;+ /** Inclusive UTC end of the returned time window. */+ end: string;+ /**+ * Number of seconds between requested samples.+ * @minimum 1+ */+ step_seconds: number;+ /** Metric series grouped by their allow-listed labels. */+ series: ManagedWarehouseMonitoringSeries[];+ }++ export interface ManagedWarehouseMonitoringWarehouse {+ /** Current managed warehouse lifecycle state, such as ready, provisioning, or resharding. */+ state: string;+ }++ export interface ManagedWarehouseMonitoringTotals {+ /**+ * Number of current non-terminal workers.+ * @minimum 0+ */+ workers: number;+ /**+ * Total CPU cores allocated to current workers.+ * @minimum 0+ */+ allocated_cpu_cores: number;+ /**+ * Total memory bytes allocated to current workers.+ * @minimum 0+ */+ allocated_memory_bytes: number;+ /**+ * Number of active database sessions across the organization's control planes.+ * @minimum 0+ */+ active_sessions: number;+ /**+ * Number of sessions currently executing a query.+ * @minimum 0+ */+ running_queries: number;+ /**+ * Number of connections waiting for worker capacity.+ * @minimum 0+ */+ queued_connections: number;+ }++ export interface ManagedWarehouseMonitoringWorkerSession {+ /** Connection protocol, such as pg or flight. */+ protocol: string;+ /** Current database session state. */+ state: string;+ /**+ * Milliseconds elapsed for the current query, or zero when the session is idle.+ * @minimum 0+ */+ elapsed_ms: number;+ /**+ * Best-effort query progress percentage, or null when DuckDB cannot estimate progress.+ * @minimum 0+ * @nullable+ */+ percentage: number | null;+ /**+ * Rows processed by the current query.+ * @minimum 0+ */+ rows: number;+ /**+ * Estimated total rows for the current query when available.+ * @minimum 0+ */+ total_rows: number;+ /** Whether the current query appears stalled. */+ stalled: boolean;+ }++ export interface ManagedWarehouseMonitoringWorker {+ /** Opaque identifier for the worker. */+ id: string;+ /** Current worker lifecycle state. */+ state: string;+ /** Worker CPU as a Kubernetes resource quantity, such as 2 or 500m. Blank when unavailable. */+ cpu: string;+ /** Worker memory as a Kubernetes resource quantity, such as 8Gi. Blank when unavailable. */+ memory: string;+ /**+ * Number of seconds the worker remains available while idle.+ * @minimum 0+ */+ ttl_seconds: number;+ /** UTC timestamp when the worker was created. */+ created_at: string;+ /** UTC timestamp of the worker's latest heartbeat. */+ last_heartbeat_at: string;+ /** Sanitized live session assigned to the worker, when one exists. */+ session?: ManagedWarehouseMonitoringWorkerSession | null;+ }++ export interface ManagedWarehouseMonitoringSnapshotResponse {+ /**+ * Version of the managed warehouse monitoring response schema.+ * @minimum 1+ * @maximum 1+ */+ schema_version: number;+ /** Organization whose managed warehouse is represented. */+ org_id: string;+ /** UTC timestamp when this snapshot was assembled. */+ as_of: string;+ /** Managed warehouse lifecycle details. */+ warehouse: ManagedWarehouseMonitoringWarehouse;+ /** Organization-level worker limits and defaults. */+ limits: ManagedWarehouseMonitoringLimits;+ /** Current organization-level activity totals. */+ totals: ManagedWarehouseMonitoringTotals;+ /** Current non-terminal workers with tenant-safe runtime details. */+ workers: ManagedWarehouseMonitoringWorker[];+ /** Completeness of the cross-control-plane live data. */+ coverage: ManagedWarehouseMonitoringCoverage;+ }+/*** * `copy` - copy* * `register` - register@@ -84800,6 +85016,61 @@ export namespace Schemas {name: string;};+ export type DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams = {+ /**+ * Allow-listed managed warehouse metric to retrieve.+ *+ * * `query_rate` - query_rate+ * * `error_ratio` - error_ratio+ * * `duration_p50` - duration_p50+ * * `duration_p95` - duration_p95+ * * `sessions_active` - sessions_active+ * * `acquire_p95` - acquire_p95+ * * `acquire_by_source` - acquire_by_source+ * * `storage_bytes` - storage_bytes+ * * `worker_crash_rate` - worker_crash_rate+ * @minLength 1+ */+ metric: DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric;+ /**+ * Trailing time window to retrieve. Defaults to 24h.+ *+ * * `1h` - 1h+ * * `6h` - 6h+ * * `24h` - 24h+ * * `7d` - 7d+ * * `30d` - 30d+ * @minLength 1+ */+ window?: DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow;+ };++ export type DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric = typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric[keyof typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric];+++ export const DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveMetric = {+ QueryRate: 'query_rate',+ ErrorRatio: 'error_ratio',+ DurationP50: 'duration_p50',+ DurationP95: 'duration_p95',+ SessionsActive: 'sessions_active',+ AcquireP95: 'acquire_p95',+ AcquireBySource: 'acquire_by_source',+ StorageBytes: 'storage_bytes',+ WorkerCrashRate: 'worker_crash_rate',+ } as const;++ export type DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow = typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow[keyof typeof DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow];+++ export const DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveWindow = {+ '1h': '1h',+ '6h': '6h',+ '24h': '24h',+ '7d': '7d',+ '30d': '30d',+ } as const;+export type DataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {/*** Imported source connection to fetch per-schema detail for.diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.tsindex 595af230538b..12178eb37f99 100644--- a/services/mcp/src/generated/data_warehouse/api.ts+++ b/services/mcp/src/generated/data_warehouse/api.ts@@ -3,11 +3,61 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 18 enabled ops+ * PostHog API - MCP 20 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'+/**+ * Get tenant-safe live worker, session, queue, and capacity data for the current organization.+ * @summary Get managed warehouse monitoring snapshot+ */+export const DataWarehouseManagedWarehouseMonitoringRetrieveParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * Get one allow-listed monitoring metric for the current organization and trailing time window.+ * @summary Get managed warehouse monitoring time series+ */+export const DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveQueryWindowDefault = `24h`++export const DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveQueryParams = /* @__PURE__ */ zod.object({+ metric: zod+ .enum([+ 'query_rate',+ 'error_ratio',+ 'duration_p50',+ 'duration_p95',+ 'sessions_active',+ 'acquire_p95',+ 'acquire_by_source',+ 'storage_bytes',+ 'worker_crash_rate',+ ])+ .describe(+ 'Allow-listed managed warehouse metric to retrieve.\n\n\* `query_rate` - query_rate\n\* `error_ratio` - error_ratio\n\* `duration_p50` - duration_p50\n\* `duration_p95` - duration_p95\n\* `sessions_active` - sessions_active\n\* `acquire_p95` - acquire_p95\n\* `acquire_by_source` - acquire_by_source\n\* `storage_bytes` - storage_bytes\n\* `worker_crash_rate` - worker_crash_rate'+ ),+ window: zod+ .enum(['1h', '6h', '24h', '7d', '30d'])+ .default(dataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveQueryWindowDefault)+ .describe(+ 'Trailing time window to retrieve. Defaults to 24h.\n\n\* `1h` - 1h\n\* `6h` - 6h\n\* `24h` - 24h\n\* `7d` - 7d\n\* `30d` - 30d'+ ),+})+export const InsightVariablesCreateParams = /* @__PURE__ */ zod.object({project_id: zod.string()diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.tsindex ec8719727b73..0d3b3f31fc52 100644--- a/services/mcp/src/tools/generated/data_warehouse.ts+++ b/services/mcp/src/tools/generated/data_warehouse.ts@@ -3,6 +3,7 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {+ DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveQueryParams,InsightVariablesCreateBody,InsightVariablesDestroyParams,InsightVariablesPartialUpdateBody,@@ -31,6 +32,47 @@ import {import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const ManagedWarehouseMetricHistoryGetSchema = DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveQueryParams++const managedWarehouseMetricHistoryGet = (): ToolBase<+ typeof ManagedWarehouseMetricHistoryGetSchema,+ Schemas.ManagedWarehouseMonitoringSeriesResponse+> => ({+ name: 'managed-warehouse-metric-history-get',+ schema: ManagedWarehouseMetricHistoryGetSchema,+ handler: async (context: Context, params: z.infer<typeof ManagedWarehouseMetricHistoryGetSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ManagedWarehouseMonitoringSeriesResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_warehouse/managed-warehouse-monitoring-timeseries/`,+ query: {+ metric: params.metric,+ window: params.window,+ },+ })+ return result+ },+})++const ManagedWarehouseMonitoringGetSchema = z.object({})++const managedWarehouseMonitoringGet = (): ToolBase<+ typeof ManagedWarehouseMonitoringGetSchema,+ Schemas.ManagedWarehouseMonitoringSnapshotResponse+> => ({+ name: 'managed-warehouse-monitoring-get',+ schema: ManagedWarehouseMonitoringGetSchema,+ // eslint-disable-next-line no-unused-vars+ handler: async (context: Context, params: z.infer<typeof ManagedWarehouseMonitoringGetSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.ManagedWarehouseMonitoringSnapshotResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_warehouse/managed-warehouse-monitoring/`,+ })+ return result+ },+})+const SavedQueryColumnAnnotationsCreateSchema = SavedQueryColumnAnnotationsCreateBody.extend({column_name: SavedQueryColumnAnnotationsCreateBody.shape['column_name'].describe('Column to describe. Use an empty string to describe the view itself.'@@ -557,6 +599,8 @@ const warehouseTablesRefreshSchemaCreate = (): ToolBase<typeof WarehouseTablesRe})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'managed-warehouse-metric-history-get': managedWarehouseMetricHistoryGet,+ 'managed-warehouse-monitoring-get': managedWarehouseMonitoringGet,'saved-query-column-annotations-create': savedQueryColumnAnnotationsCreate,'saved-query-column-annotations-list': savedQueryColumnAnnotationsList,'sql-variables-create': sqlVariablesCreate,diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex ead33a0126f6..1126091d25ab 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -327,6 +327,26 @@ describe('Tool Filtering - API Scopes', () => {expect(toolNames).not.toContain('insight-create')})+ it('should expose managed warehouse monitoring only with its read scope and feature flag', async () => {+ const managedWarehouseTools = ['managed-warehouse-monitoring-get', 'managed-warehouse-metric-history-get']+ const enabledOptions = { featureFlags: { 'data-warehouse-scene': true } }++ const authorizedTools = await getToolsFromContext(createMockContext(['warehouse_view:read']), enabledOptions)+ const wrongScopeTools = await getToolsFromContext(createMockContext(['query:read']), enabledOptions)+ const flagDisabledTools = await getToolsFromContext(createMockContext(['warehouse_view:read']), {+ featureFlags: { 'data-warehouse-scene': false },+ })+ const authorizedToolNames = authorizedTools.map((tool) => tool.name)+ const wrongScopeToolNames = wrongScopeTools.map((tool) => tool.name)+ const flagDisabledToolNames = flagDisabledTools.map((tool) => tool.name)++ for (const toolName of managedWarehouseTools) {+ expect(authorizedToolNames).toContain(toolName)+ expect(wrongScopeToolNames).not.toContain(toolName)+ expect(flagDisabledToolNames).not.toContain(toolName)+ }+ })+it('should return only tools with no required scopes when user has no matching scopes', async () => {const context = createMockContext(['some:unknown'])const tools = await getToolsFromContext(context)@@ -859,9 +879,10 @@ describe('Tool Filtering - Feature Flags', () => {'streamlit-apps','posthog-connect','experiment-behavior-comparison',+ 'data-warehouse-scene',]))- expect(flags).toHaveLength(29)+ expect(flags).toHaveLength(30)})it('every loops tool is gated on the loops flag', () => {