: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
fix(persons): return 5xx when a single-person delete removes nothing (#103144)
Nick Best477749f12faa
diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 06fbdb891340..b773f1fff7a6 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -20,7 +20,7 @@ from drf_spectacular.utils import (from opentelemetry import tracefrom prometheus_client import Counterfrom rest_framework import request, response, serializers, viewsets-from rest_framework.exceptions import MethodNotAllowed, NotFound, ValidationError+from rest_framework.exceptions import APIException, MethodNotAllowed, NotFound, ValidationErrorfrom rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.parsers import JSONParserfrom rest_framework.renderers import BaseRenderer@@ -299,14 +299,30 @@ class PersonBulkDeleteResponseSerializer(serializers.Serializer):child=serializers.DictField(),required=False,help_text="Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' "- "and 'step', the deletion step that failed for that person. A failed database delete is reported here "- "rather than as an error response, so a 202 with entries means some or all persons were not deleted. "- "A 'log_activity' step means the person was deleted but the activity log entry was not written. "+ "and 'step', the deletion step that failed for that person. Failures are reported here rather than as an "+ "error status, so a 202 with entries means those persons were not deleted and the request should be "+ "retried for them, except entries whose step is 'log_activity': that person was deleted, but the "+ "activity log entry was not written. ""Always empty when the deletion was queued (see persons_queued_for_deletion). ""Contact support if this persists.",)+class PersonDeletionFailed(APIException):+ status_code = 503+ default_code = "person_deletion_failed"+ default_detail = "Couldn't delete this person. Try again, and if it keeps happening contact support."+++def _no_person_deleted(summary: dict[str, Any]) -> bool:+ """True when persons matched, a delete was attempted, and none of them left the database.++ A ``log_activity`` failure never triggers this: the person is gone by then, and a retry would+ only find nothing to delete.+ """+ return summary["persons_found"] > 0 and summary["persons_deleted"] == 0 and bool(summary["deletion_errors"])++class PersonSplitRequestSerializer(serializers.Serializer):main_distinct_id = serializers.CharField(required=False,@@ -848,7 +864,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# Convert query params to request data format expected by bulk_delete. This path stays# synchronous under the queued-deletion flag: the app deletes one person here and reloads# the list at once, so the person has to be gone when the response returns.- self._bulk_delete_persons(+ summary = self._bulk_delete_persons(request=request,ids=[str(person.uuid)],delete_events="delete_events" in request.GET,@@ -856,6 +872,12 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):keep_person="keep_person" in request.GET,allow_queued=False,)+ if _no_person_deleted(summary):+ step = summary["deletion_errors"][0]["step"]+ raise PersonDeletionFailed(+ f"Couldn't delete this person. The {step} step failed. "+ "Try again, and if it keeps happening contact support."+ )return response.Response(status=202)except Person.DoesNotExist:@@ -869,6 +891,8 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def bulk_delete(self, request: request.Request, pk=None, **kwargs):"""This endpoint allows you to bulk delete persons, either by the PostHog person IDs or by distinct IDs. You can pass in a maximum of 1000 IDs per call. Only events captured before the request will be deleted.++ Person records are removed in the background shortly after the request returns, so a successful response reports them in `persons_queued_for_deletion` and `persons_deleted` is 0."""delete_events = bool(request.data.get("delete_events"))diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex 8ded34f1b9cc..86087c079e53 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -591,6 +591,25 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):)[0][0]self.assertEqual(ch_events, 3)+ @parameterized.expand(+ [+ ("postgres_delete_fails", "posthog.models.person.bulk_delete.delete_persons_from_postgres", 503, False),+ ("activity_log_fails", "posthog.models.person.bulk_delete.bulk_log_activity", 202, True),+ ]+ )+ def test_delete_person_fails_only_when_person_remains(self, _name, target, expected_status, person_gone):+ person = _create_person(team=self.team, distinct_ids=["person_1"], immediate=True)++ with mock.patch(target, side_effect=Exception("DB connection lost")):+ response = self.client.delete(f"/api/person/{person.uuid}/")++ self.assertEqual(response.status_code, expected_status)+ self.assertEqual(get_person_by_uuid(self.team.pk, str(person.uuid)) is None, person_gone)+ if expected_status == 503:+ data = response.json()+ self.assertEqual(data["code"], "person_deletion_failed")+ self.assertIn("delete_postgres", data["detail"])+@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)def test_delete_person_and_events(self):person = _create_person(@@ -985,8 +1004,31 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(data["persons_deleted"], 1)self.assertEqual(len(data["deletion_errors"]), 1)self.assertEqual(data["deletion_errors"][0]["person_uuid"], str(person1.uuid))+ self.assertEqual(data["deletion_errors"][0]["step"], "tombstone_clickhouse")self.assertNotIn("detail", data["deletion_errors"][0])+ @mock.patch(+ "posthog.models.person.bulk_delete.delete_persons_from_postgres",+ side_effect=Exception("DB connection lost"),+ )+ def test_bulk_delete_total_failure_reports_every_person(self, _mock_delete_from_postgres):+ person1 = _create_person(team=self.team, distinct_ids=["person_1"], immediate=True)+ person2 = _create_person(team=self.team, distinct_ids=["person_2"], immediate=True)++ response = self.client.post("/api/person/bulk_delete/", {"ids": [person1.uuid, person2.uuid]})++ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)+ data = response.json()+ self.assertEqual(data["persons_found"], 2)+ self.assertEqual(data["persons_deleted"], 0)+ self.assertEqual(+ sorted(error["person_uuid"] for error in data["deletion_errors"]),+ sorted([str(person1.uuid), str(person2.uuid)]),+ )+ self.assertEqual({error["step"] for error in data["deletion_errors"]}, {"delete_postgres"})+ self.assertIsNotNone(get_person_by_uuid(self.team.pk, str(person1.uuid)))+ self.assertIsNotNone(get_person_by_uuid(self.team.pk, str(person2.uuid)))+def test_deletion_status_rejects_invalid_status(self):"""Test that deletion_status returns 400 for invalid status filter"""response = self.client.get(f"/api/person/deletion_status/?status=invalid")diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex 5cfea23c2815..c2ea39330802 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -325,7 +325,7 @@ export interface PersonBulkDeleteResponseApi {events_queued_for_deletion: boolean/** Whether recording deletion was requested for the matched persons. If a deletion was already queued for a person, it will not be duplicated. */recordings_queued_for_deletion: boolean- /** Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. A failed database delete is reported here rather than as an error response, so a 202 with entries means some or all persons were not deleted. A 'log_activity' step means the person was deleted but the activity log entry was not written. Always empty when the deletion was queued (see persons_queued_for_deletion). Contact support if this persists. */+ /** Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. Failures are reported here rather than as an error status, so a 202 with entries means those persons were not deleted and the request should be retried for them, except entries whose step is 'log_activity': that person was deleted, but the activity log entry was not written. Always empty when the deletion was queued (see persons_queued_for_deletion). Contact support if this persists. */deletion_errors?: PersonBulkDeleteResponseApiDeletionErrorsItem[]}diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.tsindex aa1f05132d02..ac31a8dff745 100644--- a/products/persons/frontend/generated/api.ts+++ b/products/persons/frontend/generated/api.ts@@ -561,6 +561,8 @@ export const getPersonsBulkDeleteCreateUrl = (projectId: string, params?: Person/*** This endpoint allows you to bulk delete persons, either by the PostHog person IDs or by distinct IDs. You can pass in a maximum of 1000 IDs per call. Only events captured before the request will be deleted.+ *+ * Person records are removed in the background shortly after the request returns, so a successful response reports them in `persons_queued_for_deletion` and `persons_deleted` is 0.*/export const personsBulkDeleteCreate = async (projectId: string,diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.tsindex 7527eb6d8fa0..7578bde388fd 100644--- a/products/persons/frontend/generated/api.zod.ts+++ b/products/persons/frontend/generated/api.zod.ts@@ -101,6 +101,8 @@ export const PersonsBatchByUuidsCreateBody = /* @__PURE__ */ zod.object({/*** This endpoint allows you to bulk delete persons, either by the PostHog person IDs or by distinct IDs. You can pass in a maximum of 1000 IDs per call. Only events captured before the request will be deleted.+ *+ * Person records are removed in the background shortly after the request returns, so a successful response reports them in `persons_queued_for_deletion` and `persons_deleted` is 0.*/export const personsBulkDeleteCreateBodyDeleteEventsDefault = falseexport const personsBulkDeleteCreateBodyDeleteRecordingsDefault = falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 65f53222e001..6c5c55fb21c9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74653,7 +74653,7 @@ export namespace Schemas {events_queued_for_deletion: boolean;/** Whether recording deletion was requested for the matched persons. If a deletion was already queued for a person, it will not be duplicated. */recordings_queued_for_deletion: boolean;- /** Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. A failed database delete is reported here rather than as an error response, so a 202 with entries means some or all persons were not deleted. A 'log_activity' step means the person was deleted but the activity log entry was not written. Always empty when the deletion was queued (see persons_queued_for_deletion). Contact support if this persists. */+ /** Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. Failures are reported here rather than as an error status, so a 202 with entries means those persons were not deleted and the request should be retried for them, except entries whose step is 'log_activity': that person was deleted, but the activity log entry was not written. Always empty when the deletion was queued (see persons_queued_for_deletion). Contact support if this persists. */deletion_errors?: PersonBulkDeleteResponseDeletionErrorsItem[];}diff --git a/services/mcp/src/generated/persons/api.ts b/services/mcp/src/generated/persons/api.tsindex 9114d3d8ca8c..0c801db33f34 100644--- a/services/mcp/src/generated/persons/api.ts+++ b/services/mcp/src/generated/persons/api.ts@@ -213,6 +213,8 @@ export const PersonsUpdatePropertyCreateBody = () => zod.object({/*** This endpoint allows you to bulk delete persons, either by the PostHog person IDs or by distinct IDs. You can pass in a maximum of 1000 IDs per call. Only events captured before the request will be deleted.+ *+ * Person records are removed in the background shortly after the request returns, so a successful response reports them in `persons_queued_for_deletion` and `persons_deleted` is 0.*/export const PersonsBulkDeleteCreateParams = () => zod.object({project_id: zod