Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(project): lock out project under deletion with pending screen (#62126)

Yasenafd77fbf2e4e
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 1cae9887d5e3..31c5dd4c5cbc 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -1306,6 +1306,11 @@ export interface ProjectBackwardCompatApi {
/** @nullable */
proactive_tasks_enabled?: boolean | null
readonly available_setup_task_ids: readonly AvailableSetupTaskIdsEnumApi[]
+ /**
+ * Set to True when project deletion has been initiated. Blocks UI access to this project until the async task completes.
+ * @nullable
+ */
+ readonly is_pending_deletion: boolean | null
}
export type PatchedProjectBackwardCompatApiGroupTypesItem = { [key: string]: unknown }
@@ -2100,6 +2105,11 @@ export interface PatchedProjectBackwardCompatApi {
/** @nullable */
proactive_tasks_enabled?: boolean | null
readonly available_setup_task_ids?: readonly AvailableSetupTaskIdsEnumApi[]
+ /**
+ * Set to True when project deletion has been initiated. Blocks UI access to this project until the async task completes.
+ * @nullable
+ */
+ readonly is_pending_deletion?: boolean | null
}
export interface PromotedProductIntentApi {
diff --git a/frontend/src/lib/api.mock.ts b/frontend/src/lib/api.mock.ts
index 7fe0f75b980a..d683d702107d 100644
--- a/frontend/src/lib/api.mock.ts
+++ b/frontend/src/lib/api.mock.ts
@@ -223,6 +223,7 @@ export const MOCK_DEFAULT_PROJECT: ProjectType = {
name: 'MockHog App + Marketing',
organization_id: MOCK_ORGANIZATION_ID,
created_at: '2020-06-30T09:53:35.932534Z',
+ is_pending_deletion: false,
}
export const MOCK_DEFAULT_ORGANIZATION: OrganizationType = {
diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.ts
index 15c8c6919571..82e044c4aafe 100644
--- a/frontend/src/scenes/appScenes.ts
+++ b/frontend/src/scenes/appScenes.ts
@@ -140,4 +140,5 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.Wizard]: () => import('./wizard/Wizard'),
[Scene.OrganizationDeactivated]: () => import('./organization/Deactivated'),
[Scene.OrganizationPendingDeletion]: () => import('./organization/PendingDeletion'),
+ [Scene.ProjectPendingDeletion]: () => import('./project/PendingDeletion'),
}
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.stories.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.stories.tsx
index 11acce34360a..02f8d0f76a40 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.stories.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.stories.tsx
@@ -193,6 +193,7 @@ const storySecondProject: ProjectType = {
name: storySecondTeam.name,
organization_id: MOCK_ORGANIZATION_ID,
created_at: MOCK_DEFAULT_PROJECT.created_at,
+ is_pending_deletion: false,
}
const organizationWithMultipleProjects: OrganizationType = {
diff --git a/frontend/src/scenes/project/PendingDeletion.tsx b/frontend/src/scenes/project/PendingDeletion.tsx
new file mode 100644
index 000000000000..cd892b62e5a8
--- /dev/null
+++ b/frontend/src/scenes/project/PendingDeletion.tsx
@@ -0,0 +1,88 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronDown } from '@posthog/icons'
+import { LemonButton, LemonCard } from '@posthog/lemon-ui'
+
+import { newAccountMenuLogic } from 'lib/components/Account/newAccountMenuLogic'
+import { OrgSwitcher } from 'lib/components/Account/OrgSwitcher'
+import { ProjectSwitcher } from 'lib/components/Account/ProjectSwitcher'
+import { HogWelder } from 'lib/components/hedgehogs'
+import { Popover } from 'lib/lemon-ui/Popover/Popover'
+import { SupportModalButton } from 'scenes/authentication/shared/SupportModalButton'
+import { projectLogic } from 'scenes/projectLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+import { userLogic } from 'scenes/userLogic'
+
+export const scene: SceneExport = {
+ component: ProjectPendingDeletion,
+ logic: projectLogic,
+}
+
+export function ProjectPendingDeletion(): JSX.Element {
+ const { currentProject } = useValues(projectLogic)
+ const { otherOrganizations } = useValues(userLogic)
+ const { isProjectSwitcherOpen, isOrgSwitcherOpen } = useValues(newAccountMenuLogic)
+ const { openProjectSwitcher, closeProjectSwitcher, openOrgSwitcher, closeOrgSwitcher } =
+ useActions(newAccountMenuLogic)
+ const hasOtherOrgs = otherOrganizations.length > 0
+
+ return (
+ <div className="max-w-[600px] mx-auto px-2 py-8">
+ <LemonCard>
+ <div className="flex flex-col gap-4 items-center text-center">
+ <HogWelder className="h-80" />
+ <h3>
+ Disassembling {currentProject?.name ? `"${currentProject.name}"` : 'this project'} at the
+ circuit level
+ </h3>
+ <p className="text-secondary">
+ Our hedgehog engineer is carefully taking everything apart. This project will be completely
+ deleted shortly. For projects with lots of data, cleanup can take a while — we'll email you when
+ it's done.
+ </p>
+ <div className="flex items-center gap-2">
+ <Popover
+ visible={isProjectSwitcherOpen}
+ onClickOutside={closeProjectSwitcher}
+ overlay={
+ <div className="w-[320px]">
+ <ProjectSwitcher dialog={false} />
+ </div>
+ }
+ placement="bottom"
+ >
+ <LemonButton
+ type="primary"
+ onClick={() => (isProjectSwitcherOpen ? closeProjectSwitcher() : openProjectSwitcher())}
+ sideIcon={<IconChevronDown />}
+ >
+ Switch project
+ </LemonButton>
+ </Popover>
+ {hasOtherOrgs && (
+ <Popover
+ visible={isOrgSwitcherOpen}
+ onClickOutside={closeOrgSwitcher}
+ overlay={
+ <div className="w-[320px]">
+ <OrgSwitcher dialog={false} />
+ </div>
+ }
+ placement="bottom"
+ >
+ <LemonButton
+ type="secondary"
+ onClick={() => (isOrgSwitcherOpen ? closeOrgSwitcher() : openOrgSwitcher())}
+ sideIcon={<IconChevronDown />}
+ >
+ Switch organization
+ </LemonButton>
+ </Popover>
+ )}
+ </div>
+ <SupportModalButton kind="support" target_area="login" label="Contact support" />
+ </div>
+ </LemonCard>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/projectLogic.ts b/frontend/src/scenes/projectLogic.ts
index 3278b0fc96e3..aeab0f91d553 100644
--- a/frontend/src/scenes/projectLogic.ts
+++ b/frontend/src/scenes/projectLogic.ts
@@ -1,5 +1,6 @@
import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import api, { ApiConfig } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
@@ -20,6 +21,10 @@ export const projectLogic = kea<projectLogicType>([
deleteProject: (project: ProjectType) => ({ project }),
deleteProjectSuccess: true,
deleteProjectFailure: true,
+ guardPendingDeletion: (pathname: string, isPendingDeletion: boolean | null | undefined) => ({
+ pathname,
+ isPendingDeletion,
+ }),
moveProject: (project: ProjectType, organizationId: string) => ({ project, organizationId }),
}),
connect(() => ({
@@ -122,11 +127,26 @@ export const projectLogic = kea<projectLogicType>([
: null,
],
}),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
loadCurrentProjectSuccess: ({ currentProject }) => {
if (currentProject) {
ApiConfig.setCurrentProjectId(currentProject.id)
}
+ // Lock the project out once deletion has been initiated (covers full page loads / reloads)
+ actions.guardPendingDeletion(router.values.location.pathname, currentProject?.is_pending_deletion)
+ },
+ locationChanged: ({ pathname }) => {
+ actions.guardPendingDeletion(pathname, values.currentProject?.is_pending_deletion)
+ },
+ guardPendingDeletion: ({ pathname, isPendingDeletion }) => {
+ // projectBased scenes are served under a /project/:id prefix, so match the lockout path by suffix.
+ const onLockoutScreen = pathname.endsWith(urls.projectPendingDeletion())
+ if (isPendingDeletion && !onLockoutScreen) {
+ router.actions.replace(urls.projectPendingDeletion())
+ } else if (!isPendingDeletion && onLockoutScreen) {
+ // Reached the lockout screen for a project that isn't being deleted (e.g. switched projects) — send home
+ router.actions.replace(urls.projectHomepage())
+ }
},
deleteProject: async ({ project }) => {
try {
@@ -139,9 +159,9 @@ export const projectLogic = kea<projectLogicType>([
}
},
deleteProjectSuccess: () => {
- lemonToast.success('Project deletion started. You will receive an email when complete.')
- // Can't stay on current page since project is being deleted
- window.location.href = '/'
+ lemonToast.success('Project deletion has been initiated')
+ // Full reload so the bootstrap context carries is_pending_deletion and lands on the lockout screen
+ window.location.href = urls.projectPendingDeletion()
},
createProjectSuccess: ({ currentProject }) => {
if (currentProject) {
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index c274ed86c766..fc2bf0821002 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -209,6 +209,7 @@ export enum Scene {
SlackTaskContext = 'SlackTaskContext',
OrganizationDeactivated = 'OrganizationDeactivated',
OrganizationPendingDeletion = 'OrganizationPendingDeletion',
+ ProjectPendingDeletion = 'ProjectPendingDeletion',
CustomerJourneyTemplates = 'CustomerJourneyTemplates',
}
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 8ced562d7e30..ece429381b07 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -620,6 +620,11 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {
name: 'Organization Pending Deletion',
layout: 'plain',
},
+ [Scene.ProjectPendingDeletion]: {
+ projectBased: true,
+ name: 'Project Pending Deletion',
+ layout: 'plain',
+ },
...productConfiguration,
}
@@ -951,5 +956,6 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.hogFunctionNew(':templateId')]: [Scene.HogFunction, 'hogFunctionNew'],
[urls.organizationDeactivated()]: [Scene.OrganizationDeactivated, 'organizationDeactivated'],
[urls.organizationPendingDeletion()]: [Scene.OrganizationPendingDeletion, 'organizationPendingDeletion'],
+ [urls.projectPendingDeletion()]: [Scene.ProjectPendingDeletion, 'projectPendingDeletion'],
...productRoutes,
}
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 1a9db087c0e4..33e4078db598 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -284,6 +284,7 @@ export const urls = {
`/product_tours/${id}${params ? `?${params.startsWith('?') ? params.slice(1) : params}` : ''}`,
organizationDeactivated: (): string => '/organization-deactivated',
organizationPendingDeletion: (): string => '/organization-pending-deletion',
+ projectPendingDeletion: (): string => '/project-pending-deletion',
approvals: (): string => '/settings/environment-approvals#change-requests',
approval: (id: string): string => `/approvals/${id}`,
health: (): string => '/health',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 7b19a44068c9..476ad304d476 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -653,6 +653,7 @@ export interface CorrelationConfigType {
export interface ProjectType extends ProjectBasicType {
created_at: string
+ is_pending_deletion: boolean
}
export interface TeamSurveyConfigType {
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 1ad322bc4fcf..cc6f61e27231 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -92,8 +92,8 @@ class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
# Keep this serializer narrow; legacy Team-compatible fields live on ProjectBackwardCompatSerializer.
- fields = ["id", "organization_id", "name", "product_description", "created_at"]
- read_only_fields = ["id", "organization_id", "created_at"]
+ fields = ["id", "organization_id", "name", "product_description", "created_at", "is_pending_deletion"]
+ read_only_fields = ["id", "organization_id", "created_at", "is_pending_deletion"]
class ProjectBackwardCompatSerializer(
@@ -201,11 +201,13 @@ class ProjectBackwardCompatSerializer(
"logs_settings", # Compat with TeamSerializer
"proactive_tasks_enabled", # Compat with TeamSerializer
"available_setup_task_ids", # Compat with TeamSerializer
+ "is_pending_deletion",
)
read_only_fields = (
"id",
"uuid",
"organization",
+ "is_pending_deletion",
"effective_membership_level",
"has_group_types",
"group_types",
@@ -829,6 +831,9 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets
"Project deletion is temporarily disabled during database migration. Please try again later."
)
+ if project.is_pending_deletion:
+ raise exceptions.ValidationError("This project is already being deleted.")
+
# Block deletion of the last project in an org with an active subscription (cloud only).
# Fail open if the billing service is unreachable — a 500 here would create a worse stuck state.
is_last_project = project.organization.projects.count() == 1
@@ -859,6 +864,10 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets
teams = list(project.teams.only("id", "uuid", "name", "organization_id").all())
team_ids = [team.id for team in teams]
+ # Mark as pending deletion so the UI locks this project out until the async task removes it.
+ project.is_pending_deletion = True
+ project.save(update_fields=["is_pending_deletion"])
+
# Queue background task to handle all deletion
# bulky postgres, batch exports, project/team records, ClickHouse, email
delete_project_data_and_notify_task.delay(
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 85d936799d60..059b1e555362 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -406,6 +406,42 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
self.assertIn("active subscription", response.json()["detail"])
self.assertTrue(Project.objects.filter(id=self.project.id).exists())
+ @patch("posthog.api.project.delete_project_data_and_notify_task")
+ def test_project_deletion_sets_pending_deletion_flag(self, mock_delete_task):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ response = self.client.delete(f"/api/projects/{self.project.id}")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+
+ self.project.refresh_from_db()
+ self.assertTrue(self.project.is_pending_deletion)
+ mock_delete_task.delay.assert_called_once()
+
+ @patch("posthog.api.project.delete_project_data_and_notify_task")
+ def test_project_deletion_returns_pending_deletion_in_api(self, mock_delete_task):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ self.client.delete(f"/api/projects/{self.project.id}")
+
+ response = self.client.get(f"/api/projects/{self.project.id}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertTrue(response.json()["is_pending_deletion"])
+
+ @patch("posthog.api.project.delete_project_data_and_notify_task")
+ def test_delete_project_already_pending_deletion_returns_400(self, mock_delete_task):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ self.project.is_pending_deletion = True
+ self.project.save(update_fields=["is_pending_deletion"])
+
+ response = self.client.delete(f"/api/projects/{self.project.id}")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("already being deleted", response.json()["detail"])
+ mock_delete_task.delay.assert_not_called()
+
def test_team_deletion_does_not_cascade_to_persons(self):
"""Verify that deleting Team directly doesn't CASCADE delete Persons (on_delete=DO_NOTHING)."""
# Create a Person
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bd3e93f3ad3b..231bf22d1171 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31965,6 +31965,11 @@ export namespace Schemas {
/** @nullable */
proactive_tasks_enabled?: boolean | null;
readonly available_setup_task_ids?: readonly AvailableSetupTaskIdsEnum[];
+ /**
+ * Set to True when project deletion has been initiated. Blocks UI access to this project until the async task completes.
+ * @nullable
+ */
+ readonly is_pending_deletion?: boolean | null;
}
export interface PatchedProjectSecretAPIKey {
@@ -35093,6 +35098,11 @@ export namespace Schemas {
/** @nullable */
proactive_tasks_enabled?: boolean | null;
readonly available_setup_task_ids: readonly AvailableSetupTaskIdsEnum[];
+ /**
+ * Set to True when project deletion has been initiated. Blocks UI access to this project until the async task completes.
+ * @nullable
+ */
+ readonly is_pending_deletion: boolean | null;
}
/**