: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): finish managed warehouse deprovision by removing org record (#68722)
Benjamin Knofe-Viderbc44ff313e02
diff --git a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsxindex 20aacc7e1d1a..ff15f98ad03f 100644--- a/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx+++ b/frontend/src/scenes/data-warehouse/scene/SettingsTab.tsx@@ -90,6 +90,7 @@ export function SettingsTab(): JSX.Element {isProvisioning,isDeprovisioning,isInProgress,+ deprovisionTakingLong,databaseName,databaseNameAvailable,databaseNameChecking,@@ -266,15 +267,22 @@ export function SettingsTab(): JSX.Element {) : (<div className="space-y-4">{isInProgress && (- <LemonBanner type="info">+ <LemonBanner type={deprovisionTakingLong ? 'warning' : 'info'}><div className="flex items-center gap-2"><Spinner /><span>- {warehouseStatus?.state === 'deleting'- ? 'Deprovisioning in progress...'- : 'Provisioning in progress...'}+ {warehouseStatus?.status_message ||+ (warehouseStatus?.state === 'deleting'+ ? 'Deprovisioning in progress...'+ : 'Provisioning in progress...')}</span></div>+ {deprovisionTakingLong && (+ <p className="text-muted text-xs mt-2 mb-0">+ Teardown is taking longer than usual. It keeps retrying until the warehouse is fully+ removed, so this will finish on its own. You can safely leave this page.+ </p>+ )}</LemonBanner>)}diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.tsindex f882d09c48de..fba2ecd714d8 100644--- a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.test.ts@@ -62,6 +62,90 @@ describe('warehouseProvisioningLogic', () => {}).toMatchValues({ isValidDatabaseName: true, canProvision: true })})+ it('removes the org record once teardown reports the warehouse deleted, then stops polling', async () => {+ // Teardown reports `deleted` once; after delete-org the record is gone so status 404s.+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve')+ .mockResolvedValueOnce({ state: 'deleted' } as any)+ .mockResolvedValue(null as any)+ const deleteOrg = jest.spyOn(dwApi, 'dataWarehouseDeleteOrgDestroy').mockResolvedValue({} as any)++ logic = warehouseProvisioningLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['deleteOrg', 'deleteOrgComplete', 'stopPolling'])+ expect(deleteOrg).toHaveBeenCalledTimes(1)+ expect(logic.values.pollingActive).toBe(false)+ })++ it('retries removing the org record when the first delete-org attempt fails', async () => {+ // First status read is `deleted`; the successful retry then 404s, stopping the poll loop.+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve')+ .mockResolvedValueOnce({ state: 'deleted' } as any)+ .mockResolvedValue(null as any)+ const deleteOrg = jest+ .spyOn(dwApi, 'dataWarehouseDeleteOrgDestroy')+ .mockRejectedValueOnce({ message: 'boom' })+ .mockResolvedValue({} as any)++ logic = warehouseProvisioningLogic()+ logic.mount()++ // First attempt fails and settles, clearing the in-flight guard.+ await expectLogic(logic).toDispatchActions(['deleteOrg', 'deleteOrgComplete'])+ expect(logic.values.isDeletingOrg).toBe(false)++ // The next poll re-observing `deleted` re-fires delete-org rather than staying stuck.+ await expectLogic(logic, () => {+ logic.actions.loadWarehouseStatusSuccess({ state: 'deleted' } as any)+ }).toDispatchActions(['deleteOrg'])+ expect(deleteOrg).toHaveBeenCalledTimes(2)+ })++ it('does not re-delete the org when a stale `deleted` status arrives after a successful delete', async () => {+ // A single `deleted` read triggers the delete; the retry mock returns null thereafter.+ jest.spyOn(dwApi, 'dataWarehouseWarehouseStatusRetrieve')+ .mockResolvedValueOnce({ state: 'deleted' } as any)+ .mockResolvedValue(null as any)+ const deleteOrg = jest.spyOn(dwApi, 'dataWarehouseDeleteOrgDestroy').mockResolvedValue({} as any)++ logic = warehouseProvisioningLogic()+ logic.mount()++ // First `deleted` read deletes the org; success latches the guard.+ await expectLogic(logic).toDispatchActions(['deleteOrg', 'deleteOrgComplete'])+ expect(logic.values.orgDeletionSucceeded).toBe(true)++ // Provisioner propagation lag can still report `deleted` after the record is gone; the latch+ // must stop that from firing a second delete against an already-deleted org.+ await expectLogic(logic, () => {+ logic.actions.loadWarehouseStatusSuccess({ state: 'deleted' } as any)+ }).toNotHaveDispatchedActions(['deleteOrg'])+ expect(deleteOrg).toHaveBeenCalledTimes(1)+ })++ it('flags a stuck teardown once it sits in `deleting` past the warn threshold', async () => {+ logic = warehouseProvisioningLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWarehouseStatusSuccess'])++ // One `deleting` read is still "in progress", not yet "taking long".+ await expectLogic(logic, () => {+ logic.actions.loadWarehouseStatusSuccess({ state: 'deleting' } as any)+ }).toMatchValues({ deprovisionTakingLong: false })++ // 18 consecutive `deleting` reads (~3 min of polling) trips the affordance.+ await expectLogic(logic, () => {+ for (let i = 0; i < 17; i++) {+ logic.actions.loadWarehouseStatusSuccess({ state: 'deleting' } as any)+ }+ }).toMatchValues({ deprovisionTakingLong: true })++ // A non-`deleting` read resets the counter.+ await expectLogic(logic, () => {+ logic.actions.loadWarehouseStatusSuccess({ state: 'ready' } as any)+ }).toMatchValues({ deprovisionTakingLong: false })+ })+it('surfaces an info message instead of an error when a sibling project already provisioned (409)', async () => {jest.spyOn(dwApi, 'dataWarehouseProvisionCreate').mockRejectedValueOnce({ status: 409 })const infoToast = jest.spyOn(lemonToast, 'info').mockReturnValue(undefined as any)diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.tsindex cf6b91b9ae4a..97caac1ef0a4 100644--- a/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts+++ b/frontend/src/scenes/data-warehouse/scene/warehouseProvisioningLogic.ts@@ -9,6 +9,7 @@ import { Region } from '~/types'import {dataWarehouseCheckDatabaseNameRetrieve,+ dataWarehouseDeleteOrgDestroy,dataWarehouseDeprovisionCreate,dataWarehouseEnableBackfillCreate,dataWarehouseProvisionCreate,@@ -39,6 +40,12 @@ const TABLE_NAME_REGEX = /^[a-z0-9_]{1,63}$/const databaseNameStorageKey = (teamId: number | null): string =>`warehouse-provisioning-database-name-${teamId ?? 'unknown'}`+// Status is polled every 10s. Deprovision teardown has no terminal `failed` state (the+// provisioner retries indefinitely), so a genuinely stuck teardown sits in `deleting` forever.+// After this many consecutive `deleting` polls (~3 min) we surface a "still working" affordance+// instead of spinning silently. It's advisory only; polling continues.+const DELETING_POLL_WARN_THRESHOLD = 18+const currentProjectId = (): string => String(teamLogic.values.currentTeamId)export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([@@ -53,6 +60,8 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([provisionWarehouseComplete: true,deprovisionWarehouse: true,deprovisionWarehouseComplete: true,+ deleteOrg: true,+ deleteOrgComplete: (success: boolean) => ({ success }),resetPassword: true,resetPasswordComplete: true,setInitialPassword: (password: string) => ({ password }),@@ -102,6 +111,46 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([deprovisionWarehouseComplete: () => false,},],+ // Consecutive `deleting` status reads, to detect a teardown that's stuck (no terminal+ // failed state exists, so it would otherwise poll forever). Reset whenever the state+ // isn't `deleting` and when a fresh deprovision starts.+ deletingPollCount: [+ 0,+ {+ loadWarehouseStatusSuccess: (state, { warehouseStatus }) =>+ warehouseStatus?.state === 'deleting' ? state + 1 : 0,+ deprovisionWarehouse: () => 0,+ },+ ],+ // In-flight flag for the automatic delete-org call. Doubles as the fire guard: while a+ // delete-org is running we don't start another, but once it settles (success or failure)+ // the next `deleted` poll can retry.+ isDeletingOrg: [+ false,+ {+ deleteOrg: () => true,+ deleteOrgComplete: () => false,+ },+ ],+ // Latched once delete-org succeeds so a status read still reporting `deleted` (provisioner+ // propagation lag before the record 404s) can't trigger a second delete against the now-gone+ // org. Cleared on a fresh deprovision so a later cycle can delete again.+ orgDeletionSucceeded: [+ false,+ {+ deleteOrgComplete: (state, { success }) => success || state,+ deprovisionWarehouse: () => false,+ },+ ],+ // Whether the last delete-org attempt failed, so we notify the user once per failure+ // streak instead of on every 10s retry. Cleared on success and on a new deprovision.+ orgDeletionFailed: [+ false,+ {+ deleteOrgComplete: (_, { success }) => !success,+ deprovisionWarehouse: () => false,+ },+ ],pollingActive: [false,{@@ -204,6 +253,13 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([return status.state === 'pending' || status.state === 'provisioning' || status.state === 'deleting'},],+ // True once teardown has sat in `deleting` past the warn threshold, so the UI can show a+ // "still working" note rather than an indefinite spinner.+ deprovisionTakingLong: [+ (s) => [s.warehouseStatus, s.deletingPollCount],+ (status, deletingPollCount): boolean =>+ status?.state === 'deleting' && deletingPollCount >= DELETING_POLL_WARN_THRESHOLD,+ ],isValidDatabaseName: [(s) => [s.databaseName], (name): boolean => WAREHOUSE_NAME_REGEX.test(name)],// DNS zone for the connection host, resolved from the deployment region (null when unknown).warehouseDomain: [@@ -335,17 +391,40 @@ export const warehouseProvisioningLogic = kea<warehouseProvisioningLogicType>([actions.loadWarehouseStatus()},+ deleteOrg: async () => {+ try {+ // Teardown is done (status is `deleted`); remove the now-empty org record so+ // its database_name is freed. On success the next status read 404s and the UI+ // returns to the provisioning form.+ await dataWarehouseDeleteOrgDestroy(currentProjectId())+ actions.loadWarehouseStatus()+ actions.deleteOrgComplete(true)+ } catch (e: any) {+ // Polling stays active while `deleted`, so the next tick retries this; notify+ // once per failure streak rather than on every retry.+ if (!values.orgDeletionFailed) {+ lemonToast.error(`Failed to finish removing the warehouse: ${e.message || 'Unknown error'}`)+ }+ actions.deleteOrgComplete(false)+ }+ },+loadWarehouseStatusSuccess: ({ warehouseStatus }) => {- if (warehouseStatus?.state === 'deleted') {+ const state = warehouseStatus?.state+ if (state === 'deleted') {actions.setLastRequestedDatabaseName(null)window.localStorage.removeItem(databaseNameStorageKey(teamLogic.values.currentTeamId))+ // Teardown finished, so remove the org row to free the name. Skip if a delete is+ // already in flight or has already succeeded (a stale `deleted` read during+ // propagation lag must not re-delete); a failed attempt retries on the next poll.+ if (!values.isDeletingOrg && !values.orgDeletionSucceeded) {+ actions.deleteOrg()+ }}- if (- warehouseStatus &&- (warehouseStatus.state === 'pending' ||- warehouseStatus.state === 'provisioning' ||- warehouseStatus.state === 'deleting')- ) {+ // Keep polling while teardown is in flight, and while the org record still needs+ // removing (`deleted`) so a failed delete-org retries on the next tick. A+ // successful delete-org 404s the next read, which falls through to stopPolling.+ if (state === 'pending' || state === 'provisioning' || state === 'deleting' || state === 'deleted') {actions.pollStatus()} else {actions.stopPolling()diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.pyindex 817db37d45b2..79328687bf9a 100644--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py@@ -913,6 +913,35 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return admin_errorreturn managed_warehouse.deprovision(self.team.organization_id)+ @extend_schema(+ responses={+ 200: inline_serializer(+ "DeleteWarehouseOrgResponse",+ fields={+ "status": serializers.CharField(+ required=False, help_text="Deletion lifecycle message from the provisioner"+ ),+ "org": serializers.CharField(+ required=False,+ help_text="duckgres org identifier (the PostHog organization id)",+ ),+ },+ )+ },+ )+ @action(methods=["DELETE"], detail=False, url_path="delete-org", required_scopes=["warehouse_view:write"])+ def delete_org(self, request: Request, **kwargs) -> Response:+ """Remove the organization's provisioning record after teardown, freeing its warehouse name.++ Called once the warehouse status reports `deleted`: deprovision tears the warehouse+ down, this removes the now-empty org row so the database_name can be reused. Restricted+ to organization admins.+ """+ admin_error = self._require_organization_admin(request, "delete the provisioning record for")+ if admin_error is not None:+ return admin_error+ return managed_warehouse.delete_org(self.team.organization_id)+@extend_schema(responses={200: inline_serializer(diff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.pyindex d5fea9dc655c..3f134e300d48 100644--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py@@ -121,7 +121,8 @@ def _request() -> Response:"""Proxy a request to the duckgres provisioning API, gated on the org's feature flag.- Paths starting with "/" are org-scoped (`/api/v1/orgs/{org}{path}`); others are global+ An empty path targets the org resource itself (`/api/v1/orgs/{org}`, e.g. to delete it);+ paths starting with "/" are org-scoped (`/api/v1/orgs/{org}{path}`); others are globalAPI paths (`/api/v1/{path}`).`require_enabled` gates on the user-facing `data-warehouse-scene` flag and is the right@@ -144,7 +145,9 @@ def _request(status=status.HTTP_501_NOT_IMPLEMENTED,)- if path.startswith("/"):+ if path == "":+ url = f"{base_url.rstrip('/')}/api/v1/orgs/{org_id}"+ elif path.startswith("/"):url = f"{base_url.rstrip('/')}/api/v1/orgs/{org_id}{path}"else:url = f"{base_url.rstrip('/')}/api/v1/{path}"@@ -350,6 +353,17 @@ def deprovision(organization_id: UUID | str, require_enabled: bool = True) -> Rereturn _request("POST", organization_id, "/deprovision", require_enabled=require_enabled)+def delete_org(organization_id: UUID | str, require_enabled: bool = True) -> Response:+ """Delete the org's provisioning record once teardown has finished, freeing its warehouse name.++ `deprovision` tears the warehouse down (status goes deleting → deleted); this removes the+ now-empty org row from the control plane so its `database_name` can be reused. Deprovision+ teardown has no terminal failed state (the provisioner retries indefinitely), so callers+ should only issue this once the warehouse status reports `deleted`.+ """+ return _request("DELETE", organization_id, "", require_enabled=require_enabled)++def status_for(organization_id: UUID | str) -> Response:resp = _request("GET", organization_id, "/warehouse/status")if resp.status_code == 200 and isinstance(resp.data, dict):diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse.pyindex 921e40509ce7..2da5169ed0bd 100644--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py@@ -479,3 +479,20 @@ def test_enable_backfill_refuses_to_set_a_suffix_on_a_legacy_shared_team(mock_enassert resp.status_code == 400assert DuckgresServerTeam.objects.get(team_id=team.id).table_suffix is None+++@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_org_issues_delete_to_org_root(mock_internal: MagicMock, _mock_enabled: MagicMock) -> None:+ # Guards the empty-path branch in _request: delete_org must hit the org resource itself,+ # /api/v1/orgs/{org}, not a suffixed org path or the global /api/v1/ route.+ org_id = uuid4()+ mock_internal.request.return_value = MagicMock(status_code=200, **{"json.return_value": {"status": "deleted"}})++ resp = managed_warehouse.delete_org(org_id)++ 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}"diff --git a/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.py b/products/data_warehouse/backend/tests/api/test_misc_warehouse_viewsets_access_control.pyindex f67f3c4e3510..085dbbfb6e12 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@@ -168,6 +168,31 @@ class TestDataWarehouseViewSetAccessControl(WarehouseAccessControlTestMixin):self.assertEqual(response.status_code, status.HTTP_200_OK)mock_reset_password.assert_called_once_with(self.team.organization_id)+ @patch("products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.delete_org")+ def test_delete_org_blocked_for_project_editor_who_is_not_org_admin(self, mock_delete_org):+ mock_delete_org.return_value = Response({"status": "deleted"})+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)++ response = self.client.delete(self._path("delete-org/"))++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_delete_org.assert_not_called()++ @patch("products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.delete_org")+ def test_delete_org_allowed_for_org_admin_with_project_editor_access(self, mock_delete_org):+ mock_delete_org.return_value = Response({"status": "deleted"})+ 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.delete(self._path("delete-org/"))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_delete_org.assert_called_once_with(self.team.organization_id)+@pytest.mark.eeclass TestModelPathViewSetAccessControl(WarehouseAccessControlTestMixin):diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex e48e5fe26f53..d02f95f812cb 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 DeleteWarehouseOrgResponseApi {+ /** Deletion lifecycle message from the provisioner */+ status?: string+ /** duckgres org identifier (the PostHog organization id) */+ org?: string+}+export interface DeprovisionWarehouseResponseApi {/** Deprovisioning lifecycle message, e.g. 'deprovisioning started' */status: stringdiff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 82c1079dfabd..f60b9a73d792 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -18,6 +18,7 @@ import type {DataWarehouseSavedQueryColumnAnnotationApi,DataWarehouseSavedQueryDraftApi,DataWarehouseSavedQueryFolderApi,+ DeleteWarehouseOrgResponseApi,DeprovisionWarehouseResponseApi,EnableWarehouseBackfillRequestApi,EnableWarehouseBackfillResponseApi,@@ -251,6 +252,27 @@ export const dataWarehouseDataOpsDashboardRetrieve = async (})}+export const getDataWarehouseDeleteOrgDestroyUrl = (projectId: string) => {+ return `/api/projects/${projectId}/data_warehouse/delete-org/`+}++/**+ * Remove the organization's provisioning record after teardown, freeing its warehouse name.+ *+ * Called once the warehouse status reports `deleted`: deprovision tears the warehouse+ * down, this removes the now-empty org row so the database_name can be reused. Restricted+ * to organization admins.+ */+export const dataWarehouseDeleteOrgDestroy = async (+ projectId: string,+ options?: RequestInit+): Promise<DeleteWarehouseOrgResponseApi> => {+ return apiMutator<DeleteWarehouseOrgResponseApi>(getDataWarehouseDeleteOrgDestroyUrl(projectId), {+ ...options,+ method: 'DELETE',+ })+}+export const getDataWarehouseDeprovisionCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/data_warehouse/deprovision/`}diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yamlindex eeca38b91590..03934d8d1645 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -33,6 +33,9 @@ tools:data-warehouse-data-ops-dashboard-retrieve:operation: data_warehouse_data_ops_dashboard_retrieveenabled: false+ data-warehouse-delete-org-destroy:+ operation: data_warehouse_delete_org_destroy+ enabled: falsedata-warehouse-deprovision-create:operation: data_warehouse_deprovision_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 92381c72d67f..3ba57bd10509 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17701,6 +17701,13 @@ export namespace Schemas {tile_id: number;}+ export interface DeleteWarehouseOrgResponse {+ /** Deletion lifecycle message from the provisioner */+ status?: string;+ /** duckgres org identifier (the PostHog organization id) */+ org?: string;+ }+/*** * `pending` - Pending* * `delivered` - Delivered