: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): onboard teams via duckgres org-teams api (#72302)
Benjamin Knofe-Vider6720c746629f
diff --git a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsxindex ff15f98ad03f..204bcb583af0 100644--- a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx+++ b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx@@ -101,11 +101,14 @@ export function SettingsTab(): JSX.Element {initialPassword,isResettingPassword,warehouseDomain,- tableName,- isValidTableName,- isEnablingBackfill,- backfillTableSuffix,- hasBackfill,+ schemaName,+ isValidSchemaName,+ schemaNameAvailable,+ schemaNameChecking,+ isOnboardingTeam,+ canOnboardTeam,+ teamOnboarded,+ teamSchemaName,} = useValues(warehouseProvisioningLogic)const {provisionWarehouse,@@ -113,10 +116,10 @@ export function SettingsTab(): JSX.Element {setDatabaseName,clearInitialPassword,resetPassword,- setTableName,- enableBackfill,+ setSchemaName,+ onboardTeam,} = useActions(warehouseProvisioningLogic)- const deprovisionRestrictionReason = useRestrictedArea({+ const adminRestrictionReason = useRestrictedArea({scope: RestrictionScope.Organization,minimumAccessLevel: OrganizationMembershipLevel.Admin,})@@ -217,17 +220,17 @@ export function SettingsTab(): JSX.Element {) : null}</div><div>- <LemonLabel>Table name</LemonLabel>- <LemonInput value={tableName} onChange={setTableName} placeholder="my_project" fullWidth />- {tableName && !isValidTableName ? (+ <LemonLabel>Schema name</LemonLabel>+ <LemonInput value={schemaName} onChange={setSchemaName} placeholder="my_project" fullWidth />+ {schemaName && !isValidSchemaName ? (<p className="text-danger text-xs mt-1">Use lowercase letters, numbers, and underscores only (max 63 characters).</p>) : (<p className="text-muted text-xs mt-1">- This project's data lands in its own warehouse tables, suffixed with this name (e.g.{' '}- <code>events_<name></code>, <code>persons_<name></code>). Other projects- pick their own when they join.+ This project's data lands in its own schema in the warehouse. Other projects pick their+ own schema when they join. Unlike the project name, the schema name cannot be changed+ later.</p>)}</div>@@ -237,10 +240,10 @@ export function SettingsTab(): JSX.Element {disabledReason={isFailed? !canRetryProvision- ? 'Enter a valid database name and table name'+ ? 'Enter a valid database name and schema name': undefined: !canProvision- ? 'Enter an available database name and table name'+ ? 'Enter an available database name and schema name': undefined}onClick={() => {@@ -252,7 +255,7 @@ export function SettingsTab(): JSX.Element {'This will create a managed warehouse for your organization, shared by every project in it. Should take less than 5 minutes.',primaryButton: {children: isFailed ? 'Retry provisioning' : 'Provision',- onClick: () => provisionWarehouse({ databaseName: retryDatabaseName, tableName }),+ onClick: () => provisionWarehouse({ databaseName: retryDatabaseName, schemaName }),},secondaryButton: {children: 'Cancel',@@ -301,73 +304,86 @@ export function SettingsTab(): JSX.Element {)}</div>- {isReady && warehouseStatus?.connection && (+ {isReady && teamOnboarded && warehouseStatus?.connection && (<ConnectionDetails connection={warehouseStatus.connection} />)}- {isReady && (+ {isReady && !teamOnboarded && adminRestrictionReason && (<div className="border rounded p-4 space-y-3">- <h3 className="mb-0">Warehouse tables for this project</h3>- {hasBackfill ? (- // A backfill already exists — the table name is fixed (immutable), so show- // read-only state rather than re-offering the form.- backfillTableSuffix ? (- <p className="text-muted text-xs mb-0">- This project writes to its own tables <code>events_{backfillTableSuffix}</code>{' '}- / <code>persons_{backfillTableSuffix}</code>. The table name is fixed once a- backfill is running.- </p>- ) : (- <p className="text-muted text-xs mb-0">- This project writes to the shared <code>events</code> / <code>persons</code>{' '}- tables. Changing it would split existing data, so it's fixed.- </p>- )- ) : (- <>- <p className="text-muted text-xs mb-0">- Each project writes its data into its own tables in the shared warehouse so they- don't merge. Choose a name for this project's warehouse tables — lowercase- letters, numbers, and underscores only; it's used as the suffix (e.g.{' '}- <code>events_<name></code>). This can't be changed once a backfill runs.+ <h3 className="mb-0">Your organization's warehouse is running</h3>+ <p className="text-muted text-xs mb-0">+ This project isn't part of it yet. Ask an organization admin to enable it here.+ </p>+ </div>+ )}++ {isReady && !teamOnboarded && !adminRestrictionReason && (+ <div className="border rounded p-4 space-y-3">+ <h3 className="mb-0">Your organization's warehouse is running</h3>+ <p className="text-muted text-xs mb-0">+ This project isn't part of it yet. Pick a schema name to enable it. The project's data+ lands in its own schema so it doesn't mix with other projects. Unlike the project name,+ the schema name cannot be changed later.+ </p>+ <div>+ <LemonLabel>Schema name</LemonLabel>+ <div className="flex items-center gap-2">+ <LemonInput+ value={schemaName}+ onChange={setSchemaName}+ placeholder="my_project"+ fullWidth+ />+ {schemaName &&+ isValidSchemaName &&+ (schemaNameChecking ? (+ <Spinner className="text-muted" />+ ) : schemaNameAvailable === true ? (+ <IconCheck className="text-success text-xl" />+ ) : (+ <IconX className="text-danger text-xl" />+ ))}+ </div>+ {schemaName && !isValidSchemaName && (+ <p className="text-danger text-xs mt-1">+ Use lowercase letters, numbers, and underscores only (max 63 characters).</p>- <div>- <div className="flex items-end gap-2">- <div className="flex-1">- <LemonLabel>Table name</LemonLabel>- <LemonInput- value={tableName}- onChange={setTableName}- placeholder="my_project"- fullWidth- />- </div>- <LemonButton- type="primary"- loading={isEnablingBackfill}- disabledReason={- !isValidTableName ? 'Enter a valid table name' : undefined- }- onClick={() => enableBackfill({ tableName })}- data-attr="enable-warehouse-backfill"- >- Enable backfill- </LemonButton>- </div>- {tableName && !isValidTableName && (- <p className="text-danger text-xs mt-1">- Use lowercase letters, numbers, and underscores only (max 63- characters).- </p>- )}- </div>- </>- )}+ )}+ {schemaName &&+ isValidSchemaName &&+ !schemaNameChecking &&+ schemaNameAvailable !== true && (+ <p className="text-danger text-xs mt-1">+ {schemaNameAvailable === false+ ? 'This schema name is already used by another project in your organization.'+ : 'Unable to verify schema name availability.'}+ </p>+ )}+ </div>+ <LemonButton+ type="primary"+ loading={isOnboardingTeam}+ disabledReason={!canOnboardTeam ? 'Enter an available schema name' : undefined}+ onClick={() => onboardTeam({ schemaName })}+ data-attr="onboard-warehouse-team"+ >+ Enable this project+ </LemonButton>+ </div>+ )}++ {isReady && teamOnboarded && (+ <div className="border rounded p-4 space-y-3">+ <h3 className="mb-0">Warehouse schema for this project</h3>+ <p className="text-muted text-xs mb-0">+ This project's data lands in the <code>{teamSchemaName ?? 'unknown'}</code> schema. The+ schema name cannot be changed.+ </p></div>)}<div className="flex gap-2">- {isReady && (+ {isReady && teamOnboarded && (<LemonButtontype="secondary"loading={isResettingPassword}@@ -395,7 +411,7 @@ export function SettingsTab(): JSX.Element {type="secondary"status="danger"loading={isDeprovisioning}- disabledReason={deprovisionRestrictionReason ?? undefined}+ disabledReason={adminRestrictionReason ?? undefined}onClick={() => {LemonDialog.open({title: 'Deprovision managed warehouse?',diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.tsindex fba2ecd714d8..b81c7640a6ec 100644--- a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts@@ -18,6 +18,10 @@ describe('warehouseProvisioningLogic', () => {name: '',available: true,} as any)+ jest.spyOn(dwApi, 'dataWarehouseCheckSchemaNameRetrieve').mockResolvedValue({+ name: '',+ available: true,+ } as any)})afterEach(() => {@@ -155,10 +159,77 @@ describe('warehouseProvisioningLogic', () => {logic.mount()await expectLogic(logic, () => {- logic.actions.provisionWarehouse({ databaseName: 'shared-warehouse', tableName: 'shared' })+ logic.actions.provisionWarehouse({ databaseName: 'shared-warehouse', schemaName: 'shared' })}).toDispatchActions(['provisionWarehouse', 'loadWarehouseStatus', 'provisionWarehouseComplete'])expect(infoToast).toHaveBeenCalledTimes(1)expect(errorToast).not.toHaveBeenCalled()})++ it('flags a ready warehouse without team onboarding as needing onboarding', async () => {+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve').mockResolvedValue({+ state: 'ready',+ team_onboarded: false,+ schema_name: null,+ } as any)++ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadWarehouseStatusSuccess'])+ expect(logic.values.needsTeamOnboarding).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.loadWarehouseStatusSuccess({+ state: 'ready',+ team_onboarded: true,+ schema_name: 'mine',+ } as any)+ }).toMatchValues({ needsTeamOnboarding: false, teamOnboarded: true, teamSchemaName: 'mine' })+ })++ it('onboards the project and refreshes status', async () => {+ const onboard = jest.spyOn(dwApi, 'dataWarehouseOnboardTeamCreate').mockResolvedValue({+ onboarded: true,+ schema_name: 'my_schema',+ } as any)+ // After onboarding, the refreshed status reports the project as onboarded.+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve').mockResolvedValue({+ state: 'ready',+ team_onboarded: true,+ schema_name: 'my_schema',+ } as any)++ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.onboardTeam({ schemaName: 'my_schema' })+ }).toDispatchActions([+ 'onboardTeam',+ 'onboardTeamComplete',+ 'loadWarehouseStatus',+ 'loadWarehouseStatusSuccess',+ ])++ expect(onboard).toHaveBeenCalledWith(expect.any(String), { schema_name: 'my_schema' })+ expect(logic.values.teamOnboarded).toBe(true)+ expect(logic.values.teamSchemaName).toBe('my_schema')+ })++ it('marks the schema name unavailable when onboarding hits a schema conflict (409)', async () => {+ jest.spyOn(dwApi, 'dataWarehouseOnboardTeamCreate').mockRejectedValueOnce({ status: 409 })+ const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue(undefined as any)++ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.onboardTeam({ schemaName: 'taken' })+ }).toDispatchActions(['onboardTeam', 'onboardTeamComplete'])++ expect(errorToast).toHaveBeenCalledTimes(1)+ expect(logic.values.teamOnboarded).toBe(false)+ expect(logic.values.schemaNameAvailable).toBe(false)+ })})diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.tsindex e6bccb7221c4..2804e1dae959 100644--- a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts+++ b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts@@ -9,9 +9,10 @@ import { Region } from '~/types'import {dataWarehouseCheckDatabaseNameRetrieve,+ dataWarehouseCheckSchemaNameRetrieve,dataWarehouseDeleteOrgDestroy,dataWarehouseDeprovisionCreate,- dataWarehouseEnableBackfillCreate,+ dataWarehouseOnboardTeamCreate,dataWarehouseProvisionCreate,dataWarehouseResetPasswordCreate,dataWarehouseWarehouseStatusRetrieve,@@ -33,9 +34,9 @@ const MANAGED_WAREHOUSE_DOMAINS: Partial<Record<Region, string>> = {[Region.DEV]: 'dev.postwh.com',}-// The table name is used verbatim as the suffix in events_<suffix> / persons_<suffix>, so it-// must already be a safe SQL identifier. Mirrors validate_table_suffix in posthog/ducklake/common.py.-const TABLE_NAME_REGEX = /^[a-z0-9_]{1,63}$/+// The schema name is used verbatim as a SQL identifier (and as the backfill table suffix), so+// it must already be safe. Mirrors validate_schema_name in posthog/ducklake/common.py.+const SCHEMA_NAME_REGEX = /^[a-z0-9_]{1,63}$/const databaseNameStorageKey = (teamId: number | null): string =>`warehouse-provisioning-database-name-${teamId ?? 'unknown'}`@@ -51,7 +52,7 @@ const currentProjectId = (): string => String(teamLogic.values.currentTeamId)// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface warehouseProvisioningLogicValues {preflight: PreflightStatus | null // preflightLogic- backfillTableSuffix: string | null+ canOnboardTeam: booleancanProvision: booleancanRetryProvision: booleandatabaseName: string@@ -64,18 +65,23 @@ export interface warehouseProvisioningLogicValues {isActionable: booleanisDeletingOrg: booleanisDeprovisioning: boolean- isEnablingBackfill: booleanisInProgress: boolean+ isOnboardingTeam: booleanisProvisioning: booleanisResettingPassword: booleanisValidDatabaseName: boolean- isValidTableName: boolean+ isValidSchemaName: booleanlastRequestedDatabaseName: string | null+ needsTeamOnboarding: booleanorgDeletionFailed: booleanorgDeletionSucceeded: booleanpollingActive: booleanretryDatabaseName: string- tableName: string+ schemaName: string+ schemaNameAvailable: boolean | null+ schemaNameChecking: boolean+ teamOnboarded: boolean+ teamSchemaName: string | nullwarehouseDomain: string | nullwarehouseStatus: WarehouseStatusResponseApi | nullwarehouseStatusLoading: boolean@@ -86,6 +92,9 @@ export interface warehouseProvisioningLogicActions {checkDatabaseName: (name: string) => {name: string}+ checkSchemaName: (name: string) => {+ name: string+ }clearInitialPassword: () => {value: true}@@ -101,12 +110,6 @@ export interface warehouseProvisioningLogicActions {deprovisionWarehouseComplete: () => {value: true}- enableBackfill: (params: { tableName: string }) => {- tableName: string- }- enableBackfillComplete: (suffix: string | null) => {- suffix: string | null- }loadWarehouseStatus: () => anyloadWarehouseStatusFailure: (error: string,@@ -122,12 +125,18 @@ export interface warehouseProvisioningLogicActions {warehouseStatus: WarehouseStatusResponseApi | nullpayload?: any}+ onboardTeam: (params: { schemaName: string }) => {+ schemaName: string+ }+ onboardTeamComplete: (schemaName: string | null) => {+ schemaName: string | null+ }pollStatus: () => {value: true}- provisionWarehouse: (params: { databaseName: string; tableName: string }) => {+ provisionWarehouse: (params: { databaseName: string; schemaName: string }) => {databaseName: string- tableName: string+ schemaName: string}provisionWarehouseComplete: () => {value: true@@ -153,9 +162,15 @@ export interface warehouseProvisioningLogicActions {setLastRequestedDatabaseName: (name: string | null) => {name: string | null}- setTableName: (name: string) => {+ setSchemaName: (name: string) => {name: string}+ setSchemaNameAvailable: (available: boolean | null) => {+ available: boolean | null+ }+ setSchemaNameChecking: (checking: boolean) => {+ checking: boolean+ }stopPolling: () => {value: true}@@ -173,13 +188,15 @@ export interface warehouseProvisioningLogicMeta {isValidDatabaseName: (databaseName: string) => booleanwarehouseDomain: (preflight: PreflightStatus | null) => string | nullretryDatabaseName: (databaseName: string, lastRequestedDatabaseName: string | null) => string- isValidTableName: (tableName: string) => boolean+ isValidSchemaName: (schemaName: string) => boolean+ needsTeamOnboarding: (warehouseStatus: WarehouseStatusResponseApi | null, teamOnboarded: boolean) => booleancanProvision: (isValidDatabaseName: boolean,databaseNameAvailable: boolean | null,- isValidTableName: boolean+ isValidSchemaName: boolean) => boolean- canRetryProvision: (retryDatabaseName: string, isValidTableName: boolean) => boolean+ canRetryProvision: (retryDatabaseName: string, isValidSchemaName: boolean) => boolean+ canOnboardTeam: (isValidSchemaName: boolean, schemaNameAvailable: boolean | null) => boolean}}@@ -198,7 +215,7 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([})),actions({- provisionWarehouse: (params: { databaseName: string; tableName: string }) => params,+ provisionWarehouse: (params: { databaseName: string; schemaName: string }) => params,provisionWarehouseComplete: true,deprovisionWarehouse: true,deprovisionWarehouseComplete: true,@@ -215,9 +232,12 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([checkDatabaseName: (name: string) => ({ name }),setDatabaseNameAvailable: (available: boolean | null) => ({ available }),setDatabaseNameChecking: (checking: boolean) => ({ checking }),- setTableName: (name: string) => ({ name }),- enableBackfill: (params: { tableName: string }) => params,- enableBackfillComplete: (suffix: string | null) => ({ suffix }),+ setSchemaName: (name: string) => ({ name }),+ checkSchemaName: (name: string) => ({ name }),+ setSchemaNameAvailable: (available: boolean | null) => ({ available }),+ setSchemaNameChecking: (checking: boolean) => ({ checking }),+ onboardTeam: (params: { schemaName: string }) => params,+ onboardTeamComplete: (schemaName: string | null) => ({ schemaName }),}),loaders({@@ -343,34 +363,59 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([resetPasswordComplete: () => false,},],- tableName: [+ schemaName: ['',{- setTableName: (_, { name }) => name,+ setSchemaName: (_, { name }) => name,},],- isEnablingBackfill: [+ schemaNameAvailable: [+ null as boolean | null,+ {+ setSchemaNameAvailable: (_, { available }) => available,+ setSchemaName: () => null,+ },+ ],+ schemaNameChecking: [+ false,+ {+ setSchemaNameChecking: (_, { checking }) => checking,+ setSchemaName: () => false,+ },+ ],+ isOnboardingTeam: [false,{- enableBackfill: () => true,- enableBackfillComplete: () => false,+ onboardTeam: () => true,+ onboardTeamComplete: () => false,+ },+ ],+ // Whether this project is onboarded onto the organization's warehouse. When false on a+ // running warehouse, the onboarding screen is shown instead of the normal one.+ teamOnboarded: [+ false,+ {+ loadWarehouseStatusSuccess: (_, { warehouseStatus }) => warehouseStatus?.team_onboarded ?? false,+ onboardTeamComplete: (state, { schemaName }) => (schemaName ? true : state),+ deprovisionWarehouse: () => false,},],- backfillTableSuffix: [+ // The schema this project's data lands in. Fixed once onboarded — it cannot be changed.+ teamSchemaName: [null as string | null,{- loadWarehouseStatusSuccess: (_, { warehouseStatus }) => warehouseStatus?.table_suffix ?? null,- enableBackfillComplete: (state, { suffix }) => suffix ?? state,+ loadWarehouseStatusSuccess: (_, { warehouseStatus }) => warehouseStatus?.schema_name ?? null,+ onboardTeamComplete: (state, { schemaName }) => schemaName ?? state,deprovisionWarehouse: () => null,},],- // Whether this project already has a backfill configured. When true, the table name is- // fixed (immutable), so we show a read-only state instead of re-offering the enable form.+ // Whether this project already has a backfill configured. When true, the schema name is+ // fixed (immutable), so we show a read-only state instead of re-offering the form.hasBackfill: [false,{loadWarehouseStatusSuccess: (_, { warehouseStatus }) => warehouseStatus?.has_backfill ?? false,- enableBackfillComplete: (state, { suffix }) => (suffix ? true : state),+ onboardTeamComplete: (state, { schemaName }) => (schemaName ? true : state),deprovisionWarehouse: () => false,},],@@ -416,23 +461,34 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([(databaseName: string, lastRequestedDatabaseName: string | null): string =>databaseName || lastRequestedDatabaseName || '',],- // The table name is used verbatim as the table suffix, so it must already be a valid- // identifier (mirrors the backend validator) — we reject rather than silently rewrite.- isValidTableName: [(s) => [s.tableName], (name: string): boolean => TABLE_NAME_REGEX.test(name)],+ // The schema name is used verbatim as a SQL identifier, so it must already be valid+ // (mirrors the backend validator) — we reject rather than silently rewrite.+ isValidSchemaName: [(s) => [s.schemaName], (name: string): boolean => SCHEMA_NAME_REGEX.test(name)],+ // The warehouse is running but this project hasn't picked a schema yet — show onboarding.+ needsTeamOnboarding: [+ (s) => [s.warehouseStatus, s.teamOnboarded],+ (status: WarehouseStatusResponseApi | null, teamOnboarded: boolean): boolean =>+ status?.state === 'ready' && !teamOnboarded,+ ],canProvision: [- (s) => [s.isValidDatabaseName, s.databaseNameAvailable, s.isValidTableName],- (valid: boolean, available: boolean | null, validEvents: boolean): boolean =>- valid && available === true && validEvents,+ (s) => [s.isValidDatabaseName, s.databaseNameAvailable, s.isValidSchemaName],+ (valid: boolean, available: boolean | null, validSchema: boolean): boolean =>+ valid && available === true && validSchema,],canRetryProvision: [- (s) => [s.retryDatabaseName, s.isValidTableName],- (retryDatabaseName: string, validEvents: boolean): boolean =>- !!retryDatabaseName && WAREHOUSE_NAME_REGEX.test(retryDatabaseName) && validEvents,+ (s) => [s.retryDatabaseName, s.isValidSchemaName],+ (retryDatabaseName: string, validSchema: boolean): boolean =>+ !!retryDatabaseName && WAREHOUSE_NAME_REGEX.test(retryDatabaseName) && validSchema,+ ],+ canOnboardTeam: [+ (s) => [s.isValidSchemaName, s.schemaNameAvailable],+ (validSchema: boolean, available: boolean | null): boolean => validSchema && available === true,],}),listeners(({ actions, values }) => {let debounceTimer: ReturnType<typeof setTimeout> | null = null+ let schemaDebounceTimer: ReturnType<typeof setTimeout> | null = nullreturn {setDatabaseName: ({ name }) => {@@ -448,24 +504,62 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([},checkDatabaseName: async ({ name }) => {+ // Same staleness guard as checkSchemaName: only the current name's request may+ // write availability or clear the spinner.try {const result = await dataWarehouseCheckDatabaseNameRetrieve(currentProjectId(), { name })if (values.databaseName === name) {actions.setDatabaseNameAvailable(result.available)}} catch {- actions.setDatabaseNameAvailable(null)+ if (values.databaseName === name) {+ actions.setDatabaseNameAvailable(null)+ }+ }+ if (values.databaseName === name) {+ actions.setDatabaseNameChecking(false)+ }+ },++ setSchemaName: ({ name }) => {+ if (schemaDebounceTimer) {+ clearTimeout(schemaDebounceTimer)+ }+ // Availability only matters when joining an existing warehouse — at provision+ // time this is the org's first schema, so there is nothing to collide with.+ if (values.needsTeamOnboarding && SCHEMA_NAME_REGEX.test(name)) {+ actions.setSchemaNameChecking(true)+ schemaDebounceTimer = setTimeout(() => {+ actions.checkSchemaName(name)+ }, 400)+ }+ },++ checkSchemaName: async ({ name }) => {+ // Guard every state write on the request's name still being current: a stale+ // completion (success or failure) must not clobber a newer check's result.+ try {+ const result = await dataWarehouseCheckSchemaNameRetrieve(currentProjectId(), { name })+ if (values.schemaName === name) {+ actions.setSchemaNameAvailable(result.available)+ }+ } catch {+ if (values.schemaName === name) {+ actions.setSchemaNameAvailable(null)+ }+ }+ if (values.schemaName === name) {+ actions.setSchemaNameChecking(false)}- actions.setDatabaseNameChecking(false)},- provisionWarehouse: async ({ databaseName, tableName }) => {+ provisionWarehouse: async ({ databaseName, schemaName }) => {actions.setLastRequestedDatabaseName(databaseName)window.localStorage.setItem(databaseNameStorageKey(teamLogic.values.currentTeamId), databaseName)try {const result = await dataWarehouseProvisionCreate(currentProjectId(), {database_name: databaseName,- table_name: tableName,+ schema_name: schemaName,})if (result.password) {actions.setInitialPassword(result.password)@@ -486,18 +580,27 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([actions.provisionWarehouseComplete()},- enableBackfill: async ({ tableName }) => {+ onboardTeam: async ({ schemaName }) => {try {- const result = await dataWarehouseEnableBackfillCreate(currentProjectId(), {- table_name: tableName,+ const result = await dataWarehouseOnboardTeamCreate(currentProjectId(), {+ schema_name: schemaName,})- lemonToast.success('Warehouse backfill enabled for this project')- actions.enableBackfillComplete(result.table_suffix ?? null)- // Refresh from the server so the read-only state reflects the now-fixed table.+ lemonToast.success('This project is now part of the managed warehouse')+ actions.onboardTeamComplete(result.schema_name ?? schemaName)+ // Refresh from the server so the read-only state reflects the now-fixed schema.actions.loadWarehouseStatus()} catch (e: any) {- lemonToast.error(`Failed to enable backfill: ${e.detail || e.message || 'Unknown error'}`)- actions.enableBackfillComplete(null)+ if (e.status === 409) {+ // The schema name was taken between the live check and submit.+ lemonToast.error(+ e.detail ||+ 'That schema name is already used by another project in your organization. Pick a different one.'+ )+ actions.setSchemaNameAvailable(false)+ } else {+ lemonToast.error(`Failed to enable this project: ${e.detail || e.message || 'Unknown error'}`)+ }+ actions.onboardTeamComplete(null)}},@@ -573,6 +676,18 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([} else {actions.stopPolling()}+ // The default schema name is prefilled on mount, before this response can flip+ // needsTeamOnboarding to true — so its availability was never checked. Re-set it+ // here to run the debounced check once the onboarding form is actually shown.+ if (+ values.needsTeamOnboarding &&+ values.schemaName &&+ values.isValidSchemaName &&+ values.schemaNameAvailable === null &&+ !values.schemaNameChecking+ ) {+ actions.setSchemaName(values.schemaName)+ }},}}),@@ -584,17 +699,17 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([if (persistedDatabaseName) {actions.setLastRequestedDatabaseName(persistedDatabaseName)}- // Prefill the table name with a valid default derived from the project name (lowercased,+ // Prefill the schema name with a valid default derived from the project name (lowercased,// non-identifier chars collapsed to underscores). It's only a starting point — the user// edits/confirms it, and the input is validated verbatim from there.const projectName = teamLogic.values.currentTeam?.name- const defaultTableName = projectName+ const defaultSchemaName = projectName?.toLowerCase().replace(/[^a-z0-9_]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 63)- if (defaultTableName) {- actions.setTableName(defaultTableName)+ if (defaultSchemaName) {+ actions.setSchemaName(defaultSchemaName)}actions.loadWarehouseStatus()}),diff --git a/posthog/admin/admins/duckgres_server_admin.py b/posthog/admin/admins/duckgres_server_admin.pyindex cbee8682e900..2afd3b76c8e9 100644--- a/posthog/admin/admins/duckgres_server_admin.py+++ b/posthog/admin/admins/duckgres_server_admin.py@@ -147,7 +147,7 @@ class DuckgresServerAdmin(admin.ModelAdmin):organization_id = request.POST.get("organization_id", "").strip()team_id = request.POST.get("team_id", "").strip()database_name = request.POST.get("database_name", "").strip()- table_name = request.POST.get("table_name", "").strip()+ schema_name = request.POST.get("schema_name", "").strip()team = self._resolve_team(request, organization_id, team_id)if team is None:@@ -156,7 +156,7 @@ class DuckgresServerAdmin(admin.ModelAdmin):from products.data_warehouse.backend.presentation.views import managed_warehouse # noqa: PLC0415resp = managed_warehouse.provision(- team.organization_id, database_name, team.id, table_name, require_enabled=False+ team.organization_id, database_name, team.id, schema_name, require_enabled=False)if 200 <= resp.status_code < 300:# The control plane returns the root password exactly once, in this@@ -189,7 +189,7 @@ class DuckgresServerAdmin(admin.ModelAdmin):return redirect(reverse("admin:posthog_duckgresserver_provision"))def enable_backfill_view(self, request: HttpRequest, object_id: str) -> HttpResponse:- """Add another team to an already-provisioned org's warehouse with its own tables."""+ """Onboard another team onto an already-provisioned org's warehouse with its own schema."""if request.method not in {"GET", "POST"}:return HttpResponseNotAllowed(["GET", "POST"])@@ -209,7 +209,7 @@ class DuckgresServerAdmin(admin.ModelAdmin):)team_id = request.POST.get("team_id", "").strip()- table_name = request.POST.get("table_name", "").strip()+ schema_name = request.POST.get("schema_name", "").strip()team = self._resolve_team(request, str(server.organization_id), team_id)if team is None:@@ -217,8 +217,8 @@ class DuckgresServerAdmin(admin.ModelAdmin):from products.data_warehouse.backend.presentation.views import managed_warehouse # noqa: PLC0415- resp = managed_warehouse.enable_backfill(server.organization_id, team.id, table_name, require_enabled=False)- self._report(request, resp, f"Enabled warehouse backfill for team {team.id}")+ resp = managed_warehouse.onboard_team(server.organization_id, team.id, schema_name, require_enabled=False)+ self._report(request, resp, f"Onboarded team {team.id} onto the managed warehouse")if 200 <= resp.status_code < 300:return redirect(reverse("admin:posthog_duckgresserver_change", args=[object_id]))return redirect(reverse("admin:posthog_duckgresserver_enable_backfill", args=[object_id]))diff --git a/posthog/admin/test_duckgres_server_admin.py b/posthog/admin/test_duckgres_server_admin.pyindex d29f95d1eb4e..dd0636286534 100644--- a/posthog/admin/test_duckgres_server_admin.py+++ b/posthog/admin/test_duckgres_server_admin.py@@ -89,7 +89,7 @@ class TestDuckgresServerAdminProvision(BaseTest):"organization_id": str(self.organization.id),"team_id": str(self.team.id),"database_name": "my-warehouse",- "table_name": "prod_events",+ "schema_name": "prod_events",},)body = {"username": "root", "password": "sup3r-secret-pw"}@@ -113,7 +113,7 @@ class TestDuckgresServerAdminProvision(BaseTest):"organization_id": str(self.organization.id),"team_id": str(self.team.id),"database_name": "my-warehouse",- "table_name": "prod_events",+ "schema_name": "prod_events",},)with patch(f"{MW}.provision", return_value=Response({"error": "nope"}, status=400)):@@ -132,7 +132,7 @@ class TestDuckgresServerAdminProvision(BaseTest):"organization_id": str(self.organization.id),"team_id": str(other_team.id),"database_name": "my-warehouse",- "table_name": "prod_events",+ "schema_name": "prod_events",},)with patch(f"{MW}.provision") as mock_provision:@@ -148,7 +148,7 @@ class TestDuckgresServerAdminProvision(BaseTest):"organization_id": str(self.organization.id),"team_id": str(self.team.id),"database_name": "my-warehouse",- "table_name": "prod_events",+ "schema_name": "prod_events",},)with patch(f"{MW}.provision", return_value=Response({"error": "boom"}, status=400)):@@ -160,14 +160,14 @@ class TestDuckgresServerAdminProvision(BaseTest):server = self._server()request = self._post(f"/admin/posthog/duckgresserver/{server.pk}/enable-backfill/",- {"team_id": str(self.team.id), "table_name": "env_b"},+ {"team_id": str(self.team.id), "schema_name": "env_b"},)with patch(- f"{MW}.enable_backfill", return_value=Response({"enabled": True, "table_suffix": "env_b"}, status=200)- ) as mock_enable:+ f"{MW}.onboard_team", return_value=Response({"onboarded": True, "schema_name": "env_b"}, status=200)+ ) as mock_onboard:self.admin.enable_backfill_view(request, str(server.pk))- mock_enable.assert_called_once_with(self.organization.id, self.team.id, "env_b", require_enabled=False)+ mock_onboard.assert_called_once_with(self.organization.id, self.team.id, "env_b", require_enabled=False)def test_enable_backfill_invalid_server_returns_404(self) -> None:request = self._get("/admin/posthog/duckgresserver/999999/enable-backfill/")diff --git a/posthog/api/project.py b/posthog/api/project.pyindex fe40fa73c8de..5f1a0619805e 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -1479,6 +1479,21 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetsteams = list(project.teams.only("id", "uuid", "name", "organization_id").all())team_ids = [team.id for team in teams]+ # Remove each environment from the org's managed warehouse first (no-op for orgs+ # without one). Blocks when duckgres refuses — e.g. the warehouse's last team, which+ # requires deprovisioning the warehouse (or deleting the organization) instead.+ # Environments already removed before a block are re-pushed lazily on the next+ # warehouse status read, so a partial pass self-heals.+ # Keep the product API off the core import path.+ from products.data_warehouse.backend.presentation.views.managed_warehouse import ( # noqa: PLC0415+ block_team_deletion,+ )++ for team_id in team_ids:+ warehouse_block_reason = block_team_deletion(team_id, organization_id)+ if warehouse_block_reason:+ raise exceptions.ValidationError(warehouse_block_reason)+# Mark as pending deletion so the UI locks this project out until the async task removes it.project.is_pending_deletion = Trueproject.save(update_fields=["is_pending_deletion"])diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 1f18c244f25e..f9a3d1fda6c5 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -1991,6 +1991,18 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Moorganization_id = team.organization_idteam_name = team.name+ # Remove the team from the org's managed warehouse first (no-op for orgs without+ # one). Blocks when duckgres refuses — e.g. the warehouse's last team, which+ # requires deprovisioning the warehouse (or deleting the organization) instead.+ # Keep the product API off the core import path.+ from products.data_warehouse.backend.presentation.views.managed_warehouse import ( # noqa: PLC0415+ block_team_deletion,+ )++ warehouse_block_reason = block_team_deletion(team_id, organization_id)+ if warehouse_block_reason:+ raise exceptions.ValidationError(warehouse_block_reason)+user = cast(User, self.request.user)# Hand off all deletion work (bulky postgres, batch exports, team record,diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 31f4b6bc1d66..5b751c54a165 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -449,6 +449,28 @@ def team_api_test_factory():)assert mock_capture.call_args_list == expected_capture_calls+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")+ @patch(+ "products.data_warehouse.backend.presentation.views.managed_warehouse.block_team_deletion",+ return_value="Deprovision the managed warehouse first.",+ )+ def test_delete_team_blocked_by_managed_warehouse(+ self,+ mock_block: MagicMock,+ mock_start_workflow: MagicMock,+ ):+ # Wiring guard: perform_destroy must consult the managed-warehouse guard before+ # dispatching the deletion workflow, and a block must stop the deletion entirely.+ team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)++ response = self.client.delete(f"/api/environments/{team.id}")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("managed warehouse", response.json()["detail"])+ mock_block.assert_called_once()+ mock_start_workflow.assert_not_called()+ self.assertTrue(Team.objects.filter(pk=team.pk).exists())+@freeze_time("2022-02-08")def test_reset_token(self):self.organization_membership.level = OrganizationMembership.Level.ADMINdiff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.pyindex 2fa74b0ac3ca..425b48b9d116 100644--- a/posthog/ducklake/common.py+++ b/posthog/ducklake/common.py@@ -578,26 +578,33 @@ def validate_table_suffix(name: str | None) -> str | None:return None-class DucklingBackfillEnableError(Exception):- """Raised when a team's warehouse backfill cannot be enabled (no server, name collision)."""+def validate_schema_name(name: str | None) -> str | None:+ """Return a human-readable error if `name` isn't a valid duckgres schema name, else None.+ A team's schema name shares the table-suffix constraints (it doubles as the+ table suffix on the Django side): lowercase letters, numbers, and underscores,+ at most 63 characters.+ """+ if not name:+ return "schema_name is required"+ if len(name) > TABLE_SUFFIX_MAX_LENGTH:+ return f"Schema name must be at most {TABLE_SUFFIX_MAX_LENGTH} characters"+ if not TABLE_SUFFIX_PATTERN.match(name):+ return "Schema name must use only lowercase letters, numbers, and underscores"+ return None-def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_name: str) -> str:- """Enable a team's warehouse backfill with a dedicated set of per-environment tables.- The user-supplied ``table_name`` is used verbatim as the table suffix (validated, not- rewritten). Records the team↔duckling membership and the backfill suffix on a single- DuckgresServerTeam row so the Dagster backfill writes to ``events_<suffix>`` /- ``persons_<suffix>`` instead of the shared tables.+class DucklingBackfillEnableError(Exception):+ """Raised when a team's warehouse backfill cannot be enabled (no server, name collision)."""- **Write-once.** The suffix is fixed when the backfill is first created and cannot be changed- afterward — including switching a legacy NULL suffix (shared tables) to a real name. Changing- it would make the Dagster job write to a different table and split the team's existing data- across two tables. Re-calling with the team's current name is an idempotent no-op.- The org must already have a provisioned DuckgresServer, the name must be a valid identifier,- and the suffix must be unique among the org's environments. Returns the suffix, or raises- DucklingBackfillEnableError with a user-facing message.+def check_team_backfill_enable(*, team_id: int, organization_id: str | UUID, table_name: str) -> bool:+ """Run every ``enable_team_backfill`` guard without writing anything.++ Returns True when the team already has a row with this exact suffix (an idempotent+ no-op for the caller), False when a new row would be created. Raises+ DucklingBackfillEnableError with a user-facing message otherwise. Lets dual-write+ callers reject bad input before touching the duckgres control plane."""from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam@@ -606,9 +613,7 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_namraise DucklingBackfillEnableError(error)suffix = table_name- try:- server = DuckgresServer.objects.get(organization_id=organization_id)- except DuckgresServer.DoesNotExist:+ if not DuckgresServer.objects.filter(organization_id=organization_id).exists():raise DucklingBackfillEnableError("No managed warehouse is provisioned for this organization. Provision one first.")@@ -617,7 +622,7 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_namif existing is not None:if existing.table_suffix == suffix:# Same name — already set up; idempotent no-op.- return suffix+ return Truecurrent = f"events_{existing.table_suffix}" if existing.table_suffix else "the shared tables"raise DucklingBackfillEnableError(f"This project already writes to {current}, and its warehouse table can't be changed — "@@ -631,9 +636,38 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_nam)if collision:raise DucklingBackfillEnableError(- f"The table name '{suffix}' is already used by another environment in this organization."+ f"The name '{suffix}' is already used by another environment in this organization.")+ return False+++def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_name: str) -> str:+ """Enable a team's warehouse backfill with a dedicated set of per-environment tables.++ The user-supplied ``table_name`` is used verbatim as the table suffix (validated, not+ rewritten). Records the team↔duckling membership and the backfill suffix on a single+ DuckgresServerTeam row so the Dagster backfill writes to ``events_<suffix>`` /+ ``persons_<suffix>`` instead of the shared tables.++ **Write-once.** The suffix is fixed when the backfill is first created and cannot be changed+ afterward — including switching a legacy NULL suffix (shared tables) to a real name. Changing+ it would make the Dagster job write to a different table and split the team's existing data+ across two tables. Re-calling with the team's current name is an idempotent no-op.++ The org must already have a provisioned DuckgresServer, the name must be a valid identifier,+ and the suffix must be unique among the org's environments. Returns the suffix, or raises+ DucklingBackfillEnableError with a user-facing message.+ """+ from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam++ already_enabled = check_team_backfill_enable(+ team_id=team_id, organization_id=organization_id, table_name=table_name+ )+ suffix = table_name+ if already_enabled:+ return suffix+ server = DuckgresServer.objects.get(organization_id=organization_id)DuckgresServerTeam.objects.create(server=server, team_id=team_id, backfill_enabled=True, table_suffix=suffix)return suffix@@ -656,6 +690,7 @@ def get_team_backfill_state(team_id: int) -> dict[str, object]:__all__ = ["DucklingBackfillEnableError","attach_catalog",+ "check_team_backfill_enable","default_bucket_region","duckgres_data_imports_schema","duckgres_data_imports_table_name",@@ -680,5 +715,6 @@ __all__ = ["run_smoke_check","sanitize_ducklake_identifier","validate_duckgres_identifier",+ "validate_schema_name","validate_table_suffix",]diff --git a/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.html b/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.htmlindex 9f0cb9b20d85..746e6d06187b 100644--- a/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.html+++ b/posthog/templates/admin/posthog/duckgres_server/enable_backfill_form.html@@ -2,10 +2,10 @@{% load i18n %}{% block content %}-<p>Add another team to this organization's existing managed warehouse. Runs the same flow as the-in-product enable-backfill API: records the team's <code>DuckgresServerTeam</code> membership with its-own per-environment table suffix. The organization's feature-flag is not required here.</p>+<p>Onboard another team onto this organization's existing managed warehouse. Runs the same flow as the+in-product onboarding API: creates the duckgres team row and records the team's+<code>DuckgresServerTeam</code> membership with its schema name as the backfill suffix. The+organization's feature flag is not required here.</p><p>Organization: <code>{{ server.organization_id }}</code> — server <code>{{ server.host }}</code></p>@@ -16,12 +16,13 @@ flag is not required here.</p><input type="text" id="team_id" name="team_id" style="width: 400px; padding: 8px;" required /></div><div style="margin: 20px 0;">- <label for="table_name" style="display: block; margin-bottom: 5px; font-weight: bold;">Table suffix:</label>- <input type="text" id="table_name" name="table_name" style="width: 400px; padding: 8px;" required />- <p class="help">Lowercase letters, numbers and underscores. Must be unique within the org's warehouse.</p>+ <label for="schema_name" style="display: block; margin-bottom: 5px; font-weight: bold;">Schema name:</label>+ <input type="text" id="schema_name" name="schema_name" style="width: 400px; padding: 8px;" required />+ <p class="help">Lowercase letters, numbers and underscores. Must be unique within the org's warehouse.+ The schema name cannot be changed later.</p></div><div style="margin-top: 20px;">- <input type="submit" class="default" value="Enable backfill" style="padding: 10px 20px;" />+ <input type="submit" class="default" value="Onboard team" style="padding: 10px 20px;" /><a href="{% url 'admin:posthog_duckgresserver_change' server.pk %}" style="margin-left: 10px;">Cancel</a></div></form>diff --git a/posthog/templates/admin/posthog/duckgres_server/provision_form.html b/posthog/templates/admin/posthog/duckgres_server/provision_form.htmlindex 80ef6c16a37e..bd0e901525f5 100644--- a/posthog/templates/admin/posthog/duckgres_server/provision_form.html+++ b/posthog/templates/admin/posthog/duckgres_server/provision_form.html@@ -26,9 +26,9 @@ records for the team. The organization's <code>data-warehouse-scene</code> featu<p class="help">Becomes the connection's SNI subdomain — 3-63 chars, lowercase letters, numbers and hyphens, starting with a letter.</p></div><div style="margin: 20px 0;">- <label for="table_name" style="display: block; margin-bottom: 5px; font-weight: bold;">Table suffix:</label>- <input type="text" id="table_name" name="table_name" style="width: 400px; padding: 8px;" required />- <p class="help">The team's per-environment table suffix — lowercase letters, numbers and underscores. The backfill writes to <code>events_<suffix></code> / <code>persons_<suffix></code>.</p>+ <label for="schema_name" style="display: block; margin-bottom: 5px; font-weight: bold;">Schema name:</label>+ <input type="text" id="schema_name" name="schema_name" style="width: 400px; padding: 8px;" required />+ <p class="help">The team's schema in the warehouse (lowercase letters, numbers and underscores). The schema name cannot be changed later.</p></div><div style="margin-top: 20px;"><input type="submit" class="default" value="Provision" style="padding: 10px 20px;" />diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.pyindex af0a3d07041c..56595d22650d 100644--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py@@ -824,10 +824,11 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"ProvisionWarehouseRequest",fields={"database_name": serializers.CharField(help_text="Name for the new database"),- "table_name": serializers.CharField(- help_text="Name for the provisioning project's warehouse tables (events_<name>, persons_<name>, "- "…). Lowercase letters, numbers, and underscores only; used verbatim as the suffix. Required "- "so the first project gets its own per-environment tables."+ "schema_name": serializers.CharField(+ help_text="Schema name for the provisioning project's data in the warehouse. Lowercase "+ "letters, numbers, and underscores only, max 63 characters. Cannot be changed later. "+ "Required — the first project gets its own schema, and other projects pick theirs when "+ "they join."),},),@@ -857,46 +858,46 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):self.team.organization_id,request.data.get("database_name"),self.team_id,- request.data.get("table_name"),+ request.data.get("schema_name"),)@extend_schema(request=inline_serializer(- "EnableWarehouseBackfillRequest",+ "OnboardWarehouseTeamRequest",fields={- "table_name": serializers.CharField(- help_text="Name for this environment's warehouse tables (events_<name>, persons_<name>, …). "- "Lowercase letters, numbers, and underscores only; used verbatim as the suffix and must be "- "unique across the organization's environments."+ "schema_name": serializers.CharField(+ help_text="Schema name for this project's data in the organization's warehouse. Lowercase "+ "letters, numbers, and underscores only, max 63 characters. Must be unique within the "+ "organization and cannot be changed later.")},),responses={200: inline_serializer(- "EnableWarehouseBackfillResponse",+ "OnboardWarehouseTeamResponse",fields={- "enabled": serializers.BooleanField(help_text="Whether warehouse backfill is now enabled"),- "table_suffix": serializers.CharField(- help_text="Suffix used for this environment's tables (events_<suffix>, persons_<suffix>)"+ "onboarded": serializers.BooleanField(+ help_text="Whether this project is now onboarded onto the managed warehouse"),+ "schema_name": serializers.CharField(help_text="Schema this project's data lands in"),},)},)- @action(methods=["POST"], detail=False, required_scopes=["warehouse_view:write"])- def enable_backfill(self, request: Request, **kwargs) -> Response:- """Enable warehouse backfill for this environment with a dedicated set of tables.+ @action(methods=["POST"], detail=False, url_path="onboard-team", required_scopes=["warehouse_view:write"])+ def onboard_team(self, request: Request, **kwargs) -> Response:+ """Onboard this project onto the organization's existing managed warehouse.- Requires a table name and records the environment's membership in the- organization's managed warehouse. Restricted to organization admins.+ Requires a schema name; records the project's membership both in duckgres and in the+ Django backfill state. Restricted to organization admins."""- admin_error = self._require_organization_admin(request, "enable backfill for")+ admin_error = self._require_organization_admin(request, "onboard this project for")if admin_error is not None:return admin_error- return managed_warehouse.enable_backfill(+ return managed_warehouse.onboard_team(self.team.organization_id,self.team.id,- request.data.get("table_name"),+ request.data.get("schema_name"),)@extend_schema(@@ -992,16 +993,26 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):help_text="This project's per-environment table suffix (events_<suffix>). Null when the ""project still writes to the shared tables.",),+ "team_onboarded": serializers.BooleanField(+ help_text="Whether this project is onboarded onto the managed warehouse. False when the "+ "warehouse exists but this project has not picked a schema yet — show the onboarding "+ "screen in that case."+ ),+ "schema_name": serializers.CharField(+ allow_null=True,+ help_text="Schema this project's data lands in. Null when the project is not onboarded.",+ ),},)},)@action(methods=["GET"], detail=False)def warehouse_status(self, request: Request, **kwargs) -> Response:- """Get the current provisioning status of the managed warehouse, with this project's backfill state."""+ """Get the current provisioning status of the managed warehouse, with this project's onboarding state."""resp = managed_warehouse.status_for(self.team.organization_id)if resp.status_code == 200 and isinstance(resp.data, dict):resp.data.update(managed_warehouse.team_backfill_state(self.team_id))+ resp.data.update(managed_warehouse.team_onboarding_state(self.team.organization_id, self.team_id))return resp@extend_schema(responses={200: ManagedWarehouseDataStatusResponseSerializer})@@ -1072,3 +1083,32 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):def check_database_name(self, request: Request, **kwargs) -> Response:"""Check if a database name is available."""return managed_warehouse.check_name(self.team.organization_id, request.query_params.get("name"))++ @extend_schema(+ parameters=[+ inline_serializer(+ "CheckSchemaNameRequest",+ fields={"name": serializers.CharField(help_text="Schema name to check")},+ )+ ],+ responses={+ 200: inline_serializer(+ "CheckSchemaNameResponse",+ fields={+ "name": serializers.CharField(help_text="The schema name that was checked"),+ "available": serializers.BooleanField(+ help_text="Whether the schema name is free within the organization's warehouse"+ ),+ },+ )+ },+ )+ @action(methods=["GET"], detail=False, url_path="check-schema-name")+ def check_schema_name(self, request: Request, **kwargs) -> Response:+ """Check if a schema name is free within the organization's managed warehouse."""+ # Same gate as onboard_team: the check scans every project's schema in the org, so a+ # non-admin could otherwise probe names and learn what inaccessible projects use.+ admin_error = self._require_organization_admin(request, "check schema names for")+ if admin_error:+ return admin_error+ return managed_warehouse.check_schema_name(self.team.organization_id, request.query_params.get("name"))diff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.pyindex 5cb1ed30fe0c..f8b1c9ebd7c3 100644--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py@@ -11,7 +11,7 @@ per organization (not per team)."""import re-from typing import TypedDict+from typing import TypedDict, castfrom uuid import UUIDfrom django.conf import settings@@ -194,29 +194,29 @@ def provision(organization_id: UUID | str,database_name: str | None,team_id: int,- table_name: str | None,+ schema_name: str | None,require_enabled: bool = True,) -> Response:name_error = validate_warehouse_name(database_name)if name_error:return Response({"error": name_error}, status=status.HTTP_400_BAD_REQUEST)- # Validate the table name up front: the duckling backfill setup runs best-effort after the+ # Validate the schema name up front: the duckling backfill setup runs best-effort after the# provision call, so a bad name there would be swallowed — catch it before provisioning.- table_name_error = _validate_table_name(table_name)- if table_name_error or table_name is None:- return Response({"error": table_name_error or "table_name is required"}, status=status.HTTP_400_BAD_REQUEST)+ schema_name_error = _validate_schema_name(schema_name)+ if schema_name_error or schema_name is None:+ return Response({"error": schema_name_error or "schema_name is required"}, status=status.HTTP_400_BAD_REQUEST)resp = _request("POST",organization_id,"/provision",json_body={"database_name": database_name,- # The provisioning team is the warehouse's default team: duckgres pins it so- # queries without an explicit team resolve to this environment's tables. It's- # required — duckgres denies a provision without it. In-product this is the- # calling (currently active) team; in the Django admin it's the mandatory team- # field on the provision form.- "default_team_id": team_id,+ # The provisioning team becomes the warehouse's first team (and its billing+ # team): duckgres creates its team row with this schema. In-product this is+ # the calling (currently active) team; in the Django admin it's the mandatory+ # team field on the provision form.+ "team_id": team_id,+ "schema_name": schema_name,"ducklake": {"enabled": True},"metadata_store": {"type": "cnpg-shard"},"data_store": {"type": "s3bucket"},@@ -225,7 +225,7 @@ def provision()if status.is_success(resp.status_code) and isinstance(resp.data, dict):_persist_duckgres_server(organization_id, database_name, resp.data)- _register_provisioning_team(organization_id, team_id, table_name)+ _register_provisioning_team(organization_id, team_id, schema_name)# The bucket is internal infra detail, persisted above and consumed by the# backfill via cp_bucket_for — not part of the UI-facing ProvisionWarehouseResponse# schema. Strip it so the response matches its OpenAPI contract.@@ -239,12 +239,12 @@ def _strip_bucket_fields(body: dict) -> None:body.pop("bucket_region", None)-def _validate_table_name(name: str | None) -> str | None:- """Return an error message if `name` isn't a valid events/persons table suffix, else None."""+def _validate_schema_name(name: str | None) -> str | None:+ """Return an error message if `name` isn't a valid duckgres schema name, else None."""# Keep ducklake.common (and its duckdb dependency) off the API import path.- from posthog.ducklake.common import validate_table_suffix # noqa: PLC0415+ from posthog.ducklake.common import validate_schema_name # noqa: PLC0415- return validate_table_suffix(name)+ return validate_schema_name(name)def team_backfill_state(team_id: int) -> dict:@@ -255,14 +255,15 @@ def team_backfill_state(team_id: int) -> dict:return get_team_backfill_state(team_id)-def _register_provisioning_team(organization_id: UUID | str, team_id: int, table_name: str) -> None:+def _register_provisioning_team(organization_id: UUID | str, team_id: int, schema_name: str) -> None:"""Record the provisioning (calling) team's duckling membership and enable its backfill.A managed warehouse is org-scoped, but membership and backfills are per team, so provisionregisters only the provisioning team: a single `DuckgresServerTeam` row carrying its- membership and a backfill enabled with the per-environment table name the admin chose at- provision — so a newly provisioned org writes to its own `events_<suffix>` tables. Other teams- join later via `enable_backfill`, which runs the same path.+ membership and a backfill enabled with the schema name chosen at provision (stored as the+ team's table suffix, which Dagster still reads). duckgres creates its own team row from the+ provision request itself. Other teams join later via `onboard_team`, which runs the same+ dual-write.Best-effort, mirroring `_persist_duckgres_server`: a failure is logged, not raised, so theone-time provision password is never lost to it.@@ -271,7 +272,7 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int, tablefrom posthog.ducklake.common import enable_team_backfill # noqa: PLC0415try:- enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=table_name)+ enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=schema_name)except Exception:logger.exception("Failed to register provisioning team after provision", team_id=team_id)@@ -319,35 +320,323 @@ def _persist_duckgres_server(organization_id: UUID | str, database_name: str | Nlogger.exception("Failed to persist DuckgresServer after provision", organization_id=str(organization_id))-def enable_backfill(- organization_id: UUID | str, team_id: int, table_name: str | None, require_enabled: bool = True+def list_teams(organization_id: UUID | str, require_enabled: bool = True) -> Response:+ """List the org's duckgres team rows (schema names, legacy table names, billing flag)."""+ return _request("GET", organization_id, "/teams", require_enabled=require_enabled)+++def create_team(+ organization_id: UUID | str,+ team_id: int,+ schema_name: str | None,+ *,+ enabled: bool | None = None,+ backfill_enabled: bool | None = None,+ events_table_name: str | None = None,+ persons_table_name: str | None = None,+ schema_data_imports_name: str | None = None,+ require_enabled: bool = True,) -> Response:- """Enable warehouse backfill for a team's environment with dedicated per-environment tables.+ """Upsert a team row in the org's duckgres warehouse.- Per-team (not org-wide): persists the per-environment table suffix and team↔duckling- membership on the team's DuckgresServerTeam. Gated on the org's feature flag so- a team can't enable a backfill for an org that isn't entitled to the managed warehouse;- backend/ops callers (the Django admin) pass `require_enabled=False` to bypass that gate.+ duckgres answers 409 when the schema name is already used by another team in the org.+ Legacy table-name fields are only sent when set — leaving them NULL makes duckgres derive+ the layout (`<schema_name>.events`, `<schema_name>.persons`, `<schema_name>_data_imports.*`);+ grandfathered teams pass their explicit legacy names instead.+ """+ schema_error = _validate_schema_name(schema_name)+ if schema_error:+ return Response({"error": schema_error}, status=status.HTTP_400_BAD_REQUEST)+ body: dict = {"team_id": team_id, "schema_name": schema_name}+ optional_fields = {+ "enabled": enabled,+ "backfill_enabled": backfill_enabled,+ "events_table_name": events_table_name,+ "persons_table_name": persons_table_name,+ "schema_data_imports_name": schema_data_imports_name,+ }+ body.update({key: value for key, value in optional_fields.items() if value is not None})+ return _request("POST", organization_id, "/teams", json_body=body, require_enabled=require_enabled)+++def delete_team(organization_id: UUID | str, team_id: int, require_enabled: bool = True) -> Response:+ """Delete a team row from the org's duckgres warehouse.++ duckgres answers 409 for the org's last team (the org must be deprovisioned or deleted+ instead) and reassigns the billing flag to the oldest remaining team otherwise.+ """+ return _request("DELETE", organization_id, f"/teams/{team_id}", require_enabled=require_enabled)+++def onboard_team(+ organization_id: UUID | str, team_id: int, schema_name: str | None, require_enabled: bool = True+) -> Response:+ """Onboard a team onto the org's existing managed warehouse with its own schema.++ Dual-write: creates the duckgres team row (the control plane owns schema uniqueness and+ answers 409 on a conflict) and the Django DuckgresServerTeam backfill row, which Dagster+ still reads. The Django guards run first so a name the team can't use (already onboarded+ with a different name, suffix collision) is rejected before anything is written to the+ control plane — the duckgres upsert would otherwise overwrite an existing row's schema.++ Backend/ops callers (the Django admin) pass `require_enabled=False` to bypass the+ org feature-flag gate."""if require_enabled and not is_enabled(organization_id):return Response({"error": "This feature is not enabled"}, status=status.HTTP_403_FORBIDDEN)- table_name_error = _validate_table_name(table_name)- if table_name_error or table_name is None:- return Response({"error": table_name_error or "table_name is required"}, status=status.HTTP_400_BAD_REQUEST)+ schema_error = _validate_schema_name(schema_name)+ if schema_error or schema_name is None:+ return Response({"error": schema_error or "schema_name is required"}, status=status.HTTP_400_BAD_REQUEST)# Keep ducklake.common (and its duckdb dependency) off the API import path.- from posthog.ducklake.common import DucklingBackfillEnableError, enable_team_backfill # noqa: PLC0415+ from posthog.ducklake.common import ( # noqa: PLC0415+ DucklingBackfillEnableError,+ check_team_backfill_enable,+ enable_team_backfill,+ )try:- suffix = enable_team_backfill(- team_id=team_id,- organization_id=organization_id,- table_name=table_name,+ check_team_backfill_enable(team_id=team_id, organization_id=organization_id, table_name=schema_name)+ except DucklingBackfillEnableError as exc:+ return Response({"error": str(exc)}, status=status.HTTP_400_BAD_REQUEST)++ resp = create_team(organization_id, team_id, schema_name, require_enabled=require_enabled)+ if resp.status_code == status.HTTP_409_CONFLICT:+ return Response(+ {"error": f"The schema name '{schema_name}' is already used by another project in this organization."},+ status=status.HTTP_409_CONFLICT,)+ if not status.is_success(resp.status_code):+ return resp++ try:+ suffix = enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=schema_name)except DucklingBackfillEnableError as exc:+ # Rare race: the guards above passed but the write lost to a concurrent onboard. The+ # duckgres upsert is idempotent, so a retry after the user picks another name is safe.return Response({"error": str(exc)}, status=status.HTTP_400_BAD_REQUEST)- return Response({"enabled": True, "table_suffix": suffix}, status=status.HTTP_200_OK)+ return Response({"onboarded": True, "schema_name": suffix}, status=status.HTTP_200_OK)+++def _grandfathered_team_fields(team_id: int, table_suffix: str | None) -> dict:+ """Map an existing Django backfill row to an explicit duckgres team payload.++ Grandfathered teams predate the derived `<schema_name>.events` layout, so their legacy+ table names are pinned explicitly: suffixed tables when a suffix is set, the shared+ `events`/`persons` tables (what the duckling DAG writes for a NULL suffix) otherwise.+ """+ if table_suffix:+ return {+ "schema_name": table_suffix,+ "events_table_name": f"events_{table_suffix}",+ "persons_table_name": f"persons_{table_suffix}",+ "schema_data_imports_name": f"posthog_data_imports_{table_suffix}",+ }+ return {+ "schema_name": f"team_{team_id}",+ "events_table_name": "events",+ "persons_table_name": "persons",+ "schema_data_imports_name": f"posthog_data_imports_team_{team_id}",+ }+++def _teams_from_response(resp: Response) -> list[dict] | None:+ """Extract the team rows from a list-teams response, or None when unusable."""+ if not status.is_success(resp.status_code):+ return None+ data = resp.data+ if isinstance(data, dict):+ data = data.get("teams")+ if not isinstance(data, list):+ return None+ return [row for row in data if isinstance(row, dict)]+++def team_onboarding_state(organization_id: UUID | str, team_id: int) -> dict:+ """Resolve the calling team's duckgres onboarding state for the warehouse-status response.++ Best-effort on the control-plane side: a failed list-teams call falls back to the Django+ backfill row and never fails the status read.++ Lazy grandfather backfill: a team with a Django backfill row but no duckgres team row yet+ (onboarded before the control plane tracked teams) is pushed to duckgres here, with its+ explicit legacy table names. The push is idempotent (the control plane upserts) and+ best-effort — a failure is logged and retried on the next status read.++ Reverse heal: a duckgres team row without a Django backfill row means a dual-write lost its+ second half (provision registered the team with the control plane but the Django write+ failed, or `onboard_team`'s Django write raced). Recreate the Django row from the duckgres+ schema here so Dagster picks the team up, instead of reporting it onboarded forever with no+ backfill. Only rows without explicit legacy table names are healed — those are the ones the+ dual-write created, where schema name and table suffix are the same identifier.+ """+ # Keep ducklake.common (and its duckdb dependency) off the API import path.+ from posthog.ducklake.common import get_team_backfill_state # noqa: PLC0415++ backfill = get_team_backfill_state(team_id)+ has_django_row = bool(backfill["has_backfill"])+ table_suffix = cast(str | None, backfill["table_suffix"])++ duckgres_team: dict | None = None+ try:+ teams = _teams_from_response(list_teams(organization_id, require_enabled=False))+ if teams is not None:+ duckgres_team = next((row for row in teams if row.get("team_id") == team_id), None)+ if duckgres_team is None and has_django_row:+ duckgres_team = _push_grandfathered_team(organization_id, team_id, table_suffix)+ elif duckgres_team is not None and not has_django_row:+ _heal_django_backfill_row(organization_id, team_id, duckgres_team)+ except Exception:+ logger.exception(+ "Failed to resolve duckgres team onboarding state",+ organization_id=str(organization_id),+ team_id=team_id,+ )++ schema_name: str | None = None+ if duckgres_team is not None:+ schema_name = duckgres_team.get("schema_name")+ elif has_django_row:+ # Control plane unreachable but the team is onboarded Django-side: report the schema+ # its grandfather push will claim.+ schema_name = _grandfathered_team_fields(team_id, table_suffix)["schema_name"]++ return {"team_onboarded": duckgres_team is not None or has_django_row, "schema_name": schema_name}+++def _push_grandfathered_team(organization_id: UUID | str, team_id: int, table_suffix: str | None) -> dict | None:+ """Push a Django-only warehouse team into duckgres. Returns the pushed row, or None on failure."""+ fields = _grandfathered_team_fields(team_id, table_suffix)+ resp = create_team(+ organization_id,+ team_id,+ fields["schema_name"],+ events_table_name=fields["events_table_name"],+ persons_table_name=fields["persons_table_name"],+ schema_data_imports_name=fields["schema_data_imports_name"],+ require_enabled=False,+ )+ if not status.is_success(resp.status_code):+ logger.warning(+ "Failed to push grandfathered team to duckgres",+ organization_id=str(organization_id),+ team_id=team_id,+ status_code=resp.status_code,+ )+ return None+ logger.info(+ "duckgres_grandfathered_team_pushed",+ organization_id=str(organization_id),+ team_id=team_id,+ schema_name=fields["schema_name"],+ )+ return {"team_id": team_id, **fields}+++def _heal_django_backfill_row(organization_id: UUID | str, team_id: int, duckgres_team: dict) -> None:+ """Recreate the missing Django backfill row for a duckgres-registered team. Best-effort.++ Guarded to rows without explicit legacy table names: those came from the dual-write+ (provision or onboard), where the duckgres schema name IS the Django table suffix. Rows+ with legacy overrides originate from the grandfather push, which only runs off an existing+ Django row — a missing one there is unexpected, so it's logged rather than guessed at.+ """+ # Keep ducklake.common (and its duckdb dependency) off the API import path.+ from posthog.ducklake.common import enable_team_backfill # noqa: PLC0415++ schema_name = duckgres_team.get("schema_name")+ has_legacy_names = any(+ duckgres_team.get(key) for key in ("events_table_name", "persons_table_name", "schema_data_imports_name")+ )+ if not schema_name or has_legacy_names:+ logger.warning(+ "Duckgres team has no Django backfill row and cannot be healed",+ organization_id=str(organization_id),+ team_id=team_id,+ has_legacy_names=has_legacy_names,+ )+ return+ try:+ enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=schema_name)+ logger.info(+ "duckgres_team_django_backfill_healed",+ organization_id=str(organization_id),+ team_id=team_id,+ schema_name=schema_name,+ )+ except Exception:+ logger.exception(+ "Failed to heal Django backfill row for duckgres team",+ organization_id=str(organization_id),+ team_id=team_id,+ )+++def check_schema_name(organization_id: UUID | str, name: str | None) -> Response:+ """Check whether a schema name is free within the org's warehouse.++ Checks both the duckgres team rows and the Django backfill suffixes: a Django-only row+ (not yet lazily grandfathered into duckgres) still owns its future schema name.+ """+ schema_error = _validate_schema_name(name)+ if schema_error:+ return Response({"error": schema_error}, status=status.HTTP_400_BAD_REQUEST)++ resp = list_teams(organization_id)+ teams = _teams_from_response(resp)+ if teams is None:+ return resp++ taken = any(row.get("schema_name") == name for row in teams)+ if not taken:+ # Keep ducklake.models (via ducklake.common's import graph) off the API import path.+ from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415++ taken = DuckgresServerTeam.objects.filter(team__organization_id=organization_id, table_suffix=name).exists()++ return Response({"name": name, "available": not taken}, status=status.HTTP_200_OK)+++def block_team_deletion(team_id: int, organization_id: UUID | str) -> str | None:+ """Remove the team from the org's duckgres warehouse ahead of a Django team deletion.++ Returns a user-facing error message when the deletion must be blocked, else None.+ Narrow coupling: orgs without a managed warehouse never trigger a control-plane call, so+ unrelated team deletions are unaffected by a duckgres outage.++ duckgres refuses to delete the org's last team (409) — the warehouse must be deprovisioned+ (or the organization deleted) first, so the Django deletion is blocked with that guidance.+ When the control plane can't confirm the deletion for a team that is warehouse-onboarded,+ the deletion is blocked with a retry error rather than silently orphaning the duckgres row.+ """+ # Keep ducklake.models off the core API import path.+ from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415++ if not DuckgresServer.objects.filter(organization_id=organization_id).exists():+ return None++ resp = delete_team(organization_id, team_id, require_enabled=False)+ if status.is_success(resp.status_code) or resp.status_code == status.HTTP_404_NOT_FOUND:+ return None+ if resp.status_code == status.HTTP_409_CONFLICT:+ return (+ "This is the last project in your organization's managed warehouse. "+ "Deprovision the managed warehouse in Data ops settings, or delete the organization, "+ "before deleting this project."+ )+ if DuckgresServerTeam.objects.filter(team_id=team_id).exists():+ return "Could not remove this project from your organization's managed warehouse. Try again in a few minutes."+ # Org has a warehouse but this team has no Django backfill row: almost certainly not+ # onboarded, so a control-plane hiccup must not block its deletion. If a duckgres-only+ # row does exist it is orphaned here, which the control plane tolerates.+ logger.warning(+ "Proceeding with team deletion despite duckgres delete-team failure",+ organization_id=str(organization_id),+ team_id=team_id,+ status_code=resp.status_code,+ )+ return Nonedef deprovision(organization_id: UUID | str, require_enabled: bool = True) -> Response:diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse.pyindex 80e5f22f3b7a..6067f4232c74 100644--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py@@ -60,9 +60,9 @@ def test_provision_persists_duckgres_server_on_success(mock_request: MagicMock)@pytest.mark.django_db@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_provision_sends_default_team_id_to_control_plane(mock_request: MagicMock) -> None:- # duckgres denies a provision without a default team, so the provisioning team must be- # forwarded as default_team_id in the outbound body.+def test_provision_sends_team_id_and_schema_name_to_control_plane(mock_request: MagicMock) -> None:+ # The provisioning team becomes the warehouse's first (billing) team via the org-teams+ # API: the outbound body carries team_id + schema_name and never default_team_id.org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)mock_request.return_value = Response(@@ -70,10 +70,12 @@ def test_provision_sends_default_team_id_to_control_plane(mock_request: MagicMocstatus=202,)- managed_warehouse.provision(org.id, "my-warehouse", team.id, "events")+ managed_warehouse.provision(org.id, "my-warehouse", team.id, "prod_events")json_body = mock_request.call_args.kwargs["json_body"]- assert json_body["default_team_id"] == team.id+ assert json_body["team_id"] == team.id+ assert json_body["schema_name"] == "prod_events"+ assert "default_team_id" not in json_body@parameterized.expand(@@ -336,7 +338,7 @@ def test_cp_bucket_for_bypasses_feature_gate_and_reconciles(mock_internal: Magic@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")-def test_provision_rejects_invalid_table_name(mock_request: MagicMock) -> None:+def test_provision_rejects_invalid_schema_name(mock_request: MagicMock) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)@@ -392,13 +394,22 @@ def test_cp_bucket_for_returns_none_when_cp_has_no_bucket(mock_request: MagicMoc@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-def test_enable_backfill_creates_backfill_and_membership(mock_enabled: MagicMock) -> None:+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_dual_writes_duckgres_and_django(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:org, team, server = _provisioned_org()+ mock_request.return_value = Response({"team_id": team.id, "schema_name": "my_events"}, status=200)- resp = managed_warehouse.enable_backfill(org.id, team.id, "my_events")+ resp = managed_warehouse.onboard_team(org.id, team.id, "my_events")assert resp.status_code == 200- assert resp.data == {"enabled": True, "table_suffix": "my_events"}+ assert resp.data == {"onboarded": True, "schema_name": "my_events"}++ # duckgres team row created via the org-teams upsert, without legacy table names+ # (NULL legacy fields mean the derived <schema>.events layout).+ method, org_id, path = mock_request.call_args.args+ assert (method, org_id, path) == ("POST", org.id, "/teams")+ json_body = mock_request.call_args.kwargs["json_body"]+ assert json_body == {"team_id": team.id, "schema_name": "my_events"}link = DuckgresServerTeam.objects.get(server=server, team_id=team.id)assert link.backfill_enabled is True@@ -407,47 +418,75 @@ def test_enable_backfill_creates_backfill_and_membership(mock_enabled: MagicMock@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-def test_enable_backfill_rejects_invalid_name(mock_enabled: MagicMock) -> None:+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_surfaces_duckgres_schema_conflict(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:+ # duckgres owns cross-team schema uniqueness (it also knows grandfathered schemas Django+ # doesn't) — its 409 must reach the caller as a clear conflict, with no Django row written.+ org, team, _ = _provisioned_org()+ mock_request.return_value = Response({"error": "schema already in use"}, status=409)++ resp = managed_warehouse.onboard_team(org.id, team.id, "taken")++ assert resp.status_code == 409+ assert "taken" in resp.data["error"]+ assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_rejects_invalid_name_before_control_plane(+ mock_request: MagicMock, _mock_enabled: MagicMock+) -> None:org, team, _ = _provisioned_org()for bad_name in ("", "My Project", "my-project"):- resp = managed_warehouse.enable_backfill(org.id, team.id, bad_name)+ resp = managed_warehouse.onboard_team(org.id, team.id, bad_name)assert resp.status_code == 400, bad_name+ mock_request.assert_not_called()assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-def test_enable_backfill_rejects_duplicate_suffix_in_org(mock_enabled: MagicMock) -> None:+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_rejects_duplicate_suffix_before_control_plane(+ mock_request: MagicMock, _mock_enabled: MagicMock+) -> None:+ # The Django guard must run before the duckgres upsert: the upsert overwrites an existing+ # row's schema, so a rejected name must never reach the control plane.org, team_a, server = _provisioned_org()team_b = Team.objects.create(organization=org, name="Env B")DuckgresServerTeam.objects.create(server=server, team=team_a, table_suffix="shared")- resp = managed_warehouse.enable_backfill(org.id, team_b.id, "shared")+ resp = managed_warehouse.onboard_team(org.id, team_b.id, "shared")assert resp.status_code == 400+ mock_request.assert_not_called()assert not DuckgresServerTeam.objects.filter(team_id=team_b.id).exists()@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-def test_enable_backfill_without_provisioned_server(mock_enabled: MagicMock) -> None:+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_without_provisioned_server(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org, name="Env")- resp = managed_warehouse.enable_backfill(org.id, team.id, "events")+ resp = managed_warehouse.onboard_team(org.id, team.id, "events")assert resp.status_code == 400assert "provision" in resp.data["error"].lower()+ mock_request.assert_not_called()@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=False)-def test_enable_backfill_gated_on_feature_flag(mock_enabled: MagicMock) -> None:+def test_onboard_team_gated_on_feature_flag(mock_enabled: MagicMock) -> None:org, team, _ = _provisioned_org()- resp = managed_warehouse.enable_backfill(org.id, team.id, "events")+ resp = managed_warehouse.onboard_team(org.id, team.id, "events")assert resp.status_code == 403assert not DuckgresServerTeam.objects.filter(team_id=team.id).exists()@@ -455,11 +494,13 @@ def test_enable_backfill_gated_on_feature_flag(mock_enabled: MagicMock) -> None:@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-def test_enable_backfill_same_name_is_idempotent(mock_enabled: MagicMock) -> None:+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_same_name_is_idempotent(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:org, team, _ = _provisioned_org()+ mock_request.return_value = Response({"team_id": team.id, "schema_name": "first"}, status=200)- managed_warehouse.enable_backfill(org.id, team.id, "first")- resp = managed_warehouse.enable_backfill(org.id, team.id, "first")+ managed_warehouse.onboard_team(org.id, team.id, "first")+ resp = managed_warehouse.onboard_team(org.id, team.id, "first")assert resp.status_code == 200assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1@@ -468,27 +509,36 @@ def test_enable_backfill_same_name_is_idempotent(mock_enabled: MagicMock) -> Non@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-def test_enable_backfill_refuses_to_change_an_existing_suffix(mock_enabled: MagicMock) -> None:+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_refuses_to_change_an_existing_suffix(mock_request: MagicMock, _mock_enabled: MagicMock) -> None:org, team, _ = _provisioned_org()- managed_warehouse.enable_backfill(org.id, team.id, "first")+ mock_request.return_value = Response({"team_id": team.id, "schema_name": "first"}, status=200)+ managed_warehouse.onboard_team(org.id, team.id, "first")+ mock_request.reset_mock()- resp = managed_warehouse.enable_backfill(org.id, team.id, "second")+ resp = managed_warehouse.onboard_team(org.id, team.id, "second")- # Changing a set suffix would split the team's data across two tables — rejected, unchanged.+ # Changing a set suffix would split the team's data across two tables — rejected before+ # the control plane, so the duckgres row keeps its schema too.assert resp.status_code == 400+ mock_request.assert_not_called()assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix == "first"@pytest.mark.django_db@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)-def test_enable_backfill_refuses_to_set_a_suffix_on_a_legacy_shared_team(mock_enabled: MagicMock) -> None:+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+def test_onboard_team_refuses_to_set_a_suffix_on_a_legacy_shared_team(+ mock_request: MagicMock, _mock_enabled: MagicMock+) -> None:org, team, server = _provisioned_org()# A legacy team already backfilling to the shared tables (NULL suffix), e.g. backfilled by migration.DuckgresServerTeam.objects.create(server=server, team=team, backfill_enabled=True, table_suffix=None)- resp = managed_warehouse.enable_backfill(org.id, team.id, "new_name")+ resp = managed_warehouse.onboard_team(org.id, team.id, "new_name")assert resp.status_code == 400+ mock_request.assert_not_called()assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix is None@@ -507,3 +557,326 @@ def test_delete_org_issues_delete_to_org_root(mock_internal: MagicMock, _mock_enmethod, url = mock_internal.request.call_args.argsassert method == "DELETE"assert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}"+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.internal_requests")+@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")+def test_list_teams_hits_org_teams_route(mock_internal: MagicMock, _mock_enabled: MagicMock) -> None:+ org_id = uuid4()+ mock_internal.request.return_value = MagicMock(status_code=200, **{"json.return_value": []})++ resp = managed_warehouse.list_teams(org_id)++ assert resp.status_code == 200+ method, url = mock_internal.request.call_args.args+ assert method == "GET"+ assert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}/teams"+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.internal_requests")+@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")+def test_create_team_posts_upsert_with_only_set_optional_fields(+ mock_internal: MagicMock, _mock_enabled: MagicMock+) -> None:+ # Unset legacy fields must be omitted entirely — sending them as null would make duckgres+ # treat a derived-layout team as explicitly named.+ org_id = uuid4()+ mock_internal.request.return_value = MagicMock(status_code=200, **{"json.return_value": {}})++ resp = managed_warehouse.create_team(+ org_id, 42, "my_schema", events_table_name="events_my", persons_table_name="persons_my"+ )++ assert resp.status_code == 200+ method, url = mock_internal.request.call_args.args+ assert method == "POST"+ assert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}/teams"+ assert mock_internal.request.call_args.kwargs["json"] == {+ "team_id": 42,+ "schema_name": "my_schema",+ "events_table_name": "events_my",+ "persons_table_name": "persons_my",+ }+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.internal_requests")+def test_create_team_rejects_invalid_schema_name(mock_internal: MagicMock, _mock_enabled: MagicMock) -> None:+ resp = managed_warehouse.create_team(uuid4(), 42, "Bad Name")++ assert resp.status_code == 400+ mock_internal.request.assert_not_called()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.internal_requests")+@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")+def test_delete_team_hits_org_team_route(mock_internal: MagicMock, _mock_enabled: MagicMock) -> None:+ org_id = uuid4()+ mock_internal.request.return_value = MagicMock(status_code=200, **{"json.return_value": {}})++ resp = managed_warehouse.delete_team(org_id, 42)++ assert resp.status_code == 200+ method, url = mock_internal.request.call_args.args+ assert method == "DELETE"+ assert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}/teams/42"+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_team_onboarding_state_for_duckgres_team(mock_list: MagicMock, mock_create: MagicMock) -> None:+ # Branch b: the duckgres row exists — onboarded, no grandfather push.+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ mock_list.return_value = Response([{"team_id": team.id, "schema_name": "mine"}], status=200)++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": True, "schema_name": "mine"}+ mock_create.assert_not_called()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_team_onboarding_state_for_unonboarded_team(mock_list: MagicMock, mock_create: MagicMock) -> None:+ # Branch c: warehouse exists but this team has no row anywhere — the onboarding screen case.+ org, team, _ = _provisioned_org()+ mock_list.return_value = Response([{"team_id": team.id + 1, "schema_name": "other"}], status=200)++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": False, "schema_name": None}+ mock_create.assert_not_called()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_team_onboarding_state_heals_missing_django_row(mock_list: MagicMock) -> None:+ # Reverse heal: a dual-write that lost its Django half (provision registered the team with+ # duckgres but enable_team_backfill failed) is repaired on the next status read, so Dagster+ # picks the team up instead of it reporting onboarded forever with no backfill.+ org, team, _ = _provisioned_org()+ mock_list.return_value = Response([{"team_id": team.id, "schema_name": "healed_env"}], status=200)++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": True, "schema_name": "healed_env"}+ row = DuckgresServerTeam.objects.get(team=team)+ assert row.table_suffix == "healed_env"+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_team_onboarding_state_refuses_to_heal_legacy_named_row(mock_list: MagicMock) -> None:+ # A duckgres row with explicit legacy table names came from the grandfather push (which only+ # runs off an existing Django row) — a missing Django row there is unexpected, so the heal+ # must not guess a suffix that would rename the team's tables.+ org, team, _ = _provisioned_org()+ mock_list.return_value = Response(+ [{"team_id": team.id, "schema_name": "team_x", "events_table_name": "events"}], status=200+ )++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": True, "schema_name": "team_x"}+ assert not DuckgresServerTeam.objects.filter(team=team).exists()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_team_onboarding_state_survives_failed_heal(mock_list: MagicMock) -> None:+ # A heal that loses to a suffix collision is logged, never failing the status read.+ org, team, server = _provisioned_org()+ other_team = Team.objects.create(organization=org, name="other")+ DuckgresServerTeam.objects.create(server=server, team=other_team, table_suffix="taken_env")+ mock_list.return_value = Response([{"team_id": team.id, "schema_name": "taken_env"}], status=200)++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": True, "schema_name": "taken_env"}+ assert not DuckgresServerTeam.objects.filter(team=team).exists()+++ [+ # suffix set: schema is the suffix, explicit suffixed legacy names+ (+ "with_suffix",+ "prod_env",+ {+ "schema_name": "prod_env",+ "events_table_name": "events_prod_env",+ "persons_table_name": "persons_prod_env",+ "schema_data_imports_name": "posthog_data_imports_prod_env",+ },+ ),+ # NULL suffix: legacy shared tables and the team-id data-imports schema+ (+ "without_suffix",+ None,+ {+ "schema_name": None, # filled per-team below+ "events_table_name": "events",+ "persons_table_name": "persons",+ "schema_data_imports_name": None, # filled per-team below+ },+ ),+ ]+)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.internal_requests")+@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")+def test_team_onboarding_state_lazily_grandfathers_django_only_team(+ _name: str,+ table_suffix: str | None,+ expected: dict,+ mock_internal: MagicMock,+ mock_list: MagicMock,+) -> None:+ # A team onboarded before the control plane tracked teams (Django row only) is pushed to+ # duckgres during the status read, pinning its explicit legacy table names.+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=table_suffix)+ mock_list.return_value = Response([], status=200)+ mock_internal.request.return_value = MagicMock(status_code=200, **{"json.return_value": {}})++ expected = {+ **expected,+ "schema_name": expected["schema_name"] or f"team_{team.id}",+ "schema_data_imports_name": expected["schema_data_imports_name"] or f"posthog_data_imports_team_{team.id}",+ }++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": True, "schema_name": expected["schema_name"]}+ assert mock_internal.request.call_args.kwargs["json"] == {"team_id": team.id, **expected}+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_team_onboarding_state_survives_control_plane_failure(mock_list: MagicMock, mock_create: MagicMock) -> None:+ # The status read must never fail on the control plane: a Django-onboarded team still+ # reports as onboarded (with its would-be schema) when list-teams errors.+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ mock_list.return_value = Response({"error": "unreachable"}, status=502)++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": True, "schema_name": "mine"}+ mock_create.assert_not_called()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.create_team")+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_team_onboarding_state_survives_failed_grandfather_push(mock_list: MagicMock, mock_create: MagicMock) -> None:+ # A failed push is logged and retried on the next status read; the team still reports+ # onboarded from its Django row.+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ mock_list.return_value = Response([], status=200)+ mock_create.return_value = Response({"error": "boom"}, status=500)++ state = managed_warehouse.team_onboarding_state(org.id, team.id)++ assert state == {"team_onboarded": True, "schema_name": "mine"}+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_check_schema_name_availability(mock_list: MagicMock) -> None:+ # Taken by a duckgres row, taken by a Django-only (not yet grandfathered) suffix, or free.+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="django_only")+ mock_list.return_value = Response([{"team_id": 999, "schema_name": "in_duckgres"}], status=200)++ for name, available in (("in_duckgres", False), ("django_only", False), ("fresh_name", True)):+ resp = managed_warehouse.check_schema_name(org.id, name)+ assert resp.status_code == 200, name+ assert resp.data == {"name": name, "available": available}+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams")+def test_check_schema_name_rejects_invalid_name(mock_list: MagicMock) -> None:+ resp = managed_warehouse.check_schema_name(uuid4(), "Bad Name")++ assert resp.status_code == 400+ mock_list.assert_not_called()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.delete_team")+def test_block_team_deletion_skips_orgs_without_warehouse(mock_delete: MagicMock) -> None:+ # Teams with no warehouse involvement must never trigger a control-plane call.+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)++ assert managed_warehouse.block_team_deletion(team.id, org.id) is None+ mock_delete.assert_not_called()+++ [+ ("deleted", 200, None),+ ("not_in_duckgres", 404, None),+ ]+)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.delete_team")+def test_block_team_deletion_proceeds_when_duckgres_row_gone(+ _name: str, cp_status: int, expected: None, mock_delete: MagicMock+) -> None:+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ mock_delete.return_value = Response({}, status=cp_status)++ assert managed_warehouse.block_team_deletion(team.id, org.id) is expected+ mock_delete.assert_called_once_with(org.id, team.id, require_enabled=False)+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.delete_team")+def test_block_team_deletion_blocks_last_warehouse_team(mock_delete: MagicMock) -> None:+ # duckgres 409s on the org's last team: the Django deletion must be blocked with guidance+ # to deprovision the warehouse (or delete the organization) instead.+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ mock_delete.return_value = Response({"error": "last team"}, status=409)++ reason = managed_warehouse.block_team_deletion(team.id, org.id)++ assert reason is not None+ assert "deprovision" in reason.lower()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.delete_team")+def test_block_team_deletion_blocks_onboarded_team_when_control_plane_unreachable(mock_delete: MagicMock) -> None:+ # An onboarded team must not be silently orphaned in duckgres — block with a retry error.+ org, team, server = _provisioned_org()+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="mine")+ mock_delete.return_value = Response({"error": "unreachable"}, status=502)++ reason = managed_warehouse.block_team_deletion(team.id, org.id)++ assert reason is not None+ assert "try again" in reason.lower()+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.delete_team")+def test_block_team_deletion_lets_unonboarded_team_through_on_control_plane_error(mock_delete: MagicMock) -> None:+ # The org has a warehouse but this team is not onboarded Django-side: a control-plane+ # outage must not brick its deletion.+ org, team, _ = _provisioned_org()+ mock_delete.return_value = Response({"error": "unreachable"}, status=502)++ assert managed_warehouse.block_team_deletion(team.id, org.id) is Nonediff --git a/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py b/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.pyindex 3632f054a09c..79af785cd788 100644--- a/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py+++ b/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py@@ -142,13 +142,39 @@ class TestDataWarehouseViewSetAccessControl(WarehouseAccessControlTestMixin):response = self.client.post(self._path("provision/"),- data={"database_name": "x", "table_name": "x"},+ data={"database_name": "x", "schema_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", self.team.id, "x")+ @patch("products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.check_schema_name")+ def test_check_schema_name_blocked_for_project_editor_who_is_not_org_admin(self, mock_check):+ # The check scans every project's schema in the org, so a non-admin could otherwise+ # probe names and learn what inaccessible projects use.+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)++ response = self.client.get(self._path("check-schema-name/?name=probe"))++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_check.assert_not_called()++ @patch("products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.check_schema_name")+ def test_check_schema_name_allowed_for_org_admin(self, mock_check):+ mock_check.return_value = Response({"name": "probe", "available": True}, status=status.HTTP_200_OK)+ 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.get(self._path("check-schema-name/?name=probe"))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_check.assert_called_once_with(self.team.organization_id, "probe")+@patch("products.data_warehouse.backend.presentation.views.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"})diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex a33a76f440ab..db4e660736ce 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -58,6 +58,13 @@ export interface CheckDatabaseNameResponseApi {available: boolean}+export interface CheckSchemaNameResponseApi {+ /** The schema name that was checked */+ name: string+ /** Whether the schema name is free within the organization's warehouse */+ available: boolean+}+export interface DeleteWarehouseOrgResponseApi {/** Deletion lifecycle message from the provisioner */status?: string@@ -72,18 +79,6 @@ export interface DeprovisionWarehouseResponseApi {org: string}-export interface EnableWarehouseBackfillRequestApi {- /** Name for this environment's warehouse tables (events_<name>, persons_<name>, …). Lowercase letters, numbers, and underscores only; used verbatim as the suffix and must be unique across the organization's environments. */- table_name: string-}--export interface EnableWarehouseBackfillResponseApi {- /** Whether warehouse backfill is now enabled */- enabled: boolean- /** Suffix used for this environment's tables (events_<suffix>, persons_<suffix>) */- table_suffix: string-}-/*** * `not_configured` - not_configured* * `waiting` - waiting@@ -269,11 +264,23 @@ export interface ManagedWarehouseSourceSchemasResponseApi {schemas: ManagedWarehouseSourceTableStatusApi[]}+export interface OnboardWarehouseTeamRequestApi {+ /** Schema name for this project's data in the organization's warehouse. Lowercase letters, numbers, and underscores only, max 63 characters. Must be unique within the organization and cannot be changed later. */+ schema_name: string+}++export interface OnboardWarehouseTeamResponseApi {+ /** Whether this project is now onboarded onto the managed warehouse */+ onboarded: boolean+ /** Schema this project's data lands in */+ schema_name: string+}+export interface ProvisionWarehouseRequestApi {/** Name for the new database */database_name: string- /** Name for the provisioning project's warehouse tables (events_<name>, persons_<name>, …). Lowercase letters, numbers, and underscores only; used verbatim as the suffix. Required so the first project gets its own per-environment tables. */- table_name: string+ /** Schema name for the provisioning project's data in the warehouse. Lowercase letters, numbers, and underscores only, max 63 characters. Cannot be changed later. Required — the first project gets its own schema, and other projects pick theirs when they join. */+ schema_name: string}export interface ProvisionWarehouseResponseApi {@@ -363,6 +370,13 @@ export interface WarehouseStatusResponseApi {* @nullable*/table_suffix: string | null+ /** Whether this project is onboarded onto the managed warehouse. False when the warehouse exists but this project has not picked a schema yet — show the onboarding screen in that case. */+ team_onboarded: boolean+ /**+ * Schema this project's data lands in. Null when the project is not onboarded.+ * @nullable+ */+ schema_name: string | null}/**@@ -3137,6 +3151,14 @@ export type DataWarehouseCheckDatabaseNameRetrieveParams = {name: string}+export type DataWarehouseCheckSchemaNameRetrieveParams = {+ /**+ * Schema name to check+ * @minLength 1+ */+ name: string+}+export type DataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {/*** Imported source connection to fetch per-schema detail for.diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex ae21822f8bec..295beb1a0a66 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -10,9 +10,11 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'*/import type {CheckDatabaseNameResponseApi,+ CheckSchemaNameResponseApi,DataModelingJobApi,DataModelingJobsListParams,DataWarehouseCheckDatabaseNameRetrieveParams,+ DataWarehouseCheckSchemaNameRetrieveParams,DataWarehouseManagedWarehouseSourceSchemasRetrieveParams,DataWarehouseModelPathApi,DataWarehouseSavedQueryApi,@@ -21,13 +23,13 @@ import type {DataWarehouseSavedQueryFolderApi,DeleteWarehouseOrgResponseApi,DeprovisionWarehouseResponseApi,- EnableWarehouseBackfillRequestApi,- EnableWarehouseBackfillResponseApi,FixHogqlListParams,InsightVariableApi,InsightVariablesListParams,ManagedWarehouseDataStatusResponseApi,ManagedWarehouseSourceSchemasResponseApi,+ OnboardWarehouseTeamRequestApi,+ OnboardWarehouseTeamResponseApi,PaginatedDataModelingJobListApi,PaginatedDataWarehouseModelPathListApi,PaginatedDataWarehouseSavedQueryColumnAnnotationListApi,@@ -202,6 +204,39 @@ export const dataWarehouseCheckDatabaseNameRetrieve = async (})}+export const getDataWarehouseCheckSchemaNameRetrieveUrl = (+ projectId: string,+ params: DataWarehouseCheckSchemaNameRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/data_warehouse/check-schema-name/?${stringifiedParams}`+ : `/api/projects/${projectId}/data_warehouse/check-schema-name/`+}++/**+ * Check if a schema name is free within the organization's managed warehouse.+ */+export const dataWarehouseCheckSchemaNameRetrieve = async (+ projectId: string,+ params: DataWarehouseCheckSchemaNameRetrieveParams,+ options?: RequestInit+): Promise<CheckSchemaNameResponseApi> => {+ return apiMutator<CheckSchemaNameResponseApi>(getDataWarehouseCheckSchemaNameRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getDataWarehouseCompletedActivityRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/data_warehouse/completed_activity/`}@@ -293,29 +328,6 @@ export const dataWarehouseDeprovisionCreate = async (})}-export const getDataWarehouseEnableBackfillCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/data_warehouse/enable_backfill/`-}--/**- * Enable warehouse backfill for this environment with a dedicated set of tables.- *- * Requires a table name and records the environment's membership in the- * organization's managed warehouse. Restricted to organization admins.- */-export const dataWarehouseEnableBackfillCreate = async (- projectId: string,- enableWarehouseBackfillRequestApi: EnableWarehouseBackfillRequestApi,- options?: RequestInit-): Promise<EnableWarehouseBackfillResponseApi> => {- return apiMutator<EnableWarehouseBackfillResponseApi>(getDataWarehouseEnableBackfillCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(enableWarehouseBackfillRequestApi),- })-}-export const getDataWarehouseJobStatsRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/data_warehouse/job_stats/`}@@ -388,6 +400,29 @@ export const dataWarehouseManagedWarehouseSourceSchemasRetrieve = async ()}+export const getDataWarehouseOnboardTeamCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_warehouse/onboard-team/`+}++/**+ * Onboard this project onto the organization's existing managed warehouse.+ *+ * Requires a schema name; records the project's membership both in duckgres and in the+ * Django backfill state. Restricted to organization admins.+ */+export const dataWarehouseOnboardTeamCreate = async (+ projectId: string,+ onboardWarehouseTeamRequestApi: OnboardWarehouseTeamRequestApi,+ options?: RequestInit+): Promise<OnboardWarehouseTeamResponseApi> => {+ return apiMutator<OnboardWarehouseTeamResponseApi>(getDataWarehouseOnboardTeamCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(onboardWarehouseTeamRequestApi),+ })+}+export const getDataWarehousePropertyValuesRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/data_warehouse/property_values/`}@@ -474,7 +509,7 @@ export const getDataWarehouseWarehouseStatusRetrieveUrl = (projectId: string) =>}/**- * Get the current provisioning status of the managed warehouse, with this project's backfill state.+ * Get the current provisioning status of the managed warehouse, with this project's onboarding state.*/export const dataWarehouseWarehouseStatusRetrieve = async (projectId: string,diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.tsindex fc0c983261a1..5b7cb79f1f78 100644--- a/products/data_warehouse/frontend/generated/api.zod.ts+++ b/products/data_warehouse/frontend/generated/api.zod.ts@@ -10,16 +10,16 @@import * as zod from 'zod'/**- * Enable warehouse backfill for this environment with a dedicated set of tables.+ * Onboard this project onto the organization's existing managed warehouse.*- * Requires a table name and records the environment's membership in the- * organization's managed warehouse. Restricted to organization admins.+ * Requires a schema name; records the project's membership both in duckgres and in the+ * Django backfill state. Restricted to organization admins.*/-export const DataWarehouseEnableBackfillCreateBody = /* @__PURE__ */ zod.object({- table_name: zod+export const DataWarehouseOnboardTeamCreateBody = /* @__PURE__ */ zod.object({+ schema_name: zod.string().describe(- "Name for this environment's warehouse tables (events_<name>, persons_<name>, …). Lowercase letters, numbers, and underscores only; used verbatim as the suffix and must be unique across the organization's environments."+ "Schema name for this project's data in the organization's warehouse. Lowercase letters, numbers, and underscores only, max 63 characters. Must be unique within the organization and cannot be changed later."),})@@ -28,10 +28,10 @@ export const DataWarehouseEnableBackfillCreateBody = /* @__PURE__ */ zod.object(*/export const DataWarehouseProvisionCreateBody = /* @__PURE__ */ zod.object({database_name: zod.string().describe('Name for the new database'),- table_name: zod+ schema_name: zod.string().describe(- "Name for the provisioning project's warehouse tables (events_<name>, persons_<name>, …). Lowercase letters, numbers, and underscores only; used verbatim as the suffix. Required so the first project gets its own per-environment tables."+ "Schema name for the provisioning project's data in the warehouse. Lowercase letters, numbers, and underscores only, max 63 characters. Cannot be changed later. Required — the first project gets its own schema, and other projects pick theirs when they join."),})diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex f83c499fb220..4a63da335ba7 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -24,6 +24,9 @@ tools:data-warehouse-check-database-name-retrieve:operation: data_warehouse_check_database_name_retrieveenabled: false+ data-warehouse-check-schema-name-retrieve:+ operation: data_warehouse_check_schema_name_retrieve+ enabled: falsedata-warehouse-completed-activity-retrieve:operation: data_warehouse_completed_activity_retrieveenabled: false@@ -39,9 +42,6 @@ tools:data-warehouse-deprovision-create:operation: data_warehouse_deprovision_createenabled: false- data-warehouse-enable-backfill-create:- operation: data_warehouse_enable_backfill_create- enabled: falsedata-warehouse-job-stats-retrieve:operation: data_warehouse_job_stats_retrieveenabled: false@@ -51,6 +51,9 @@ tools:data-warehouse-managed-warehouse-source-schemas-retrieve:operation: data_warehouse_managed_warehouse_source_schemas_retrieveenabled: false+ data-warehouse-onboard-team-create:+ operation: data_warehouse_onboard_team_create+ enabled: falsedata-warehouse-property-values-retrieve:operation: data_warehouse_property_values_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 87e873919fac..6e8d6d13c086 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13957,6 +13957,13 @@ export namespace Schemas {available: boolean;}+ export interface CheckSchemaNameResponse {+ /** The schema name that was checked */+ name: string;+ /** Whether the schema name is free within the organization's warehouse */+ available: boolean;+ }+/*** * `new` - new* * `rate_shift` - rate_shift@@ -21545,18 +21552,6 @@ export namespace Schemas {remediation: string | null;}- export interface EnableWarehouseBackfillRequest {- /** Name for this environment's warehouse tables (events_<name>, persons_<name>, …). Lowercase letters, numbers, and underscores only; used verbatim as the suffix and must be unique across the organization's environments. */- table_name: string;- }-- export interface EnableWarehouseBackfillResponse {- /** Whether warehouse backfill is now enabled */- enabled: boolean;- /** Suffix used for this environment's tables (events_<suffix>, persons_<suffix>) */- table_suffix: string;- }-export interface EndExperiment {/** The conclusion of the experiment.*@@ -36713,6 +36708,18 @@ export namespace Schemas {results: unknown[][];}+ export interface OnboardWarehouseTeamRequest {+ /** Schema name for this project's data in the organization's warehouse. Lowercase letters, numbers, and underscores only, max 63 characters. Must be unique within the organization and cannot be changed later. */+ schema_name: string;+ }++ export interface OnboardWarehouseTeamResponse {+ /** Whether this project is now onboarded onto the managed warehouse */+ onboarded: boolean;+ /** Schema this project's data lands in */+ schema_name: string;+ }+/*** * `later` - Later* * `other` - Other@@ -52230,8 +52237,8 @@ export namespace Schemas {export interface ProvisionWarehouseRequest {/** Name for the new database */database_name: string;- /** Name for the provisioning project's warehouse tables (events_<name>, persons_<name>, …). Lowercase letters, numbers, and underscores only; used verbatim as the suffix. Required so the first project gets its own per-environment tables. */- table_name: string;+ /** Schema name for the provisioning project's data in the warehouse. Lowercase letters, numbers, and underscores only, max 63 characters. Cannot be changed later. Required — the first project gets its own schema, and other projects pick theirs when they join. */+ schema_name: string;}export interface ProvisionWarehouseResponse {@@ -63958,6 +63965,13 @@ export namespace Schemas {* @nullable*/table_suffix: string | null;+ /** Whether this project is onboarded onto the managed warehouse. False when the warehouse exists but this project has not picked a schema yet — show the onboarding screen in that case. */+ team_onboarded: boolean;+ /**+ * Schema this project's data lands in. Null when the project is not onboarded.+ * @nullable+ */+ schema_name: string | null;}/**@@ -66945,6 +66959,14 @@ export namespace Schemas {name: string;};+ export type EnvironmentsDataWarehouseCheckSchemaNameRetrieveParams = {+ /**+ * Schema name to check+ * @minLength 1+ */+ name: string;+ };+export type EnvironmentsDataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {/*** Imported source connection to fetch per-schema detail for.@@ -73622,6 +73644,14 @@ export namespace Schemas {name: string;};+ export type DataWarehouseCheckSchemaNameRetrieveParams = {+ /**+ * Schema name to check+ * @minLength 1+ */+ name: string;+ };+export type DataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {/*** Imported source connection to fetch per-schema detail for.