:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): provision a managed warehouse per organization (#63637)
Eric Duong1f240f26af3a
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex c5598f38ad0f..d37adb8ae909 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -95,17 +95,12 @@ import {DataModelingEdge,DataModelingJob,DataModelingNode,- DataWarehouseActivityRecord,- DataWarehouseJobStats,- DataWarehouseJobStatsRequestPayload,DataWarehouseManagedViewsetSavedQuery,DataWarehouseSavedQuery,DataWarehouseSavedQueryDependencies,DataWarehouseSavedQueryDraft,DataWarehouseSavedQueryFolder,DataWarehouseSavedQueryRunHistory,- DataWarehouseProvisioningStatus,- DataWarehouseSourceRowCount,DataWarehouseTable,DataWarehouseViewLink,DataWarehouseViewLinkValidation,@@ -1761,10 +1756,6 @@ export class ApiRequest {return this.externalDataSources(teamId).addPathComponent('connections')}- public dataWarehouse(teamId?: TeamType['id']): ApiRequest {- return this.environmentsDetail(teamId).addPathComponent('data_warehouse')- }-public externalDataSchemas(teamId?: TeamType['id']): ApiRequest {return this.environmentsDetail(teamId).addPathComponent('external_data_schemas')}@@ -5715,106 +5706,6 @@ const api = {},},- dataWarehouse: {- async totalRowsStats(options?: ApiMethodOptions): Promise<DataWarehouseSourceRowCount> {- return await new ApiRequest().dataWarehouse().withAction('total_rows_stats').get(options)- },-- async runningActivity(- options?: ApiMethodOptions & {- limit?: number- offset?: number- cutoff_days?: number- }- ): Promise<PaginatedResponse<DataWarehouseActivityRecord>> {- return await new ApiRequest()- .dataWarehouse()- .withAction('running_activity')- .withQueryString({- limit: options?.limit,- offset: options?.offset,- cutoff_days: options?.cutoff_days,- })- .get(options)- },-- async completedActivity(- options?: ApiMethodOptions & {- limit?: number- offset?: number- cutoff_days?: number- }- ): Promise<PaginatedResponse<DataWarehouseActivityRecord>> {- return await new ApiRequest()- .dataWarehouse()- .withAction('completed_activity')- .withQueryString({- limit: options?.limit,- offset: options?.offset,- cutoff_days: options?.cutoff_days,- })- .get(options)- },-- async jobStats(- options?: ApiMethodOptions & DataWarehouseJobStatsRequestPayload- ): Promise<DataWarehouseJobStats> {- return await new ApiRequest()- .dataWarehouse()- .withAction('job_stats')- .withQueryString({ days: options?.days })- .get(options)- },-- async dataOpsDashboard(options?: ApiMethodOptions): Promise<{ dashboard_id: number }> {- return await new ApiRequest().dataWarehouse().withAction('data_ops_dashboard').get(options)- },-- async provisionWarehouse(- databaseName: string,- options?: ApiMethodOptions- ): Promise<{- status: string- org: string- username: string- password: string- }> {- return await new ApiRequest()- .dataWarehouse()- .withAction('provision')- .create({- data: { database_name: databaseName },- ...options,- } as any)- },-- async deprovisionWarehouse(options?: ApiMethodOptions): Promise<{ status: string; org: string }> {- return await new ApiRequest()- .dataWarehouse()- .withAction('deprovision')- .create(options as any)- },-- async warehouseStatus(options?: ApiMethodOptions): Promise<DataWarehouseProvisioningStatus> {- return await new ApiRequest().dataWarehouse().withAction('warehouse_status').get(options)- },-- async checkDatabaseName(name: string): Promise<{ name: string; available: boolean }> {- return await new ApiRequest()- .dataWarehouse()- .withAction('check-database-name')- .withQueryString({ name })- .get()- },-- async resetPassword(): Promise<{ username: string; password: string }> {- return await new ApiRequest()- .dataWarehouse()- .withAction('reset_password')- .create({} as any)- },- },-externalDataSchemas: {async get(schemaId: ExternalDataSourceSchema['id']): Promise<ExternalDataSchemaWithSource> {return await new ApiRequest().externalDataSourceSchema(schemaId).get()diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 3021aa0a394a..534824c84bc0 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -444,7 +444,6 @@ export const FEATURE_FLAGS = {PROMOTED_PRODUCT: 'promoted-product', // owner: @pauldambra #team-growth multivariate=control,control_b,intent,intent_plus, experiment for surfacing the team's primary onboarding product directly under HomePROMPT_MANAGEMENT: 'prompt-management', // owner: #team-ai-observabilityPROPERTY_ACCESS_CONTROL: 'property-access-control', // owner: @reecejones #team-platform-features- PROVISION_MANAGED_WAREHOUSE_BETA: 'provision-managed-warehouse-beta', // owner: @EDsCODE #team-managed-warehouseQUICK_START_PULSE_INDICATOR: 'quick-start-pulse-indicator', // owner: @fercgomes #team-growth multivariate=control,testRBAC_UI_REDESIGN: 'rbac-ui-redesign', // owner: @reece #team-platform-featuresREAD_ONLY_MODE: 'read-only-mode', // owner: @pauldambra, experiment: force users into read-only and steer mutations through Max/MCPdiff --git a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsxindex 8324808c8104..c9637d3d6a61 100644--- a/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx+++ b/frontend/src/scenes/data-warehouse/DataWarehouseScene.tsx@@ -1,5 +1,4 @@-import { useValues } from 'kea'-import { combineUrl, router } from 'kea-router'+import { useActions, useValues } from 'kea'import { NotFound } from 'lib/components/NotFound'import { FEATURE_FLAGS } from 'lib/constants'@@ -7,16 +6,13 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'-import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'-import { DashboardTab } from './scene/DashboardTab'import { DataModelingTab } from './scene/DataModelingTab'-import { OverviewTab } from './scene/OverviewTab'import { SettingsTab } from './scene/SettingsTab'export const scene: SceneExport = {@@ -25,12 +21,27 @@ export const scene: SceneExport = {productKey: ProductKey.DATA_WAREHOUSE,}+const TAB_LABELS: Record<DataWarehouseTab, string> = {+ [DataWarehouseTab.SETTINGS]: 'Settings',+ [DataWarehouseTab.MODELING]: 'Modeling',+}++function tabContent(tab: DataWarehouseTab): JSX.Element {+ switch (tab) {+ case DataWarehouseTab.SETTINGS:+ return <SettingsTab />+ case DataWarehouseTab.MODELING:+ return <DataModelingTab />+ }+}+export function DataWarehouseScene(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)- const { activeTab } = useValues(dataWarehouseSceneLogic)- const { searchParams } = useValues(router)+ const { availableTabs, activeTab } = useValues(dataWarehouseSceneLogic)+ const { setActiveTab } = useActions(dataWarehouseSceneLogic)- if (!featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {+ // Nothing to show without the scene flag, or when no tab's feature flag is enabled.+ if (!featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE] || !activeTab) {return <NotFound object="Data warehouse" />}@@ -43,53 +54,20 @@ export function DataWarehouseScene(): JSX.Element {type: sceneConfigurations[Scene.DataOps].iconType || 'default_icon_type',}}/>- <LemonTabs- activeKey={activeTab}- sceneInset- tabs={[- {- key: DataWarehouseTab.OVERVIEW,- label: 'Overview',- content: <OverviewTab />,- link: urls.dataOps(),- },- {- key: DataWarehouseTab.DASHBOARD,- label: 'Dashboard',- content: <DashboardTab />,- link: combineUrl(urls.dataOps(), {- ...searchParams,- tab: DataWarehouseTab.DASHBOARD,- }).url,- },- ...(featureFlags[FEATURE_FLAGS.DATA_MODELING_TAB]- ? [- {- key: DataWarehouseTab.MODELING,- label: 'Modeling',- content: <DataModelingTab />,- link: combineUrl(urls.dataOps(), {- ...searchParams,- tab: DataWarehouseTab.MODELING,- }).url,- },- ]- : []),- ...(featureFlags[FEATURE_FLAGS.PROVISION_MANAGED_WAREHOUSE_BETA]- ? [- {- key: DataWarehouseTab.SETTINGS,- label: 'Settings',- content: <SettingsTab />,- link: combineUrl(urls.dataOps(), {- ...searchParams,- tab: DataWarehouseTab.SETTINGS,- }).url,- },- ]- : []),- ]}- />+ {availableTabs.length > 1 ? (+ <LemonTabs+ activeKey={activeTab}+ sceneInset+ onChange={setActiveTab}+ tabs={availableTabs.map((tab) => ({+ key: tab,+ label: TAB_LABELS[tab],+ content: tabContent(tab),+ }))}+ />+ ) : (+ tabContent(activeTab)+ )}</SceneContent>)}diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.tsnew file mode 100644index 000000000000..cac67d3fb1b1--- /dev/null+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.test.ts@@ -0,0 +1,36 @@+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { DataWarehouseTab, dataWarehouseSceneLogic } from './dataWarehouseSceneLogic'++describe('dataWarehouseSceneLogic', () => {+ let logic: ReturnType<typeof dataWarehouseSceneLogic.build>+ let flagsLogic: ReturnType<typeof featureFlagLogic.build>++ beforeEach(() => {+ initKeaTests()+ flagsLogic = featureFlagLogic()+ flagsLogic.mount()+ logic = dataWarehouseSceneLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ flagsLogic.unmount()+ })++ it('uses data-warehouse-scene to expose the managed warehouse settings tab', async () => {+ await expectLogic(flagsLogic, () => {+ flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_WAREHOUSE_SCENE], {+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: true,+ })+ })++ expect(logic.values.availableTabs).toEqual([DataWarehouseTab.SETTINGS])+ })+})diff --git a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.tsindex 9a1078c53b05..ccdc8ea7f46a 100644--- a/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts+++ b/frontend/src/scenes/data-warehouse/dataWarehouseSceneLogic.ts@@ -1,238 +1,56 @@-import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'+import { actions, connect, kea, path, reducers, selectors } from 'kea'import { actionToUrl, router, urlToAction } from 'kea-router'-import posthog from 'posthog-js'-import api, { PaginatedResponse } from 'lib/api'-import { billingLogic } from 'scenes/billing/billingLogic'-import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'-import { DatabaseSchemaDataWarehouseTable } from '~/queries/schema/schema-general'-import {- BillingProductV2Type,- DataWarehouseActivityRecord,- DataWarehouseJobStats,- DataWarehouseJobStatsRequestPayload,- DataWarehouseSavedQuery,- DataWarehouseSourceRowCount,-} from '~/types'--import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'import type { dataWarehouseSceneLogicType } from './dataWarehouseSceneLogicType'-import { dataWarehouseViewsLogic } from './saved_queries/dataWarehouseViewsLogic'export enum DataWarehouseTab {- OVERVIEW = 'overview',- DASHBOARD = 'dashboard',- MODELING = 'modeling',SETTINGS = 'settings',+ MODELING = 'modeling',}+// Single source of truth for which tabs the Data ops scene exposes. The scene, the URL+// state, and the default tab all derive from availableTabs / activeTab below.export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([path(['scenes', 'data-warehouse', 'dataWarehouseSceneLogic']),connect(() => ({- values: [- databaseTableListLogic,- ['database', 'dataWarehouseTables', 'databaseLoading'],- sourcesDataLogic,- ['dataWarehouseSources', 'dataWarehouseSourcesLoading'],- billingLogic,- ['billingPeriodUTC', 'billing'],- dataWarehouseViewsLogic,- ['dataWarehouseSavedQueries'],- ],- actions: [- databaseTableListLogic,- ['loadDatabase'],- sourcesDataLogic,- ['loadSources'],- billingLogic,- ['loadBilling'],- ],+ values: [featureFlagLogic, ['featureFlags']],})),actions({- loadMoreRunningActivity: true,- loadMoreCompletedActivity: true,- setActivityRunningCurrentPage: (page: number) => ({ page }),- setActivityCompletedCurrentPage: (page: number) => ({ page }),- checkAutoLoadMoreRunning: true,- checkAutoLoadMoreCompleted: true,setActiveTab: (tab: DataWarehouseTab) => ({ tab }),}),- loaders(() => ({- totalRowsStats: [- {} as DataWarehouseSourceRowCount,- {- loadTotalRowsStats: async () => {- return await api.dataWarehouse.totalRowsStats()- },- },- ],- runningActivityResponse: [- null as PaginatedResponse<DataWarehouseActivityRecord> | null,- {- loadRunningActivityResponse: async () => {- return await api.dataWarehouse.runningActivity({ limit: 20, offset: 0, cutoff_days: 30 })- },- },- ],- completedActivityResponse: [- null as PaginatedResponse<DataWarehouseActivityRecord> | null,- {- loadCompletedActivityResponse: async () => {- return await api.dataWarehouse.completedActivity({ limit: 20, offset: 0, cutoff_days: 30 })- },- },- ],- jobStats: [- null as DataWarehouseJobStats | null,- {- loadJobStats: async ({ days }: DataWarehouseJobStatsRequestPayload) => {- return await api.dataWarehouse.jobStats({ days })- },- },- ],- dataOpsDashboardId: [- null as number | null,- {- loadDataOpsDashboardId: async () => {- const response = await api.dataWarehouse.dataOpsDashboard()- return response.dashboard_id- },- },- ],- })),- reducers(() => ({- activeTab: [- DataWarehouseTab.OVERVIEW as DataWarehouseTab,+ reducers({+ selectedTab: [+ DataWarehouseTab.SETTINGS as DataWarehouseTab,{setActiveTab: (_, { tab }) => tab,},],- activityRunningCurrentPage: [- 1 as number,- {- setActivityRunningCurrentPage: (_, { page }) => page,- loadRunningActivityResponse: () => 1,- },- ],- activityCompletedCurrentPage: [- 1 as number,- {- setActivityCompletedCurrentPage: (_, { page }) => page,- loadCompletedActivityResponse: () => 1,- },- ],- runningActivityMoreLoading: [- false as boolean,- {- loadMoreRunningActivity: () => true,- loadRunningActivityResponseSuccess: () => false,- },- ],- completedActivityMoreLoading: [- false as boolean,- {- loadMoreCompletedActivity: () => true,- loadCompletedActivityResponseSuccess: () => false,- },- ],- })),+ }),selectors({- recentActivityRunning: [- (s) => [s.runningActivityResponse],- (response: PaginatedResponse<DataWarehouseActivityRecord> | null): DataWarehouseActivityRecord[] => {- return response?.results || []- },- ],- recentActivityCompleted: [- (s) => [s.completedActivityResponse],- (response: PaginatedResponse<DataWarehouseActivityRecord> | null): DataWarehouseActivityRecord[] => {- return response?.results || []- },- ],- recentActivityRunningHasMore: [- (s) => [s.runningActivityResponse],- (response: PaginatedResponse<DataWarehouseActivityRecord> | null): boolean => {- return !!response?.next- },- ],- recentActivityCompletedHasMore: [- (s) => [s.completedActivityResponse],- (response: PaginatedResponse<DataWarehouseActivityRecord> | null): boolean => {- return !!response?.next- },- ],- selfManagedTables: [- (s) => [s.dataWarehouseTables],- (dataWarehouseTables): DatabaseSchemaDataWarehouseTable[] => {- return dataWarehouseTables.filter((table) => !table.source)- },- ],- activityRunningPaginationState: [- (s) => [s.recentActivityRunning, s.activityRunningCurrentPage],- (recentActivityRunning: DataWarehouseActivityRecord[], activityRunningCurrentPage: number) => {- const pageSize = 8- const totalData = recentActivityRunning.length- const pageCount = Math.max(Math.ceil(totalData / pageSize), 1)- const startIndex = (activityRunningCurrentPage - 1) * pageSize- const endIndex = Math.min(startIndex + pageSize, totalData)- const dataSourcePage = recentActivityRunning.slice(startIndex, endIndex)-- return {- currentPage: activityRunningCurrentPage,- pageCount,- dataSourcePage,- currentStartIndex: startIndex,- currentEndIndex: endIndex,- entryCount: totalData,- isOnLastPage: activityRunningCurrentPage === pageCount,- hasDataOnCurrentPage: dataSourcePage.length > 0,+ availableTabs: [+ (s) => [s.featureFlags],+ (featureFlags): DataWarehouseTab[] => {+ const tabs: DataWarehouseTab[] = []+ if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {+ tabs.push(DataWarehouseTab.SETTINGS)}- },- ],- activityCompletedPaginationState: [- (s) => [s.recentActivityCompleted, s.activityCompletedCurrentPage],- (recentActivityCompleted: DataWarehouseActivityRecord[], activityCompletedCurrentPage: number) => {- const pageSize = 8- const totalData = recentActivityCompleted.length- const pageCount = Math.max(Math.ceil(totalData / pageSize), 1)- const startIndex = (activityCompletedCurrentPage - 1) * pageSize- const endIndex = Math.min(startIndex + pageSize, totalData)- const dataSourcePage = recentActivityCompleted.slice(startIndex, endIndex)-- return {- currentPage: activityCompletedCurrentPage,- pageCount,- dataSourcePage,- currentStartIndex: startIndex,- currentEndIndex: endIndex,- entryCount: totalData,- isOnLastPage: activityCompletedCurrentPage === pageCount,- hasDataOnCurrentPage: dataSourcePage.length > 0,+ if (featureFlags[FEATURE_FLAGS.DATA_MODELING_TAB]) {+ tabs.push(DataWarehouseTab.MODELING)}+ return tabs},],- tablesLoading: [- (s) => [s.databaseLoading, s.dataWarehouseSourcesLoading],- (databaseLoading: boolean, dataWarehouseSourcesLoading: boolean): boolean => {- return databaseLoading || dataWarehouseSourcesLoading- },- ],- dataWarehouseProduct: [- (s) => [s.billing],- (billing): BillingProductV2Type | null => {- return billing?.products?.find((product) => product.type === 'data_warehouse') || null- },- ],- materializedViews: [- (s) => [s.dataWarehouseSavedQueries],- (queries: DataWarehouseSavedQuery[]) => {- return queries.filter((q) => q.is_materialized)- },+ // The selected tab clamped to what's actually available (null when nothing is).+ activeTab: [+ (s) => [s.selectedTab, s.availableTabs],+ (selectedTab, availableTabs): DataWarehouseTab | null =>+ availableTabs.includes(selectedTab) ? selectedTab : (availableTabs[0] ?? null),],[SIDE_PANEL_CONTEXT_KEY]: [() => [],@@ -241,107 +59,26 @@ export const dataWarehouseSceneLogic = kea<dataWarehouseSceneLogicType>([}),],}),- listeners(({ values, actions }) => ({- setActivityRunningCurrentPage: () => {- actions.checkAutoLoadMoreRunning()- },- setActivityCompletedCurrentPage: () => {- actions.checkAutoLoadMoreCompleted()- },- checkAutoLoadMoreRunning: () => {- const paginationState = values.activityRunningPaginationState- const { isOnLastPage, hasDataOnCurrentPage } = paginationState- const { recentActivityRunningHasMore, runningActivityResponseLoading } = values-- if (- isOnLastPage &&- hasDataOnCurrentPage &&- recentActivityRunningHasMore &&- !runningActivityResponseLoading- ) {- actions.loadMoreRunningActivity()- }- },- checkAutoLoadMoreCompleted: () => {- const paginationState = values.activityCompletedPaginationState- const { isOnLastPage, hasDataOnCurrentPage } = paginationState- const { recentActivityCompletedHasMore, completedActivityResponseLoading } = values-- if (- isOnLastPage &&- hasDataOnCurrentPage &&- recentActivityCompletedHasMore &&- !completedActivityResponseLoading- ) {- actions.loadMoreCompletedActivity()- }- },- loadMoreRunningActivity: async () => {- try {- const currentData = values.recentActivityRunning- const response = await api.dataWarehouse.runningActivity({- limit: 20,- offset: currentData.length,- cutoff_days: 30,- })- const newData = [...currentData, ...(response.results || [])]- const newResponse = { ...response, results: newData }-- actions.loadRunningActivityResponseSuccess(newResponse)- } catch (error) {- posthog.captureException(error)- }- },- loadMoreCompletedActivity: async () => {- try {- const currentData = values.recentActivityCompleted- const response = await api.dataWarehouse.completedActivity({- limit: 20,- offset: currentData.length,- cutoff_days: 30,- })- const newData = [...currentData, ...(response.results || [])]- const newResponse = { ...response, results: newData }-- actions.loadCompletedActivityResponseSuccess(newResponse)- } catch (error) {- posthog.captureException(error)- }- },- setActiveTab: ({ tab }) => {- if (tab === DataWarehouseTab.DASHBOARD && values.dataOpsDashboardId === null) {- actions.loadDataOpsDashboardId()- }- },- })),- afterMount(({ actions, values }) => {- if (!values.database && !values.databaseLoading) {- actions.loadDatabase()- }- actions.loadSources()- actions.loadRunningActivityResponse()- actions.loadCompletedActivityResponse()- actions.loadTotalRowsStats()- actions.loadJobStats({ days: 7 })- actions.loadBilling()- }),urlToAction(({ actions, values }) => ({[urls.dataOps()]: (_, searchParams) => {- const tab = searchParams.tab as DataWarehouseTab | undefined- if (tab && Object.values(DataWarehouseTab).includes(tab) && tab !== values.activeTab) {- actions.setActiveTab(tab)- } else if (!tab && values.activeTab !== DataWarehouseTab.OVERVIEW) {- actions.setActiveTab(DataWarehouseTab.OVERVIEW)+ const requested = searchParams.tab as DataWarehouseTab | undefined+ const target =+ requested && values.availableTabs.includes(requested)+ ? requested+ : (values.availableTabs[0] ?? DataWarehouseTab.SETTINGS)+ if (target !== values.selectedTab) {+ actions.setActiveTab(target)}},})),actionToUrl(({ values }) => ({setActiveTab: () => {const searchParams = { ...router.values.searchParams }- if (values.activeTab === DataWarehouseTab.OVERVIEW) {- delete searchParams.tab- } else {+ // The default (first available) tab is canonical at /data-ops with no ?tab.+ if (values.activeTab && values.activeTab !== values.availableTabs[0]) {searchParams.tab = values.activeTab+ } else {+ delete searchParams.tab}return [urls.dataOps(), searchParams]},diff --git a/frontend/src/scenes/data-warehouse/scene/DashboardTab.tsx b/frontend/src/scenes/data-warehouse/scene/DashboardTab.tsxdeleted file mode 100644index 680436bc45af..000000000000--- a/frontend/src/scenes/data-warehouse/scene/DashboardTab.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { useValues } from 'kea'-import { combineUrl } from 'kea-router'--import { LemonSkeleton } from '@posthog/lemon-ui'--import { Dashboard } from 'scenes/dashboard/Dashboard'-import { urls } from 'scenes/urls'--import { DashboardPlacement } from '~/types'--import { DataWarehouseTab, dataWarehouseSceneLogic } from '../dataWarehouseSceneLogic'--export function DashboardTab(): JSX.Element {- const { dataOpsDashboardId, dataOpsDashboardIdLoading } = useValues(dataWarehouseSceneLogic)-- if (dataOpsDashboardIdLoading || dataOpsDashboardId === null) {- return (- <div className="flex flex-col gap-4 mt-4">- <LemonSkeleton className="h-48 w-full" />- <LemonSkeleton className="h-48 w-full" />- </div>- )- }-- return (- <Dashboard- id={dataOpsDashboardId.toString()}- placement={DashboardPlacement.DataOps}- backTo={{ url: combineUrl(urls.dataOps(), { tab: DataWarehouseTab.DASHBOARD }).url, name: 'Data ops' }}- />- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx b/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsxdeleted file mode 100644index 0e5fbcdc371b..000000000000--- a/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx+++ /dev/null@@ -1,246 +0,0 @@-import { useActions, useValues } from 'kea'--import { IconInfo } from '@posthog/icons'-import { LemonCard, LemonSegmentedButton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'--import { TZLabel } from 'lib/components/TZLabel'-import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { PaginationControl } from 'lib/lemon-ui/PaginationControl'--import { DataWarehouseSavedQueryOrigin } from '~/queries/schema/schema-general'-import { DataWarehouseActivityRecord } from '~/types'--import { dataWarehouseSceneLogic } from '../dataWarehouseSceneLogic'-import { DataWarehousePricingCard } from './components/DataWarehousePricingCard'-import { JobStatsChart } from './components/JobStatsChart'-import { StatusIcon, StatusTag } from './components/StatusComponents'--const LIST_SIZE = 8--function formatOrigin(origin: DataWarehouseSavedQueryOrigin | null | undefined): string {- if (!origin || origin === DataWarehouseSavedQueryOrigin.DATA_WAREHOUSE) {- return ''- }- return origin.replace(/_/g, ' ')-}--export function OverviewTab(): JSX.Element {- const {- activityRunningPaginationState,- activityCompletedPaginationState,- totalRowsStats,- totalRowsStatsLoading,- tablesLoading,- jobStats,- jobStatsLoading,- runningActivityResponse,- completedActivityResponse,- dataWarehouseSources,- materializedViews,- dataWarehouseProduct,- } = useValues(dataWarehouseSceneLogic)- const { setActivityRunningCurrentPage, setActivityCompletedCurrentPage, loadJobStats } =- useActions(dataWarehouseSceneLogic)-- const activityRunningPagination = {- currentPage: activityRunningPaginationState.currentPage,- pageCount: activityRunningPaginationState.pageCount,- dataSourcePage: activityRunningPaginationState.dataSourcePage,- currentStartIndex: activityRunningPaginationState.currentStartIndex,- currentEndIndex: activityRunningPaginationState.currentEndIndex,- entryCount: activityRunningPaginationState.entryCount,- setCurrentPage: setActivityRunningCurrentPage,- pagination: { pageSize: LIST_SIZE },- }-- const activityCompletedPagination = {- currentPage: activityCompletedPaginationState.currentPage,- pageCount: activityCompletedPaginationState.pageCount,- dataSourcePage: activityCompletedPaginationState.dataSourcePage,- currentStartIndex: activityCompletedPaginationState.currentStartIndex,- currentEndIndex: activityCompletedPaginationState.currentEndIndex,- entryCount: activityCompletedPaginationState.entryCount,- setCurrentPage: setActivityCompletedCurrentPage,- pagination: { pageSize: LIST_SIZE },- }-- const activityColumns: LemonTableColumns<DataWarehouseActivityRecord> = [- {- title: 'Activity',- key: 'name',- render: (_, activity) => {- const formattedOrigin = formatOrigin(activity.origin)- const tagText = formattedOrigin ? `${activity.type} created by ${formattedOrigin}` : activity.type- return (- <div className="flex items-center gap-1">- <StatusIcon status={activity.status} />- <span>{activity.name}</span>- <LemonTag size="medium" type="muted" className="px-1 rounded-lg ml-1">- {tagText}- </LemonTag>- </div>- )- },- },- {- title: 'When',- key: 'created_at',- tooltip: 'Time when this job was created',- render: (_, activity) => <TZLabel time={activity.created_at} />,- },- {- title: 'Rows',- key: 'rows',- align: 'right',- tooltip: 'Number of rows processed in this job',- render: (_, activity) => (activity.rows !== null ? activity.rows.toLocaleString() : '0'),- },- {- title: 'Status',- key: 'status',- align: 'right',- render: (_, activity) => <StatusTag status={activity.status} />,- },- ]-- return (- <>- <div className="grid grid-cols-1 md:grid-cols-3 gap-4">- <LemonCard className="p-4 hover:transform-none">- <div className="flex items-start gap-1">- <div className="text-sm text-muted">Rows processed</div>- <Tooltip- title="Total rows processed this month by all data sources and materialized views"- placement="bottom"- >- <IconInfo className="text-muted mt-0.5" />- </Tooltip>- </div>- <div className="text-2xl font-semibold mt-1 flex items-center gap-2">- {totalRowsStatsLoading && !totalRowsStats?.total_rows ? (- <Spinner className="text-muted" />- ) : (- (totalRowsStats?.total_rows ?? 0).toLocaleString()- )}- </div>- </LemonCard>-- <LemonCard className="p-4 hover:transform-none">- <div className="flex items-center justify-between">- <div className="text-sm text-muted">Data sources</div>- {jobStats && jobStats.external_data_jobs.running > 0 && (- <LemonTag type="primary" size="small">- {jobStats.external_data_jobs.running} syncing- </LemonTag>- )}- </div>- <div className="text-2xl font-semibold mt-1 flex items-center gap-2">- {tablesLoading && !dataWarehouseSources ? (- <Spinner className="text-muted" />- ) : (- (dataWarehouseSources?.results?.length ?? 0)- )}- </div>- </LemonCard>-- <LemonCard className="p-4 hover:transform-none">- <div className="flex items-center justify-between">- <div className="text-sm text-muted">Materialized views</div>- {jobStats && jobStats.modeling_jobs.running > 0 && (- <LemonTag type="primary" size="small">- {jobStats.modeling_jobs.running} syncing- </LemonTag>- )}- </div>- <div className="text-2xl font-semibold mt-1 flex items-center gap-2">- {tablesLoading && !materializedViews ? (- <Spinner className="text-muted" />- ) : (- (materializedViews?.length ?? 0)- )}- </div>- </LemonCard>- </div>-- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mt-4">- {/* Pricing breakdown - 1/3 width */}- <div className="lg:col-span-1">- <DataWarehousePricingCard product={dataWarehouseProduct} />- </div>-- {/* Sync Success Rate - 2/3 width */}- <div className="lg:col-span-2">- <LemonCard className="p-4 hover:transform-none min-h-96 flex flex-col h-full">- <div className="flex items-center justify-between mb-4 flex-shrink-0">- <div className="flex items-center gap-2">- <div className="flex items-start gap-1">- <div className="text-lg font-medium">Sync success rate</div>- </div>- {jobStatsLoading && <Spinner className="text-muted" />}- </div>- <LemonSegmentedButton- size="xsmall"- value={jobStats?.days ?? 7}- onChange={(value) => loadJobStats({ days: value as 1 | 7 | 30 })}- options={[- { value: 1, label: '24h' },- { value: 7, label: '7d' },- { value: 30, label: '30d' },- ]}- />- </div>- {jobStats && (- <div className="flex-1 min-h-0">- <JobStatsChart jobStats={jobStats} />- </div>- )}- </LemonCard>- </div>- </div>-- <div className="mt-6 mb-2">- <h2 className="text-xl font-semibold">Source and materialization jobs</h2>- </div>-- <LemonCard className="hover:transform-none mt-4">- <div className="flex items-center gap-2 pb-2">- <span className="font-medium text-lg">Currently running</span>- {tablesLoading && runningActivityResponse !== null && <Spinner className="text-muted" />}- </div>- <LemonTable- dataSource={activityRunningPagination.dataSourcePage as DataWarehouseActivityRecord[]}- columns={activityColumns}- rowKey={(r) => `${r.type}-${r.name}-${r.created_at}`}- loading={tablesLoading && runningActivityResponse === null}- loadingSkeletonRows={3}- emptyState="No currently running activities"- />- {activityRunningPagination.entryCount > 0 && (- <div className="px-4 pb-4">- <PaginationControl {...activityRunningPagination} nouns={['activity', 'activities']} />- </div>- )}- </LemonCard>-- <LemonCard className="hover:transform-none mt-4">- <div className="flex items-center gap-2 pb-2">- <span className="font-medium text-lg">Recently completed</span>- {tablesLoading && completedActivityResponse !== null && <Spinner className="text-muted" />}- </div>- <LemonTable- dataSource={activityCompletedPagination.dataSourcePage as DataWarehouseActivityRecord[]}- columns={activityColumns}- rowKey={(r) => `${r.type}-${r.name}-${r.created_at}`}- loading={tablesLoading && completedActivityResponse === null}- loadingSkeletonRows={3}- emptyState="No recently completed activities"- />- {activityCompletedPagination.entryCount > 0 && (- <div className="px-4 pb-4">- <PaginationControl {...activityCompletedPagination} nouns={['activity', 'activities']} />- </div>- )}- </LemonCard>- </>- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsxindex 81cd01c6b273..12d4aecbae7e 100644--- a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx+++ b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx@@ -3,6 +3,8 @@ import { useActions, useValues } from 'kea'import { IconCheck, IconX } from '@posthog/icons'import { CodeSnippet } from 'lib/components/CodeSnippet'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { OrganizationMembershipLevel } from 'lib/constants'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'@@ -11,11 +13,14 @@ import { LemonLabel } from 'lib/lemon-ui/LemonLabel'import { LemonTag } from 'lib/lemon-ui/LemonTag'import { Spinner } from 'lib/lemon-ui/Spinner'-import { DataWarehouseProvisioningConnection, DataWarehouseProvisioningState } from '~/types'+import type {+ WarehouseConnectionApi,+ WarehouseStatusResponseStateEnumApi,+} from 'products/data_warehouse/frontend/generated/api.schemas'import { warehouseProvisioningLogic } from './warehouseProvisioningLogic'-function stateToTagType(state: DataWarehouseProvisioningState): 'success' | 'warning' | 'danger' | 'default' {+function stateToTagType(state: WarehouseStatusResponseStateEnumApi): 'success' | 'warning' | 'danger' | 'default' {switch (state) {case 'ready':return 'success'@@ -31,7 +36,7 @@ function stateToTagType(state: DataWarehouseProvisioningState): 'success' | 'war}}-function ConnectionDetails({ connection }: { connection: DataWarehouseProvisioningConnection }): JSX.Element {+function ConnectionDetails({ connection }: { connection: WarehouseConnectionApi }): JSX.Element {const { host, port, database, username } = connectionconst psqlCmd = `psql "host=${host} port=${port} dbname=${database} user=${username} sslmode=require"`@@ -66,10 +71,14 @@ function ConnectionDetails({ connection }: { connection: DataWarehouseProvisioni</div><div><LemonLabel>Connect with psql</LemonLabel>- <CodeSnippet compact thing="psql command">+ <CodeSnippet compact wrap thing="psql command">{psqlCmd}</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>)}@@ -86,26 +95,31 @@ export function SettingsTab(): JSX.Element {databaseNameChecking,isValidDatabaseName,canProvision,+ canRetryProvision,retryDatabaseName,initialPassword,isResettingPassword,} = useValues(warehouseProvisioningLogic)const { provisionWarehouse, deprovisionWarehouse, setDatabaseName, clearInitialPassword, resetPassword } =useActions(warehouseProvisioningLogic)+ const deprovisionRestrictionReason = useRestrictedArea({+ scope: RestrictionScope.Organization,+ minimumAccessLevel: OrganizationMembershipLevel.Admin,+ })const hasWarehouse = warehouseStatus && warehouseStatus.state !== 'deleted'const isReady = warehouseStatus?.state === 'ready'const isFailed = warehouseStatus?.state === 'failed'const showProvisionForm = !hasWarehouse || isFailed- const canRetryProvision = !!retryDatabaseName && /^[a-z][a-z0-9_-]{2,62}$/.test(retryDatabaseName)return (<div className="mt-4 space-y-4 max-w-160"><div>- <h2 className="mb-2">Managed Warehouse</h2>+ <h2 className="mb-2">Managed warehouse</h2>{!isReady && (<p className="text-muted mb-4">- Provision a dedicated data warehouse with Aurora, S3, and isolated compute for your team.+ Provision a dedicated data warehouse with Aurora, S3, and isolated compute for your+ organization. It's shared by every project in the organization.</p>)}</div>@@ -134,7 +148,7 @@ export function SettingsTab(): JSX.Element {</LemonBanner>)}<div>- <LemonLabel>Database name</LemonLabel>+ <LemonLabel>Warehouse name</LemonLabel><div className="flex items-center gap-2"><LemonInputvalue={databaseName}@@ -166,15 +180,16 @@ export function SettingsTab(): JSX.Element {)}{databaseName && !isValidDatabaseName && (<p className="text-danger text-xs mt-1">- Must be 3-63 characters, start with a lowercase letter, and contain only lowercase- letters, numbers, hyphens, or underscores.+ Must be 3-63 characters: lowercase letters, numbers, and hyphens, starting with a letter+ and ending with a letter or number.</p>)}{(!databaseName ||(isValidDatabaseName && (databaseNameChecking || databaseNameAvailable === true))) && (<p className="text-muted text-xs mt-1">- Unique name for your database. This is what you'll use in <code>dbname=</code> when- connecting.+ Unique name for your warehouse. It becomes the subdomain of your connection host (e.g.{' '}+ <code>my-warehouse.dw.us.postwh.com</code>). You always connect with{' '}+ <code>dbname=ducklake</code>.</p>)}</div>@@ -196,7 +211,7 @@ export function SettingsTab(): JSX.Element {? 'Retry managed warehouse provisioning?': 'Provision managed warehouse?',description:- 'This will create dedicated AWS resources (Aurora database, S3 bucket, IAM roles) for your team. This typically takes 5-15 minutes.',+ 'This will create dedicated AWS resources (Aurora database, S3 bucket, IAM roles) for your organization, shared by every project in it. This typically takes 5-15 minutes.',primaryButton: {children: isFailed ? 'Retry provisioning' : 'Provision',onClick: () => provisionWarehouse({ databaseName: retryDatabaseName }),@@ -274,11 +289,12 @@ export function SettingsTab(): JSX.Element {type="secondary"status="danger"loading={isDeprovisioning}+ disabledReason={deprovisionRestrictionReason ?? undefined}onClick={() => {LemonDialog.open({title: 'Deprovision managed warehouse?',description:- 'This will delete all AWS resources (Aurora database, S3 bucket, IAM roles) for your team. This action cannot be undone.',+ 'This will delete all AWS resources (Aurora database, S3 bucket, IAM roles) for your organization and every project in it. This action cannot be undone.',primaryButton: {children: 'Deprovision',status: 'danger',diff --git a/frontend/src/scenes/data-warehouse/scene/components/DataWarehousePricingCard.tsx b/frontend/src/scenes/data-warehouse/scene/components/DataWarehousePricingCard.tsxdeleted file mode 100644index fbd142083483..000000000000--- a/frontend/src/scenes/data-warehouse/scene/components/DataWarehousePricingCard.tsx+++ /dev/null@@ -1,69 +0,0 @@-import { LemonCard } from '@posthog/lemon-ui'--import { compactNumber } from 'lib/utils'--import { BillingProductV2AddonType, BillingProductV2Type } from '~/types'--import { DataWarehouseTierBreakdown } from './DataWarehouseTierBreakdown'--function FreeRowsDisplay({ addon }: { addon: BillingProductV2AddonType }): JSX.Element {- const currentUsage = addon.current_usage-- return (- <div className="border rounded-lg p-4 mb-3 bg-bg-light">- <div className="flex flex-col items-center justify-between">- <div>- <div className="font-medium text-sm mb-1">Free historical rows</div>- </div>- <div className="text-xl font-semibold ">{`${compactNumber(currentUsage)}`}</div>- </div>- </div>- )-}--const HISTORICAL_ROWS_ADDON_KEY = 'data_warehouse_historical'--export function DataWarehousePricingCard({ product }: { product: BillingProductV2Type | null }): JSX.Element {- if (!product || !product.tiers || product.tiers.length === 0) {- return (- <LemonCard className="hover:transform-none">- <div>- <h2 className="text-xl font-semibold mb-3">Cost breakdown</h2>- <div className="py-8 text-center text-muted">- <div className="mb-2">No billing data available</div>- <div className="text-xs">Cost breakdown will appear when you have usage data</div>- </div>- </div>- </LemonCard>- )- }-- const currentTotal = parseFloat(product.current_amount_usd || '0')- const projectedTotal = parseFloat(product.projected_amount_usd || '0')- const hasProjected = projectedTotal !== currentTotal-- // Find the data warehouse historical addon- const historicalAddon = product.addons?.find((addon) => addon.type === HISTORICAL_ROWS_ADDON_KEY)-- return (- <LemonCard className="hover:transform-none p-4">- <div className="pb-4">- <h2 className="text-lg font-medium mb-3">Cost breakdown</h2>- <div className="flex items-center justify-between py-3 px-4 bg-bg-3000 rounded border">- <div className="text-center flex-1">- <div className="text-xs text-muted mb-1">Current period</div>- <div className="text-2xl font-bold">${currentTotal.toFixed(2)}</div>- </div>- {hasProjected && (- <div className="text-center flex-1">- <div className="text-xs text-muted mb-1">Projected total</div>- <div className="text-2xl font-bold text-muted-3000">${projectedTotal.toFixed(2)}</div>- </div>- )}- </div>- </div>- {historicalAddon && <FreeRowsDisplay addon={historicalAddon} />}- <DataWarehouseTierBreakdown product={product} />- </LemonCard>- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/components/DataWarehouseTierBreakdown.tsx b/frontend/src/scenes/data-warehouse/scene/components/DataWarehouseTierBreakdown.tsxdeleted file mode 100644index d6d4df5ad455..000000000000--- a/frontend/src/scenes/data-warehouse/scene/components/DataWarehouseTierBreakdown.tsx+++ /dev/null@@ -1,154 +0,0 @@-import { Tooltip } from 'lib/lemon-ui/Tooltip'-import { compactNumber } from 'lib/utils'--import { BillingProductV2Type, BillingTierType } from '~/types'--function formatPrice(price: string | number): string {- const numPrice = typeof price === 'string' ? parseFloat(price) : price- if (numPrice === 0) {- return 'Free'- }- return `$${numPrice.toFixed(6).replace(/\.?0+$/, '')}`-}--function getTierName(tier: BillingTierType, index: number, tiers: BillingTierType[]): string {- if (index === 0 && tier.up_to) {- return `First ${compactNumber(tier.up_to)} rows`- }-- const previousTier = index > 0 ? tiers[index - 1] : null- const start = previousTier?.up_to ? compactNumber(previousTier.up_to) : '0'-- if (tier.up_to) {- return `${start} - ${compactNumber(tier.up_to)} rows`- }-- return `${start}+ rows`-}--type TierGaugeProps = {- tier: BillingTierType- index: number- tiers: BillingTierType[]- unit: string-}--function TierGauge({ tier, index, tiers, unit }: TierGaugeProps): JSX.Element {- const tierName = getTierName(tier, index, tiers)- const unitPrice = parseFloat(tier.unit_amount_usd || '0')- const currentCost = parseFloat(tier.current_amount_usd || '0')-- const previousTier = index > 0 ? tiers[index - 1] : null- const tierStart = previousTier?.up_to || 0- const tierCapacity = tier.up_to ? tier.up_to - tierStart : Math.max(tier.current_usage, tier.projected_usage || 0)-- const currentPercentage = tierCapacity === 0 ? 0 : Math.min(100, (tier.current_usage / tierCapacity) * 100)- const projectedPercentage =- tier.projected_usage !== null && tierCapacity > 0- ? Math.min(100, (tier.projected_usage / tierCapacity) * 100)- : currentPercentage-- const hasProjected = tier.projected_usage !== null && tier.projected_usage !== tier.current_usage- const projectedCost = parseFloat(tier.projected_amount_usd || '0')-- return (- <div className="border rounded-lg p-4 bg-bg-light hover:bg-bg-3000 transition-colors">- <div className="flex items-start justify-between mb-4">- <div className="flex-1">- <div className="font-medium text-sm mb-1">{tierName}</div>- <div className="text-xs text-muted">- {unitPrice === 0 ? (- 'Free tier'- ) : (- <>- {formatPrice(unitPrice)} per {unit}- </>- )}- </div>- </div>- <div className="text-right">- <div className="text-xl font-semibold">${currentCost.toFixed(2)}</div>- <div className="text-xs text-muted">{compactNumber(tier.current_usage)} rows</div>- </div>- </div>-- <div className="relative h-2 bg-border-light rounded overflow-hidden mb-3">- {/* Current usage bar */}- <Tooltip- title={`Current: ${compactNumber(tier.current_usage)} rows ($${currentCost.toFixed(2)})`}- placement="top"- >- <div- className="absolute top-0 left-0 bottom-0 rounded z-[2] transition-all duration-700"- // eslint-disable-next-line react/forbid-dom-props- style={{- width: `${currentPercentage}%`,- background: 'var(--brand-blue)',- transitionTimingFunction: 'cubic-bezier(0.15, 0.15, 0.2, 1)',- }}- />- </Tooltip>-- {/* Projected usage bar (if different) */}- {hasProjected && (- <Tooltip- title={`Projected: ${compactNumber(tier.projected_usage || 0)} rows ($${projectedCost.toFixed(2)})`}- placement="top"- >- <div- className="absolute top-0 left-0 bottom-0 rounded opacity-50 z-[1] transition-all duration-700"- // eslint-disable-next-line react/forbid-dom-props- style={{- width: `${projectedPercentage}%`,- background:- 'repeating-linear-gradient(-45deg, var(--data-color-1), var(--data-color-1) 0.5rem, var(--data-color-1-hover) 0.5rem, var(--data-color-1-hover) 1rem)',- transitionTimingFunction: 'cubic-bezier(0.15, 0.15, 0.2, 1)',- }}- />- </Tooltip>- )}-- {/* Labels */}- <div className="flex flex-col gap-1 mt-2 text-sm">- <div className="flex items-center gap-2">- <span- className="w-2.5 h-2.5 rounded-full flex-shrink-0"- // eslint-disable-next-line react/forbid-dom-props- style={{ background: 'var(--brand-blue)' }}- />- <span className="font-medium">{compactNumber(tier.current_usage)} rows</span>- </div>- {hasProjected && (- <div className="flex items-center gap-2">- <span- className="w-2.5 h-2.5 rounded-full flex-shrink-0"- // eslint-disable-next-line react/forbid-dom-props- style={{- background:- 'repeating-linear-gradient(-45deg, var(--data-color-1), var(--data-color-1) 0.125rem, var(--data-color-1-hover) 0.125rem, var(--data-color-1-hover) 0.25rem)',- }}- />- <span className="text-muted">- Projected: {compactNumber(tier.projected_usage || 0)} rows · ${projectedCost.toFixed(2)}- </span>- </div>- )}- </div>- </div>- </div>- )-}--export function DataWarehouseTierBreakdown({ product }: { product: BillingProductV2Type }): JSX.Element {- if (!product.tiers || product.tiers.length === 0) {- return <div className="text-muted">No tier data available</div>- }-- return (- <div className="space-y-3">- {product.tiers.map((tier, index) => (- <TierGauge key={index} tier={tier} index={index} tiers={product.tiers!} unit={product.unit || 'row'} />- ))}- </div>- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/components/JobStatsChart.tsx b/frontend/src/scenes/data-warehouse/scene/components/JobStatsChart.tsxdeleted file mode 100644index 53418c9dcddc..000000000000--- a/frontend/src/scenes/data-warehouse/scene/components/JobStatsChart.tsx+++ /dev/null@@ -1,96 +0,0 @@-import { useMemo } from 'react'--import { LineGraph } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'-import { ChartDisplayType, DataWarehouseJobStats } from '~/types'--interface JobStatsChartProps {- jobStats: DataWarehouseJobStats-}--export function JobStatsChart({ jobStats }: JobStatsChartProps): JSX.Element {- const { xData, yData } = useMemo(() => {- if (!jobStats?.breakdown) {- return { xData: null, yData: [] }- }-- const timestamps = Object.keys(jobStats.breakdown).sort()- const successData = timestamps.map((ts) => jobStats.breakdown[ts].successful)- const failedData = timestamps.map((ts) => jobStats.breakdown[ts].failed)-- const isHourly = jobStats.days === 1-- const labels = timestamps.map((ts) => {- const d = new Date(ts)- if (isHourly) {- return d.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true })- }- return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })- })-- const successColor = getComputedStyle(document.body).getPropertyValue('--success').trim() || '#388600'- const dangerColor = getComputedStyle(document.body).getPropertyValue('--danger').trim() || '#db3707'-- return {- xData: {- column: {- name: 'timestamp',- type: {- name: 'STRING' as const,- isNumerical: false,- },- label: 'Time',- dataIndex: 0,- },- data: labels,- },- yData: [- {- column: {- name: 'successful',- type: { name: 'INTEGER' as const, isNumerical: true },- label: 'Successful',- dataIndex: 0,- },- data: successData,- settings: {- display: {- color: successColor,- displayType: 'bar' as const,- },- },- },- {- column: {- name: 'failed',- type: { name: 'INTEGER' as const, isNumerical: true },- label: 'Failed',- dataIndex: 1,- },- data: failedData,- settings: {- display: {- color: dangerColor,- displayType: 'bar' as const,- },- },- },- ],- }- }, [jobStats])-- if (!jobStats?.breakdown) {- return <div className="relative h-full min-h-48 flex items-center justify-center">No data available</div>- }-- return (- <LineGraph- className="h-full min-h-80"- xData={xData}- yData={yData}- visualizationType={ChartDisplayType.ActionsStackedBar}- chartSettings={{- stackBars100: false,- }}- />- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/components/StatusComponents.tsx b/frontend/src/scenes/data-warehouse/scene/components/StatusComponents.tsxdeleted file mode 100644index 7761a9376ffd..000000000000--- a/frontend/src/scenes/data-warehouse/scene/components/StatusComponents.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { IconCheckCircle } from '@posthog/icons'-import { LemonTag } from '@posthog/lemon-ui'--import { IconCancel, IconExclamation, IconRadioButtonUnchecked, IconSync } from 'lib/lemon-ui/icons'--import { ExternalDataJobStatus } from '~/types'--import { StatusTagSetting } from 'products/data_warehouse/frontend/utils'--export function StatusIcon({ status }: { status?: ExternalDataJobStatus }): JSX.Element {- if (!status) {- return <IconRadioButtonUnchecked className="text-muted" />- }-- if (status === ExternalDataJobStatus.Failed) {- return <IconCancel className="text-danger" />- }- if (status === ExternalDataJobStatus.BillingLimits || status === ExternalDataJobStatus.BillingLimitTooLow) {- return <IconExclamation className="text-warning" />- }- if (status === ExternalDataJobStatus.Running) {- return <IconSync className="animate-spin" />- }- if (status === ExternalDataJobStatus.Completed) {- return <IconCheckCircle className="text-success" />- }- return <IconRadioButtonUnchecked className="text-muted" />-}--export function StatusTag({ status }: { status?: ExternalDataJobStatus }): JSX.Element {- if (!status) {- return (- <LemonTag size="small" type="muted" className="px-1 rounded-lg">- —- </LemonTag>- )- }-- const type = StatusTagSetting[status] || 'muted'-- return (- <LemonTag size="medium" type={type} className="px-1 rounded-lg">- {status}- </LemonTag>- )-}diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.tsnew file mode 100644index 000000000000..fe9bcc67b8de--- /dev/null+++ b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts@@ -0,0 +1,80 @@+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { initKeaTests } from '~/test/init'++import * as dwApi from 'products/data_warehouse/frontend/generated/api'++import { warehouseProvisioningLogic } from './warehouseProvisioningLogic'++describe('warehouseProvisioningLogic', () => {+ let logic: ReturnType<typeof warehouseProvisioningLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve').mockResolvedValue(null as any)+ jest.spyOn(dwApi, 'dataWarehouseCheckDatabaseNameRetrieve').mockResolvedValue({+ name: '',+ available: true,+ } as any)+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it('loads warehouse status on mount', async () => {+ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadWarehouseStatus', 'loadWarehouseStatusSuccess'])+ expect(dwApi.dataWarehouseWarehouseStatusRetrieve).toHaveBeenCalled()+ })++ it('treats a 404 status as no warehouse', async () => {+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve').mockRejectedValueOnce({ status: 404 })++ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadWarehouseStatusSuccess'])+ expect(logic.values.warehouseStatus).toBeNull()+ })++ it('validates database names and gates provisioning on availability', async () => {+ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.setDatabaseName('Bad Name')+ }).toMatchValues({ isValidDatabaseName: false, canProvision: false })++ // Underscores are not valid in a DNS subdomain+ await expectLogic(logic, () => {+ logic.actions.setDatabaseName('bad_name')+ }).toMatchValues({ isValidDatabaseName: false })++ await expectLogic(logic, () => {+ logic.actions.setDatabaseName('valid-name')+ logic.actions.setDatabaseNameAvailable(true)+ }).toMatchValues({ isValidDatabaseName: true, canProvision: true })+ })++ it('surfaces an info message instead of an error when a sibling project already provisioned (409)', async () => {+ jest.spyOn(dwApi, 'dataWarehouseProvisionCreate').mockRejectedValueOnce({ status: 409 })+ const infoToast = jest.spyOn(lemonToast, 'info').mockReturnValue(undefined as any)+ const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue(undefined as any)++ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.provisionWarehouse({ databaseName: 'shared-warehouse' })+ }).toDispatchActions(['provisionWarehouse', 'loadWarehouseStatus', 'provisionWarehouseComplete'])++ expect(infoToast).toHaveBeenCalledTimes(1)+ expect(errorToast).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.tsindex f49b1441c0f3..4fdcd7e038b7 100644--- a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts+++ b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts@@ -1,17 +1,30 @@import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { teamLogic } from 'scenes/teamLogic'-import { DataWarehouseProvisioningStatus } from '~/types'+import {+ dataWarehouseCheckDatabaseNameRetrieve,+ dataWarehouseDeprovisionCreate,+ dataWarehouseProvisionCreate,+ dataWarehouseResetPasswordCreate,+ dataWarehouseWarehouseStatusRetrieve,+} from 'products/data_warehouse/frontend/generated/api'+import type { WarehouseStatusResponseApi } from 'products/data_warehouse/frontend/generated/api.schemas'import type { warehouseProvisioningLogicType } from './warehouseProvisioningLogicType'+// The warehouse name becomes the connection's SNI subdomain (a DNS-1123 label), so it+// mirrors the backend validator in products/data_warehouse/backend/api/managed_warehouse.py:+// 3-63 chars, lowercase alphanumerics and hyphens, starting/ending alphanumeric (no underscores).+const WAREHOUSE_NAME_REGEX = /^[a-z][a-z0-9-]{1,61}[a-z0-9]$/+const databaseNameStorageKey = (teamId: number | null): string =>`warehouse-provisioning-database-name-${teamId ?? 'unknown'}`+const currentProjectId = (): string => String(teamLogic.values.currentTeamId)+export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([path(['scenes', 'data-warehouse', 'scene', 'warehouseProvisioningLogic']),@@ -35,11 +48,11 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([loaders({warehouseStatus: [- null as DataWarehouseProvisioningStatus | null,+ null as WarehouseStatusResponseApi | null,{loadWarehouseStatus: async () => {try {- return await api.dataWarehouse.warehouseStatus()+ return await dataWarehouseWarehouseStatusRetrieve(currentProjectId())} catch (e: any) {if (e.status === 404) {return null@@ -137,7 +150,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([return status.state === 'pending' || status.state === 'provisioning' || status.state === 'deleting'},],- isValidDatabaseName: [(s) => [s.databaseName], (name): boolean => /^[a-z][a-z0-9_-]{2,62}$/.test(name)],+ isValidDatabaseName: [(s) => [s.databaseName], (name): boolean => WAREHOUSE_NAME_REGEX.test(name)],retryDatabaseName: [(s) => [s.databaseName, s.lastRequestedDatabaseName],(databaseName, lastRequestedDatabaseName): string => databaseName || lastRequestedDatabaseName || '',@@ -146,6 +159,10 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([(s) => [s.isValidDatabaseName, s.databaseNameAvailable],(valid, available): boolean => valid && available === true,],+ canRetryProvision: [+ (s) => [s.retryDatabaseName],+ (retryDatabaseName): boolean => !!retryDatabaseName && WAREHOUSE_NAME_REGEX.test(retryDatabaseName),+ ],}),listeners(({ actions, values }) => {@@ -156,7 +173,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([if (debounceTimer) {clearTimeout(debounceTimer)}- if (/^[a-z][a-z0-9_-]{2,62}$/.test(name)) {+ if (WAREHOUSE_NAME_REGEX.test(name)) {actions.setDatabaseNameChecking(true)debounceTimer = setTimeout(() => {actions.checkDatabaseName(name)@@ -166,7 +183,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([checkDatabaseName: async ({ name }) => {try {- const result = await api.dataWarehouse.checkDatabaseName(name)+ const result = await dataWarehouseCheckDatabaseNameRetrieve(currentProjectId(), { name })if (values.databaseName === name) {actions.setDatabaseNameAvailable(result.available)}@@ -180,7 +197,9 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([actions.setLastRequestedDatabaseName(databaseName)window.localStorage.setItem(databaseNameStorageKey(teamLogic.values.currentTeamId), databaseName)try {- const result = await api.dataWarehouse.provisionWarehouse(databaseName)+ const result = await dataWarehouseProvisionCreate(currentProjectId(), {+ database_name: databaseName,+ })if (result.password) {actions.setInitialPassword(result.password)}@@ -188,14 +207,21 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([actions.loadWarehouseStatus()actions.pollStatus()} catch (e: any) {- lemonToast.error(`Failed to provision warehouse: ${e.message || 'Unknown error'}`)+ if (e.status === 409) {+ // Another project in this organization already provisioned the shared warehouse.+ lemonToast.info('This organization already has a managed warehouse')+ actions.loadWarehouseStatus()+ actions.pollStatus()+ } else {+ lemonToast.error(`Failed to provision warehouse: ${e.message || 'Unknown error'}`)+ }}actions.provisionWarehouseComplete()},resetPassword: async () => {try {- const result = await api.dataWarehouse.resetPassword()+ const result = await dataWarehouseResetPasswordCreate(currentProjectId())if (result.password) {actions.setInitialPassword(result.password)}@@ -209,7 +235,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([deprovisionWarehouse: async () => {window.localStorage.removeItem(databaseNameStorageKey(teamLogic.values.currentTeamId))try {- await api.dataWarehouse.deprovisionWarehouse()+ await dataWarehouseDeprovisionCreate(currentProjectId())lemonToast.success('Warehouse deprovisioning started')actions.loadWarehouseStatus()actions.pollStatus()diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 048c6e9c613e..dbb56ca0d29d 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7365,28 +7365,6 @@ export interface DataWarehouseActivityRecord {origin?: DataWarehouseSavedQueryOrigin | null}-export type DataWarehouseProvisioningState = 'pending' | 'provisioning' | 'ready' | 'failed' | 'deleting' | 'deleted'--export interface DataWarehouseProvisioningConnection {- host: string- port: number- database: string- username: string-}--export interface DataWarehouseProvisioningStatus {- org_id: string- state: DataWarehouseProvisioningState- status_message: string- s3_state: DataWarehouseProvisioningState- metadata_store_state: DataWarehouseProvisioningState- identity_state: DataWarehouseProvisioningState- secrets_state: DataWarehouseProvisioningState- ready_at: string | null- failed_at: string | null- connection: DataWarehouseProvisioningConnection | null-}-export type HeatmapType = 'screenshot' | 'iframe' | 'recording'export type HeatmapStatus = 'processing' | 'completed' | 'failed'diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 6d49343cbf78..74e1aab26ab2 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -66,7 +66,6 @@ LLM_ANALYTICS_INTERNAL_TEAM_ID: int = 2# Duckgres - URL, internal secret, and PG endpoint for the managed warehouse serviceDUCKGRES_API_URL: str | None = get_from_env("DUCKGRES_API_URL", optional=True)DUCKGRES_INTERNAL_SECRET: str | None = get_from_env("DUCKGRES_INTERNAL_SECRET", optional=True)-DUCKGRES_PG_URL: str | None = get_from_env("DUCKGRES_PG_URL", optional=True)DUCKGRES_PG_PORT: int = get_from_env("DUCKGRES_PG_PORT", 5432, type_cast=int)# Bulk deletion operations can be disabled during database migrationsdiff --git a/products/data_warehouse/backend/api/data_warehouse.py b/products/data_warehouse/backend/api/data_warehouse.pyindex 405b4cc9ff7e..0017fe72168a 100644--- a/products/data_warehouse/backend/api/data_warehouse.py+++ b/products/data_warehouse/backend/api/data_warehouse.py@@ -2,14 +2,11 @@ from datetime import datetime, timedeltafrom typing import castfrom zoneinfo import ZoneInfo-from django.conf import settings as django_settingsfrom django.db import connectionfrom django.db.models import Count, Q, Sumfrom django.db.models.functions import TruncDate, TruncHour-import requests as http_requestsimport structlog-import posthoganalyticsfrom dateutil import parserfrom drf_spectacular.utils import extend_schema, inline_serializerfrom opentelemetry import trace@@ -27,14 +24,15 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.helpers.dashboard_templates import create_data_ops_dashboard+from posthog.models.organization import OrganizationMembershipfrom posthog.models.team.extensions import get_or_create_team_extension-from posthog.security.outbound_proxy import internal_requests as _internal_requestsfrom posthog.utils import convert_property_value, flattenfrom products.batch_exports.backend.models.batch_export import BatchExportRunfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionState, HogFunctionTypefrom products.data_modeling.backend.models.data_modeling_job import DataModelingJobfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_warehouse.backend.api import managed_warehousefrom products.data_warehouse.backend.models.team_data_warehouse_config import TeamDataWarehouseConfigfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -57,6 +55,23 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "warehouse_view"serializer_class = _FallbackSerializer+ def _require_organization_admin(self, request: Request, action: str) -> Response | None:+ if not request.user.is_authenticated:+ return Response(+ {"error": f"Only organization admins can {action} the managed warehouse"},+ status=status.HTTP_403_FORBIDDEN,+ )++ membership = OrganizationMembership.objects.filter(+ organization_id=self.team.organization_id, user=request.user+ ).first()+ if membership is None or membership.level < OrganizationMembership.Level.ADMIN:+ return Response(+ {"error": f"Only organization admins can {action} the managed warehouse"},+ status=status.HTTP_403_FORBIDDEN,+ )+ return None+@action(methods=["GET"], detail=False, required_scopes=["query:read"])def property_values(self, request: Request, **kwargs) -> Response:with (@@ -798,94 +813,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):first_dashboard = config.overview_dashboards.order_by("id").first()return Response({"dashboard_id": first_dashboard.id if first_dashboard else None})- # --- Managed warehouse provisioning (proxied to duckgres) ----- def _is_managed_warehouse_enabled(self) -> bool:- try:- return posthoganalytics.feature_enabled(- "provision-managed-warehouse-beta",- str(self.team.uuid),- groups={- "organization": str(self.team.organization_id),- "project": str(self.team.id),- },- group_properties={- "organization": {- "id": str(self.team.organization_id),- },- "project": {- "id": str(self.team.id),- },- },- only_evaluate_locally=True,- send_feature_flag_events=False,- )- except Exception:- logger.warning("Failed to evaluate managed warehouse feature flag", team_id=self.team_id)- return False-- def _provisioning_request(- self, method: str, path: str, json_body: dict | None = None, params: dict | None = None, timeout: int = 30- ) -> Response:- """Proxy a request to the duckgres provisioning API."""- if not self._is_managed_warehouse_enabled():- return Response({"error": "This feature is not enabled"}, status=status.HTTP_403_FORBIDDEN)-- base_url = getattr(django_settings, "DUCKGRES_API_URL", None)- token = getattr(django_settings, "DUCKGRES_INTERNAL_SECRET", None)-- if not base_url:- logger.warning("Provisioning request rejected: DUCKGRES_API_URL not configured", team_id=self.team_id)- return Response(- {"error": "Managed warehouse provisioning is not configured"},- status=status.HTTP_501_NOT_IMPLEMENTED,- )-- # Use the PostHog team_id as the duckgres org identifier.- # Paths starting with / are org-scoped, otherwise treated as absolute API paths.- team_id = str(self.team_id)- if path.startswith("/"):- url = f"{base_url.rstrip('/')}/api/v1/orgs/{team_id}{path}"- else:- url = f"{base_url.rstrip('/')}/api/v1/{path}"- headers = {}- if token:- headers["X-Duckgres-Internal-Secret"] = token-- try:- resp = _internal_requests.request(- method, url, json=json_body, params=params, headers=headers, timeout=timeout- )- except http_requests.Timeout:- logger.warning("Provisioning API timeout", method=method, path=path, team_id=team_id)- return Response({"error": "Provisioning service timed out"}, status=status.HTTP_504_GATEWAY_TIMEOUT)- except http_requests.ConnectionError:- logger.warning("Provisioning API connection refused", method=method, path=path, team_id=team_id)- return Response({"error": "Provisioning service is unreachable"}, status=status.HTTP_502_BAD_GATEWAY)- except Exception:- logger.exception("Provisioning API unexpected error", method=method, path=path, team_id=team_id)- return Response(- {"error": "An error occurred contacting the provisioning service"},- status=status.HTTP_500_INTERNAL_SERVER_ERROR,- )-- if resp.status_code >= 400:- logger.warning(- "Provisioning API returned error",- method=method,- path=path,- team_id=team_id,- status_code=resp.status_code,- response_body=resp.text[:500],- )- else:- logger.info("Provisioning API request succeeded", method=method, path=path, team_id=team_id)-- try:- body = resp.json()- except ValueError:- body = {"error": resp.text[:500]}- return Response(body, status=resp.status_code)+ # --- Managed warehouse provisioning (proxied to duckgres, see managed_warehouse.py) ---@extend_schema(request=inline_serializer(@@ -893,58 +821,84 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):fields={"database_name": serializers.CharField(help_text="Name for the new database")},),responses={- 200: inline_serializer(+ 202: inline_serializer("ProvisionWarehouseResponse",fields={- "status": serializers.CharField(),- "team": serializers.CharField(),+ "status": serializers.CharField(+ help_text="Provisioning lifecycle message, e.g. 'provisioning started'"+ ),+ "org": serializers.CharField(help_text="duckgres org identifier (the PostHog organization id)"),+ "username": serializers.CharField(help_text="Root database username"),+ "password": serializers.CharField(+ help_text="Root database password — returned only here at provision time and on reset-password"+ ),},)},)@action(methods=["POST"], detail=False, required_scopes=["warehouse_view:write"])def provision(self, request: Request, **kwargs) -> Response:- """Start provisioning a managed warehouse for this team."""- database_name = request.data.get("database_name")- if not database_name:- return Response({"error": "database_name is required"}, status=status.HTTP_400_BAD_REQUEST)- return self._provisioning_request(- "POST",- "/provision",- json_body={- "database_name": database_name,- "metadata_store": {"type": "aurora", "aurora": {"min_acu": 0.5, "max_acu": 2}},- },- )+ """Start provisioning a managed warehouse for this organization (shared by all its teams)."""+ admin_error = self._require_organization_admin(request, "provision")+ if admin_error is not None:+ return admin_error+ return managed_warehouse.provision(self.team.organization_id, request.data.get("database_name"))@extend_schema(responses={- 200: inline_serializer(+ 202: inline_serializer("DeprovisionWarehouseResponse",fields={- "status": serializers.CharField(),- "team": serializers.CharField(),+ "status": serializers.CharField(+ help_text="Deprovisioning lifecycle message, e.g. 'deprovisioning started'"+ ),+ "org": serializers.CharField(help_text="duckgres org identifier (the PostHog organization id)"),},)},)@action(methods=["POST"], detail=False, required_scopes=["warehouse_view:write"])def deprovision(self, request: Request, **kwargs) -> Response:- """Start deprovisioning the managed warehouse for this team."""- return self._provisioning_request("POST", "/deprovision")+ """Start deprovisioning the organization's managed warehouse. Restricted to organization admins."""+ admin_error = self._require_organization_admin(request, "deprovision")+ if admin_error is not None:+ return admin_error+ return managed_warehouse.deprovision(self.team.organization_id)@extend_schema(responses={200: inline_serializer("WarehouseStatusResponse",fields={- "team_name": serializers.CharField(),+ "org_id": serializers.CharField(help_text="duckgres org identifier (the PostHog organization id)"),"state": serializers.ChoiceField(- choices=["pending", "provisioning", "ready", "failed", "deleting", "deleted"]+ choices=["pending", "provisioning", "ready", "failed", "deleting", "deleted"],+ help_text="Overall provisioning lifecycle state",+ ),+ "status_message": serializers.CharField(help_text="Human-readable detail for the current state"),+ "s3_state": serializers.CharField(help_text="Object-store sub-resource provisioning state"),+ "metadata_store_state": serializers.CharField(+ help_text="Metadata-store sub-resource provisioning state"+ ),+ "identity_state": serializers.CharField(+ help_text="Worker identity sub-resource provisioning state"+ ),+ "secrets_state": serializers.CharField(help_text="Credentials sub-resource provisioning state"),+ "ready_at": serializers.DateTimeField(allow_null=True, help_text="When the warehouse became ready"),+ "failed_at": serializers.DateTimeField(allow_null=True, help_text="When provisioning failed"),+ "connection": inline_serializer(+ "WarehouseConnection",+ fields={+ "host": serializers.CharField(+ help_text="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'"),+ "username": serializers.CharField(help_text="Root database username"),+ },+ required=False,+ allow_null=True,),- "status_message": serializers.CharField(),- "ready_at": serializers.DateTimeField(allow_null=True),- "failed_at": serializers.DateTimeField(allow_null=True),},)},@@ -952,15 +906,7 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@action(methods=["GET"], detail=False)def warehouse_status(self, request: Request, **kwargs) -> Response:"""Get the current provisioning status of the managed warehouse."""- resp = self._provisioning_request("GET", "/warehouse/status")- # Override connection host/port with the public-facing duckgres PG endpoint- if resp.status_code == 200 and isinstance(resp.data, dict) and resp.data.get("connection"):- pg_url = getattr(django_settings, "DUCKGRES_PG_URL", None)- pg_port = getattr(django_settings, "DUCKGRES_PG_PORT", 5432)- if pg_url:- resp.data["connection"]["host"] = pg_url- resp.data["connection"]["port"] = pg_port- return resp+ return managed_warehouse.status_for(self.team.organization_id)@extend_schema(responses={@@ -976,7 +922,10 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@action(methods=["POST"], detail=False, url_path="reset-password", required_scopes=["warehouse_view:write"])def reset_password(self, request: Request, **kwargs) -> Response:"""Reset the root password for the managed warehouse."""- return self._provisioning_request("POST", "/reset-password")+ admin_error = self._require_organization_admin(request, "reset the root password for")+ if admin_error is not None:+ return admin_error+ return managed_warehouse.reset_password(self.team.organization_id)@extend_schema(parameters=[@@ -998,8 +947,4 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):@action(methods=["GET"], detail=False, url_path="check-database-name")def check_database_name(self, request: Request, **kwargs) -> Response:"""Check if a database name is available."""- name = request.query_params.get("name")- if not name:- return Response({"error": "name query parameter is required"}, status=status.HTTP_400_BAD_REQUEST)-- return self._provisioning_request("GET", "database-name/check", params={"name": name}, timeout=10)+ return managed_warehouse.check_name(self.team.organization_id, request.query_params.get("name"))diff --git a/products/data_warehouse/backend/api/managed_warehouse.py b/products/data_warehouse/backend/api/managed_warehouse.pynew file mode 100644index 000000000000..83c04588f468--- /dev/null+++ b/products/data_warehouse/backend/api/managed_warehouse.py@@ -0,0 +1,219 @@+"""Adapter for the org-scoped managed warehouse provisioning API (duckgres).++Centralizes everything the `DataWarehouseViewSet` provisioning actions need so the+ViewSet stays a thin pass-through: org-scoped feature gating, duckgres org-URL+construction and request/error mapping, warehouse-name validation (shared by provision+and availability checks), and connection presentation.++A managed warehouse is shared by every team in an organization, so the duckgres org+identifier is the PostHog `organization_id` and the Data ops feature flag is evaluated+per organization (not per team).+"""++import re+from typing import TypedDict+from uuid import UUID++from django.conf import settings++import requests as http_requests+import structlog+import posthoganalytics+from rest_framework import status+from rest_framework.response import Response++from posthog.security.outbound_proxy import internal_requests++logger = structlog.get_logger(__name__)++DATA_WAREHOUSE_SCENE_FLAG = "data-warehouse-scene"++# The Postgres database to connect to is always "ducklake"; the user-chosen warehouse+# name becomes the SNI subdomain (e.g. my-warehouse.dw.us.postwh.com) and the DNS zone+# is selected by the deployment.+MANAGED_WAREHOUSE_DATABASE = "ducklake"+_MANAGED_WAREHOUSE_DOMAINS = {+ "US": "us.postwh.com",+ "EU": "eu.postwh.com",+ "DEV": "dev.postwh.com",+}++# A warehouse name becomes a DNS-1123 label (the connection's SNI subdomain), so it must+# be lowercase alphanumerics and hyphens, starting and ending alphanumeric — no+# underscores. Mirrors duckgres's own org-id constraint.+WAREHOUSE_NAME_MIN_LENGTH = 3+WAREHOUSE_NAME_MAX_LENGTH = 63+WAREHOUSE_NAME_PATTERN = re.compile(r"^[a-z]([a-z0-9-]*[a-z0-9])?$")+++class PresentedConnection(TypedDict):+ host: str+ port: int+ database: str+ username: str+++def managed_warehouse_domain() -> str:+ deployment = (getattr(settings, "CLOUD_DEPLOYMENT", None) or "").upper()+ return _MANAGED_WAREHOUSE_DOMAINS.get(deployment, "test.local")+++def validate_warehouse_name(name: str | None) -> str | None:+ """Return a human-readable error if `name` is not a valid warehouse name, else None."""+ if not name:+ return "database_name is required"+ if not (WAREHOUSE_NAME_MIN_LENGTH <= len(name) <= WAREHOUSE_NAME_MAX_LENGTH):+ return f"Warehouse name must be {WAREHOUSE_NAME_MIN_LENGTH}-{WAREHOUSE_NAME_MAX_LENGTH} characters"+ if not WAREHOUSE_NAME_PATTERN.match(name):+ return (+ "Warehouse name must be a DNS label: lowercase letters, numbers, and hyphens, "+ "starting and ending with a letter or number"+ )+ return None+++def is_enabled(organization_id: UUID | str) -> bool:+ """Evaluate the managed-warehouse flag for the organization.++ Identity is the organization so every team in the org resolves the same value.+ """+ org_id = str(organization_id)+ try:+ return bool(+ posthoganalytics.feature_enabled(+ DATA_WAREHOUSE_SCENE_FLAG,+ org_id,+ groups={"organization": org_id},+ group_properties={"organization": {"id": org_id}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.warning("Failed to evaluate managed warehouse feature flag", organization_id=org_id)+ return False+++def _present_connection(raw: dict) -> PresentedConnection:+ """Build the public-facing connection from duckgres's raw status connection.++ duckgres returns the org's chosen warehouse name as `database`; that becomes the SNI+ subdomain of the host, and the database to connect to is always "ducklake".+ """+ warehouse_name = raw.get("database")+ host = f"{warehouse_name}.dw.{managed_warehouse_domain()}" if warehouse_name else raw.get("host", "")+ return PresentedConnection(+ host=host,+ port=getattr(settings, "DUCKGRES_PG_PORT", 5432),+ database=MANAGED_WAREHOUSE_DATABASE,+ username=raw.get("username", "root"),+ )+++def _request(+ method: str,+ organization_id: UUID | str,+ path: str,+ json_body: dict | None = None,+ params: dict | None = None,+ timeout: int = 30,+) -> Response:+ """Proxy a request to the duckgres provisioning API, gated on the org's feature flag.++ Paths starting with "/" are org-scoped (`/api/v1/orgs/{org}{path}`); others are global+ API paths (`/api/v1/{path}`).+ """+ if not is_enabled(organization_id):+ return Response({"error": "This feature is not enabled"}, status=status.HTTP_403_FORBIDDEN)++ base_url = getattr(settings, "DUCKGRES_API_URL", None)+ token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)+ org_id = str(organization_id)++ if not base_url:+ logger.warning("Provisioning request rejected: DUCKGRES_API_URL not configured", organization_id=org_id)+ return Response(+ {"error": "Managed warehouse provisioning is not configured"},+ status=status.HTTP_501_NOT_IMPLEMENTED,+ )++ if path.startswith("/"):+ url = f"{base_url.rstrip('/')}/api/v1/orgs/{org_id}{path}"+ else:+ url = f"{base_url.rstrip('/')}/api/v1/{path}"++ headers = {}+ if token:+ headers["X-Duckgres-Internal-Secret"] = token++ try:+ resp = internal_requests.request(method, url, json=json_body, params=params, headers=headers, timeout=timeout)+ except http_requests.Timeout:+ logger.warning("Provisioning API timeout", method=method, path=path, organization_id=org_id)+ return Response({"error": "Provisioning service timed out"}, status=status.HTTP_504_GATEWAY_TIMEOUT)+ except http_requests.ConnectionError:+ logger.warning("Provisioning API connection refused", method=method, path=path, organization_id=org_id)+ return Response({"error": "Provisioning service is unreachable"}, status=status.HTTP_502_BAD_GATEWAY)+ except Exception:+ logger.exception("Provisioning API unexpected error", method=method, path=path, organization_id=org_id)+ return Response(+ {"error": "An error occurred contacting the provisioning service"},+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )++ if resp.status_code >= 400:+ logger.warning(+ "Provisioning API returned error",+ method=method,+ path=path,+ organization_id=org_id,+ status_code=resp.status_code,+ response_body=resp.text[:500],+ )+ else:+ logger.info("Provisioning API request succeeded", method=method, path=path, organization_id=org_id)++ try:+ body = resp.json()+ except ValueError:+ body = {"error": resp.text[:500]}+ return Response(body, status=resp.status_code)+++def provision(organization_id: UUID | str, database_name: str | None) -> Response:+ name_error = validate_warehouse_name(database_name)+ if name_error:+ return Response({"error": name_error}, status=status.HTTP_400_BAD_REQUEST)+ return _request(+ "POST",+ organization_id,+ "/provision",+ json_body={+ "database_name": database_name,+ "ducklake": {"enabled": True},+ "metadata_store": {"type": "cnpg-shard"},+ "data_store": {"type": "s3bucket"},+ },+ )+++def deprovision(organization_id: UUID | str) -> Response:+ return _request("POST", organization_id, "/deprovision")+++def status_for(organization_id: UUID | str) -> Response:+ resp = _request("GET", organization_id, "/warehouse/status")+ if resp.status_code == 200 and isinstance(resp.data, dict) and isinstance(resp.data.get("connection"), dict):+ resp.data["connection"] = _present_connection(resp.data["connection"])+ return resp+++def reset_password(organization_id: UUID | str) -> Response:+ return _request("POST", organization_id, "/reset-password")+++def check_name(organization_id: UUID | str, name: str | None) -> Response:+ name_error = validate_warehouse_name(name)+ if name_error:+ return Response({"error": name_error}, status=status.HTTP_400_BAD_REQUEST)+ return _request("GET", organization_id, "database-name/check", params={"name": name}, timeout=10)diff --git a/products/data_warehouse/backend/api/test/test_managed_warehouse.py b/products/data_warehouse/backend/api/test/test_managed_warehouse.pynew file mode 100644index 000000000000..11a2267db570--- /dev/null+++ b/products/data_warehouse/backend/api/test/test_managed_warehouse.py@@ -0,0 +1,22 @@+from uuid import uuid4++from unittest.mock import MagicMock, patch++from products.data_warehouse.backend.api import managed_warehouse+++@patch("products.data_warehouse.backend.api.managed_warehouse.posthoganalytics.feature_enabled")+def test_is_enabled_uses_data_warehouse_scene_flag(mock_feature_enabled: MagicMock) -> None:+ organization_id = uuid4()+ mock_feature_enabled.return_value = True++ assert managed_warehouse.is_enabled(organization_id) is True++ mock_feature_enabled.assert_called_once_with(+ "data-warehouse-scene",+ str(organization_id),+ groups={"organization": str(organization_id)},+ group_properties={"organization": {"id": str(organization_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )diff --git a/products/data_warehouse/backend/api/test/test_misc_warehouse_viewsets_access_control.py b/products/data_warehouse/backend/api/test/test_misc_warehouse_viewsets_access_control.pyindex a2f2f80d6358..47471fe8fd87 100644--- a/products/data_warehouse/backend/api/test/test_misc_warehouse_viewsets_access_control.py+++ b/products/data_warehouse/backend/api/test/test_misc_warehouse_viewsets_access_control.py@@ -11,6 +11,9 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.response import Response++from posthog.models.organization import OrganizationMembershipfrom products.data_modeling.backend.models.datawarehouse_managed_viewset import DataWarehouseManagedViewSetfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -110,6 +113,60 @@ class TestDataWarehouseViewSetAccessControl(WarehouseAccessControlTestMixin):)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ @patch("products.data_warehouse.backend.api.data_warehouse.managed_warehouse.provision")+ def test_provision_blocked_for_project_editor_who_is_not_org_admin(self, mock_provision):+ mock_provision.return_value = Response({"status": "provisioning"}, status=status.HTTP_202_ACCEPTED)+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)++ response = self.client.post(+ self._path("provision/"), data={"database_name": "x"}, content_type="application/json"+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_provision.assert_not_called()++ @patch("products.data_warehouse.backend.api.data_warehouse.managed_warehouse.provision")+ def test_provision_allowed_for_org_admin_with_project_editor_access(self, mock_provision):+ mock_provision.return_value = Response({"status": "provisioning"}, status=status.HTTP_202_ACCEPTED)+ membership = OrganizationMembership.objects.get(user=self.editor_user, organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)++ response = self.client.post(+ self._path("provision/"), data={"database_name": "x"}, content_type="application/json"+ )++ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)+ mock_provision.assert_called_once_with(self.team.organization_id, "x")++ @patch("products.data_warehouse.backend.api.data_warehouse.managed_warehouse.reset_password")+ def test_reset_password_blocked_for_project_editor_who_is_not_org_admin(self, mock_reset_password):+ mock_reset_password.return_value = Response({"username": "root", "password": "secret"})+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)++ response = self.client.post(self._path("reset-password/"))++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_reset_password.assert_not_called()++ @patch("products.data_warehouse.backend.api.data_warehouse.managed_warehouse.reset_password")+ def test_reset_password_allowed_for_org_admin_with_project_editor_access(self, mock_reset_password):+ mock_reset_password.return_value = Response({"username": "root", "password": "secret"})+ membership = OrganizationMembership.objects.get(user=self.editor_user, organization=self.organization)+ membership.level = OrganizationMembership.Level.ADMIN+ membership.save()+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)++ response = self.client.post(self._path("reset-password/"))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_reset_password.assert_called_once_with(self.team.organization_id)+@pytest.mark.eeclass TestModelPathViewSetAccessControl(WarehouseAccessControlTestMixin):diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex e32de726031a..cd4469e0e33e 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -58,8 +58,10 @@ export interface CheckDatabaseNameResponseApi {}export interface DeprovisionWarehouseResponseApi {+ /** Deprovisioning lifecycle message, e.g. 'deprovisioning started' */status: string- team: string+ /** duckgres org identifier (the PostHog organization id) */+ org: string}export interface ProvisionWarehouseRequestApi {@@ -68,8 +70,14 @@ export interface ProvisionWarehouseRequestApi {}export interface ProvisionWarehouseResponseApi {+ /** Provisioning lifecycle message, e.g. 'provisioning started' */status: string- team: string+ /** duckgres org identifier (the PostHog organization id) */+ org: string+ /** Root database username */+ username: string+ /** Root database password — returned only here at provision time and on reset-password */+ password: string}export interface ResetPasswordResponseApi {@@ -97,14 +105,50 @@ export const WarehouseStatusResponseStateEnumApi = {Deleted: 'deleted',} as const+export interface WarehouseConnectionApi {+ /** 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+ /** Database to connect to — always 'ducklake' */+ database: string+ /** Root database username */+ username: string+}+export interface WarehouseStatusResponseApi {- team_name: string+ /** duckgres org identifier (the PostHog organization id) */+ org_id: string+ /** Overall provisioning lifecycle state+ *+ * * `pending` - pending+ * * `provisioning` - provisioning+ * * `ready` - ready+ * * `failed` - failed+ * * `deleting` - deleting+ * * `deleted` - deleted */state: WarehouseStatusResponseStateEnumApi+ /** Human-readable detail for the current state */status_message: string- /** @nullable */+ /** Object-store sub-resource provisioning state */+ s3_state: string+ /** Metadata-store sub-resource provisioning state */+ metadata_store_state: string+ /** Worker identity sub-resource provisioning state */+ identity_state: string+ /** Credentials sub-resource provisioning state */+ secrets_state: string+ /**+ * When the warehouse became ready+ * @nullable+ */ready_at: string | null- /** @nullable */+ /**+ * When provisioning failed+ * @nullable+ */failed_at: string | null+ connection?: WarehouseConnectionApi | null}/**diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 74e974178e1b..96673e3a2644 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -265,7 +265,7 @@ export const getDataWarehouseDeprovisionCreateUrl = (projectId: string) => {}/**- * Start deprovisioning the managed warehouse for this team.+ * Start deprovisioning the organization's managed warehouse. Restricted to organization admins.*/export const dataWarehouseDeprovisionCreate = async (projectId: string,@@ -311,7 +311,7 @@ export const getDataWarehouseProvisionCreateUrl = (projectId: string) => {}/**- * Start provisioning a managed warehouse for this team.+ * Start provisioning a managed warehouse for this organization (shared by all its teams).*/export const dataWarehouseProvisionCreate = async (projectId: string,diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex 34abdbd1823b..23b52de32809 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -10,7 +10,7 @@import * as zod from 'zod'/**- * Start provisioning a managed warehouse for this team.+ * Start provisioning a managed warehouse for this organization (shared by all its teams).*/export const DataWarehouseProvisionCreateBody = /* @__PURE__ */ zod.object({database_name: zod.string().describe('Name for the new database'),diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 146d9293a36e..69b814e9c1d0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -16516,8 +16516,10 @@ export namespace Schemas {}export interface DeprovisionWarehouseResponse {+ /** Deprovisioning lifecycle message, e.g. 'deprovisioning started' */status: string;- team: string;+ /** duckgres org identifier (the PostHog organization id) */+ org: string;}/**@@ -40481,8 +40483,14 @@ export namespace Schemas {}export interface ProvisionWarehouseResponse {+ /** Provisioning lifecycle message, e.g. 'provisioning started' */status: string;- team: string;+ /** duckgres org identifier (the PostHog organization id) */+ org: string;+ /** Root database username */+ username: string;+ /** Root database password — returned only here at provision time and on reset-password */+ password: string;}/**@@ -47561,6 +47569,17 @@ export namespace Schemas {readonly projected_monthly_observations: number;}+ export interface WarehouseConnection {+ /** 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;+ /** Database to connect to — always 'ducklake' */+ database: string;+ /** Root database username */+ username: string;+ }+/*** * `pending` - pending* * `provisioning` - provisioning@@ -47582,13 +47601,38 @@ export namespace Schemas {} as const;export interface WarehouseStatusResponse {- team_name: string;+ /** duckgres org identifier (the PostHog organization id) */+ org_id: string;+ /** Overall provisioning lifecycle state+ *+ * * `pending` - pending+ * * `provisioning` - provisioning+ * * `ready` - ready+ * * `failed` - failed+ * * `deleting` - deleting+ * * `deleted` - deleted */state: WarehouseStatusResponseStateEnum;+ /** Human-readable detail for the current state */status_message: string;- /** @nullable */+ /** Object-store sub-resource provisioning state */+ s3_state: string;+ /** Metadata-store sub-resource provisioning state */+ metadata_store_state: string;+ /** Worker identity sub-resource provisioning state */+ identity_state: string;+ /** Credentials sub-resource provisioning state */+ secrets_state: string;+ /**+ * When the warehouse became ready+ * @nullable+ */ready_at: string | null;- /** @nullable */+ /**+ * When provisioning failed+ * @nullable+ */failed_at: string | null;+ connection?: WarehouseConnection | null;}export interface WeeklyDigestResponse {