Skip to content

: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.

feat(data-warehouse): add a trino variant of the data ops scene (#110369)

Eric Duong0fa54380573d
diff --git a/docs/internal/managed-warehouse-monitoring.md b/docs/internal/managed-warehouse-monitoring.md
index 341cb807df14..1c320255e4d9 100644
--- a/docs/internal/managed-warehouse-monitoring.md
+++ b/docs/internal/managed-warehouse-monitoring.md
@@ -1,7 +1,7 @@
# 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.
+It has two variants. Organizations on `data-warehouse-scene` see the DuckDB worker variant described first. Organizations on `data-warehouse-scene-trino` see the Trino variant described under "Trino variant". The Trino flag wins when both are on.
## Request path and tenant boundary
@@ -62,6 +62,34 @@ The dashboard loads historical data when the selected range changes or the user
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.
+## Trino variant
+
+Organizations on `data-warehouse-scene-trino` query through Trino, so the tab shows query activity instead of workers.
+
+The browser calls:
+
+- `GET /api/projects/{team_id}/data_warehouse/managed-warehouse-trino-monitoring/`
+- `GET /api/projects/{team_id}/data_warehouse/managed-warehouse-trino-monitoring-timeseries/?metric=...&window=...`
+
+Trino monitoring requests use the Hogtower adapter when `HOGTOWER_API_URL` is configured.
+The adapter forwards the snapshot and series paths to `/api/v2/warehouses/:id/monitoring/trino/` and preserves the metric and window query parameters.
+
+Each monitoring endpoint serves one variant. A Trino organization gets 404 from the DuckDB endpoints, and a DuckDB organization gets 404 from the Trino endpoints. This matters because workers still run a Trino organization's internal writes, and that data is not for its users.
+
+The snapshot contains the organization's Trino lifecycle state, its concurrency and queue limits, in-flight totals, and at most 200 in-flight queries, longest-running first.
+`in_flight` equals `running` plus `queued`, and `blocked` is a subset of `running`.
+Query text has literal values replaced with `?`. The control plane does the masking, so unmasked SQL never reaches PostHog.
+When `available` is false the live data could not be read. The UI shows that state instead of presenting zero as an idle warehouse.
+
+The Trino series metrics are queries in flight by state, query rate and outcomes, query duration, queue time, data scanned, CPU time, and storage size.
+The query counts are best-effort on a very busy warehouse and are not billing totals.
+
+Changing the Monitoring time range clears the previous range while the new metrics load.
+A failed refresh within the same range keeps the last successful data and shows a warning.
+
+MCP clients get the same data through `managed-warehouse-trino-monitoring-get` and `managed-warehouse-trino-metric-history-get`, available when `data-warehouse-scene-trino` is enabled.
+An organization with both flags still sees the two DuckDB tools listed. Those calls return the 404 that names the Trino endpoints.
+
## Usage scope
This first version reports operational activity and allocated capacity.
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
index 2c0bb2afe330..6ff128146103 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx
@@ -15,6 +15,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getEntryAccessDisabledReason, getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { withTimeout } from 'lib/utils/async'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { getCurrentTeamIdOrNone, getCurrentUserIdOrNone } from 'lib/utils/getAppContext'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { capitalizeFirstLetter, humanList, identifierToHuman, pluralize } from 'lib/utils/strings'
@@ -1672,7 +1673,7 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
convertFileSystemEntryToTreeDataItem({
root: protocol,
imports: imports
- .filter((f) => !f.flag || (featureFlags as Record<string, boolean>)[f.flag])
+ .filter((f) => isFileSystemImportFlagEnabled(f, featureFlags))
.map((i) => ({
...i,
protocol,
@@ -1760,7 +1761,7 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([
.filter((p): p is FileSystemImport => p !== null)
const imports = selectedProducts
- .filter((f) => !f.flag || (featureFlags as Record<string, boolean>)[f.flag])
+ .filter((f) => isFileSystemImportFlagEnabled(f, featureFlags))
.map((i) => ({
...i,
protocol: 'custom-products://',
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/flat-nav/flatNavLogic.ts b/frontend/src/layout/panel-layout/navbar/tabs/flat-nav/flatNavLogic.ts
index 54e95326a95b..13ee61bdcd68 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/flat-nav/flatNavLogic.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/flat-nav/flatNavLogic.ts
@@ -2,6 +2,7 @@ import { MakeLogicType, connect, kea, path, selectors } from 'kea'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'
import { getDefaultTreeProducts } from '~/layout/panel-layout/ProjectTree/defaultTree'
@@ -63,7 +64,7 @@ export const flatNavLogic = kea<flatNavLogicType>([
const product = catalog.get(productPath)
if (
!product?.href ||
- (product.flag && !(featureFlags as Record<string, boolean | string>)[product.flag]) ||
+ !isFileSystemImportFlagEnabled(product, featureFlags) ||
// Products the user has no access to are hidden instead of shown disabled
getProductAccessDisabledReason(product)
) {
diff --git a/frontend/src/layout/panel-layout/navbar/tabs/navProductItems.ts b/frontend/src/layout/panel-layout/navbar/tabs/navProductItems.ts
index d109941fb902..eadfb72fb456 100644
--- a/frontend/src/layout/panel-layout/navbar/tabs/navProductItems.ts
+++ b/frontend/src/layout/panel-layout/navbar/tabs/navProductItems.ts
@@ -1,4 +1,5 @@
import { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { DEFINITIONS_TABS } from 'scenes/data-management/definitionsSceneTabsLogic'
import { urls } from 'scenes/urls'
@@ -53,11 +54,7 @@ export function getNavProductItems(featureFlags: FeatureFlagsSet): FileSystemImp
]
const destinations = new Map<string, FileSystemImport>()
for (const item of items) {
- if (
- !item.href ||
- DEFINITIONS_TAB_HREFS.has(item.href) ||
- (item.flag && !featureFlags[item.flag as keyof FeatureFlagsSet])
- ) {
+ if (!item.href || DEFINITIONS_TAB_HREFS.has(item.href) || !isFileSystemImportFlagEnabled(item, featureFlags)) {
continue
}
const existing = destinations.get(item.href)
diff --git a/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushAdLogic.ts b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushAdLogic.ts
index 9e49d55b2f62..3aa03cab4710 100644
--- a/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushAdLogic.ts
+++ b/frontend/src/lib/components/NavPanelAdvertisement/navPanelProductPushAdLogic.ts
@@ -2,6 +2,7 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,
import posthog from 'posthog-js'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { addProductIntent } from 'lib/utils/product-intents'
import { isExternalLink } from 'lib/utils/url'
@@ -106,7 +107,7 @@ export const navPanelProductPushAdLogic = kea<navPanelProductPushAdLogicType>([
(
productInfo: FileSystemImport | undefined,
featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet
- ): boolean => !!productInfo?.flag && !(featureFlags as Record<string, boolean>)[productInfo.flag],
+ ): boolean => !!productInfo && !isFileSystemImportFlagEnabled(productInfo, featureFlags),
],
// A surface links to its own href/label; a catalog product resolves them from its catalog entry.
destination: [
diff --git a/frontend/src/lib/components/Search/searchListsLogic.test.ts b/frontend/src/lib/components/Search/searchListsLogic.test.ts
index 81aad561c789..8d59f28c66f2 100644
--- a/frontend/src/lib/components/Search/searchListsLogic.test.ts
+++ b/frontend/src/lib/components/Search/searchListsLogic.test.ts
@@ -19,6 +19,20 @@ describe('searchListsLogic', () => {
logic.unmount()
})
+ it.each([
+ [false, false, false],
+ [true, false, true],
+ [false, true, true],
+ [true, true, true],
+ ])('shows Data ops with DuckDB=%s and Trino=%s', (duckdb, trino, visible) => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: duckdb,
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]: trino,
+ })
+
+ expect(logic.values.productsItems.some((item) => item.id === 'product-Data warehouse')).toBe(visible)
+ })
+
it.each([false, true])('gates the command-menu terminal toggle when enabled=%s', (enabled) => {
logic.unmount()
logic = searchListsLogic({ commandPalette: true })
diff --git a/frontend/src/lib/components/Search/searchListsLogic.tsx b/frontend/src/lib/components/Search/searchListsLogic.tsx
index 439acbe729b4..e5d5d96db744 100644
--- a/frontend/src/lib/components/Search/searchListsLogic.tsx
+++ b/frontend/src/lib/components/Search/searchListsLogic.tsx
@@ -8,6 +8,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'
import { newInternalTab } from 'lib/utils/newInternalTab'
@@ -253,7 +254,7 @@ export const searchListsLogic = kea<searchListsLogicType>([
if (!isDev && !user?.is_staff && product.category === 'Unreleased') {
return false
}
- if (!isEnabledByFlag(product.flag, featureFlags)) {
+ if (!isFileSystemImportFlagEnabled(product, featureFlags)) {
return false
}
return true
@@ -310,7 +311,7 @@ export const searchListsLogic = kea<searchListsLogicType>([
if (!isDev && !user?.is_staff && item.category === 'Unreleased') {
return false
}
- if (!isEnabledByFlag(item.flag, featureFlags)) {
+ if (!isFileSystemImportFlagEnabled(item, featureFlags)) {
return false
}
return true
@@ -359,7 +360,7 @@ export const searchListsLogic = kea<searchListsLogicType>([
if (!isDev && !user?.is_staff && item.category === 'Unreleased') {
return false
}
- if (!isEnabledByFlag(item.flag, featureFlags)) {
+ if (!isFileSystemImportFlagEnabled(item, featureFlags)) {
return false
}
return true
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3df305e5c15a..fae36ffd2ef7 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -321,6 +321,7 @@ export const FEATURE_FLAGS = {
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sources
DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modeling
+ DATA_WAREHOUSE_SCENE_TRINO: 'data-warehouse-scene-trino', // owner: #team-data-modeling
DISCUSSIONS_SLACK_SYNC: 'discussions-slack-sync', // owner: #team-platform-features
DROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analytics
DWH_POSTGRES_CDC: 'dwh-postgres-cdc', // owner: #team-warehouse-sources
diff --git a/frontend/src/lib/utils/fileSystemImportFlags.test.ts b/frontend/src/lib/utils/fileSystemImportFlags.test.ts
new file mode 100644
index 000000000000..87853df104bc
--- /dev/null
+++ b/frontend/src/lib/utils/fileSystemImportFlags.test.ts
@@ -0,0 +1,28 @@
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+import { isFileSystemImportFlagEnabled } from './fileSystemImportFlags'
+
+describe('isFileSystemImportFlagEnabled', () => {
+ const flags = (enabled: string[]): FeatureFlagsSet =>
+ Object.fromEntries(enabled.map((flag) => [flag, true])) as FeatureFlagsSet
+
+ it.each([
+ { name: 'no flag', item: {}, enabled: [], expected: true },
+ { name: 'flag on', item: { flag: 'a' }, enabled: ['a'], expected: true },
+ { name: 'flag off', item: { flag: 'a' }, enabled: [], expected: false },
+ {
+ name: 'flag off, alternative on',
+ item: { flag: 'a', alternativeFlags: ['b'] },
+ enabled: ['b'],
+ expected: true,
+ },
+ {
+ name: 'flag and alternatives off',
+ item: { flag: 'a', alternativeFlags: ['b', 'c'] },
+ enabled: ['d'],
+ expected: false,
+ },
+ ])('$name', ({ item, enabled, expected }) => {
+ expect(isFileSystemImportFlagEnabled(item, flags(enabled))).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/utils/fileSystemImportFlags.ts b/frontend/src/lib/utils/fileSystemImportFlags.ts
new file mode 100644
index 000000000000..dede2e462d0c
--- /dev/null
+++ b/frontend/src/lib/utils/fileSystemImportFlags.ts
@@ -0,0 +1,15 @@
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+import type { FileSystemImport } from '~/queries/schema/schema-general'
+
+/** Whether a navigation item's feature flag gate is open. An item with no flag is always shown. */
+export function isFileSystemImportFlagEnabled(
+ item: Pick<FileSystemImport, 'flag' | 'alternativeFlags'>,
+ featureFlags: FeatureFlagsSet
+): boolean {
+ if (!item.flag) {
+ return true
+ }
+ const flags = featureFlags as Record<string, boolean | string | undefined>
+ return [item.flag, ...(item.alternativeFlags ?? [])].some((flag) => !!flags[flag])
+}
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 16d74fc3b7ad..4b910f601f07 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -2496,6 +2496,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
searchKeywords: ['managed warehouse', 'data lake', 'lakehouse'],
searchTabs: [{ name: 'Monitoring', href: urls.dataOps('monitoring') }],
flag: FEATURE_FLAGS.DATA_WAREHOUSE_SCENE,
+ alternativeFlags: [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO],
iconType: 'data_warehouse',
iconColor: ['var(--color-product-data-warehouse-light)'],
sceneKey: 'DataOps',
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index fdf694d4202c..e067ad4cb34c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -27991,6 +27991,13 @@
"description": "Used to indicate pending actions, frontend only",
"type": "boolean"
},
+ "alternativeFlags": {
+ "description": "Other flags that also show the item. The item is shown when `flag` or any of these is on.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"category": {
"description": "Category label to place this under",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 12ad30b31806..53cf147d8e38 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5558,6 +5558,8 @@ export interface FileSystemImport extends Omit<FileSystemEntry, 'id'> {
id?: string
iconType?: FileSystemIconType
flag?: string
+ /** Other flags that also show the item. The item is shown when `flag` or any of these is on. */
+ alternativeFlags?: string[]
/** Order of object in tree */
visualOrder?: number
/** Tag for the product 'beta' / 'alpha' */
diff --git a/frontend/src/scenes/library/libraryLogic.ts b/frontend/src/scenes/library/libraryLogic.ts
index c2f08eb79d04..a20354b5f1c7 100644
--- a/frontend/src/scenes/library/libraryLogic.ts
+++ b/frontend/src/scenes/library/libraryLogic.ts
@@ -5,6 +5,7 @@ import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { urls } from 'scenes/urls'
import { fileSystemTypes, getTreeItemsNew } from '~/products'
@@ -211,7 +212,7 @@ export const libraryLogic = kea<libraryLogicType>([
const byType: Record<string, FileSystemImport[]> = {}
for (const item of getTreeItemsNew()) {
const type = baseObjectType(item.type)
- if (!item.href || (item.flag && !featureFlags[item.flag as keyof FeatureFlagsSet])) {
+ if (!item.href || !isFileSystemImportFlagEnabled(item, featureFlags)) {
continue
}
byType[type] = [...(byType[type] ?? []), item]
diff --git a/frontend/src/scenes/settings/user/SidebarSettings.tsx b/frontend/src/scenes/settings/user/SidebarSettings.tsx
index d2a366e66454..f4f33d3ba5a6 100644
--- a/frontend/src/scenes/settings/user/SidebarSettings.tsx
+++ b/frontend/src/scenes/settings/user/SidebarSettings.tsx
@@ -5,6 +5,7 @@ import { LemonLabel, LemonSegmentedButton, LemonSwitch } from '@posthog/lemon-ui
import { Link } from 'lib/lemon-ui/Link'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { customProductsLogic } from '~/layout/panel-layout/ProjectTree/customProductsLogic'
import { getDefaultTreeProducts, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
@@ -187,7 +188,7 @@ export function SidebarMyProductsSetting(): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const products = getDefaultTreeProducts()
- .filter((product) => !product.flag || (featureFlags as Record<string, boolean | string>)[product.flag])
+ .filter((product) => isFileSystemImportFlagEnabled(product, featureFlags))
.filter((product) => !getProductAccessDisabledReason(product))
const productsByCategory = new Map<string, FileSystemImport[]>()
for (const product of products) {
diff --git a/frontend/src/scenes/tools/toolsLogic.ts b/frontend/src/scenes/tools/toolsLogic.ts
index cc51f239a45e..4b7e6aca2cd9 100644
--- a/frontend/src/scenes/tools/toolsLogic.ts
+++ b/frontend/src/scenes/tools/toolsLogic.ts
@@ -2,6 +2,7 @@ import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'
+import { isFileSystemImportFlagEnabled } from 'lib/utils/fileSystemImportFlags'
import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { FileSystemImport } from '~/queries/schema/schema-general'
@@ -52,7 +53,7 @@ export const toolsLogic = kea<toolsLogicType>([
!item.href ||
!isToolItem(item) ||
seen.has(item.href) ||
- (item.flag && !featureFlags[item.flag as keyof FeatureFlagsSet]) ||
+ !isFileSystemImportFlagEnabled(item, featureFlags) ||
getProductAccessDisabledReason(item)
) {
return false
diff --git a/posthog/schema.py b/posthog/schema.py
index 091dbf1aedf5..cea9410d0cd8 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5977,6 +5977,10 @@ class FileSystemImport(BaseModel):
alias="_loading",
description="Used to indicate pending actions, frontend only",
)
+ alternativeFlags: list[str] | None = Field(
+ default=None,
+ description=("Other flags that also show the item. The item is shown when `flag` or any of these is on."),
+ )
category: str | None = Field(default=None, description="Category label to place this under")
created_at: str | None = Field(
default=None,
diff --git a/products/data_warehouse/backend/presentation/managed_warehouse_monitoring.py b/products/data_warehouse/backend/presentation/managed_warehouse_monitoring.py
index b08099fd1264..a4021c5e21bc 100644
--- a/products/data_warehouse/backend/presentation/managed_warehouse_monitoring.py
+++ b/products/data_warehouse/backend/presentation/managed_warehouse_monitoring.py
@@ -225,7 +225,7 @@ class ManagedWarehouseMonitoringSeriesResponseSerializer(serializers.Serializer)
def serialize_monitoring_snapshot(raw: object, *, expected_organization_id: str) -> dict[str, object]:
- return _serialize_monitoring_response(
+ return serialize_monitoring_response(
raw,
serializer_class=ManagedWarehouseMonitoringSnapshotResponseSerializer,
expected_organization_id=expected_organization_id,
@@ -238,7 +238,7 @@ def serialize_monitoring_series(
expected_organization_id: str,
expected_metric: str,
) -> dict[str, object]:
- data = _serialize_monitoring_response(
+ data = serialize_monitoring_response(
raw,
serializer_class=ManagedWarehouseMonitoringSeriesResponseSerializer,
expected_organization_id=expected_organization_id,
@@ -254,7 +254,7 @@ def serialize_monitoring_series(
return data
-def _serialize_monitoring_response(
+def serialize_monitoring_response(
raw: object,
*,
serializer_class: type[serializers.Serializer],
diff --git a/products/data_warehouse/backend/presentation/managed_warehouse_trino_monitoring.py b/products/data_warehouse/backend/presentation/managed_warehouse_trino_monitoring.py
new file mode 100644
index 000000000000..aedad804b579
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/managed_warehouse_trino_monitoring.py
@@ -0,0 +1,185 @@
+from collections.abc import Mapping
+from typing import cast
+
+from django.db import models
+
+from rest_framework import serializers
+
+from products.data_warehouse.backend.presentation.managed_warehouse_monitoring import (
+ MANAGED_WAREHOUSE_MONITORING_WINDOWS,
+ ManagedWarehouseMonitoringSeriesResponseSerializer,
+ ManagedWarehouseMonitoringUpstreamError,
+ serialize_monitoring_response,
+)
+
+
+class ManagedWarehouseTrinoMonitoringMetric(models.TextChoices):
+ QUERIES_IN_FLIGHT = "queries_in_flight", "queries_in_flight"
+ QUERY_RATE = "query_rate", "query_rate"
+ ERROR_RATIO = "error_ratio", "error_ratio"
+ DURATION_P50 = "duration_p50", "duration_p50"
+ DURATION_P95 = "duration_p95", "duration_p95"
+ QUEUE_TIME_P95 = "queue_time_p95", "queue_time_p95"
+ SCANNED_BYTES_RATE = "scanned_bytes_rate", "scanned_bytes_rate"
+ CPU_SECONDS_RATE = "cpu_seconds_rate", "cpu_seconds_rate"
+ STORAGE_BYTES = "storage_bytes", "storage_bytes"
+
+
+class WarehouseTrinoStatusState(models.TextChoices):
+ NOT_ENABLED = "not_enabled", "not_enabled"
+ PENDING = "pending", "pending"
+ PROVISIONING = "provisioning", "provisioning"
+ READY = "ready", "ready"
+ FAILED = "failed", "failed"
+ UNAVAILABLE = "unavailable", "unavailable"
+
+
+MANAGED_WAREHOUSE_TRINO_MONITORING_LABELS = {
+ "queries_in_flight": frozenset({"state"}),
+ "query_rate": frozenset({"status", "error_type"}),
+ "error_ratio": frozenset(),
+ "duration_p50": frozenset(),
+ "duration_p95": frozenset(),
+ "queue_time_p95": frozenset(),
+ "scanned_bytes_rate": frozenset(),
+ "cpu_seconds_rate": frozenset(),
+ "storage_bytes": frozenset(),
+}
+
+
+class ManagedWarehouseTrinoMonitoringStateSerializer(serializers.Serializer):
+ state = serializers.CharField(
+ help_text="Trino lifecycle state for the organization: not_enabled, pending, provisioning, ready, or failed."
+ )
+ ready_at = serializers.DateTimeField(
+ allow_null=True, help_text="UTC timestamp when Trino became ready for the organization, or null."
+ )
+ failed_at = serializers.DateTimeField(
+ allow_null=True, help_text="UTC timestamp when Trino setup last failed for the organization, or null."
+ )
+
+
+class ManagedWarehouseTrinoMonitoringLimitsSerializer(serializers.Serializer):
+ max_running_queries = serializers.IntegerField(
+ min_value=0,
+ help_text="Maximum number of the organization's queries that run at the same time. Zero when Trino is not enabled.",
+ )
+ max_queued_queries = serializers.IntegerField(
+ min_value=0,
+ help_text="Maximum number of the organization's queries that can wait in the queue. Zero when Trino is not enabled.",
+ )
+
+
+class ManagedWarehouseTrinoMonitoringTotalsSerializer(serializers.Serializer):
+ in_flight = serializers.IntegerField(
+ min_value=0, help_text="Queries submitted and not yet finished. Equals running plus queued."
+ )
+ running = serializers.IntegerField(
+ min_value=0,
+ help_text="In-flight queries past the queue. This is the count the concurrency limit applies to.",
+ )
+ queued = serializers.IntegerField(min_value=0, help_text="Queries waiting for a running slot.")
+ blocked = serializers.IntegerField(
+ min_value=0,
+ help_text="Running queries whose work is all waiting on data or metadata. A subset of running.",
+ )
+ longest_running_ms = serializers.IntegerField(
+ min_value=0, help_text="Elapsed milliseconds of the longest in-flight query, or zero when there is none."
+ )
+ physical_input_bytes = serializers.IntegerField(
+ min_value=0, help_text="Bytes read so far by all in-flight queries."
+ )
+
+
+class ManagedWarehouseTrinoMonitoringQuerySerializer(serializers.Serializer):
+ query_id = serializers.CharField(help_text="Trino query identifier.")
+ state = serializers.CharField(
+ help_text="Trino query state in lower case, such as queued, planning, starting, running, or finishing."
+ )
+ user = serializers.CharField(
+ allow_blank=True, help_text="Warehouse username that ran the query. Blank when it cannot be resolved."
+ )
+ source = serializers.CharField( # type: ignore[assignment] # Response field shadows DRF's source option.
+ allow_blank=True, help_text="Client-reported source of the query, such as a tool name. Blank when not set."
+ )
+ query = serializers.CharField(
+ allow_blank=True,
+ help_text="SQL text with literal values replaced by ? and comments removed. A placeholder when unavailable.",
+ )
+ created_at = serializers.DateTimeField(
+ allow_null=True, help_text="UTC timestamp when the query was submitted, or null when Trino does not report it."
+ )
+ elapsed_ms = serializers.IntegerField(min_value=0, help_text="Milliseconds since the query was submitted.")
+ queued_ms = serializers.IntegerField(min_value=0, help_text="Milliseconds the query spent queued.")
+ cpu_ms = serializers.IntegerField(min_value=0, help_text="CPU milliseconds the query has used.")
+ physical_input_bytes = serializers.IntegerField(min_value=0, help_text="Bytes the query has read from storage.")
+ peak_memory_bytes = serializers.IntegerField(min_value=0, help_text="Peak memory the query has reserved, in bytes.")
+ processed_input_rows = serializers.IntegerField(min_value=0, help_text="Rows the query has read.")
+ progress_percentage = serializers.FloatField(
+ min_value=0,
+ allow_null=True,
+ help_text="Best-effort progress percentage, or null when Trino cannot estimate it.",
+ )
+ blocked = serializers.BooleanField(help_text="Whether all of the query's work is waiting on data or metadata.")
+
+
+class ManagedWarehouseTrinoMonitoringSnapshotResponseSerializer(serializers.Serializer):
+ schema_version = serializers.IntegerField(
+ min_value=1, max_value=1, help_text="Version of the Trino 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.")
+ trino = ManagedWarehouseTrinoMonitoringStateSerializer(help_text="Trino lifecycle details for the organization.")
+ available = serializers.BooleanField(
+ help_text="Whether live query data could be read. When false, totals are zero and do not mean the warehouse is idle."
+ )
+ limits = ManagedWarehouseTrinoMonitoringLimitsSerializer(help_text="Concurrency and queue limits.")
+ totals = ManagedWarehouseTrinoMonitoringTotalsSerializer(help_text="Current in-flight query totals.")
+ queries = ManagedWarehouseTrinoMonitoringQuerySerializer(
+ many=True, help_text="In-flight queries, longest-running first, capped at 200 rows."
+ )
+ queries_truncated = serializers.BooleanField(
+ help_text="Whether the query list was capped. Totals always cover every in-flight query."
+ )
+
+
+class ManagedWarehouseTrinoMonitoringSeriesQuerySerializer(serializers.Serializer):
+ metric = serializers.ChoiceField(
+ choices=ManagedWarehouseTrinoMonitoringMetric.choices,
+ help_text="Allow-listed Trino metric to retrieve.",
+ )
+ window = serializers.ChoiceField(
+ choices=MANAGED_WAREHOUSE_MONITORING_WINDOWS,
+ default="24h",
+ help_text="Trailing time window to retrieve. Defaults to 24h.",
+ )
+
+
+def serialize_trino_monitoring_snapshot(raw: object, *, expected_organization_id: str) -> dict[str, object]:
+ return serialize_monitoring_response(
+ raw,
+ serializer_class=ManagedWarehouseTrinoMonitoringSnapshotResponseSerializer,
+ expected_organization_id=expected_organization_id,
+ )
+
+
+def serialize_trino_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_TRINO_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
diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.py
index 0a38fd54f857..b642fcf02929 100644
--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py
@@ -55,6 +55,13 @@ from products.data_warehouse.backend.presentation.managed_warehouse_monitoring i
serialize_monitoring_series,
serialize_monitoring_snapshot,
)
+from products.data_warehouse.backend.presentation.managed_warehouse_trino_monitoring import (
+ ManagedWarehouseTrinoMonitoringSeriesQuerySerializer,
+ ManagedWarehouseTrinoMonitoringSnapshotResponseSerializer,
+ WarehouseTrinoStatusState,
+ serialize_trino_monitoring_series,
+ serialize_trino_monitoring_snapshot,
+)
from products.data_warehouse.backend.presentation.pipeline_stats import (
CompletedActivityQuerySerializer,
DataHealthIssuesResponseSerializer,
@@ -91,7 +98,7 @@ _MONITORING_ERROR_RESPONSES = {
),
status.HTTP_404_NOT_FOUND: OpenApiResponse(
response=ManagedWarehouseMonitoringErrorResponseSerializer,
- description="The organization does not have a managed warehouse.",
+ description="The organization does not have a managed warehouse, or this endpoint does not match its query engine.",
),
status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(
response=ManagedWarehouseMonitoringErrorResponseSerializer,
@@ -108,6 +115,23 @@ _MONITORING_ERROR_RESPONSES = {
}
+_TRINO_VARIANT_MONITORING_ERROR = (
+ "This warehouse runs on Trino. Use the Trino monitoring endpoints "
+ "(managed-warehouse-trino-monitoring and managed-warehouse-trino-monitoring-timeseries) instead. "
+ "The matching MCP tools are managed-warehouse-trino-monitoring-get and managed-warehouse-trino-metric-history-get."
+)
+
+_DUCKDB_VARIANT_MONITORING_ERROR = (
+ "This warehouse doesn't run on Trino. Use the managed warehouse monitoring endpoints "
+ "(managed-warehouse-monitoring and managed-warehouse-monitoring-timeseries) instead. "
+ "The matching MCP tools are managed-warehouse-monitoring-get and managed-warehouse-metric-history-get."
+)
+
+
+def _wrong_monitoring_variant_response(message: str) -> Response:
+ return Response({"error": message}, status=status.HTTP_404_NOT_FOUND)
+
+
def _managed_warehouse_monitoring_error_response(upstream_response: Response) -> Response:
upstream_status = upstream_response.status_code
if upstream_status == status.HTTP_403_FORBIDDEN:
@@ -250,6 +274,11 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
def _readable_team_schema_ids(self) -> list:
return list(self._readable_schema_ids(list(self._team_schemas())))
+ def _managed_warehouse_disabled_response(self) -> Response | None:
+ if managed_warehouse.is_enabled(self.team.organization_id):
+ return None
+ return Response({"error": "This feature is not enabled"}, status=status.HTTP_403_FORBIDDEN)
+
def _require_organization_admin(self, request: Request, action: str) -> Response | None:
if not request.user.is_authenticated:
return Response(
@@ -1308,7 +1337,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"WarehouseConnection",
fields={
"host": serializers.CharField(
- help_text="Connection host — the warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com"
+ help_text="Postgres connection host. The warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com"
),
"port": serializers.IntegerField(help_text="Postgres wire-protocol port"),
"database": serializers.CharField(help_text="Database to connect to — always 'ducklake'"),
@@ -1316,6 +1345,36 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
},
required=False,
allow_null=True,
+ help_text="Postgres connection target. Null for organizations on the Trino Data ops variant.",
+ ),
+ "trino": inline_serializer(
+ "WarehouseTrinoStatus",
+ fields={
+ "state": serializers.ChoiceField(
+ choices=WarehouseTrinoStatusState.choices,
+ help_text="Trino lifecycle state for the organization. `unavailable` means the "
+ "state could not be read.",
+ ),
+ "ready_at": serializers.DateTimeField(
+ allow_null=True, help_text="When Trino became ready for the organization"
+ ),
+ "connection": inline_serializer(
+ "WarehouseTrinoConnection",
+ fields={
+ "host": serializers.CharField(help_text="Trino host to connect to over HTTPS"),
+ "port": serializers.IntegerField(help_text="Trino HTTPS port"),
+ "catalog": serializers.CharField(
+ help_text="Trino catalog that holds the organization's data"
+ ),
+ "username": serializers.CharField(help_text="Root username"),
+ },
+ allow_null=True,
+ help_text="Trino connection target. Null until Trino is ready and reachable.",
+ ),
+ },
+ required=False,
+ allow_null=True,
+ help_text="Trino status for organizations on the Trino Data ops variant, once the warehouse is ready. Null otherwise.",
),
"has_backfill": serializers.BooleanField(
help_text="Whether this project already has a warehouse backfill configured. When true, its "
@@ -1351,6 +1410,17 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
# connection for enrolled projects. Best-effort scheduling coalesces repeated scene loads.
if resp.data.get("state") == "ready" and onboarding_state["team_onboarded"]:
managed_warehouse.ensure_direct_connection_tables(self.team_id, self.team.organization_id)
+ if managed_warehouse.data_ops_variant(self.team.organization_id) == "trino":
+ # Users of a Trino organization connect only through Trino.
+ resp.data["connection"] = None
+ # Trino's state only matters once the warehouse is ready, and the scene polls while it is not.
+ resp.data["trino"] = (
+ managed_warehouse.trino_status_for(self.team.organization_id)
+ if resp.data.get("state") == "ready"
+ else None
+ )
+ else:
+ resp.data["trino"] = None
return resp
@extend_schema(
@@ -1374,6 +1444,9 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
def managed_warehouse_monitoring(self, request: Request, **kwargs) -> Response:
organization_id = str(self.team.organization_id)
+ # Workers still run a Trino organization's internal writes. That data is not for its users.
+ if managed_warehouse.data_ops_variant(organization_id) == "trino":
+ return _wrong_monitoring_variant_response(_TRINO_VARIANT_MONITORING_ERROR)
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)
@@ -1413,6 +1486,8 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
def managed_warehouse_monitoring_timeseries(self, request: Request, **kwargs) -> Response:
organization_id = str(self.team.organization_id)
+ if managed_warehouse.data_ops_variant(organization_id) == "trino":
+ return _wrong_monitoring_variant_response(_TRINO_VARIANT_MONITORING_ERROR)
metric = cast(
managed_warehouse.ManagedWarehouseMonitoringMetric,
request.validated_query_data["metric"],
@@ -1440,6 +1515,97 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
return _managed_warehouse_monitoring_error_response(Response(status=status.HTTP_502_BAD_GATEWAY))
return Response(data)
+ @extend_schema(
+ responses={
+ status.HTTP_200_OK: OpenApiResponse(
+ response=ManagedWarehouseTrinoMonitoringSnapshotResponseSerializer,
+ description="Current organization-scoped Trino query activity.",
+ ),
+ **_MONITORING_ERROR_RESPONSES,
+ },
+ summary="Get managed warehouse Trino monitoring snapshot",
+ description="Get tenant-safe live Trino query totals, limits, and in-flight queries for the current organization.",
+ )
+ # nosemgrep: api-path-underscore -- sits under the shipped data_warehouse prefix, a rename breaks clients
+ @action(
+ methods=["GET"],
+ detail=False,
+ url_path="managed-warehouse-trino-monitoring",
+ required_scopes=["warehouse_view:read"],
+ requires_resource_level_access=True,
+ )
+ def managed_warehouse_trino_monitoring(self, request: Request, **kwargs) -> Response:
+ organization_id = str(self.team.organization_id)
+ if managed_warehouse.data_ops_variant(organization_id) == "duckdb":
+ return _wrong_monitoring_variant_response(_DUCKDB_VARIANT_MONITORING_ERROR)
+ upstream_response = managed_warehouse.trino_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_trino_monitoring_snapshot(
+ upstream_response.data,
+ expected_organization_id=organization_id,
+ )
+ except ManagedWarehouseMonitoringUpstreamError:
+ logger.warning(
+ "Managed warehouse Trino 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=ManagedWarehouseTrinoMonitoringSeriesQuerySerializer,
+ responses={
+ status.HTTP_200_OK: OpenApiResponse(
+ response=ManagedWarehouseMonitoringSeriesResponseSerializer,
+ description="One organization-scoped Trino monitoring metric over time.",
+ ),
+ **_MONITORING_ERROR_RESPONSES,
+ },
+ summary="Get managed warehouse Trino monitoring time series",
+ description="Get one allow-listed Trino monitoring metric for the current organization and trailing time window.",
+ )
+ # nosemgrep: api-path-underscore -- sits under the shipped data_warehouse prefix, a rename breaks clients
+ @action(
+ methods=["GET"],
+ detail=False,
+ url_path="managed-warehouse-trino-monitoring-timeseries",
+ required_scopes=["warehouse_view:read"],
+ requires_resource_level_access=True,
+ )
+ def managed_warehouse_trino_monitoring_timeseries(self, request: Request, **kwargs) -> Response:
+ organization_id = str(self.team.organization_id)
+ if managed_warehouse.data_ops_variant(organization_id) == "duckdb":
+ return _wrong_monitoring_variant_response(_DUCKDB_VARIANT_MONITORING_ERROR)
+ metric = cast(
+ managed_warehouse.ManagedWarehouseTrinoMonitoringMetric,
+ request.validated_query_data["metric"],
+ )
+ window = cast(
+ managed_warehouse.ManagedWarehouseMonitoringWindow,
+ request.validated_query_data["window"],
+ )
+ upstream_response = managed_warehouse.trino_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_trino_monitoring_series(
+ upstream_response.data,
+ expected_organization_id=organization_id,
+ expected_metric=metric,
+ )
+ except ManagedWarehouseMonitoringUpstreamError:
+ logger.warning(
+ "Managed warehouse Trino 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})
# nosemgrep: api-path-underscore -- shipped public API path, a rename breaks clients
@action(
@@ -1450,6 +1616,8 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
def managed_warehouse_data_status(self, request: Request, **kwargs) -> Response:
"""Get events, persons, and imported source readiness for the managed warehouse."""
+ if (disabled := self._managed_warehouse_disabled_response()) is not None:
+ return disabled
return Response(get_managed_warehouse_data_status(self.team_id, user_access_control=self.user_access_control))
@validated_request(
@@ -1467,6 +1635,8 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
required_scopes=["warehouse_view:read", "external_data_source:read"],
)
def managed_warehouse_source_schemas(self, request: Request, **kwargs) -> Response:
+ if (disabled := self._managed_warehouse_disabled_response()) is not None:
+ return disabled
source_id = str(request.validated_query_data["source_id"])
return Response(
{
diff --git a/products/data_warehouse/backend/tests/api/test_data_warehouse.py b/products/data_warehouse/backend/tests/api/test_data_warehouse.py
index 6f427907a876..947724576084 100644
--- a/products/data_warehouse/backend/tests/api/test_data_warehouse.py
+++ b/products/data_warehouse/backend/tests/api/test_data_warehouse.py
@@ -24,6 +24,21 @@ from products.warehouse_sources.backend.facade.models import (
class TestDataWarehouseAPI(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("data_status", "managed-warehouse-data-status/"),
+ ("source_schemas", "managed-warehouse-source-schemas/?source_id=00000000-0000-0000-0000-000000000000"),
+ ]
+ )
+ def test_overview_endpoints_require_a_managed_warehouse_flag(self, _name: str, path: str) -> None:
+ with patch(
+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.is_enabled",
+ return_value=False,
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/data_warehouse/{path}")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
@parameterized.expand(
[
("onboarded", True, True),
@@ -58,6 +73,63 @@ class TestDataWarehouseAPI(APIBaseTest):
else:
ensure_tables.assert_not_called()
+ @parameterized.expand([("trino", "trino"), ("duckdb", "duckdb")])
+ def test_warehouse_status_presents_the_connection_for_the_variant(self, _name: str, variant: str) -> None:
+ views = "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse"
+ pgwire = {"host": "my-warehouse.dw.example.com", "port": 5432, "database": "ducklake", "username": "root"}
+ trino_status = {
+ "state": "ready",
+ "ready_at": "2026-09-01T12:00:00Z",
+ "connection": {
+ "host": "my-warehouse.dw.example.com",
+ "port": 443,
+ "catalog": "org_my_warehouse",
+ "username": "root",
+ },
+ }
+ with (
+ patch(f"{views}.status_for", return_value=Response({"state": "ready", "connection": pgwire}, status=200)),
+ patch(f"{views}.team_backfill_state", return_value={"has_backfill": True, "table_suffix": "prod"}),
+ patch(f"{views}.team_onboarding_state", return_value={"team_onboarded": True, "schema_name": "prod"}),
+ patch(f"{views}.ensure_direct_connection_tables"),
+ patch(f"{views}.data_ops_variant", return_value=variant),
+ patch(f"{views}.trino_status_for", return_value=trino_status) as mock_trino_status,
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/data_warehouse/warehouse_status/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ if variant == "trino":
+ self.assertIsNone(body["connection"])
+ self.assertEqual(body["trino"], trino_status)
+ mock_trino_status.assert_called_once_with(self.organization.id)
+ else:
+ self.assertEqual(body["connection"], pgwire)
+ self.assertIsNone(body["trino"])
+ mock_trino_status.assert_not_called()
+
+ def test_warehouse_status_skips_the_trino_read_until_the_warehouse_is_ready(self) -> None:
+ views = "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse"
+ pgwire = {"host": "my-warehouse.dw.example.com", "port": 5432, "database": "ducklake", "username": "root"}
+ with (
+ patch(
+ f"{views}.status_for",
+ return_value=Response({"state": "provisioning", "connection": pgwire}, status=200),
+ ),
+ patch(f"{views}.team_backfill_state", return_value={"has_backfill": False, "table_suffix": None}),
+ patch(f"{views}.team_onboarding_state", return_value={"team_onboarded": False, "schema_name": None}),
+ patch(f"{views}.ensure_direct_connection_tables"),
+ patch(f"{views}.data_ops_variant", return_value="trino"),
+ patch(f"{views}.trino_status_for") as mock_trino_status,
+ ):
+ response = self.client.get(f"/api/projects/{self.team.id}/data_warehouse/warehouse_status/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.json()
+ self.assertIsNone(body["connection"])
+ self.assertIsNone(body["trino"])
+ mock_trino_status.assert_not_called()
+
@patch("products.data_warehouse.backend.presentation.views.data_warehouse.execute_hogql_query")
def test_property_values_returns_results_with_cache_control(self, mock_execute_hogql_query):
table = DataWarehouseTable.objects.create(
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.py
index b82648eacfb1..72b732788ece 100644
--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse_monitoring.py
+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse_monitoring.py
@@ -17,6 +17,8 @@ from products.data_warehouse.backend.presentation.managed_warehouse_monitoring i
)
from products.warehouse_sources.backend.facade.testing import WarehouseAccessControlTestMixin
+_VIEWS = "products.data_warehouse.backend.presentation.views.data_warehouse"
+
def _snapshot(organization_id: object) -> dict[str, object]:
return {
@@ -110,6 +112,22 @@ class TestManagedWarehouseMonitoringAPI(APIBaseTest):
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}"
+ @parameterized.expand([("snapshot",), ("series",)])
+ def test_duckdb_monitoring_returns_404_for_a_trino_organization(self, endpoint: str) -> None:
+ url = self._snapshot_url() if endpoint == "snapshot" else self._series_url()
+ with (
+ patch(f"{_VIEWS}.managed_warehouse.data_ops_variant", return_value="trino"),
+ patch(f"{_VIEWS}.managed_warehouse.monitoring_snapshot_for") as mock_snapshot,
+ patch(f"{_VIEWS}.managed_warehouse.monitoring_series_for") as mock_series,
+ ):
+ response = self.client.get(url)
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert "Trino" in response.json()["error"]
+ assert "managed-warehouse-trino-monitoring-get" in response.json()["error"]
+ mock_snapshot.assert_not_called()
+ mock_series.assert_not_called()
+
@patch(
"products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.monitoring_snapshot_for"
)
@@ -313,6 +331,16 @@ class TestManagedWarehouseMonitoringAccessControl(WarehouseAccessControlTestMixi
"monitoring_series_for",
"managed-warehouse-monitoring-timeseries/?metric=query_rate&window=6h",
),
+ (
+ "trino_snapshot",
+ "trino_monitoring_snapshot_for",
+ "managed-warehouse-trino-monitoring/",
+ ),
+ (
+ "trino_timeseries",
+ "trino_monitoring_series_for",
+ "managed-warehouse-trino-monitoring-timeseries/?metric=query_rate&window=6h",
+ ),
]
)
def test_org_wide_monitoring_requires_resource_level_warehouse_access(
@@ -364,3 +392,19 @@ class TestManagedWarehouseMonitoringPersonalAPIKey(APIBaseTest):
assert allowed_response.status_code == status.HTTP_200_OK
assert denied_response.status_code == status.HTTP_403_FORBIDDEN
assert mock_snapshot.call_count == 1
+
+ @patch(
+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.trino_monitoring_snapshot_for"
+ )
+ def test_trino_snapshot_requires_the_warehouse_view_read_scope(self, mock_snapshot: MagicMock) -> None:
+ mock_snapshot.return_value = Response({"error": "unused"}, status=status.HTTP_502_BAD_GATEWAY)
+ url = f"/api/projects/{self.team.id}/data_warehouse/managed-warehouse-trino-monitoring/"
+ 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.client.get(url, headers={"authorization": f"Bearer {allowed_token}"})
+ denied_response = self.client.get(url, headers={"authorization": f"Bearer {denied_token}"})
+
+ assert allowed_response.status_code == status.HTTP_502_BAD_GATEWAY
+ assert denied_response.status_code == status.HTTP_403_FORBIDDEN
+ assert mock_snapshot.call_count == 1
diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse_trino_monitoring.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse_trino_monitoring.py
new file mode 100644
index 000000000000..bf7030a10735
--- /dev/null
+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse_trino_monitoring.py
@@ -0,0 +1,177 @@
+import json
+from typing import cast
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.response import Response
+
+_VIEWS = "products.data_warehouse.backend.presentation.views.data_warehouse"
+
+
+def _trino_snapshot(organization_id: object) -> dict[str, object]:
+ return {
+ "schema_version": 1,
+ "org_id": str(organization_id),
+ "as_of": "2026-09-30T17:00:00Z",
+ "trino": {"state": "ready", "ready_at": "2026-09-01T12:00:00Z", "failed_at": None},
+ "available": True,
+ "limits": {"max_running_queries": 10, "max_queued_queries": 50},
+ "totals": {
+ "in_flight": 2,
+ "running": 1,
+ "queued": 1,
+ "blocked": 0,
+ "longest_running_ms": 9000,
+ "physical_input_bytes": 150,
+ },
+ "queries": [
+ {
+ "query_id": "20260930_170000_00001_abcde",
+ "state": "running",
+ "user": "analyst",
+ "source": "dbt",
+ "query": "SELECT * FROM t WHERE email = ?",
+ "created_at": "2026-09-30T16:59:51Z",
+ "elapsed_ms": 9000,
+ "queued_ms": 20,
+ "cpu_ms": 900,
+ "physical_input_bytes": 150,
+ "peak_memory_bytes": 64,
+ "processed_input_rows": 7,
+ "progress_percentage": 50.0,
+ "blocked": False,
+ }
+ ],
+ "queries_truncated": False,
+ }
+
+
+def _trino_series(organization_id: object, metric: str = "queries_in_flight") -> dict[str, object]:
+ return {
+ "schema_version": 1,
+ "org_id": str(organization_id),
+ "metric": metric,
+ "unit": "queries",
+ "start": "2026-09-29T17:00:00Z",
+ "end": "2026-09-30T17:00:00Z",
+ "step_seconds": 60,
+ "series": [{"labels": {"state": "running"}, "points": [{"timestamp": "2026-09-30T16:59:00Z", "value": 3}]}],
+ }
+
+
+class TestManagedWarehouseTrinoMonitoringAPI(APIBaseTest):
+ def _snapshot_url(self) -> str:
+ return f"/api/projects/{self.team.id}/data_warehouse/managed-warehouse-trino-monitoring/"
+
+ def _series_url(self, query: str = "metric=queries_in_flight&window=6h") -> str:
+ return f"/api/projects/{self.team.id}/data_warehouse/managed-warehouse-trino-monitoring-timeseries/?{query}"
+
+ @patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_snapshot_for")
+ def test_snapshot_derives_the_organization_and_removes_unknown_fields(self, mock_snapshot: MagicMock) -> None:
+ upstream = _trino_snapshot(self.organization.id)
+ upstream["cell"] = {"id": "sensitive-cell"}
+ cast(dict[str, object], upstream["trino"])["status_message"] = "sensitive reconcile detail"
+ query = cast(dict[str, object], cast(list[object], upstream["queries"])[0])
+ query["principal"] = "sensitive-principal"
+ query["resource_group"] = "root.tenants.growth.sensitive"
+ 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",
+ "trino",
+ "available",
+ "limits",
+ "totals",
+ "queries",
+ "queries_truncated",
+ }
+ assert body["queries"][0]["query"] == "SELECT * FROM t WHERE email = ?"
+ serialized = json.dumps(body)
+ for forbidden in ("sensitive", "principal", "resource_group", "status_message", "cell"):
+ assert forbidden not in serialized
+
+ @patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_snapshot_for")
+ def test_snapshot_accepts_a_query_without_a_start_time_or_progress(self, mock_snapshot: MagicMock) -> None:
+ upstream = _trino_snapshot(self.organization.id)
+ query = cast(dict[str, object], cast(list[object], upstream["queries"])[0])
+ query["created_at"] = None
+ query["progress_percentage"] = None
+ query["user"] = ""
+ query["source"] = ""
+ 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()["queries"][0]["created_at"] is None
+
+ @patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_snapshot_for")
+ def test_snapshot_rejects_an_upstream_organization_mismatch(self, mock_snapshot: MagicMock) -> None:
+ mock_snapshot.return_value = Response(_trino_snapshot("different-organization"), 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()
+
+ @parameterized.expand([("snapshot",), ("series",)])
+ def test_trino_monitoring_returns_404_for_a_duckdb_organization(self, endpoint: str) -> None:
+ url = self._snapshot_url() if endpoint == "snapshot" else self._series_url()
+ with (
+ patch(f"{_VIEWS}.managed_warehouse.data_ops_variant", return_value="duckdb"),
+ patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_snapshot_for") as mock_snapshot,
+ patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_series_for") as mock_series,
+ ):
+ response = self.client.get(url)
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert "managed-warehouse-monitoring" in response.json()["error"]
+ mock_snapshot.assert_not_called()
+ mock_series.assert_not_called()
+
+ @patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_series_for")
+ def test_timeseries_validates_and_forwards_the_allow_listed_query(self, mock_series: MagicMock) -> None:
+ mock_series.return_value = Response(_trino_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), "queries_in_flight", "6h")
+ assert response.json()["series"][0]["labels"] == {"state": "running"}
+
+ @parameterized.expand(
+ [
+ ("duckdb_only_metric", "metric=sessions_active&window=1h"),
+ ("worker_metric", "metric=acquire_p95&window=1h"),
+ ("unknown_window", "metric=query_rate&window=2h"),
+ ]
+ )
+ @patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_series_for")
+ def test_timeseries_rejects_invalid_query_before_calling_upstream(
+ self, _name: str, query: str, mock_series: MagicMock
+ ) -> None:
+ response = self.client.get(self._series_url(query))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_series.assert_not_called()
+
+ @patch(f"{_VIEWS}.managed_warehouse.trino_monitoring_series_for")
+ def test_timeseries_rejects_an_unexpected_upstream_label(self, mock_series: MagicMock) -> None:
+ upstream = _trino_series(self.organization.id)
+ cast(list[dict[str, object]], upstream["series"])[0]["labels"] = {"state": "running", "pod": "private-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 "private-pod" not in response.content.decode()
diff --git a/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py b/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py
index 8e76d2d673f4..25b5100d171c 100644
--- a/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py
+++ b/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py
@@ -286,13 +286,17 @@ class TestDataWarehouseViewSetAccessControl(WarehouseAccessControlTestMixin):
)
self.client.force_login(self.viewer_user)
- summary_response = self.client.get(self._path("managed-warehouse-data-status/"))
- detail_response = self.client.get(
- self._path(f"managed-warehouse-source-schemas/?source_id={blocked_source.id}")
- )
- allowed_detail_response = self.client.get(
- self._path(f"managed-warehouse-source-schemas/?source_id={allowed_source.id}")
- )
+ with patch(
+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.is_enabled",
+ return_value=True,
+ ):
+ summary_response = self.client.get(self._path("managed-warehouse-data-status/"))
+ detail_response = self.client.get(
+ self._path(f"managed-warehouse-source-schemas/?source_id={blocked_source.id}")
+ )
+ allowed_detail_response = self.client.get(
+ self._path(f"managed-warehouse-source-schemas/?source_id={allowed_source.id}")
+ )
self.assertEqual(summary_response.status_code, status.HTTP_200_OK)
self.assertEqual(
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 26581e4846b6..dcc370987707 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -712,6 +712,148 @@ export interface ManagedWarehouseSourceSchemasResponseApi {
schemas: ManagedWarehouseSourceTableStatusApi[]
}
+export interface ManagedWarehouseTrinoMonitoringStateApi {
+ /** Trino lifecycle state for the organization: not_enabled, pending, provisioning, ready, or failed. */
+ state: string
+ /**
+ * UTC timestamp when Trino became ready for the organization, or null.
+ * @nullable
+ */
+ ready_at: string | null
+ /**
+ * UTC timestamp when Trino setup last failed for the organization, or null.
+ * @nullable
+ */
+ failed_at: string | null
+}
+
+export interface ManagedWarehouseTrinoMonitoringLimitsApi {
+ /**
+ * Maximum number of the organization's queries that run at the same time. Zero when Trino is not enabled.
+ * @minimum 0
+ */
+ max_running_queries: number
+ /**
+ * Maximum number of the organization's queries that can wait in the queue. Zero when Trino is not enabled.
+ * @minimum 0
+ */
+ max_queued_queries: number
+}
+
+export interface ManagedWarehouseTrinoMonitoringTotalsApi {
+ /**
+ * Queries submitted and not yet finished. Equals running plus queued.
+ * @minimum 0
+ */
+ in_flight: number
+ /**
+ * In-flight queries past the queue. This is the count the concurrency limit applies to.
+ * @minimum 0
+ */
+ running: number
+ /**
+ * Queries waiting for a running slot.
+ * @minimum 0
+ */
+ queued: number
+ /**
+ * Running queries whose work is all waiting on data or metadata. A subset of running.
+ * @minimum 0
+ */
+ blocked: number
+ /**
+ * Elapsed milliseconds of the longest in-flight query, or zero when there is none.
+ * @minimum 0
+ */
+ longest_running_ms: number
+ /**
+ * Bytes read so far by all in-flight queries.
+ * @minimum 0
+ */
+ physical_input_bytes: number
+}
+
+export interface ManagedWarehouseTrinoMonitoringQueryApi {
+ /** Trino query identifier. */
+ query_id: string
+ /** Trino query state in lower case, such as queued, planning, starting, running, or finishing. */
+ state: string
+ /** Warehouse username that ran the query. Blank when it cannot be resolved. */
+ user: string
+ /** Client-reported source of the query, such as a tool name. Blank when not set. */
+ source: string
+ /** SQL text with literal values replaced by ? and comments removed. A placeholder when unavailable. */
+ query: string
+ /**
+ * UTC timestamp when the query was submitted, or null when Trino does not report it.
+ * @nullable
+ */
+ created_at: string | null
+ /**
+ * Milliseconds since the query was submitted.
+ * @minimum 0
+ */
+ elapsed_ms: number
+ /**
+ * Milliseconds the query spent queued.
+ * @minimum 0
+ */
+ queued_ms: number
+ /**
+ * CPU milliseconds the query has used.
+ * @minimum 0
+ */
+ cpu_ms: number
+ /**
+ * Bytes the query has read from storage.
+ * @minimum 0
+ */
+ physical_input_bytes: number
+ /**
+ * Peak memory the query has reserved, in bytes.
+ * @minimum 0
+ */
+ peak_memory_bytes: number
+ /**
+ * Rows the query has read.
+ * @minimum 0
+ */
+ processed_input_rows: number
+ /**
+ * Best-effort progress percentage, or null when Trino cannot estimate it.
+ * @minimum 0
+ * @nullable
+ */
+ progress_percentage: number | null
+ /** Whether all of the query's work is waiting on data or metadata. */
+ blocked: boolean
+}
+
+export interface ManagedWarehouseTrinoMonitoringSnapshotResponseApi {
+ /**
+ * Version of the Trino 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
+ /** Trino lifecycle details for the organization. */
+ trino: ManagedWarehouseTrinoMonitoringStateApi
+ /** Whether live query data could be read. When false, totals are zero and do not mean the warehouse is idle. */
+ available: boolean
+ /** Concurrency and queue limits. */
+ limits: ManagedWarehouseTrinoMonitoringLimitsApi
+ /** Current in-flight query totals. */
+ totals: ManagedWarehouseTrinoMonitoringTotalsApi
+ /** In-flight queries, longest-running first, capped at 200 rows. */
+ queries: ManagedWarehouseTrinoMonitoringQueryApi[]
+ /** Whether the query list was capped. Totals always cover every in-flight query. */
+ queries_truncated: boolean
+}
+
export interface OnboardWarehouseTeamRequestApi {
/** Schema name for this project's data in the organization's warehouse. Lowercase letters, numbers, and underscores only, max 63 characters. Must be unique within the organization and cannot be changed later. */
schema_name: string
@@ -803,7 +945,7 @@ export const WarehouseStatusResponseStateEnumApi = {
} as const
export interface WarehouseConnectionApi {
- /** Connection host — the warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com */
+ /** Postgres connection host. The warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com */
host: string
/** Postgres wire-protocol port */
port: number
@@ -813,6 +955,56 @@ export interface WarehouseConnectionApi {
username: string
}
+/**
+ * * `not_enabled` - not_enabled
+ * * `pending` - pending
+ * * `provisioning` - provisioning
+ * * `ready` - ready
+ * * `failed` - failed
+ * * `unavailable` - unavailable
+ */
+export type WarehouseTrinoStatusStateEnumApi =
+ (typeof WarehouseTrinoStatusStateEnumApi)[keyof typeof WarehouseTrinoStatusStateEnumApi]
+
+export const WarehouseTrinoStatusStateEnumApi = {
+ NotEnabled: 'not_enabled',
+ Pending: 'pending',
+ Provisioning: 'provisioning',
+ Ready: 'ready',
+ Failed: 'failed',
+ Unavailable: 'unavailable',
+} as const
+
+export interface WarehouseTrinoConnectionApi {
+ /** Trino host to connect to over HTTPS */
+ host: string
+ /** Trino HTTPS port */
+ port: number
+ /** Trino catalog that holds the organization's data */
+ catalog: string
+ /** Root username */
+ username: string
+}
+
+export interface WarehouseTrinoStatusApi {
+ /** Trino lifecycle state for the organization. `unavailable` means the state could not be read.
+ *
+ * * `not_enabled` - not_enabled
+ * * `pending` - pending
+ * * `provisioning` - provisioning
+ * * `ready` - ready
+ * * `failed` - failed
+ * * `unavailable` - unavailable */
+ state: WarehouseTrinoStatusStateEnumApi
+ /**
+ * When Trino became ready for the organization
+ * @nullable
+ */
+ ready_at: string | null
+ /** Trino connection target. Null until Trino is ready and reachable. */
+ connection: WarehouseTrinoConnectionApi | null
+}
+
export interface WarehouseStatusResponseApi {
/** duckgres org identifier (the PostHog organization id) */
org_id: string
@@ -845,7 +1037,10 @@ export interface WarehouseStatusResponseApi {
* @nullable
*/
failed_at: string | null
+ /** Postgres connection target. Null for organizations on the Trino Data ops variant. */
connection?: WarehouseConnectionApi | null
+ /** Trino status for organizations on the Trino Data ops variant, once the warehouse is ready. Null otherwise. */
+ trino?: WarehouseTrinoStatusApi | null
/** Whether this project already has a warehouse backfill configured. When true, its table name is fixed and the enable form should not be shown. */
has_backfill: boolean
/**
@@ -5477,6 +5672,61 @@ export type DataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {
source_id: string
}
+export type DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams = {
+ /**
+ * Allow-listed Trino metric to retrieve.
+ *
+ * * `queries_in_flight` - queries_in_flight
+ * * `query_rate` - query_rate
+ * * `error_ratio` - error_ratio
+ * * `duration_p50` - duration_p50
+ * * `duration_p95` - duration_p95
+ * * `queue_time_p95` - queue_time_p95
+ * * `scanned_bytes_rate` - scanned_bytes_rate
+ * * `cpu_seconds_rate` - cpu_seconds_rate
+ * * `storage_bytes` - storage_bytes
+ * @minLength 1
+ */
+ metric: DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric
+ /**
+ * Trailing time window to retrieve. Defaults to 24h.
+ *
+ * * `1h` - 1h
+ * * `6h` - 6h
+ * * `24h` - 24h
+ * * `7d` - 7d
+ * * `30d` - 30d
+ * @minLength 1
+ */
+ window?: DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow
+}
+
+export type DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric =
+ (typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric)[keyof typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric]
+
+export const DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric = {
+ QueriesInFlight: 'queries_in_flight',
+ QueryRate: 'query_rate',
+ ErrorRatio: 'error_ratio',
+ DurationP50: 'duration_p50',
+ DurationP95: 'duration_p95',
+ QueueTimeP95: 'queue_time_p95',
+ ScannedBytesRate: 'scanned_bytes_rate',
+ CpuSecondsRate: 'cpu_seconds_rate',
+ StorageBytes: 'storage_bytes',
+} as const
+
+export type DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow =
+ (typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow)[keyof typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow]
+
+export const DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow = {
+ '1h': '1h',
+ '6h': '6h',
+ '24h': '24h',
+ '7d': '7d',
+ '30d': '30d',
+} as const
+
export type DataWarehouseRunningActivityRetrieveParams = {
/**
* Only include runs created within this many days of now. Defaults to 30.
diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.ts
index b461ae049bbd..4b2d7c1a72c9 100644
--- a/products/data_warehouse/frontend/generated/api.ts
+++ b/products/data_warehouse/frontend/generated/api.ts
@@ -27,6 +27,7 @@ import type {
DataWarehouseManagedViewSetUpdateResponseApi,
DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams,
DataWarehouseManagedWarehouseSourceSchemasRetrieveParams,
+ DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams,
DataWarehouseRunningActivityRetrieveParams,
DataWarehouseSavedQueryApi,
DataWarehouseSavedQueryColumnAnnotationApi,
@@ -43,6 +44,7 @@ import type {
ManagedWarehouseMonitoringSeriesResponseApi,
ManagedWarehouseMonitoringSnapshotResponseApi,
ManagedWarehouseSourceSchemasResponseApi,
+ ManagedWarehouseTrinoMonitoringSnapshotResponseApi,
OnboardWarehouseTeamRequestApi,
OnboardWarehouseTeamResponseApi,
PaginatedDataModelingJobListApi,
@@ -558,6 +560,64 @@ export const dataWarehouseManagedWarehouseSourceSchemasRetrieve = async (
)
}
+export const getDataWarehouseManagedWarehouseTrinoMonitoringRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_warehouse/managed-warehouse-trino-monitoring/`
+}
+
+/**
+ * Get tenant-safe live Trino query totals, limits, and in-flight queries for the current organization.
+ * @summary Get managed warehouse Trino monitoring snapshot
+ */
+export const dataWarehouseManagedWarehouseTrinoMonitoringRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ManagedWarehouseTrinoMonitoringSnapshotResponseApi> => {
+ return apiMutator<ManagedWarehouseTrinoMonitoringSnapshotResponseApi>(
+ getDataWarehouseManagedWarehouseTrinoMonitoringRetrieveUrl(projectId),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveUrl = (
+ projectId: string,
+ params: DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams
+) => {
+ 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-trino-monitoring-timeseries/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_warehouse/managed-warehouse-trino-monitoring-timeseries/`
+}
+
+/**
+ * Get one allow-listed Trino monitoring metric for the current organization and trailing time window.
+ * @summary Get managed warehouse Trino monitoring time series
+ */
+export const dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve = async (
+ projectId: string,
+ params: DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams,
+ options?: RequestInit
+): Promise<ManagedWarehouseMonitoringSeriesResponseApi> => {
+ return apiMutator<ManagedWarehouseMonitoringSeriesResponseApi>(
+ getDataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getDataWarehouseOnboardTeamCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/data_warehouse/onboard-team/`
}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/DataWarehouseScene.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/DataWarehouseScene.tsx
index 3d3fdc130639..a3f72be48d11 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/DataWarehouseScene.tsx
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/DataWarehouseScene.tsx
@@ -1,10 +1,8 @@
import { useActions, useValues } from 'kea'
import { NotFound } from 'lib/components/NotFound'
-import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Spinner } from 'lib/lemon-ui/Spinner'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
@@ -12,10 +10,12 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
+import type { DataOpsVariant } from './dataOpsVariant'
import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'
import { MonitoringTab } from './tabs/MonitoringTab'
import { OverviewTab } from './tabs/OverviewTab'
import { SettingsTab } from './tabs/SettingsTab'
+import { TrinoMonitoringTab } from './tabs/TrinoMonitoringTab'
export const scene: SceneExport = {
component: DataWarehouseScene,
@@ -29,24 +29,23 @@ const TAB_LABELS: Record<DataWarehouseTab, string> = {
[DataWarehouseTab.SETTINGS]: 'Settings',
}
-function tabContent(tab: DataWarehouseTab): JSX.Element {
+function tabContent(tab: DataWarehouseTab, variant: DataOpsVariant): JSX.Element {
switch (tab) {
case DataWarehouseTab.OVERVIEW:
return <OverviewTab />
case DataWarehouseTab.MONITORING:
- return <MonitoringTab />
+ return variant === 'trino' ? <TrinoMonitoringTab /> : <MonitoringTab />
case DataWarehouseTab.SETTINGS:
return <SettingsTab />
}
}
export function DataWarehouseScene(): JSX.Element {
- const { featureFlags } = useValues(featureFlagLogic)
- const { availableTabs, activeTab, warehouseStatusResolved } = useValues(dataWarehouseSceneLogic)
+ const { availableTabs, activeTab, dataOpsVariant, warehouseStatusResolved } = useValues(dataWarehouseSceneLogic)
const { setActiveTab } = useActions(dataWarehouseSceneLogic)
- // Nothing to show without the scene flag, or when no tab's feature flag is enabled.
- if (!featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE] || !activeTab) {
+ // Nothing to show without either scene flag, or when no tab's feature flag is enabled.
+ if (!dataOpsVariant || !activeTab) {
return <NotFound object="Data warehouse" />
}
@@ -74,11 +73,11 @@ export function DataWarehouseScene(): JSX.Element {
tabs={availableTabs.map((tab) => ({
key: tab,
label: TAB_LABELS[tab],
- content: tabContent(tab),
+ content: tabContent(tab, dataOpsVariant),
}))}
/>
) : (
- tabContent(activeTab)
+ tabContent(activeTab, dataOpsVariant)
)}
</SceneContent>
)
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/dataOpsVariant.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/dataOpsVariant.ts
new file mode 100644
index 000000000000..ceec7c4ba169
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/dataOpsVariant.ts
@@ -0,0 +1,16 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+export type DataOpsVariant = 'trino' | 'duckdb'
+
+// Mirrors data_ops_variant in products/managed_warehouse/backend/presentation/views.py.
+// The backend enforces the same rule, so a change here needs the same change there.
+export function dataOpsVariantFromFlags(featureFlags: FeatureFlagsSet): DataOpsVariant | null {
+ if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]) {
+ return 'trino'
+ }
+ if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {
+ return 'duckdb'
+ }
+ return null
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts
index a2136d40b399..e0afdd1a11a1 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts
@@ -13,7 +13,7 @@ import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneL
describe('dataWarehouseSceneLogic', () => {
let logic: ReturnType<typeof dataWarehouseSceneLogic.build>
let flagsLogic: ReturnType<typeof featureFlagLogic.build>
- let warehouseStatusResponse: [number, Record<string, string>]
+ let warehouseStatusResponse: [number, Record<string, unknown>]
const mountScene = (): void => {
logic = dataWarehouseSceneLogic()
@@ -67,6 +67,55 @@ describe('dataWarehouseSceneLogic', () => {
expect(logic.values.activeTab).toBe(expectedTabs[0])
})
+ const useOnlyTheTrinoFlag = (): void => {
+ flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO], {
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]: true,
+ })
+ }
+
+ it('gives the DuckDB variant on the existing flag', async () => {
+ mountScene()
+ await waitForWarehouseStatus()
+
+ expect(logic.values.dataOpsVariant).toBe('duckdb')
+ })
+
+ it('prefers the Trino variant when both flags are on', async () => {
+ flagsLogic.actions.setFeatureFlags(
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE, FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO],
+ { [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: true, [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]: true }
+ )
+ mountScene()
+ await waitForWarehouseStatus()
+
+ expect(logic.values.dataOpsVariant).toBe('trino')
+ })
+
+ // A Trino organization has nothing to query until Trino itself is ready, so the warehouse
+ // being ready is not enough to show Overview and Monitoring.
+ it.each([
+ { name: 'Trino ready', trinoState: 'ready', expectsDataTabs: true },
+ { name: 'Trino provisioning', trinoState: 'provisioning', expectsDataTabs: false },
+ { name: 'Trino not enabled', trinoState: 'not_enabled', expectsDataTabs: false },
+ { name: 'Trino failed', trinoState: 'failed', expectsDataTabs: false },
+ { name: 'Trino status unavailable', trinoState: 'unavailable', expectsDataTabs: false },
+ ])('Trino variant on the Trino flag alone: $name', async ({ trinoState, expectsDataTabs }) => {
+ useOnlyTheTrinoFlag()
+ warehouseStatusResponse = [
+ 200,
+ { state: 'ready', trino: { state: trinoState, ready_at: null, connection: null } },
+ ]
+ mountScene()
+ await waitForWarehouseStatus()
+
+ expect(logic.values.dataOpsVariant).toBe('trino')
+ expect(logic.values.availableTabs).toEqual(
+ expectsDataTabs
+ ? [DataWarehouseTab.OVERVIEW, DataWarehouseTab.MONITORING, DataWarehouseTab.SETTINGS]
+ : [DataWarehouseTab.SETTINGS]
+ )
+ })
+
it('leaves the tab set unresolved until the warehouse status lands', () => {
warehouseStatusResponse = [200, { state: 'ready' }]
mountScene()
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.ts
index fd7d93728646..6d86add1b972 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.ts
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.ts
@@ -1,7 +1,6 @@
import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
-import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'
@@ -9,6 +8,8 @@ import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import type { WarehouseStatusResponseApi } from '../../generated/api.schemas'
+import { dataOpsVariantFromFlags } from './dataOpsVariant'
+import type { DataOpsVariant } from './dataOpsVariant'
import { warehouseProvisioningLogic } from './tabs/warehouseProvisioningLogic'
export enum DataWarehouseTab {
@@ -27,6 +28,7 @@ export interface dataWarehouseSceneLogicValues {
warehouseStatus: WarehouseStatusResponseApi | null // warehouseProvisioningLogic
activeTab: DataWarehouseTab | null
availableTabs: DataWarehouseTab[]
+ dataOpsVariant: DataOpsVariant | null
selectedTab: DataWarehouseTab | null
sidePanelContext: SidePanelSceneContext
warehouseReady: boolean
@@ -57,8 +59,12 @@ export interface dataWarehouseSceneLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataWarehouseSceneLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- warehouseReady: (warehouseStatus: WarehouseStatusResponseApi | null) => boolean
- availableTabs: (featureFlags: FeatureFlagsSet, warehouseReady: boolean) => DataWarehouseTab[]
+ dataOpsVariant: (featureFlags: FeatureFlagsSet) => DataOpsVariant | null
+ warehouseReady: (
+ warehouseStatus: WarehouseStatusResponseApi | null,
+ dataOpsVariant: DataOpsVariant | null
+ ) => boolean
+ availableTabs: (dataOpsVariant: DataOpsVariant | null, warehouseReady: boolean) => DataWarehouseTab[]
activeTab: (selectedTab: DataWarehouseTab | null, availableTabs: DataWarehouseTab[]) => DataWarehouseTab | null
}
}
@@ -100,28 +106,28 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([
],
}),
selectors({
+ dataOpsVariant: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): DataOpsVariant | null => dataOpsVariantFromFlags(featureFlags),
+ ],
// A warehouse that isn't serving yet has nothing to report on, so Overview stays hidden
- // until it's ready and the scene shows the setup form on its own.
+ // until it's ready and the scene shows the setup form on its own. Users of a Trino
+ // organization query through Trino, so for them Trino has to be ready too.
warehouseReady: [
- (s) => [s.warehouseStatus],
- (
- warehouseStatus:
- | null
- | import('products/data_warehouse/frontend/generated/api.schemas').WarehouseStatusResponseApi
- ): boolean => warehouseStatus?.state === 'ready',
+ (s) => [s.warehouseStatus, s.dataOpsVariant],
+ (warehouseStatus: WarehouseStatusResponseApi | null, dataOpsVariant: DataOpsVariant | null): boolean =>
+ warehouseStatus?.state === 'ready' &&
+ (dataOpsVariant !== 'trino' || warehouseStatus.trino?.state === 'ready'),
],
availableTabs: [
- (s) => [s.featureFlags, s.warehouseReady],
- (
- featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,
- warehouseReady: boolean
- ): DataWarehouseTab[] => {
+ (s) => [s.dataOpsVariant, s.warehouseReady],
+ (dataOpsVariant: DataOpsVariant | null, warehouseReady: boolean): DataWarehouseTab[] => {
const tabs: DataWarehouseTab[] = []
- if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE] && warehouseReady) {
+ if (dataOpsVariant && warehouseReady) {
tabs.push(DataWarehouseTab.OVERVIEW)
tabs.push(DataWarehouseTab.MONITORING)
}
- if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {
+ if (dataOpsVariant) {
tabs.push(DataWarehouseTab.SETTINGS)
}
return tabs
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringChart.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringChart.tsx
new file mode 100644
index 000000000000..0412f7913d61
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringChart.tsx
@@ -0,0 +1,61 @@
+import { useMemo } from 'react'
+
+import { TimeSeriesLineChart } from '@posthog/quill-charts'
+import type { TimeSeriesLineChartConfig } from '@posthog/quill-charts'
+
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+
+import type { ManagedWarehouseMonitoringSeriesResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { buildMonitoringChartData } from './monitoringChartData'
+import type { MonitoringChartMetricConfig } from './monitoringChartData'
+
+export 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' },
+ yAxis,
+ legend: { show: data.series.length > 1, interactive: true, position: 'bottom' },
+ tooltip: { placement: 'cursor', sortedByValue: true, valueFormatter },
+ }),
+ [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>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringMetricCard.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringMetricCard.tsx
new file mode 100644
index 000000000000..babf4fe21062
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringMetricCard.tsx
@@ -0,0 +1,26 @@
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+
+export 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>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringSection.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringSection.tsx
new file mode 100644
index 000000000000..7c842b4ed218
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringSection.tsx
@@ -0,0 +1,21 @@
+import type { ReactNode } from 'react'
+
+export 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>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringTab.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringTab.tsx
index 3f2a8e264009..74a02e64a72b 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringTab.tsx
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/MonitoringTab.tsx
@@ -1,18 +1,12 @@
import { useActions, useValues } from 'kea'
-import { memo, useMemo } from 'react'
-import type { ReactNode } from 'react'
+import { memo } from 'react'
import { IconRefresh } from '@posthog/icons'
-import { TimeSeriesLineChart } 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'
@@ -26,8 +20,9 @@ import type {
import { MONITORING_WINDOW_OPTIONS, managedWarehouseMonitoringLogic } from './managedWarehouseMonitoringLogic'
import type { MonitoringWorker } from './managedWarehouseMonitoringLogic'
-import { buildMonitoringChartData } from './monitoringChartData'
-import type { MonitoringChartMetricConfig } from './monitoringChartData'
+import { MonitoringChart } from './MonitoringChart'
+import { MonitoringMetricCard } from './MonitoringMetricCard'
+import { MonitoringSection } from './MonitoringSection'
const WORKER_STATE_TAGS: Record<string, LemonTagType> = {
hot: 'success',
@@ -53,78 +48,6 @@ function sentenceCase(value: string): string {
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' },
- yAxis,
- legend: { show: data.series.length > 1, interactive: true, position: 'bottom' },
- tooltip: { placement: 'cursor', sortedByValue: true, valueFormatter },
- }),
- [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>
@@ -260,26 +183,6 @@ function SummaryCards({
)
}
-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
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.test.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.test.tsx
new file mode 100644
index 000000000000..fb769533011b
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.test.tsx
@@ -0,0 +1,89 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import * as dwApi from 'products/data_warehouse/frontend/generated/api'
+import type { WarehouseStatusResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { SettingsTab } from './SettingsTab'
+import { warehouseStatusFixture } from './warehouseStatusFixtures'
+
+describe('SettingsTab', () => {
+ const renderWithStatus = (status: WarehouseStatusResponseApi, flags: string[]): void => {
+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve').mockResolvedValue(status)
+ jest.spyOn(dwApi, 'dataWarehouseCheckSchemaNameRetrieve').mockResolvedValue({
+ name: '',
+ available: true,
+ } as any)
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags(flags, Object.fromEntries(flags.map((flag) => [flag, true])))
+ render(
+ <Provider>
+ <SettingsTab />
+ </Provider>
+ )
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.restoreAllMocks()
+ })
+
+ it('shows the Trino connection and no Postgres details for a Trino organization', async () => {
+ renderWithStatus(
+ warehouseStatusFixture({
+ state: 'ready',
+ status_message: '',
+ ready_at: '2026-08-01T12:00:00Z',
+ connection: null,
+ team_onboarded: true,
+ schema_name: 'analytics',
+ trino: {
+ state: 'ready',
+ ready_at: '2026-09-01T12:00:00Z',
+ connection: {
+ host: 'my-warehouse.dw.example.com',
+ port: 443,
+ catalog: 'org_my_warehouse',
+ username: 'root',
+ },
+ },
+ }),
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]
+ )
+
+ expect(await screen.findByText('Catalog')).toBeInTheDocument()
+ // CodeSnippet can split its text across elements, so these read the page text.
+ const pageText = document.body.textContent ?? ''
+ expect(pageText).toContain('--catalog org_my_warehouse --schema analytics')
+ expect(pageText).not.toMatch(/psql|ducklake/i)
+ })
+
+ it('keeps the Postgres connection for a DuckDB organization', async () => {
+ renderWithStatus(
+ warehouseStatusFixture({
+ state: 'ready',
+ status_message: '',
+ ready_at: '2026-08-01T12:00:00Z',
+ connection: { host: 'my-warehouse.dw.example.com', port: 5432, database: 'ducklake', username: 'root' },
+ team_onboarded: true,
+ schema_name: 'analytics',
+ trino: null,
+ }),
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]
+ )
+
+ expect(await screen.findByText('Connect with psql')).toBeInTheDocument()
+ expect(screen.queryByText('Catalog')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.tsx
index 618111378941..d51b693329dc 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.tsx
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.tsx
@@ -19,6 +19,10 @@ import type {
WarehouseStatusResponseStateEnumApi,
} from 'products/data_warehouse/frontend/generated/api.schemas'
+import { dataWarehouseSceneLogic } from '../dataWarehouseSceneLogic'
+import { TrinoConnectionDetails } from './TrinoConnectionDetails'
+import { trinoCombinedStatus } from './trinoWarehouseStatus'
+import type { TrinoCombinedState } from './trinoWarehouseStatus'
import { warehouseProvisioningLogic } from './warehouseProvisioningLogic'
function stateToTagType(state: WarehouseStatusResponseStateEnumApi): 'success' | 'warning' | 'danger' | 'default' {
@@ -37,6 +41,17 @@ function stateToTagType(state: WarehouseStatusResponseStateEnumApi): 'success' |
}
}
+function combinedStateToTagType(state: TrinoCombinedState): 'success' | 'warning' | 'danger' | 'default' {
+ if (state === 'not_enabled' || state === 'unavailable') {
+ return 'warning'
+ }
+ return stateToTagType(state)
+}
+
+function combinedStateLabel(state: TrinoCombinedState): string {
+ return state.replaceAll('_', ' ').toUpperCase()
+}
+
function ConnectionDetails({ connection }: { connection: WarehouseConnectionApi }): JSX.Element {
const { host, port, database, username } = connection
const psqlCmd = `psql "host=${host} port=${port} dbname=${database} user=${username} sslmode=require"`
@@ -129,11 +144,14 @@ export function SettingsTab(): JSX.Element {
scope: RestrictionScope.Organization,
minimumAccessLevel: OrganizationMembershipLevel.Admin,
})
+ const { dataOpsVariant } = useValues(dataWarehouseSceneLogic)
+ const isTrino = dataOpsVariant === 'trino'
const hasWarehouse = warehouseStatus && warehouseStatus.state !== 'deleted'
const isReady = warehouseStatus?.state === 'ready'
const isFailed = warehouseStatus?.state === 'failed'
const showProvisionForm = !hasWarehouse || isFailed
+ const trinoStatus = isTrino && warehouseStatus ? trinoCombinedStatus(warehouseStatus) : null
return (
<div className="mt-4 space-y-4 max-w-160">
@@ -204,11 +222,19 @@ export function SettingsTab(): JSX.Element {
and ending with a letter or number.
</p>
)}
- {databaseName &&
- isValidDatabaseName &&
- !databaseNameChecking &&
- databaseNameAvailable === true &&
- warehouseDomain ? (
+ {isTrino ? (
+ (!databaseName ||
+ (isValidDatabaseName && (databaseNameChecking || databaseNameAvailable === true))) && (
+ <p className="text-muted text-xs mt-1">
+ Your warehouse name is used in your connection host and catalog. Connection details
+ appear here once the warehouse is ready.
+ </p>
+ )
+ ) : databaseName &&
+ isValidDatabaseName &&
+ !databaseNameChecking &&
+ databaseNameAvailable === true &&
+ warehouseDomain ? (
<p className="text-muted text-xs mt-1">
Your warehouse will be available at{' '}
<code>
@@ -275,12 +301,12 @@ export function SettingsTab(): JSX.Element {
</div>
) : (
<div className="space-y-4">
- {isInProgress && (
+ {(trinoStatus ? trinoStatus.inProgress : isInProgress) && (
<LemonBanner type={deprovisionTakingLong ? 'warning' : 'info'}>
<div className="flex items-center gap-2">
<Spinner />
<span>
- {warehouseStatus?.status_message ||
+ {(trinoStatus ? trinoStatus.message : warehouseStatus?.status_message) ||
(warehouseStatus?.state === 'deleting'
? 'Deprovisioning in progress...'
: 'Provisioning in progress...')}
@@ -295,24 +321,53 @@ export function SettingsTab(): JSX.Element {
</LemonBanner>
)}
+ {trinoStatus && !trinoStatus.inProgress && trinoStatus.message && (
+ <LemonBanner type={trinoStatus.state === 'failed' ? 'error' : 'warning'}>
+ {trinoStatus.message}
+ </LemonBanner>
+ )}
+
<div className="border rounded px-4 pt-4 pb-3 space-y-2">
<div className="flex items-center justify-between">
<h3 className="mb-0">Status</h3>
- <LemonTag type={stateToTagType(warehouseStatus!.state)}>
- {warehouseStatus!.state.toUpperCase()}
- </LemonTag>
+ {trinoStatus ? (
+ <LemonTag type={combinedStateToTagType(trinoStatus.state)}>
+ {combinedStateLabel(trinoStatus.state)}
+ </LemonTag>
+ ) : (
+ <LemonTag type={stateToTagType(warehouseStatus!.state)}>
+ {warehouseStatus!.state.toUpperCase()}
+ </LemonTag>
+ )}
</div>
- {warehouseStatus!.ready_at && (
+ {(trinoStatus ? trinoStatus.readyAt : warehouseStatus!.ready_at) && (
<p className="text-muted text-xs">
- Ready since: {new Date(warehouseStatus!.ready_at).toLocaleString()}
+ Ready since:{' '}
+ {new Date(
+ (trinoStatus ? trinoStatus.readyAt : warehouseStatus!.ready_at)!
+ ).toLocaleString()}
</p>
)}
</div>
- {isReady && teamOnboarded && warehouseStatus?.connection && (
- <ConnectionDetails connection={warehouseStatus.connection} />
- )}
+ {isTrino
+ ? isReady &&
+ teamOnboarded &&
+ trinoStatus?.state === 'ready' &&
+ (warehouseStatus?.trino?.connection ? (
+ <TrinoConnectionDetails
+ connection={warehouseStatus.trino.connection}
+ schemaName={teamSchemaName}
+ />
+ ) : (
+ <p className="text-muted text-xs mb-0">
+ Connection details are temporarily unavailable. Refresh to try again.
+ </p>
+ ))
+ : isReady &&
+ teamOnboarded &&
+ warehouseStatus?.connection && <ConnectionDetails connection={warehouseStatus.connection} />}
{isReady && !teamOnboarded && adminRestrictionReason && (
<div className="border rounded p-4 space-y-3">
@@ -396,8 +451,9 @@ export function SettingsTab(): JSX.Element {
onClick={() => {
LemonDialog.open({
title: 'Reset root password?',
- description:
- 'This will generate a new password and invalidate the current one. Make sure to save the new password.',
+ description: isTrino
+ ? 'This will generate a new password and invalidate the current one. The new password can take up to five minutes to apply. Make sure to save it.'
+ : 'This will generate a new password and invalidate the current one. Make sure to save the new password.',
primaryButton: {
children: 'Reset password',
onClick: () => resetPassword(),
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoConnectionDetails.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoConnectionDetails.tsx
new file mode 100644
index 000000000000..d05831c0886b
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoConnectionDetails.tsx
@@ -0,0 +1,78 @@
+import posthog from 'posthog-js'
+
+import { CodeSnippet } from 'lib/components/CodeSnippet'
+import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
+
+import type { WarehouseTrinoConnectionApi } from 'products/data_warehouse/frontend/generated/api.schemas'
+
+export function TrinoConnectionDetails({
+ connection,
+ schemaName,
+}: {
+ connection: WarehouseTrinoConnectionApi
+ schemaName: string | null
+}): JSX.Element {
+ const { host, port, catalog, username } = connection
+ const cliCommand =
+ `trino --server https://${host}:${port} --user ${username} --password --catalog ${catalog}` +
+ (schemaName ? ` --schema ${schemaName}` : '')
+
+ return (
+ <div className="border rounded p-4 space-y-3">
+ <h3 className="mb-2">Connection details</h3>
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-3 @lg:grid-cols-2">
+ <div>
+ <LemonLabel>Host</LemonLabel>
+ <CodeSnippet compact thing="host">
+ {host}
+ </CodeSnippet>
+ </div>
+ <div>
+ <LemonLabel>Port</LemonLabel>
+ <CodeSnippet compact thing="port">
+ {String(port)}
+ </CodeSnippet>
+ </div>
+ <div>
+ <LemonLabel>Catalog</LemonLabel>
+ <CodeSnippet compact thing="catalog">
+ {catalog}
+ </CodeSnippet>
+ </div>
+ {schemaName && (
+ <div>
+ <LemonLabel>Schema</LemonLabel>
+ <CodeSnippet compact thing="schema">
+ {schemaName}
+ </CodeSnippet>
+ </div>
+ )}
+ <div>
+ <LemonLabel>Username</LemonLabel>
+ <CodeSnippet compact thing="username">
+ {username}
+ </CodeSnippet>
+ </div>
+ </div>
+ </div>
+ <div>
+ <LemonLabel>Connect with the Trino CLI</LemonLabel>
+ <CodeSnippet
+ compact
+ wrap
+ thing="Trino CLI command"
+ onCopy={() =>
+ posthog.capture('managed warehouse connection details copied', { connection_type: 'trino_cli' })
+ }
+ >
+ {cliCommand}
+ </CodeSnippet>
+ </div>
+ <p className="text-muted text-xs mb-0">
+ The password is shown only once, when you provision the warehouse. If you didn't save it, use "Reset
+ password" below to generate a new one.
+ </p>
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoHistoricalCharts.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoHistoricalCharts.tsx
new file mode 100644
index 000000000000..2ad6c3a213ea
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoHistoricalCharts.tsx
@@ -0,0 +1,120 @@
+import { memo } from 'react'
+
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber, humanizeBytes, percentage } from 'lib/utils/numbers'
+
+import type { ManagedWarehouseMonitoringSeriesResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { MonitoringChart } from './MonitoringChart'
+import { MonitoringSection } from './MonitoringSection'
+
+interface TrinoHistoricalChartsProps {
+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[]
+ initialLoading: boolean
+}
+
+export const TrinoHistoricalCharts = memo(function TrinoHistoricalCharts({
+ monitoringSeries,
+ initialLoading,
+}: TrinoHistoricalChartsProps): JSX.Element {
+ return (
+ <>
+ <MonitoringSection
+ title="Query health"
+ description="Query volume, failures, and duration for the selected time range."
+ >
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-4 @5xl:grid-cols-3">
+ <MonitoringChart
+ title="Query rate"
+ description="Queries per second, split by outcome"
+ 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_scaled' }}
+ 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>
+ </div>
+ </MonitoringSection>
+
+ <MonitoringSection
+ title="Load"
+ description="How much work the warehouse is doing, and how long queries wait."
+ >
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-4 @5xl:grid-cols-2">
+ <MonitoringChart
+ title="Queries in flight"
+ description="Queries not yet finished, by state"
+ responses={monitoringSeries}
+ metrics={[{ metric: 'queries_in_flight', fallbackLabel: 'Queries' }]}
+ valueFormatter={(value) => humanFriendlyNumber(value)}
+ loading={initialLoading}
+ />
+ <MonitoringChart
+ title="Queue time"
+ description="p95 time a query waits before it runs"
+ responses={monitoringSeries}
+ metrics={[{ metric: 'queue_time_p95', fallbackLabel: 'p95' }]}
+ yAxis={{ format: 'duration' }}
+ valueFormatter={(value) => humanFriendlyDuration(value, { secondsPrecision: 2 })}
+ loading={initialLoading}
+ />
+ <MonitoringChart
+ title="Data scanned"
+ description="Bytes read from storage per second by finished queries"
+ responses={monitoringSeries}
+ metrics={[{ metric: 'scanned_bytes_rate', fallbackLabel: 'Scanned' }]}
+ yAxis={{ tickFormatter: (value: number) => `${humanizeBytes(value)}/s` }}
+ valueFormatter={(value) => `${humanizeBytes(value)}/s`}
+ loading={initialLoading}
+ />
+ <MonitoringChart
+ title="CPU time"
+ description="CPU seconds used per second by finished queries"
+ responses={monitoringSeries}
+ metrics={[{ metric: 'cpu_seconds_rate', fallbackLabel: 'CPU' }]}
+ valueFormatter={(value) => humanFriendlyNumber(value)}
+ loading={initialLoading}
+ />
+ </div>
+ </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>
+ </>
+ )
+})
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringSummaryCards.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringSummaryCards.tsx
new file mode 100644
index 000000000000..a30d768b478c
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringSummaryCards.tsx
@@ -0,0 +1,63 @@
+import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
+
+import type { ManagedWarehouseTrinoMonitoringSnapshotResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { MonitoringMetricCard } from './MonitoringMetricCard'
+import { duration, withLimit } from './trinoMonitoringFormat'
+
+export function TrinoMonitoringSummaryCards({
+ snapshot,
+ loading,
+}: {
+ snapshot: ManagedWarehouseTrinoMonitoringSnapshotResponseApi | null
+ loading: boolean
+}): JSX.Element {
+ // Totals are zero when live data is unavailable. A dash keeps that from reading as an idle warehouse.
+ const live = snapshot?.available ? snapshot : null
+ return (
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-3 @md:grid-cols-2 @4xl:grid-cols-3 @7xl:grid-cols-6">
+ <MonitoringMetricCard
+ label="Queries in flight"
+ value={live ? humanFriendlyNumber(live.totals.in_flight) : '-'}
+ description="Queries submitted and not yet finished"
+ loading={loading}
+ />
+ <MonitoringMetricCard
+ label="Running"
+ value={live ? withLimit(live.totals.running, live.limits.max_running_queries) : '-'}
+ description={
+ live && live.limits.max_running_queries > 0
+ ? 'Queries past the queue, and how many can run at once'
+ : 'Queries past the queue'
+ }
+ loading={loading}
+ />
+ <MonitoringMetricCard
+ label="Queued"
+ value={live ? withLimit(live.totals.queued, live.limits.max_queued_queries) : '-'}
+ description="Queries waiting for a running slot"
+ loading={loading}
+ />
+ <MonitoringMetricCard
+ label="Blocked"
+ value={live ? humanFriendlyNumber(live.totals.blocked) : '-'}
+ description="Running queries waiting on data or metadata"
+ loading={loading}
+ />
+ <MonitoringMetricCard
+ label="Longest running"
+ value={live ? duration(live.totals.longest_running_ms) : '-'}
+ description="Longest in-flight query"
+ loading={loading}
+ />
+ <MonitoringMetricCard
+ label="Data scanned"
+ value={live ? humanizeBytes(live.totals.physical_input_bytes) : '-'}
+ description="Read so far by in-flight queries"
+ loading={loading}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringTab.test.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringTab.test.tsx
new file mode 100644
index 000000000000..325d714af5a0
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringTab.test.tsx
@@ -0,0 +1,127 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { initKeaTests } from '~/test/init'
+
+import {
+ dataWarehouseManagedWarehouseTrinoMonitoringRetrieve,
+ dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve,
+} from 'products/data_warehouse/frontend/generated/api'
+import type { ManagedWarehouseTrinoMonitoringSnapshotResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { TrinoMonitoringTab } from './TrinoMonitoringTab'
+
+jest.mock('@posthog/quill-charts', () => ({
+ ...jest.requireActual('@posthog/quill-charts'),
+ TimeSeriesLineChart: jest.fn(() => <div data-testid="monitoring-chart" />),
+}))
+
+jest.mock('products/data_warehouse/frontend/generated/api', () => ({
+ dataWarehouseManagedWarehouseTrinoMonitoringRetrieve: jest.fn(),
+ dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve: jest.fn(),
+}))
+
+const mockSnapshotRetrieve = dataWarehouseManagedWarehouseTrinoMonitoringRetrieve as jest.MockedFunction<
+ typeof dataWarehouseManagedWarehouseTrinoMonitoringRetrieve
+>
+const mockSeriesRetrieve = dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve as jest.MockedFunction<
+ typeof dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve
+>
+
+const busySnapshot: ManagedWarehouseTrinoMonitoringSnapshotResponseApi = {
+ schema_version: 1,
+ org_id: 'org-1',
+ as_of: '2026-09-30T10:00:00Z',
+ trino: { state: 'ready', ready_at: '2026-09-01T12:00:00Z', failed_at: null },
+ available: true,
+ limits: { max_running_queries: 10, max_queued_queries: 50 },
+ totals: {
+ in_flight: 5,
+ running: 3,
+ queued: 2,
+ blocked: 1,
+ longest_running_ms: 400_000,
+ physical_input_bytes: 2048,
+ },
+ queries: [
+ {
+ query_id: 'query-1',
+ state: 'running',
+ user: 'analyst',
+ source: 'dbt',
+ query: 'SELECT * FROM t WHERE email = ?',
+ created_at: '2026-09-30T09:53:20Z',
+ elapsed_ms: 400_000,
+ queued_ms: 20,
+ cpu_ms: 900,
+ physical_input_bytes: 2048,
+ peak_memory_bytes: 64,
+ processed_input_rows: 7,
+ progress_percentage: 50,
+ blocked: true,
+ },
+ ],
+ queries_truncated: true,
+}
+
+const unavailableSnapshot: ManagedWarehouseTrinoMonitoringSnapshotResponseApi = {
+ ...busySnapshot,
+ available: false,
+ totals: { in_flight: 0, running: 0, queued: 0, blocked: 0, longest_running_ms: 0, physical_input_bytes: 0 },
+ queries: [],
+ queries_truncated: false,
+}
+
+describe('TrinoMonitoringTab', () => {
+ const renderTab = (): void => {
+ render(
+ <Provider>
+ <TrinoMonitoringTab />
+ </Provider>
+ )
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ silenceKeaLoadersErrors()
+ mockSnapshotRetrieve.mockReset()
+ mockSeriesRetrieve.mockReset()
+ mockSeriesRetrieve.mockRejectedValue(new Error('series unavailable'))
+ })
+
+ afterEach(() => {
+ cleanup()
+ resumeKeaLoadersErrors()
+ })
+
+ it('shows live totals against their limits and the in-flight queries', async () => {
+ mockSnapshotRetrieve.mockResolvedValue(busySnapshot)
+ renderTab()
+
+ expect(await screen.findByText('SELECT * FROM t WHERE email = ?')).toBeInTheDocument()
+ expect(screen.getByText('3 / 10')).toBeInTheDocument()
+ expect(screen.getByText('2 / 50')).toBeInTheDocument()
+ expect(screen.getByText('analyst')).toBeInTheDocument()
+ expect(screen.getByText('Long running')).toBeInTheDocument()
+ expect(screen.getByText('Showing the 200 longest-running queries.')).toBeInTheDocument()
+ expect(screen.queryByText(/worker/i)).not.toBeInTheDocument()
+ })
+
+ // Totals are zero when the coordinator cannot be read. Showing them would tell the user the
+ // warehouse is idle during an outage.
+ it('does not present an unavailable coordinator as an idle warehouse', async () => {
+ mockSnapshotRetrieve.mockResolvedValue(unavailableSnapshot)
+ renderTab()
+
+ expect(
+ await screen.findByText(
+ 'Live query data is temporarily unavailable. Historical charts may still be up to date.'
+ )
+ ).toBeInTheDocument()
+ expect(screen.queryByText('No queries are running right now.')).not.toBeInTheDocument()
+ expect(screen.queryByText('0 / 10')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringTab.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringTab.tsx
new file mode 100644
index 000000000000..197c89622a00
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoMonitoringTab.tsx
@@ -0,0 +1,223 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { humanizeBytes } from 'lib/utils/numbers'
+
+import {
+ TRINO_MONITORING_WINDOW_OPTIONS,
+ managedWarehouseTrinoMonitoringLogic,
+} from './managedWarehouseTrinoMonitoringLogic'
+import type { TrinoMonitoringQuery } from './managedWarehouseTrinoMonitoringLogic'
+import { MonitoringSection } from './MonitoringSection'
+import { TrinoHistoricalCharts } from './TrinoHistoricalCharts'
+import { duration, stateLabel } from './trinoMonitoringFormat'
+import { TrinoMonitoringSummaryCards } from './TrinoMonitoringSummaryCards'
+import { TrinoQueryDetails } from './TrinoQueryDetails'
+
+const LONG_RUNNING_MS = 5 * 60 * 1000
+
+const TRINO_STATE_TAGS: Record<string, LemonTagType> = {
+ ready: 'success',
+ pending: 'warning',
+ provisioning: 'warning',
+ failed: 'danger',
+}
+
+const QUERY_STATE_TAGS: Record<string, LemonTagType> = {
+ running: 'success',
+ finishing: 'success',
+ queued: 'warning',
+}
+
+function QueryState({ query }: { query: TrinoMonitoringQuery }): JSX.Element {
+ return (
+ <div className="flex flex-wrap items-center gap-1">
+ <LemonTag type={QUERY_STATE_TAGS[query.state] ?? 'primary'}>{stateLabel(query.state)}</LemonTag>
+ {query.blocked && <LemonTag type="caution">Blocked</LemonTag>}
+ {query.elapsed_ms >= LONG_RUNNING_MS && <LemonTag type="warning">Long running</LemonTag>}
+ </div>
+ )
+}
+
+function QueryProgress({ query }: { query: TrinoMonitoringQuery }): JSX.Element {
+ const progress = query.progress_percentage
+ if (progress === null || progress === undefined) {
+ return <span className="text-muted">Not available</span>
+ }
+ return (
+ <div className="min-w-24">
+ <LemonProgress percent={Math.min(100, progress)} />
+ </div>
+ )
+}
+
+const queryColumns: LemonTableColumns<TrinoMonitoringQuery> = [
+ {
+ title: 'State',
+ key: 'state',
+ render: (_, query) => <QueryState query={query} />,
+ },
+ {
+ title: 'User',
+ dataIndex: 'user',
+ render: (user) => (user ? String(user) : <span className="text-muted">Unknown</span>),
+ },
+ {
+ title: 'Query',
+ dataIndex: 'query',
+ render: (text) => (
+ <code className="block max-w-80 truncate" title={String(text)}>
+ {String(text)}
+ </code>
+ ),
+ },
+ {
+ title: 'Elapsed',
+ dataIndex: 'elapsed_ms',
+ render: (elapsed) => duration(Number(elapsed)),
+ },
+ {
+ title: 'Data scanned',
+ dataIndex: 'physical_input_bytes',
+ render: (bytes) => humanizeBytes(Number(bytes)),
+ },
+ {
+ title: 'Progress',
+ key: 'progress',
+ render: (_, query) => <QueryProgress query={query} />,
+ },
+]
+
+export function TrinoMonitoringTab(): JSX.Element {
+ const {
+ monitoringSnapshot,
+ monitoringSnapshotLoading,
+ monitoringSnapshotError,
+ monitoringSeries,
+ initialMonitoringSeriesLoading,
+ monitoringSeriesLoading,
+ monitoringSeriesError,
+ monitoringWindow,
+ } = useValues(managedWarehouseTrinoMonitoringLogic)
+ const { refreshMonitoring, setMonitoringWindow } = useActions(managedWarehouseTrinoMonitoringLogic)
+ const initialLoading = monitoringSnapshotLoading && !monitoringSnapshot
+ const liveDataUnavailable = !!monitoringSnapshot && !monitoringSnapshot.available
+
+ 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={TRINO_STATE_TAGS[monitoringSnapshot.trino.state] ?? 'default'}>
+ {stateLabel(monitoringSnapshot.trino.state)}
+ </LemonTag>
+ )}
+ </div>
+ <p className="mb-0 text-muted">
+ View query activity, performance, and storage for 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={TRINO_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 query data couldn't be refreshed. Showing the most recent available data.
+ </LemonBanner>
+ )}
+ {liveDataUnavailable && (
+ <LemonBanner type="warning">
+ Live query data is temporarily unavailable. Historical charts may still be up to date.
+ </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>
+ )}
+
+ <TrinoMonitoringSummaryCards snapshot={monitoringSnapshot} loading={initialLoading} />
+
+ <TrinoHistoricalCharts
+ monitoringSeries={monitoringSeries}
+ initialLoading={initialMonitoringSeriesLoading}
+ />
+
+ <MonitoringSection
+ title="Queries in flight"
+ description="Queries submitted to the warehouse and not yet finished."
+ >
+ <div className="@container">
+ <LemonTable
+ columns={queryColumns}
+ dataSource={monitoringSnapshot?.queries ?? []}
+ rowKey="query_id"
+ loading={initialLoading}
+ loadingSkeletonRows={3}
+ pagination={{ pageSize: 20 }}
+ expandable={{
+ expandedRowRender: (query) => <TrinoQueryDetails query={query} />,
+ noIndent: true,
+ }}
+ emptyState={
+ liveDataUnavailable
+ ? 'Live query data is not available right now.'
+ : 'No queries are running right now.'
+ }
+ />
+ </div>
+ {monitoringSnapshot?.queries_truncated && (
+ <p className="mb-0 text-xs text-muted">Showing the 200 longest-running queries.</p>
+ )}
+ </MonitoringSection>
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoQueryDetails.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoQueryDetails.tsx
new file mode 100644
index 000000000000..016cf0ac9542
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/TrinoQueryDetails.tsx
@@ -0,0 +1,29 @@
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'
+
+import type { TrinoMonitoringQuery } from './managedWarehouseTrinoMonitoringLogic'
+import { duration } from './trinoMonitoringFormat'
+
+export function TrinoQueryDetails({ query }: { query: TrinoMonitoringQuery }): JSX.Element {
+ const details: [string, string][] = [
+ ['Source', query.source || 'Not set'],
+ ['Queue time', duration(query.queued_ms)],
+ ['CPU time', duration(query.cpu_ms)],
+ ['Peak memory', humanizeBytes(query.peak_memory_bytes)],
+ ['Rows read', humanFriendlyNumber(query.processed_input_rows)],
+ ['Started', query.created_at ? humanFriendlyDetailedTime(query.created_at) : 'Unknown'],
+ ]
+ return (
+ <div className="sticky left-0 max-w-[100cqw] space-y-3 p-3">
+ <dl className="mb-0 flex flex-wrap gap-x-6 gap-y-2">
+ {details.map(([label, value]) => (
+ <div key={label}>
+ <dt className="text-xs text-muted">{label}</dt>
+ <dd className="mb-0">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ <pre className="mb-0 whitespace-pre-wrap break-words text-xs">{query.query}</pre>
+ </div>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/managedWarehouseTrinoMonitoringLogic.test.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/managedWarehouseTrinoMonitoringLogic.test.ts
new file mode 100644
index 000000000000..2692a60bb3a8
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/managedWarehouseTrinoMonitoringLogic.test.ts
@@ -0,0 +1,186 @@
+import { MOCK_TEAM_ID } from 'lib/api.mock'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { initKeaTests } from '~/test/init'
+
+import {
+ dataWarehouseManagedWarehouseTrinoMonitoringRetrieve,
+ dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve,
+} from 'products/data_warehouse/frontend/generated/api'
+import type {
+ ManagedWarehouseMonitoringSeriesResponseApi,
+ ManagedWarehouseTrinoMonitoringSnapshotResponseApi,
+} from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { managedWarehouseTrinoMonitoringLogic } from './managedWarehouseTrinoMonitoringLogic'
+
+jest.mock('products/data_warehouse/frontend/generated/api', () => ({
+ dataWarehouseManagedWarehouseTrinoMonitoringRetrieve: jest.fn(),
+ dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve: jest.fn(),
+}))
+
+const mockSnapshotRetrieve = dataWarehouseManagedWarehouseTrinoMonitoringRetrieve as jest.MockedFunction<
+ typeof dataWarehouseManagedWarehouseTrinoMonitoringRetrieve
+>
+const mockSeriesRetrieve = dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve as jest.MockedFunction<
+ typeof dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve
+>
+
+function snapshot(inFlight = 0): ManagedWarehouseTrinoMonitoringSnapshotResponseApi {
+ return {
+ schema_version: 1,
+ org_id: 'org-1',
+ as_of: '2026-09-30T10:00:00Z',
+ trino: { state: 'ready', ready_at: '2026-09-01T12:00:00Z', failed_at: null },
+ available: true,
+ limits: { max_running_queries: 10, max_queued_queries: 50 },
+ totals: {
+ in_flight: inFlight,
+ running: inFlight,
+ queued: 0,
+ blocked: 0,
+ longest_running_ms: 0,
+ physical_input_bytes: 0,
+ },
+ queries: [],
+ queries_truncated: false,
+ }
+}
+
+function seriesResponse(metric: string): ManagedWarehouseMonitoringSeriesResponseApi {
+ return {
+ schema_version: 1,
+ org_id: 'org-1',
+ metric,
+ unit: 'count',
+ start: '2026-09-30T09:59:00Z',
+ end: '2026-09-30T10:00:00Z',
+ step_seconds: 60,
+ series: [{ labels: {}, points: [{ timestamp: '2026-09-30T10:00:00Z', value: 1 }] }],
+ }
+}
+
+describe('managedWarehouseTrinoMonitoringLogic', () => {
+ let logic: ReturnType<typeof managedWarehouseTrinoMonitoringLogic.build>
+
+ const mountLogic = (): void => {
+ logic = managedWarehouseTrinoMonitoringLogic()
+ logic.mount()
+ }
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ initKeaTests()
+ mockSnapshotRetrieve.mockReset()
+ mockSeriesRetrieve.mockReset()
+ mockSnapshotRetrieve.mockResolvedValue(snapshot())
+ mockSeriesRetrieve.mockImplementation(async (_teamId, { metric }) => seriesResponse(metric))
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ resumeKeaLoadersErrors()
+ jest.useRealTimers()
+ })
+
+ it('loads the live snapshot and every Trino series on mount', async () => {
+ mountLogic()
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(mockSnapshotRetrieve).toHaveBeenCalledWith(String(MOCK_TEAM_ID))
+ expect(mockSeriesRetrieve.mock.calls.map(([, { metric }]) => metric)).toEqual([
+ 'query_rate',
+ 'error_ratio',
+ 'duration_p50',
+ 'duration_p95',
+ 'queries_in_flight',
+ 'queue_time_p95',
+ 'scanned_bytes_rate',
+ 'cpu_seconds_rate',
+ 'storage_bytes',
+ ])
+ expect(mockSeriesRetrieve.mock.calls.every(([, params]) => params.window === '24h')).toBe(true)
+ expect(logic.values.monitoringSeries).toHaveLength(9)
+ })
+
+ it.each([
+ { name: 'queries in flight', inFlight: 1, intervalMs: 15_000 },
+ { name: 'an idle warehouse', inFlight: 0, intervalMs: 60_000 },
+ ])('polls the snapshot at the expected interval for $name', async ({ inFlight, intervalMs }) => {
+ mockSnapshotRetrieve.mockResolvedValue(snapshot(inFlight))
+ mountLogic()
+ await jest.advanceTimersByTimeAsync(0)
+
+ await jest.advanceTimersByTimeAsync(intervalMs - 1)
+ expect(mockSnapshotRetrieve).toHaveBeenCalledTimes(1)
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(mockSnapshotRetrieve).toHaveBeenCalledTimes(2)
+ })
+
+ 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.each([true, false])('clears the previous range while a new range loads (failure: %s)', async (fails) => {
+ silenceKeaLoadersErrors()
+ mountLogic()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(logic.values.monitoringSeries).toHaveLength(9)
+
+ let resolve: () => void = () => {}
+ let reject: (reason: Error) => void = () => {}
+ const pending = new Promise<void>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ mockSeriesRetrieve.mockImplementation(async (_teamId, { metric }) => {
+ await pending
+ return seriesResponse(metric)
+ })
+
+ logic.actions.setMonitoringWindow('1h')
+ expect(logic.values.monitoringWindow).toBe('1h')
+ expect(logic.values.monitoringSeries).toEqual([])
+ expect(logic.values.initialMonitoringSeriesLoading).toBe(true)
+
+ if (fails) {
+ reject(new Error('series unavailable'))
+ } else {
+ resolve()
+ }
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(logic.values.monitoringSeries).toHaveLength(fails ? 0 : 9)
+ expect(logic.values.monitoringSeriesError).toBe(fails)
+ expect(logic.values.initialMonitoringSeriesLoading).toBe(false)
+ expect(logic.values.monitoringSeriesWindow).toBe(fails ? null : '1h')
+ })
+
+ 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)
+ })
+})
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/managedWarehouseTrinoMonitoringLogic.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/managedWarehouseTrinoMonitoringLogic.ts
new file mode 100644
index 000000000000..7f6469efcbd5
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/managedWarehouseTrinoMonitoringLogic.ts
@@ -0,0 +1,351 @@
+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 {
+ dataWarehouseManagedWarehouseTrinoMonitoringRetrieve,
+ dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve,
+} from 'products/data_warehouse/frontend/generated/api'
+import type {
+ DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams,
+ ManagedWarehouseMonitoringSeriesResponseApi,
+ ManagedWarehouseTrinoMonitoringSnapshotResponseApi,
+} 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 TrinoMonitoringWindow = NonNullable<
+ DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams['window']
+>
+export type TrinoMonitoringMetric = NonNullable<
+ DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams['metric']
+>
+export type TrinoMonitoringQuery = ManagedWarehouseTrinoMonitoringSnapshotResponseApi['queries'][number]
+
+export const TRINO_MONITORING_WINDOW_OPTIONS: { label: string; value: TrinoMonitoringWindow }[] = [
+ { label: '1h', value: '1h' },
+ { label: '6h', value: '6h' },
+ { label: '24h', value: '24h' },
+ { label: '7d', value: '7d' },
+ { label: '30d', value: '30d' },
+]
+
+const TRINO_MONITORING_METRICS: TrinoMonitoringMetric[] = [
+ 'query_rate',
+ 'error_ratio',
+ 'duration_p50',
+ 'duration_p95',
+ 'queries_in_flight',
+ 'queue_time_p95',
+ 'scanned_bytes_rate',
+ 'cpu_seconds_rate',
+ 'storage_bytes',
+]
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface managedWarehouseTrinoMonitoringLogicValues {
+ currentTeamId: number | null // teamLogic
+ hasLiveActivity: boolean
+ initialMonitoringSeriesLoading: boolean
+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[]
+ monitoringSeriesError: boolean
+ monitoringSeriesLoading: boolean
+ monitoringSeriesResolved: boolean
+ monitoringSeriesWindow: TrinoMonitoringWindow | null
+ monitoringSnapshot: ManagedWarehouseTrinoMonitoringSnapshotResponseApi | null
+ monitoringSnapshotError: boolean
+ monitoringSnapshotLoading: boolean
+ monitoringWindow: TrinoMonitoringWindow
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface managedWarehouseTrinoMonitoringLogicActions {
+ loadMonitoringSeries: (requestedWindow: TrinoMonitoringWindow | undefined) => TrinoMonitoringWindow | undefined
+ loadMonitoringSeriesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMonitoringSeriesSuccess: (
+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[],
+ payload?: TrinoMonitoringWindow | undefined
+ ) => {
+ monitoringSeries: ManagedWarehouseMonitoringSeriesResponseApi[]
+ payload?: TrinoMonitoringWindow | undefined
+ }
+ loadMonitoringSnapshot: (_: void) => void
+ loadMonitoringSnapshotFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMonitoringSnapshotSuccess: (
+ monitoringSnapshot: ManagedWarehouseTrinoMonitoringSnapshotResponseApi | null,
+ payload?: void
+ ) => {
+ monitoringSnapshot: ManagedWarehouseTrinoMonitoringSnapshotResponseApi | null
+ payload?: void
+ }
+ refreshMonitoring: () => {
+ value: true
+ }
+ resetMonitoringData: () => {
+ value: true
+ }
+ setMonitoringSeriesError: (hasError: boolean) => {
+ hasError: boolean
+ }
+ setMonitoringSnapshotError: (hasError: boolean) => {
+ hasError: boolean
+ }
+ setMonitoringWindow: (monitoringWindow: TrinoMonitoringWindow) => {
+ monitoringWindow: TrinoMonitoringWindow
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface managedWarehouseTrinoMonitoringLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ initialMonitoringSeriesLoading: (
+ monitoringSeriesLoading: boolean,
+ monitoringSeriesResolved: boolean,
+ monitoringSeriesError: boolean
+ ) => boolean
+ hasLiveActivity: (monitoringSnapshot: ManagedWarehouseTrinoMonitoringSnapshotResponseApi | null) => boolean
+ }
+}
+
+export type managedWarehouseTrinoMonitoringLogicType = MakeLogicType<
+ managedWarehouseTrinoMonitoringLogicValues,
+ managedWarehouseTrinoMonitoringLogicActions,
+ Record<string, any>,
+ managedWarehouseTrinoMonitoringLogicMeta
+>
+
+export const managedWarehouseTrinoMonitoringLogic = kea<managedWarehouseTrinoMonitoringLogicType>([
+ path(['scenes', 'data-warehouse', 'scene', 'managedWarehouseTrinoMonitoringLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+ actions({
+ refreshMonitoring: true,
+ resetMonitoringData: true,
+ setMonitoringSeriesError: (hasError: boolean) => ({ hasError }),
+ setMonitoringSnapshotError: (hasError: boolean) => ({ hasError }),
+ setMonitoringWindow: (monitoringWindow: TrinoMonitoringWindow) => ({ monitoringWindow }),
+ }),
+ loaders(({ values, actions }) => ({
+ monitoringSnapshot: [
+ null as ManagedWarehouseTrinoMonitoringSnapshotResponseApi | null,
+ {
+ loadMonitoringSnapshot: async (_: void, breakpoint) => {
+ const requestedTeamId = values.currentTeamId
+ if (!requestedTeamId) {
+ return null
+ }
+ let response: ManagedWarehouseTrinoMonitoringSnapshotResponseApi
+ try {
+ response = await dataWarehouseManagedWarehouseTrinoMonitoringRetrieve(String(requestedTeamId))
+ } catch (error) {
+ breakpoint()
+ throw error
+ }
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ monitoringSeries: [
+ [] as ManagedWarehouseMonitoringSeriesResponseApi[],
+ {
+ loadMonitoringSeries: async (requestedWindow: TrinoMonitoringWindow | undefined, breakpoint) => {
+ const requestedTeamId = values.currentTeamId
+ if (!requestedTeamId) {
+ return []
+ }
+ const monitoringWindow = requestedWindow ?? values.monitoringWindow
+ const results = await Promise.allSettled(
+ TRINO_MONITORING_METRICS.map((metric) =>
+ dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieve(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 TRINO_MONITORING_METRICS.flatMap((metric) => {
+ const response = responsesByMetric.get(metric)
+ return response ? [response] : []
+ })
+ },
+ },
+ ],
+ })),
+ reducers({
+ monitoringWindow: [
+ '24h' as TrinoMonitoringWindow,
+ {
+ setMonitoringWindow: (_, { monitoringWindow }) => monitoringWindow,
+ },
+ ],
+ monitoringSnapshot: {
+ resetMonitoringData: () => null,
+ },
+ monitoringSeries: {
+ setMonitoringWindow: () => [],
+ resetMonitoringData: () => [],
+ },
+ monitoringSeriesResolved: [
+ false,
+ {
+ loadMonitoringSeriesSuccess: () => true,
+ loadMonitoringSeriesFailure: () => true,
+ setMonitoringWindow: () => false,
+ resetMonitoringData: () => false,
+ },
+ ],
+ monitoringSeriesWindow: [
+ null as TrinoMonitoringWindow | null,
+ {
+ loadMonitoringSeriesSuccess: (state, { payload }) => payload ?? state,
+ setMonitoringWindow: () => null,
+ resetMonitoringData: () => null,
+ },
+ ],
+ monitoringSnapshotError: [
+ false,
+ {
+ loadMonitoringSnapshot: () => false,
+ setMonitoringSnapshotError: (_, { hasError }) => hasError,
+ resetMonitoringData: () => false,
+ },
+ ],
+ monitoringSeriesError: [
+ false,
+ {
+ setMonitoringWindow: () => 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: ManagedWarehouseTrinoMonitoringSnapshotResponseApi | null): boolean =>
+ !!monitoringSnapshot && monitoringSnapshot.totals.in_flight > 0,
+ ],
+ }),
+ 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/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/monitoringChartData.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/monitoringChartData.ts
index 28538e7a3540..1a395fa0c569 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/monitoringChartData.ts
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/monitoringChartData.ts
@@ -1,17 +1,11 @@
import type { Series } from '@posthog/quill-charts'
-import type {
- DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveParams,
- ManagedWarehouseMonitoringSeriesResponseApi,
-} from 'products/data_warehouse/frontend/generated/api.schemas'
+import type { 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
+ metric: string
fallbackLabel: string
}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoMonitoringFormat.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoMonitoringFormat.ts
new file mode 100644
index 000000000000..fdb6ec65af97
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoMonitoringFormat.ts
@@ -0,0 +1,15 @@
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+export function stateLabel(state: string): string {
+ const normalized = state.replaceAll('_', ' ')
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1)
+}
+
+export function duration(milliseconds: number): string {
+ return humanFriendlyDuration(milliseconds / 1000, { secondsPrecision: 2 }) || '0s'
+}
+
+export function withLimit(value: number, limit: number): string {
+ return limit > 0 ? `${humanFriendlyNumber(value)} / ${humanFriendlyNumber(limit)}` : humanFriendlyNumber(value)
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoWarehouseStatus.test.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoWarehouseStatus.test.ts
new file mode 100644
index 000000000000..004e17271df1
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoWarehouseStatus.test.ts
@@ -0,0 +1,101 @@
+import type {
+ WarehouseStatusResponseApi,
+ WarehouseTrinoStatusApi,
+} from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import { trinoCombinedStatus } from './trinoWarehouseStatus'
+import { trinoStatusFixture, warehouseStatusFixture } from './warehouseStatusFixtures'
+
+describe('trinoCombinedStatus', () => {
+ const status = (
+ state: WarehouseStatusResponseApi['state'],
+ trinoState?: WarehouseTrinoStatusApi['state'],
+ statusMessage = ''
+ ): WarehouseStatusResponseApi =>
+ warehouseStatusFixture({
+ state,
+ status_message: statusMessage,
+ trino: trinoState ? trinoStatusFixture({ state: trinoState }) : null,
+ })
+
+ it.each([
+ {
+ name: 'warehouse still provisioning',
+ input: status('provisioning', 'pending', 'Creating storage'),
+ expected: { state: 'provisioning', message: 'Creating storage', readyAt: null, inProgress: true },
+ },
+ {
+ name: 'warehouse ready, Trino provisioning',
+ input: status('ready', 'provisioning'),
+ expected: {
+ state: 'provisioning',
+ message: 'Setting up the query engine...',
+ readyAt: null,
+ inProgress: true,
+ },
+ },
+ {
+ name: 'warehouse ready, Trino pending',
+ input: status('ready', 'pending'),
+ expected: {
+ state: 'provisioning',
+ message: 'Setting up the query engine...',
+ readyAt: null,
+ inProgress: true,
+ },
+ },
+ {
+ name: 'both ready',
+ input: status('ready', 'ready'),
+ expected: { state: 'ready', message: null, readyAt: '2026-09-01T12:00:00Z', inProgress: false },
+ },
+ {
+ name: 'Trino failed',
+ input: status('ready', 'failed'),
+ expected: {
+ state: 'failed',
+ message: 'Query engine setup failed. Contact support.',
+ readyAt: null,
+ inProgress: false,
+ },
+ },
+ {
+ name: 'Trino not enabled',
+ input: status('ready', 'not_enabled'),
+ expected: {
+ state: 'not_enabled',
+ message: "The query engine isn't set up for this warehouse yet. Contact support.",
+ readyAt: null,
+ inProgress: false,
+ },
+ },
+ {
+ name: 'Trino status unavailable',
+ input: status('ready', 'unavailable'),
+ expected: {
+ state: 'unavailable',
+ message: "Couldn't check the query engine status. Refresh to try again.",
+ readyAt: null,
+ inProgress: false,
+ },
+ },
+ {
+ // The backend sends no trino block when its own variant check disagrees with the frontend's.
+ name: 'Trino block missing',
+ input: status('ready'),
+ expected: {
+ state: 'unavailable',
+ message: "Couldn't check the query engine status. Refresh to try again.",
+ readyAt: null,
+ inProgress: false,
+ },
+ },
+ {
+ name: 'warehouse deleting',
+ input: status('deleting', 'ready'),
+ expected: { state: 'deleting', message: null, readyAt: null, inProgress: true },
+ },
+ ])('$name', ({ input, expected }) => {
+ expect(trinoCombinedStatus(input)).toEqual(expected)
+ })
+})
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoWarehouseStatus.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoWarehouseStatus.ts
new file mode 100644
index 000000000000..d0d6052bd4e2
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/trinoWarehouseStatus.ts
@@ -0,0 +1,61 @@
+import type {
+ WarehouseStatusResponseApi,
+ WarehouseStatusResponseStateEnumApi,
+} from 'products/data_warehouse/frontend/generated/api.schemas'
+
+export type TrinoCombinedState = WarehouseStatusResponseStateEnumApi | 'not_enabled' | 'unavailable'
+
+export interface TrinoCombinedStatus {
+ state: TrinoCombinedState
+ message: string | null
+ readyAt: string | null
+ inProgress: boolean
+}
+
+const WAREHOUSE_IN_PROGRESS_STATES: WarehouseStatusResponseApi['state'][] = ['pending', 'provisioning', 'deleting']
+
+// A Trino organization has two lifecycles: the warehouse and Trino on top of it. Users see one
+// status, so Trino's state only matters once the warehouse itself is ready.
+export function trinoCombinedStatus(status: WarehouseStatusResponseApi): TrinoCombinedStatus {
+ if (status.state !== 'ready') {
+ return {
+ state: status.state,
+ message: status.status_message || null,
+ readyAt: null,
+ inProgress: WAREHOUSE_IN_PROGRESS_STATES.includes(status.state),
+ }
+ }
+ switch (status.trino?.state) {
+ case 'ready':
+ return { state: 'ready', message: null, readyAt: status.trino.ready_at ?? null, inProgress: false }
+ case 'pending':
+ case 'provisioning':
+ return {
+ state: 'provisioning',
+ message: 'Setting up the query engine...',
+ readyAt: null,
+ inProgress: true,
+ }
+ case 'failed':
+ return {
+ state: 'failed',
+ message: 'Query engine setup failed. Contact support.',
+ readyAt: null,
+ inProgress: false,
+ }
+ case 'not_enabled':
+ return {
+ state: 'not_enabled',
+ message: "The query engine isn't set up for this warehouse yet. Contact support.",
+ readyAt: null,
+ inProgress: false,
+ }
+ default:
+ return {
+ state: 'unavailable',
+ message: "Couldn't check the query engine status. Refresh to try again.",
+ readyAt: null,
+ inProgress: false,
+ }
+ }
+}
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.test.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.test.ts
index b81c7640a6ec..83169d214a92 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.test.ts
@@ -5,8 +5,10 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { initKeaTests } from '~/test/init'
import * as dwApi from 'products/data_warehouse/frontend/generated/api'
+import type { WarehouseTrinoStatusApi } from 'products/data_warehouse/frontend/generated/api.schemas'
import { warehouseProvisioningLogic } from './warehouseProvisioningLogic'
+import { trinoStatusFixture, warehouseStatusFixture } from './warehouseStatusFixtures'
describe('warehouseProvisioningLogic', () => {
let logic: ReturnType<typeof warehouseProvisioningLogic.build>
@@ -37,6 +39,24 @@ describe('warehouseProvisioningLogic', () => {
expect(dwApi.dataWarehouseWarehouseStatusRetrieve).toHaveBeenCalled()
})
+ // The warehouse reports ready before Trino does. Without polling through that gap, a Trino
+ // organization would sit on "Setting up the query engine..." until the user reloads.
+ it.each<{ name: string; trinoState: WarehouseTrinoStatusApi['state']; expectedAction: string }>([
+ { name: 'keeps polling while Trino is provisioning', trinoState: 'provisioning', expectedAction: 'pollStatus' },
+ { name: 'keeps polling while Trino is pending', trinoState: 'pending', expectedAction: 'pollStatus' },
+ { name: 'stops polling once Trino is ready', trinoState: 'ready', expectedAction: 'stopPolling' },
+ { name: 'stops polling when Trino failed', trinoState: 'failed', expectedAction: 'stopPolling' },
+ ])('$name', async ({ trinoState, expectedAction }) => {
+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve').mockResolvedValue(
+ warehouseStatusFixture({ trino: trinoStatusFixture({ state: trinoState, ready_at: null }) })
+ )
+
+ logic = warehouseProvisioningLogic()
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadWarehouseStatusSuccess', expectedAction])
+ })
+
it('treats a 404 status as no warehouse', async () => {
jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve').mockRejectedValueOnce({ status: 404 })
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.ts
index a5e5b3d0f1ad..22b473c81c41 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.ts
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseProvisioningLogic.ts
@@ -712,7 +712,17 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([
// Keep polling while teardown is in flight, and while the org record still needs
// removing (`deleted`) so a failed delete-org retries on the next tick. A
// successful delete-org 404s the next read, which falls through to stopPolling.
- if (state === 'pending' || state === 'provisioning' || state === 'deleting' || state === 'deleted') {
+ // The trino block is only present for the Trino variant, where the warehouse is
+ // usable once Trino is ready too.
+ const trinoState = warehouseStatus?.trino?.state
+ const trinoSettingUp = state === 'ready' && (trinoState === 'pending' || trinoState === 'provisioning')
+ if (
+ state === 'pending' ||
+ state === 'provisioning' ||
+ state === 'deleting' ||
+ state === 'deleted' ||
+ trinoSettingUp
+ ) {
actions.pollStatus()
} else {
actions.stopPolling()
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseStatusFixtures.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseStatusFixtures.ts
new file mode 100644
index 000000000000..748cccdcff7a
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/warehouseStatusFixtures.ts
@@ -0,0 +1,31 @@
+import type {
+ WarehouseStatusResponseApi,
+ WarehouseTrinoStatusApi,
+} from 'products/data_warehouse/frontend/generated/api.schemas'
+
+export function warehouseStatusFixture(
+ overrides: Partial<WarehouseStatusResponseApi> = {}
+): WarehouseStatusResponseApi {
+ return {
+ org_id: 'org-1',
+ state: 'ready',
+ status_message: '',
+ s3_state: 'ready',
+ metadata_store_state: 'ready',
+ identity_state: 'ready',
+ secrets_state: 'ready',
+ ready_at: '2026-08-01T12:00:00Z',
+ failed_at: null,
+ connection: null,
+ trino: null,
+ has_backfill: false,
+ table_suffix: null,
+ team_onboarded: true,
+ schema_name: 'analytics',
+ ...overrides,
+ }
+}
+
+export function trinoStatusFixture(overrides: Partial<WarehouseTrinoStatusApi> = {}): WarehouseTrinoStatusApi {
+ return { state: 'ready', ready_at: '2026-09-01T12:00:00Z', connection: null, ...overrides }
+}
diff --git a/products/data_warehouse/manifest.tsx b/products/data_warehouse/manifest.tsx
index 1d3155a22dad..d6511de76bae 100644
--- a/products/data_warehouse/manifest.tsx
+++ b/products/data_warehouse/manifest.tsx
@@ -176,6 +176,7 @@ export const manifest: ProductManifest = {
searchKeywords: ['managed warehouse', 'data lake', 'lakehouse'],
searchTabs: [{ name: 'Monitoring', href: urls.dataOps('monitoring') }],
flag: FEATURE_FLAGS.DATA_WAREHOUSE_SCENE,
+ alternativeFlags: [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO],
iconType: 'data_warehouse',
iconColor: ['var(--color-product-data-warehouse-light)'],
sceneKey: 'DataOps',
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yaml
index 2ddcf47d20c2..f2f03194cb03 100644
--- a/products/data_warehouse/mcp/tools.yaml
+++ b/products/data_warehouse/mcp/tools.yaml
@@ -37,6 +37,39 @@ tools:
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-scene
+ managed-warehouse-trino-metric-history-get:
+ operation: data_warehouse_managed_warehouse_trino_monitoring_timeseries_retrieve
+ enabled: true
+ scopes:
+ - warehouse_view:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get managed warehouse Trino metric history
+ description: >
+ Get one operational metric over a trailing time window for the active project's managed warehouse when it
+ runs on Trino. Available metrics cover queries in flight by state, query rate and errors, query duration,
+ queue time, data scanned, CPU time, and storage size. The response includes units and labeled series. These
+ values are not billing totals.
+ feature_flag: data-warehouse-scene-trino
+ managed-warehouse-trino-monitoring-get:
+ operation: data_warehouse_managed_warehouse_trino_monitoring_retrieve
+ enabled: true
+ scopes:
+ - warehouse_view:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get managed warehouse Trino monitoring
+ description: >
+ Get current Trino query activity for the active project's managed warehouse: queries in flight, running,
+ queued, and blocked counts, concurrency and queue limits, and the in-flight queries with literal values
+ removed from their SQL. Use this to inspect current workload. When `available` is false the live data could
+ not be read, so the totals do not mean the warehouse is idle. These values describe operational activity,
+ not invoiced usage.
+ feature_flag: data-warehouse-scene-trino
saved-query-column-annotations-create:
operation: saved_query_column_annotations_create
enabled: true
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.md
index d3c1fcb99fc6..b08568e07b25 100644
--- a/products/managed_warehouse/backend/README.md
+++ b/products/managed_warehouse/backend/README.md
@@ -118,15 +118,17 @@ This path currently supports Parquet only. Support for Azure Blob Storage, CSV,
## Feature flag gating
-Each workflow evaluates a feature flag through `feature_enabled`. Create or update the appropriate flag locally. The copy flags target the project, while `data-warehouse-scene` targets the organization. Otherwise, the workflow will be skipped even if the rest of the configuration is correct.
+Each workflow evaluates a feature flag through `feature_enabled`. Create or update the appropriate flag locally. The copy flags target the project, while `data-warehouse-scene` and `data-warehouse-scene-trino` target the organization. Otherwise, the workflow will be skipped even if the rest of the configuration is correct.
-| Workflow | Feature Flag |
-| ------------------------ | -------------------------------------- |
-| Data Modeling | `ducklake-data-modeling-copy-workflow` |
-| Data Imports | `ducklake-data-imports-copy-workflow` |
-| Data Import Registration | `data-warehouse-scene` |
+| Workflow | Feature Flag |
+| ------------------------ | ------------------------------------------------------ |
+| Data Modeling | `ducklake-data-modeling-copy-workflow` |
+| Data Imports | `ducklake-data-imports-copy-workflow` |
+| Data Import Registration | `data-warehouse-scene` or `data-warehouse-scene-trino` |
-The data-import copy and registration paths target the same stable DuckLake table. An organization with `data-warehouse-scene` enabled runs registration. Disable `ducklake-data-imports-copy-workflow` for its projects to avoid both paths applying the same import. If both run, the last atomic table swap wins.
+The data-import copy and registration paths target the same stable DuckLake table. An organization with either managed warehouse flag enabled runs registration. Disable `ducklake-data-imports-copy-workflow` for its projects to avoid both paths applying the same import. If both run, the last atomic table swap wins.
+
+The two organization flags also select the Data ops variant. `data-warehouse-scene-trino` gives the Trino variant and wins when both are on. `data-warehouse-scene` alone gives the DuckDB variant. `data_ops_variant` in `presentation/views.py` is the single backend implementation of that rule.
## Data Ops workflow status
diff --git a/products/managed_warehouse/backend/facade/feature_flags.py b/products/managed_warehouse/backend/facade/feature_flags.py
index a9c75da10769..15b8b97c6bbd 100644
--- a/products/managed_warehouse/backend/facade/feature_flags.py
+++ b/products/managed_warehouse/backend/facade/feature_flags.py
@@ -1,2 +1,5 @@
DATA_WAREHOUSE_SCENE_FLAG = "data-warehouse-scene"
+DATA_WAREHOUSE_SCENE_TRINO_FLAG = "data-warehouse-scene-trino"
+# Either flag gives an organization the managed warehouse.
+MANAGED_WAREHOUSE_ACCESS_FLAGS = (DATA_WAREHOUSE_SCENE_TRINO_FLAG, DATA_WAREHOUSE_SCENE_FLAG)
DATA_MODELING_SHADOW_FLAG = "managed-warehouse-data-modeling-shadow"
diff --git a/products/managed_warehouse/backend/presentation/hogtower.py b/products/managed_warehouse/backend/presentation/hogtower.py
index 1e68474ec397..eafc112008d4 100644
--- a/products/managed_warehouse/backend/presentation/hogtower.py
+++ b/products/managed_warehouse/backend/presentation/hogtower.py
@@ -419,6 +419,8 @@ _ORG_ROUTES: dict[tuple[str, str], Callable[[_Call], TranslatedResponse]] = {
("POST", "/service-credentials/refresh"): _refresh_credential,
("GET", "/monitoring/snapshot"): _org_passthrough("/monitoring/snapshot"),
("GET", "/monitoring/series"): _org_passthrough("/monitoring/series"),
+ ("GET", "/monitoring/trino/snapshot"): _org_passthrough("/monitoring/trino/snapshot"),
+ ("GET", "/monitoring/trino/series"): _org_passthrough("/monitoring/trino/series"),
}
# Global v1 paths (under /api/v1) keyed by (method, path).
diff --git a/products/managed_warehouse/backend/presentation/views.py b/products/managed_warehouse/backend/presentation/views.py
index 62e3dfef1f49..fd6f5bd51c09 100644
--- a/products/managed_warehouse/backend/presentation/views.py
+++ b/products/managed_warehouse/backend/presentation/views.py
@@ -14,7 +14,7 @@ import re
from collections.abc import Callable
from datetime import date
from functools import partial
-from typing import Literal, TypedDict
+from typing import Literal, TypedDict, cast
from uuid import UUID
from django.conf import settings
@@ -27,7 +27,10 @@ from rest_framework.response import Response
from posthog.security.outbound_proxy import internal_requests
-from products.managed_warehouse.backend.facade.feature_flags import DATA_WAREHOUSE_SCENE_FLAG
+from products.managed_warehouse.backend.facade.feature_flags import (
+ DATA_WAREHOUSE_SCENE_FLAG,
+ DATA_WAREHOUSE_SCENE_TRINO_FLAG,
+)
from products.managed_warehouse.backend.presentation import hogtower
logger = structlog.get_logger(__name__)
@@ -57,6 +60,25 @@ class PresentedConnection(TypedDict):
username: str
+class PresentedTrinoConnection(TypedDict):
+ host: str
+ port: int
+ catalog: str
+ username: str
+
+
+TrinoStatusState = Literal["not_enabled", "pending", "provisioning", "ready", "failed", "unavailable"]
+
+
+class PresentedTrinoStatus(TypedDict):
+ state: TrinoStatusState
+ ready_at: str | None
+ connection: PresentedTrinoConnection | None
+
+
+_TRINO_LIFECYCLE_STATES = frozenset({"pending", "provisioning", "ready", "failed"})
+
+
ManagedWarehouseMonitoringMetric = Literal[
"query_rate",
"error_ratio",
@@ -69,7 +91,19 @@ ManagedWarehouseMonitoringMetric = Literal[
"storage_bytes",
"worker_crash_rate",
]
+ManagedWarehouseTrinoMonitoringMetric = Literal[
+ "queries_in_flight",
+ "query_rate",
+ "error_ratio",
+ "duration_p50",
+ "duration_p95",
+ "queue_time_p95",
+ "scanned_bytes_rate",
+ "cpu_seconds_rate",
+ "storage_bytes",
+]
ManagedWarehouseMonitoringWindow = Literal["1h", "6h", "24h", "7d", "30d"]
+DataOpsVariant = Literal["trino", "duckdb"]
def managed_warehouse_domain() -> str:
@@ -91,8 +125,8 @@ def validate_warehouse_name(name: str | None) -> str | None:
return None
-def is_enabled(organization_id: UUID | str) -> bool:
- """Evaluate the managed-warehouse flag for the organization.
+def _organization_flag_enabled(flag: str, organization_id: UUID | str) -> bool:
+ """Evaluate one managed-warehouse flag for the organization.
Identity is the organization so every team in the org resolves the same value.
"""
@@ -100,7 +134,7 @@ def is_enabled(organization_id: UUID | str) -> bool:
try:
return bool(
posthoganalytics.feature_enabled(
- DATA_WAREHOUSE_SCENE_FLAG,
+ flag,
org_id,
groups={"organization": org_id},
group_properties={"organization": {"id": org_id}},
@@ -109,10 +143,28 @@ def is_enabled(organization_id: UUID | str) -> bool:
)
)
except Exception:
- logger.warning("Failed to evaluate managed warehouse feature flag", organization_id=org_id)
+ logger.warning("Failed to evaluate managed warehouse feature flag", organization_id=org_id, flag=flag)
return False
+def data_ops_variant(organization_id: UUID | str) -> DataOpsVariant | None:
+ """Which Data ops variant the organization gets, or None when it has neither flag.
+
+ The Trino flag wins when both are on, so an organization never moves between variants
+ because of Trino's state.
+ """
+ if _organization_flag_enabled(DATA_WAREHOUSE_SCENE_TRINO_FLAG, organization_id):
+ return "trino"
+ if _organization_flag_enabled(DATA_WAREHOUSE_SCENE_FLAG, organization_id):
+ return "duckdb"
+ return None
+
+
+def is_enabled(organization_id: UUID | str) -> bool:
+ """Whether the organization has the managed warehouse through either flag."""
+ return data_ops_variant(organization_id) is not None
+
+
def _present_connection(raw: dict) -> PresentedConnection:
"""Build the public-facing connection from duckgres's raw status connection.
@@ -148,7 +200,7 @@ def _request(
paths starting with "/" are org-scoped (`/api/v1/orgs/{org}{path}`); others are global
API paths (`/api/v1/{path}`).
- `require_enabled` gates on the user-facing `data-warehouse-scene` flag and is the right
+ `require_enabled` gates on the user-facing managed warehouse flags and is the right
default for UI-driven calls. Backend/background callers (e.g. the Dagster duckling
backfill) must pass `require_enabled=False`: the flag is evaluated only-locally and a
worker without the flag definition loaded would otherwise get a spurious 403 even when
@@ -1093,6 +1145,64 @@ def status_for(organization_id: UUID | str) -> Response:
return resp
+def _present_trino_connection(trino_status: dict) -> PresentedTrinoConnection | None:
+ catalog = trino_status.get("trino_catalog_name") or trino_status.get("catalog")
+ connection = trino_status.get("connection")
+ if not isinstance(catalog, str) or not catalog.strip() or not isinstance(connection, dict):
+ return None
+ host = connection.get("host")
+ username = connection.get("username")
+ port = connection.get("port")
+ if not isinstance(host, str) or not host.strip() or not isinstance(username, str) or not username.strip():
+ return None
+ if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
+ return None
+ return PresentedTrinoConnection(host=host.strip(), port=port, catalog=catalog.strip(), username=username.strip())
+
+
+def trino_status_for(organization_id: UUID | str) -> PresentedTrinoStatus:
+ """Customer-safe summary of the organization's Trino enablement, for the Trino Data ops variant.
+
+ The control plane's Trino status is an operator payload. Only the lifecycle state, the ready
+ time, and the connection target leave this function.
+ """
+ unavailable = PresentedTrinoStatus(state="unavailable", ready_at=None, connection=None)
+ resp = _request("GET", organization_id, "/trino", timeout=10)
+ if not status.is_success(resp.status_code) or not isinstance(resp.data, dict):
+ return unavailable
+ if resp.data.get("enabled") is not True:
+ return PresentedTrinoStatus(state="not_enabled", ready_at=None, connection=None)
+
+ trino_status = resp.data.get("status")
+ if not isinstance(trino_status, dict):
+ return unavailable
+ if str(trino_status.get("org")) != str(organization_id):
+ logger.warning(
+ "refusing_trino_status_for_mismatched_organization",
+ requested_organization_id=str(organization_id),
+ response_organization_id=str(trino_status.get("org")),
+ )
+ return unavailable
+
+ raw_state = trino_status.get("state")
+ # A row that has not been reconciled yet has no state, which means pending.
+ if raw_state is None or raw_state == "":
+ state: TrinoStatusState = "pending"
+ elif isinstance(raw_state, str) and raw_state in _TRINO_LIFECYCLE_STATES:
+ state = cast(TrinoStatusState, raw_state)
+ else:
+ # The control plane has lifecycle states this view does not present, such as deleting. Showing
+ # them as pending would make the scene poll for a setup that never completes.
+ logger.warning("unexpected_trino_lifecycle_state", organization_id=str(organization_id), state=str(raw_state))
+ return unavailable
+ ready_at = trino_status.get("ready_at")
+ return PresentedTrinoStatus(
+ state=state,
+ ready_at=ready_at if isinstance(ready_at, str) else None,
+ connection=_present_trino_connection(trino_status) if state == "ready" else None,
+ )
+
+
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)
@@ -1113,6 +1223,26 @@ def monitoring_series_for(
)
+def trino_monitoring_snapshot_for(organization_id: UUID | str) -> Response:
+ """Fetch tenant-safe live Trino query data for one organization."""
+ return _request("GET", organization_id, "/monitoring/trino/snapshot", timeout=10)
+
+
+def trino_monitoring_series_for(
+ organization_id: UUID | str,
+ metric: ManagedWarehouseTrinoMonitoringMetric,
+ window: ManagedWarehouseMonitoringWindow,
+) -> Response:
+ """Fetch one allow-listed Trino monitoring series for one organization."""
+ return _request(
+ "GET",
+ organization_id,
+ "/monitoring/trino/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/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
index 6014f9dff779..e5dce8721445 100644
--- a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py
@@ -47,7 +47,7 @@ from products.managed_warehouse.backend.facade.contracts import (
ManagedWarehouseSourceJobUpdate,
ManagedWarehouseSourceJobWorkflow,
)
-from products.managed_warehouse.backend.facade.feature_flags import DATA_WAREHOUSE_SCENE_FLAG
+from products.managed_warehouse.backend.facade.feature_flags import MANAGED_WAREHOUSE_ACCESS_FLAGS
from products.managed_warehouse.backend.models import ManagedWarehouseSourceJob
from products.managed_warehouse.backend.storage import connect_to_duckgres, setup_duckgres_session
from products.managed_warehouse.backend.temporal.metrics import (
@@ -254,19 +254,26 @@ async def ducklake_register_data_imports_gate_activity(inputs: DuckLakeRegisterD
return False
organization_id = str(team.organization_id)
- try:
- flag_enabled = feature_enabled_or_false(
- DATA_WAREHOUSE_SCENE_FLAG,
- organization_id,
- groups={"organization": organization_id},
- group_properties={"organization": {"id": organization_id}},
- only_evaluate_locally=True,
- send_feature_flag_events=False,
- )
- except Exception as error:
- await logger.awarning("Failed to evaluate DuckLake data imports registration feature flag", error=str(error))
- capture_exception(error)
- return False
+ flag_enabled = False
+ # Each flag is evaluated on its own, so an error on one flag cannot hide access the other grants.
+ for flag in MANAGED_WAREHOUSE_ACCESS_FLAGS:
+ try:
+ flag_enabled = feature_enabled_or_false(
+ flag,
+ organization_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ except Exception as error:
+ await logger.awarning(
+ "Failed to evaluate DuckLake data imports registration feature flag", flag=flag, error=str(error)
+ )
+ capture_exception(error)
+ continue
+ if flag_enabled:
+ break
if not flag_enabled:
return False
diff --git a/products/managed_warehouse/backend/tests/api/test_presentation.py b/products/managed_warehouse/backend/tests/api/test_presentation.py
index bfa70b8c3427..d62c0c704f30 100644
--- a/products/managed_warehouse/backend/tests/api/test_presentation.py
+++ b/products/managed_warehouse/backend/tests/api/test_presentation.py
@@ -38,15 +38,26 @@ def _onboarding_side_effects():
clear_team_membership_cache()
+ "enabled_flags, expected_variant",
+ [
+ ({"data-warehouse-scene-trino"}, "trino"),
+ ({"data-warehouse-scene-trino", "data-warehouse-scene"}, "trino"),
+ ({"data-warehouse-scene"}, "duckdb"),
+ (set(), None),
+ ],
+)
@patch("products.managed_warehouse.backend.presentation.views.posthoganalytics.feature_enabled")
-def test_is_enabled_uses_data_warehouse_scene_flag(mock_feature_enabled: MagicMock) -> None:
+def test_data_ops_variant_prefers_the_trino_flag(
+ mock_feature_enabled: MagicMock, enabled_flags: set[str], expected_variant: str | None
+) -> None:
organization_id = uuid4()
- mock_feature_enabled.return_value = True
-
- assert managed_warehouse.is_enabled(organization_id) is True
+ mock_feature_enabled.side_effect = lambda flag, *_args, **_kwargs: flag in enabled_flags
- mock_feature_enabled.assert_called_once_with(
- "data-warehouse-scene",
+ assert managed_warehouse.data_ops_variant(organization_id) == expected_variant
+ assert managed_warehouse.is_enabled(organization_id) is (expected_variant is not None)
+ mock_feature_enabled.assert_any_call(
+ "data-warehouse-scene-trino",
str(organization_id),
groups={"organization": str(organization_id)},
group_properties={"organization": {"id": str(organization_id)}},
@@ -55,6 +66,14 @@ def test_is_enabled_uses_data_warehouse_scene_flag(mock_feature_enabled: MagicMo
)
+@patch(
+ "products.managed_warehouse.backend.presentation.views.posthoganalytics.feature_enabled",
+ side_effect=RuntimeError("flags unavailable"),
+)
+def test_data_ops_variant_fails_closed_when_flag_evaluation_errors(_mock_feature_enabled: MagicMock) -> None:
+ assert managed_warehouse.data_ops_variant(uuid4()) is None
+
+
@patch("products.managed_warehouse.backend.facade.connection.update_managed_warehouse_root_password")
@patch("products.managed_warehouse.backend.presentation.views._request")
def test_reset_password_reports_local_persistence_failure(
@@ -1313,3 +1332,77 @@ def test_update_team_puts_only_passed_fields_to_org_team_route(mock_internal: Ma
assert method == "PUT"
assert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}/teams/42"
assert mock_internal.request.call_args.kwargs["json"] == {"earliest_event_date": "2020-06-15"}
+
+
+_TRINO_ORG_ID = "0193f1a4-0000-7000-8000-000000000001"
+_TRINO_CONNECTION = {"host": "my-warehouse.dw.example.com", "port": 443, "username": "root"}
+
+
+def _trino_upstream(**status_overrides: object) -> Response:
+ trino_status: dict[str, object] = {
+ "org": _TRINO_ORG_ID,
+ "state": "ready",
+ "ready_at": "2026-09-01T12:00:00Z",
+ "trino_catalog_name": "org_my_warehouse",
+ "connection": _TRINO_CONNECTION,
+ "status_message": "sensitive reconcile detail",
+ "cell": "sensitive-cell",
+ "principal": "sensitive-principal",
+ }
+ trino_status.update(status_overrides)
+ return Response({"enabled": True, "available": True, "status": trino_status}, status=200)
+
+
+ "upstream, expected",
+ [
+ (
+ _trino_upstream(),
+ {
+ "state": "ready",
+ "ready_at": "2026-09-01T12:00:00Z",
+ "connection": {
+ "host": "my-warehouse.dw.example.com",
+ "port": 443,
+ "catalog": "org_my_warehouse",
+ "username": "root",
+ },
+ },
+ ),
+ # The coordinator is unreachable, so duckgres advertises no connection.
+ (_trino_upstream(connection=None), {"state": "ready", "ready_at": "2026-09-01T12:00:00Z", "connection": None}),
+ (
+ _trino_upstream(state="provisioning", ready_at=None),
+ {"state": "provisioning", "ready_at": None, "connection": None},
+ ),
+ (
+ _trino_upstream(state="failed"),
+ {"state": "failed", "ready_at": "2026-09-01T12:00:00Z", "connection": None},
+ ),
+ (_trino_upstream(state="", ready_at=None), {"state": "pending", "ready_at": None, "connection": None}),
+ (_trino_upstream(state=None, ready_at=None), {"state": "pending", "ready_at": None, "connection": None}),
+ (_trino_upstream(state="resharding"), {"state": "unavailable", "ready_at": None, "connection": None}),
+ (_trino_upstream(state=["ready"]), {"state": "unavailable", "ready_at": None, "connection": None}),
+ (
+ Response({"enabled": False, "assigned": False}, status=200),
+ {"state": "not_enabled", "ready_at": None, "connection": None},
+ ),
+ (_trino_upstream(org="another-organization"), {"state": "unavailable", "ready_at": None, "connection": None}),
+ (
+ Response({"error": "the assigned Trino cell is not configured"}, status=409),
+ {"state": "unavailable", "ready_at": None, "connection": None},
+ ),
+ (
+ Response({"error": "Provisioning service is unreachable"}, status=502),
+ {"state": "unavailable", "ready_at": None, "connection": None},
+ ),
+ ],
+)
+@patch("products.managed_warehouse.backend.presentation.views._request")
+def test_trino_status_for_presents_only_customer_safe_fields(
+ mock_request: MagicMock, upstream: Response, expected: dict[str, object]
+) -> None:
+ mock_request.return_value = upstream
+
+ assert managed_warehouse.trino_status_for(_TRINO_ORG_ID) == expected
+ mock_request.assert_called_once_with("GET", _TRINO_ORG_ID, "/trino", timeout=10)
diff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
index 75222967e9fe..a9a7b88def7d 100644
--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
@@ -53,25 +53,34 @@ def _cp_no_rows():
@pytest.mark.asyncio
@pytest.mark.django_db
[email protected]("flag_enabled", [True, False])
-async def test_registration_gate_uses_data_warehouse_scene_flag(monkeypatch, ateam, flag_enabled):
- captured: dict[str, object] = {}
+ "enabled_flags, failing_flags, expected",
+ [
+ ({"data-warehouse-scene"}, set(), True),
+ ({"data-warehouse-scene-trino"}, set(), True),
+ (set(), set(), False),
+ ({"data-warehouse-scene"}, {"data-warehouse-scene-trino"}, True),
+ ],
+)
+async def test_registration_gate_accepts_either_managed_warehouse_flag(
+ monkeypatch, ateam, enabled_flags, failing_flags, expected
+):
+ calls: list[dict[str, object]] = []
def fake_feature_enabled(key, distinct_id, **kwargs):
- captured.update(key=key, distinct_id=distinct_id, **kwargs)
- return flag_enabled
+ calls.append({"key": key, "distinct_id": distinct_id, **kwargs})
+ if key in failing_flags:
+ raise RuntimeError("flag evaluation failed")
+ return key in enabled_flags
monkeypatch.setattr(registration_module, "feature_enabled_or_false", fake_feature_enabled)
result = await ducklake_register_data_imports_gate_activity(DuckLakeRegisterDataImportsGateInputs(team_id=ateam.id))
- assert result is flag_enabled
- assert captured["key"] == "data-warehouse-scene"
- assert captured["distinct_id"] == str(ateam.organization_id)
- assert captured["groups"] == {"organization": str(ateam.organization_id)}
- assert captured["group_properties"] == {"organization": {"id": str(ateam.organization_id)}}
- assert captured["only_evaluate_locally"] is True
- assert captured["send_feature_flag_events"] is False
+ assert result is expected
+ assert calls[0]["distinct_id"] == str(ateam.organization_id)
+ assert calls[0]["groups"] == {"organization": str(ateam.organization_id)}
+ assert calls[0]["group_properties"] == {"organization": {"id": str(ateam.organization_id)}}
@pytest.mark.asyncio
diff --git a/products/managed_warehouse/backend/tests/test_hogtower.py b/products/managed_warehouse/backend/tests/test_hogtower.py
index 4eb0c535bf6d..e01a1033ae0c 100644
--- a/products/managed_warehouse/backend/tests/test_hogtower.py
+++ b/products/managed_warehouse/backend/tests/test_hogtower.py
@@ -298,12 +298,20 @@ class TestWarehouseRoutes:
{
("GET", f"{W}/monitoring/snapshot"): (200, {"sessions": 1}),
("GET", f"{W}/monitoring/series"): (200, {"points": []}),
+ ("GET", f"{W}/monitoring/trino/snapshot"): (200, {"queries": []}),
+ ("GET", f"{W}/monitoring/trino/series"): (200, {"points": []}),
}
)
- def test_monitoring_is_passed_through(self, fake: FakeHogtower) -> None:
- assert _mapped("GET", "/monitoring/snapshot").json() == {"sessions": 1}
+ @pytest.mark.parametrize("engine", ["duckdb", "trino"])
+ def test_monitoring_is_passed_through(self, fake: FakeHogtower, engine: str) -> None:
+ prefix = "/monitoring/trino" if engine == "trino" else "/monitoring"
+ snapshot: dict[str, object] = {"queries": []} if engine == "trino" else {"sessions": 1}
+ response = _mapped("GET", f"{prefix}/snapshot")
+ assert (response.status_code, response.json()) == (200, snapshot)
params = {"metric": "query_rate", "window": "1h"}
- assert _mapped("GET", "/monitoring/series", params=params).json() == {"points": []}
+ response = _mapped("GET", f"{prefix}/series", params=params)
+ assert (response.status_code, response.json()) == (200, {"points": []})
+ assert fake.paths == [("GET", f"{W}{prefix}/snapshot"), ("GET", f"{W}{prefix}/series")]
assert fake.calls[1]["params"] == params
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 005c37203cb9..ef25b93691c9 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -528,7 +528,7 @@ class TestScoutTrialTaskVisibility(BaseTaskAPITest):
format="json",
)
assert response.status_code == status.HTTP_200_OK, response.json()
- signal_completion.assert_called_once_with(run.id, TaskRun.Status.FAILED, "Synthetic failure")
+ signal_completion.assert_called_once_with(run.id, TaskRun.Status.FAILED, "Synthetic failure", None)
run.refresh_from_db()
assert run.status == TaskRun.Status.FAILED
assert run.error_message == "Synthetic failure"
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 35983d3c6822..d4a7c3b96edf 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9355,6 +9355,36 @@
},
"feature_flag": "data-warehouse-scene"
},
+ "managed-warehouse-trino-metric-history-get": {
+ "description": "Get one operational metric over a trailing time window for the active project's managed warehouse when it runs on Trino. Available metrics cover queries in flight by state, query rate and errors, query duration, queue time, data scanned, CPU time, and storage size. The response includes units and labeled series. These values are not billing totals.",
+ "category": "Data warehouse",
+ "feature": "data_warehouse",
+ "summary": "Get managed warehouse Trino metric history",
+ "title": "Get managed warehouse Trino metric history",
+ "required_scopes": ["warehouse_view:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "data-warehouse-scene-trino"
+ },
+ "managed-warehouse-trino-monitoring-get": {
+ "description": "Get current Trino query activity for the active project's managed warehouse: queries in flight, running, queued, and blocked counts, concurrency and queue limits, and the in-flight queries with literal values removed from their SQL. Use this to inspect current workload. When `available` is false the live data could not be read, so the totals do not mean the warehouse is idle. These values describe operational activity, not invoiced usage.",
+ "category": "Data warehouse",
+ "feature": "data_warehouse",
+ "summary": "Get managed warehouse Trino monitoring",
+ "title": "Get managed warehouse Trino monitoring",
+ "required_scopes": ["warehouse_view:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "data-warehouse-scene-trino"
+ },
"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.json
index 44005e7ace2e..4f0bf9d1f13a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9752,6 +9752,36 @@
},
"feature_flag": "data-warehouse-scene"
},
+ "managed-warehouse-trino-metric-history-get": {
+ "description": "Get one operational metric over a trailing time window for the active project's managed warehouse when it runs on Trino. Available metrics cover queries in flight by state, query rate and errors, query duration, queue time, data scanned, CPU time, and storage size. The response includes units and labeled series. These values are not billing totals.",
+ "category": "Data warehouse",
+ "feature": "data_warehouse",
+ "summary": "Get managed warehouse Trino metric history",
+ "title": "Get managed warehouse Trino metric history",
+ "required_scopes": ["warehouse_view:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "data-warehouse-scene-trino"
+ },
+ "managed-warehouse-trino-monitoring-get": {
+ "description": "Get current Trino query activity for the active project's managed warehouse: queries in flight, running, queued, and blocked counts, concurrency and queue limits, and the in-flight queries with literal values removed from their SQL. Use this to inspect current workload. When `available` is false the live data could not be read, so the totals do not mean the warehouse is idle. These values describe operational activity, not invoiced usage.",
+ "category": "Data warehouse",
+ "feature": "data_warehouse",
+ "summary": "Get managed warehouse Trino monitoring",
+ "title": "Get managed warehouse Trino monitoring",
+ "required_scopes": ["warehouse_view:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "data-warehouse-scene-trino"
+ },
"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.ts
index 93d0e4b0dab3..0767602bee30 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -65628,6 +65628,148 @@ export namespace Schemas {
schemas: ManagedWarehouseSourceTableStatus[];
}
+ export interface ManagedWarehouseTrinoMonitoringLimits {
+ /**
+ * Maximum number of the organization's queries that run at the same time. Zero when Trino is not enabled.
+ * @minimum 0
+ */
+ max_running_queries: number;
+ /**
+ * Maximum number of the organization's queries that can wait in the queue. Zero when Trino is not enabled.
+ * @minimum 0
+ */
+ max_queued_queries: number;
+ }
+
+ export interface ManagedWarehouseTrinoMonitoringQuery {
+ /** Trino query identifier. */
+ query_id: string;
+ /** Trino query state in lower case, such as queued, planning, starting, running, or finishing. */
+ state: string;
+ /** Warehouse username that ran the query. Blank when it cannot be resolved. */
+ user: string;
+ /** Client-reported source of the query, such as a tool name. Blank when not set. */
+ source: string;
+ /** SQL text with literal values replaced by ? and comments removed. A placeholder when unavailable. */
+ query: string;
+ /**
+ * UTC timestamp when the query was submitted, or null when Trino does not report it.
+ * @nullable
+ */
+ created_at: string | null;
+ /**
+ * Milliseconds since the query was submitted.
+ * @minimum 0
+ */
+ elapsed_ms: number;
+ /**
+ * Milliseconds the query spent queued.
+ * @minimum 0
+ */
+ queued_ms: number;
+ /**
+ * CPU milliseconds the query has used.
+ * @minimum 0
+ */
+ cpu_ms: number;
+ /**
+ * Bytes the query has read from storage.
+ * @minimum 0
+ */
+ physical_input_bytes: number;
+ /**
+ * Peak memory the query has reserved, in bytes.
+ * @minimum 0
+ */
+ peak_memory_bytes: number;
+ /**
+ * Rows the query has read.
+ * @minimum 0
+ */
+ processed_input_rows: number;
+ /**
+ * Best-effort progress percentage, or null when Trino cannot estimate it.
+ * @minimum 0
+ * @nullable
+ */
+ progress_percentage: number | null;
+ /** Whether all of the query's work is waiting on data or metadata. */
+ blocked: boolean;
+ }
+
+ export interface ManagedWarehouseTrinoMonitoringState {
+ /** Trino lifecycle state for the organization: not_enabled, pending, provisioning, ready, or failed. */
+ state: string;
+ /**
+ * UTC timestamp when Trino became ready for the organization, or null.
+ * @nullable
+ */
+ ready_at: string | null;
+ /**
+ * UTC timestamp when Trino setup last failed for the organization, or null.
+ * @nullable
+ */
+ failed_at: string | null;
+ }
+
+ export interface ManagedWarehouseTrinoMonitoringTotals {
+ /**
+ * Queries submitted and not yet finished. Equals running plus queued.
+ * @minimum 0
+ */
+ in_flight: number;
+ /**
+ * In-flight queries past the queue. This is the count the concurrency limit applies to.
+ * @minimum 0
+ */
+ running: number;
+ /**
+ * Queries waiting for a running slot.
+ * @minimum 0
+ */
+ queued: number;
+ /**
+ * Running queries whose work is all waiting on data or metadata. A subset of running.
+ * @minimum 0
+ */
+ blocked: number;
+ /**
+ * Elapsed milliseconds of the longest in-flight query, or zero when there is none.
+ * @minimum 0
+ */
+ longest_running_ms: number;
+ /**
+ * Bytes read so far by all in-flight queries.
+ * @minimum 0
+ */
+ physical_input_bytes: number;
+ }
+
+ export interface ManagedWarehouseTrinoMonitoringSnapshotResponse {
+ /**
+ * Version of the Trino 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;
+ /** Trino lifecycle details for the organization. */
+ trino: ManagedWarehouseTrinoMonitoringState;
+ /** Whether live query data could be read. When false, totals are zero and do not mean the warehouse is idle. */
+ available: boolean;
+ /** Concurrency and queue limits. */
+ limits: ManagedWarehouseTrinoMonitoringLimits;
+ /** Current in-flight query totals. */
+ totals: ManagedWarehouseTrinoMonitoringTotals;
+ /** In-flight queries, longest-running first, capped at 200 rows. */
+ queries: ManagedWarehouseTrinoMonitoringQuery[];
+ /** Whether the query list was capped. Totals always cover every in-flight query. */
+ queries_truncated: boolean;
+ }
+
export interface MarkToleratedInput {
/** UUID of the changed snapshot to mark as a known tolerated alternate. Future runs that produce the same alternate hash for this identifier will not be flagged as changes. */
snapshot_id: string;
@@ -112941,7 +113083,7 @@ export namespace Schemas {
}
export interface WarehouseConnection {
- /** Connection host — the warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com */
+ /** Postgres connection host. The warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com */
host: string;
/** Postgres wire-protocol port */
port: number;
@@ -112971,6 +113113,56 @@ export namespace Schemas {
Deleted: 'deleted',
} as const;
+ /**
+ * * `not_enabled` - not_enabled
+ * * `pending` - pending
+ * * `provisioning` - provisioning
+ * * `ready` - ready
+ * * `failed` - failed
+ * * `unavailable` - unavailable
+ */
+ export type WarehouseTrinoStatusStateEnum = typeof WarehouseTrinoStatusStateEnum[keyof typeof WarehouseTrinoStatusStateEnum];
+
+
+ export const WarehouseTrinoStatusStateEnum = {
+ NotEnabled: 'not_enabled',
+ Pending: 'pending',
+ Provisioning: 'provisioning',
+ Ready: 'ready',
+ Failed: 'failed',
+ Unavailable: 'unavailable',
+ } as const;
+
+ export interface WarehouseTrinoConnection {
+ /** Trino host to connect to over HTTPS */
+ host: string;
+ /** Trino HTTPS port */
+ port: number;
+ /** Trino catalog that holds the organization's data */
+ catalog: string;
+ /** Root username */
+ username: string;
+ }
+
+ export interface WarehouseTrinoStatus {
+ /** Trino lifecycle state for the organization. `unavailable` means the state could not be read.
+ *
+ * * `not_enabled` - not_enabled
+ * * `pending` - pending
+ * * `provisioning` - provisioning
+ * * `ready` - ready
+ * * `failed` - failed
+ * * `unavailable` - unavailable */
+ state: WarehouseTrinoStatusStateEnum;
+ /**
+ * When Trino became ready for the organization
+ * @nullable
+ */
+ ready_at: string | null;
+ /** Trino connection target. Null until Trino is ready and reachable. */
+ connection: WarehouseTrinoConnection | null;
+ }
+
export interface WarehouseStatusResponse {
/** duckgres org identifier (the PostHog organization id) */
org_id: string;
@@ -113003,7 +113195,10 @@ export namespace Schemas {
* @nullable
*/
failed_at: string | null;
+ /** Postgres connection target. Null for organizations on the Trino Data ops variant. */
connection?: WarehouseConnection | null;
+ /** Trino status for organizations on the Trino Data ops variant, once the warehouse is ready. Null otherwise. */
+ trino?: WarehouseTrinoStatus | null;
/** Whether this project already has a warehouse backfill configured. When true, its table name is fixed and the enable form should not be shown. */
has_backfill: boolean;
/**
@@ -121728,6 +121923,61 @@ export namespace Schemas {
source_id: string;
};
+ export type DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams = {
+ /**
+ * Allow-listed Trino metric to retrieve.
+ *
+ * * `queries_in_flight` - queries_in_flight
+ * * `query_rate` - query_rate
+ * * `error_ratio` - error_ratio
+ * * `duration_p50` - duration_p50
+ * * `duration_p95` - duration_p95
+ * * `queue_time_p95` - queue_time_p95
+ * * `scanned_bytes_rate` - scanned_bytes_rate
+ * * `cpu_seconds_rate` - cpu_seconds_rate
+ * * `storage_bytes` - storage_bytes
+ * @minLength 1
+ */
+ metric: DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric;
+ /**
+ * Trailing time window to retrieve. Defaults to 24h.
+ *
+ * * `1h` - 1h
+ * * `6h` - 6h
+ * * `24h` - 24h
+ * * `7d` - 7d
+ * * `30d` - 30d
+ * @minLength 1
+ */
+ window?: DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow;
+ };
+
+ export type DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric = typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric[keyof typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric];
+
+
+ export const DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveMetric = {
+ QueriesInFlight: 'queries_in_flight',
+ QueryRate: 'query_rate',
+ ErrorRatio: 'error_ratio',
+ DurationP50: 'duration_p50',
+ DurationP95: 'duration_p95',
+ QueueTimeP95: 'queue_time_p95',
+ ScannedBytesRate: 'scanned_bytes_rate',
+ CpuSecondsRate: 'cpu_seconds_rate',
+ StorageBytes: 'storage_bytes',
+ } as const;
+
+ export type DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow = typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow[keyof typeof DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow];
+
+
+ export const DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveWindow = {
+ '1h': '1h',
+ '6h': '6h',
+ '24h': '24h',
+ '7d': '7d',
+ '30d': '30d',
+ } as const;
+
export type DataWarehouseRunningActivityRetrieveParams = {
/**
* Only include runs created within this many days of now. Defaults to 30.
diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.ts
index f2013beb4d91..ad42e7499866 100644
--- a/services/mcp/src/generated/data_warehouse/api.ts
+++ b/services/mcp/src/generated/data_warehouse/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 21 enabled ops
+ * PostHog API - MCP 23 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -58,6 +58,56 @@ export const DataWarehouseManagedWarehouseMonitoringTimeseriesRetrieveQueryParam
),
})
+/**
+ * Get tenant-safe live Trino query totals, limits, and in-flight queries for the current organization.
+ * @summary Get managed warehouse Trino monitoring snapshot
+ */
+export const DataWarehouseManagedWarehouseTrinoMonitoringRetrieveParams = () => 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 Trino monitoring metric for the current organization and trailing time window.
+ * @summary Get managed warehouse Trino monitoring time series
+ */
+export const DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveParams = () => 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 dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveQueryWindowDefault = `24h`
+
+export const DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveQueryParams = () => zod.object({
+ metric: zod
+ .enum([
+ 'queries_in_flight',
+ 'query_rate',
+ 'error_ratio',
+ 'duration_p50',
+ 'duration_p95',
+ 'queue_time_p95',
+ 'scanned_bytes_rate',
+ 'cpu_seconds_rate',
+ 'storage_bytes',
+ ])
+ .describe(
+ 'Allow-listed Trino metric to retrieve.\n\n\* `queries_in_flight` - queries_in_flight\n\* `query_rate` - query_rate\n\* `error_ratio` - error_ratio\n\* `duration_p50` - duration_p50\n\* `duration_p95` - duration_p95\n\* `queue_time_p95` - queue_time_p95\n\* `scanned_bytes_rate` - scanned_bytes_rate\n\* `cpu_seconds_rate` - cpu_seconds_rate\n\* `storage_bytes` - storage_bytes'
+ ),
+ window: zod
+ .enum(['1h', '6h', '24h', '7d', '30d'])
+ .default(dataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveQueryWindowDefault)
+ .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 = () => 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.ts
index 6fab39a510b8..8d8e3c4ee45c 100644
--- a/services/mcp/src/tools/generated/data_warehouse.ts
+++ b/services/mcp/src/tools/generated/data_warehouse.ts
@@ -58,6 +58,56 @@ const managedWarehouseMonitoringGet = (): ToolBase<
},
})
+const ManagedWarehouseTrinoMetricHistoryGetSchema = () => {
+ const DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveQueryParams =
+ orvalSchemas.DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveQueryParams()
+ return DataWarehouseManagedWarehouseTrinoMonitoringTimeseriesRetrieveQueryParams
+}
+
+const managedWarehouseTrinoMetricHistoryGet = (): ToolBase<
+ ReturnType<typeof ManagedWarehouseTrinoMetricHistoryGetSchema>,
+ Schemas.ManagedWarehouseMonitoringSeriesResponse
+> => ({
+ name: 'managed-warehouse-trino-metric-history-get',
+ schema: ManagedWarehouseTrinoMetricHistoryGetSchema(),
+ handler: async (
+ context: Context,
+ params: z.infer<ReturnType<typeof ManagedWarehouseTrinoMetricHistoryGetSchema>>
+ ) => {
+ 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-trino-monitoring-timeseries/`,
+ query: {
+ metric: params.metric,
+ window: params.window,
+ },
+ })
+ return result
+ },
+})
+
+const ManagedWarehouseTrinoMonitoringGetSchema = () => z.object({})
+
+const managedWarehouseTrinoMonitoringGet = (): ToolBase<
+ ReturnType<typeof ManagedWarehouseTrinoMonitoringGetSchema>,
+ Schemas.ManagedWarehouseTrinoMonitoringSnapshotResponse
+> => ({
+ name: 'managed-warehouse-trino-monitoring-get',
+ schema: ManagedWarehouseTrinoMonitoringGetSchema(),
+ handler: async (
+ context: Context,
+ _params: z.infer<ReturnType<typeof ManagedWarehouseTrinoMonitoringGetSchema>>
+ ) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ManagedWarehouseTrinoMonitoringSnapshotResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/data_warehouse/managed-warehouse-trino-monitoring/`,
+ })
+ return result
+ },
+})
+
const SavedQueryColumnAnnotationsCreateSchema = () => {
const SavedQueryColumnAnnotationsCreateBody = orvalSchemas.SavedQueryColumnAnnotationsCreateBody()
return SavedQueryColumnAnnotationsCreateBody.extend({
@@ -727,6 +777,8 @@ const warehouseTablesRefreshSchemaCreate = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'managed-warehouse-metric-history-get': managedWarehouseMetricHistoryGet,
'managed-warehouse-monitoring-get': managedWarehouseMonitoringGet,
+ 'managed-warehouse-trino-metric-history-get': managedWarehouseTrinoMetricHistoryGet,
+ 'managed-warehouse-trino-monitoring-get': managedWarehouseTrinoMonitoringGet,
'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.ts
index 7abf35e7fd22..0d7cfabcc642 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -427,6 +427,26 @@ describe('Tool Filtering - API Scopes', () => {
}
})
+ it('should expose managed warehouse Trino monitoring only with its read scope and feature flag', async () => {
+ const trinoTools = ['managed-warehouse-trino-monitoring-get', 'managed-warehouse-trino-metric-history-get']
+ const enabledOptions = { featureFlags: { 'data-warehouse-scene-trino': true } }
+
+ const authorizedTools = await getToolsFromContext(createMockContext(['warehouse_view:read']), enabledOptions)
+ const wrongScopeTools = await getToolsFromContext(createMockContext(['query:read']), enabledOptions)
+ const duckdbFlagOnlyTools = await getToolsFromContext(createMockContext(['warehouse_view:read']), {
+ featureFlags: { 'data-warehouse-scene': true },
+ })
+ const authorizedToolNames = authorizedTools.map((tool) => tool.name)
+ const wrongScopeToolNames = wrongScopeTools.map((tool) => tool.name)
+ const duckdbFlagOnlyToolNames = duckdbFlagOnlyTools.map((tool) => tool.name)
+
+ for (const toolName of trinoTools) {
+ expect(authorizedToolNames).toContain(toolName)
+ expect(wrongScopeToolNames).not.toContain(toolName)
+ expect(duckdbFlagOnlyToolNames).not.toContain(toolName)
+ }
+ })
+
it.each([
['notebooks-widget-generate', ['notebook:write', 'query:read']],
['notebooks-widget-status', ['notebook:read']],
@@ -1069,6 +1089,7 @@ describe('Tool Filtering - Feature Flags', () => {
'scouts-tool-access',
'replay-vision-scanner-dashboard',
'metrics-dashboard-import',
+ 'data-warehouse-scene-trino',
]
expect(allFlags).toEqual(expect.arrayContaining(branchFlags))
// The flags branches add are asserted on the line above and held out of the list and