: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(persons): accept a list of keys in delete_property (#75593)
Luke Belton2760bbcc4861
diff --git a/posthog/api/fields.py b/posthog/api/fields.pyindex 15fae220f327..aa2acd4b6ef0 100644--- a/posthog/api/fields.py+++ b/posthog/api/fields.py@@ -63,3 +63,40 @@ class JSONTolerantListField(serializers.ListField):if isinstance(parsed, list):return parsedreturn value+++@extend_schema_field(+ {+ "oneOf": [+ {"type": "string", "minLength": 1},+ {"type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1},+ ]+ }+)+class CoercedStringListField(serializers.Field):+ """A single string or a non-empty list of non-empty strings, normalized to ``list[str]``.++ Blank strings and non-string items are rejected. ``max_items`` bounds the list length.+ Override ``error_messages["invalid"]`` for an endpoint-specific message. Subclass with+ ``@extend_schema_field`` to add endpoint-specific schema bounds (e.g. ``maxItems``).+ """++ default_error_messages = {+ "invalid": "Provide a string or a non-empty list of non-empty strings.",+ "max_items": "Ensure this field has no more than {max_items} elements.",+ }++ def __init__(self, *, max_items: int | None = None, **kwargs: Any) -> None:+ self.max_items = max_items+ super().__init__(**kwargs)++ def to_representation(self, value: Any) -> Any:+ return value++ def to_internal_value(self, data: Any) -> list[str]:+ items = [data] if isinstance(data, str) else data+ if not isinstance(items, list) or not items or not all(isinstance(item, str) and item for item in items):+ self.fail("invalid")+ if self.max_items is not None and len(items) > self.max_items:+ self.fail("max_items", max_items=self.max_items)+ return itemsdiff --git a/posthog/api/person.py b/posthog/api/person.pyindex dd5d5caae69f..95b5350dd6ed 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -32,6 +32,8 @@ from posthog.hogql.constants import CSV_EXPORT_LIMITfrom posthog.api.capture import CaptureInternalError, capture_internalfrom posthog.api.documentation import PersonPropertiesSerializer+from posthog.api.fields import CoercedStringListField+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action@@ -177,11 +179,38 @@ class PersonUpdatePropertyRequestSerializer(serializers.Serializer):value = serializers.JSONField(help_text="The property value. Can be a string, number, boolean, or object.")+# Matches the cap on the persons bulk-delete endpoint; also keeps the resulting+# capture event safely under the ~1 MB Kafka message limit.+MAX_UNSET_KEYS_PER_REQUEST = 1000+++@extend_schema_field(+ {+ "oneOf": [+ {"type": "string", "minLength": 1},+ {+ "type": "array",+ "items": {"type": "string", "minLength": 1},+ "minItems": 1,+ "maxItems": MAX_UNSET_KEYS_PER_REQUEST,+ },+ ]+ }+)+class UnsetPropertyKeysField(CoercedStringListField):+ default_error_messages = {+ "invalid": "Provide '$unset' as a property key or a non-empty list of property keys.",+ }++class PersonDeletePropertyRequestSerializer(serializers.Serializer):def get_fields(self):fields = super().get_fields()- # The endpoint reads request.data["$unset"], so the field name must include the $ prefix.- fields["$unset"] = serializers.CharField(help_text="The property key to remove from this person.")+ # The handler reads validated_data["$unset"], so the field name must include the $ prefix.+ fields["$unset"] = UnsetPropertyKeysField(+ max_items=MAX_UNSET_KEYS_PER_REQUEST,+ help_text="A property key, or a list of property keys, to remove from this person.",+ )return fields@@ -963,26 +992,32 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):self._set_properties({key: request.data["value"]}, request.user)return Response(status=202)- @extend_schema(request=PersonDeletePropertyRequestSerializer, parameters=[_PERSON_ID_PARAMETER])+ @validated_request(PersonDeletePropertyRequestSerializer, parameters=[_PERSON_ID_PARAMETER])@action(methods=["POST"], detail=True, required_scopes=["person:write"])- def delete_property(self, request: request.Request, pk=None, **kwargs) -> response.Response:+ def delete_property(self, request: ValidatedRequest, pk=None, **kwargs) -> response.Response:# Only distinct_ids[0] is used (to attribute the property-update event), so bound the fetch to one.with personhog_caller_tag("persons/delete-property"):person = get_person_by_pk_or_uuid(self.team_id, pk, distinct_id_limit=1)if person is None:raise Person.DoesNotExist- key = request.data.get("$unset")- if key:- non_writable = self._get_non_writable_person_properties(request)- if key in non_writable:- raise ValidationError(f'You do not have write access to the property "{key}".')+ keys = request.validated_data["$unset"]++ non_writable = self._get_non_writable_person_properties(request)+ forbidden = sorted(set(keys) & non_writable)+ if forbidden:+ raise ValidationError(f"You do not have write access to the following properties: {', '.join(forbidden)}.")++ # distinct_ids can be empty for a person orphaned by a merge, or when a concurrent+ # merge lands between the person fetch and the distinct-id fetch (two separate RPCs).+ if not person.distinct_ids:+ raise ValidationError("This person has no distinct IDs, so its properties can't be removed.")event_name = "$delete_person_property"distinct_id = person.distinct_ids[0]timestamp = datetime.now(UTC)properties = {- "$unset": [request.data["$unset"]],+ "$unset": keys,}try:diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex a0cfa3efe32b..4e3a5abc4c28 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -1077,16 +1077,22 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):process_person_profile=True,)+ @parameterized.expand(+ [+ ("single_key", "foo", ["foo"]),+ ("list_of_keys", ["foo", "bar"], ["foo", "bar"]),+ ]+ )@mock.patch("posthog.api.person.capture_internal")- def test_new_delete_person_properties(self, mock_capture) -> None:+ def test_new_delete_person_properties(self, _name, unset, expected, mock_capture) -> None:person = _create_person(team=self.team,distinct_ids=["some_distinct_id"],- properties={"$browser": "whatever", "$os": "Mac OS X"},+ properties={"foo": "a", "bar": "b"},immediate=True,)- self.client.post(f"/api/person/{person.uuid}/delete_property", {"$unset": "foo"})+ self.client.post(f"/api/person/{person.uuid}/delete_property", {"$unset": unset}, format="json")mock_capture.assert_called_once_with(token=self.team.api_token,@@ -1095,11 +1101,82 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):distinct_id="some_distinct_id",timestamp=mock.ANY,properties={- "$unset": ["foo"],+ "$unset": expected,},process_person_profile=True,)+ @parameterized.expand(+ [+ ("empty_list", {"$unset": []}, set()),+ ("blank_key_in_list", {"$unset": ["foo", ""]}, set()),+ ("non_string_key", {"$unset": ["foo", 123]}, set()),+ ("missing_unset", {}, set()),+ ("non_dict_body", ["foo"], set()),+ ("oversized_list", {"$unset": ["k"] * 1001}, set()),+ ("forbidden_key_in_list", {"$unset": ["foo", "secret"]}, {"secret"}),+ ]+ )+ @mock.patch("posthog.api.person.capture_internal")+ def test_delete_property_rejects_invalid_or_forbidden_unset(self, _name, body, non_writable, mock_capture) -> None:+ person = _create_person(+ team=self.team,+ distinct_ids=["some_distinct_id"],+ properties={"foo": "a", "secret": "b"},+ immediate=True,+ )++ with mock.patch(+ "posthog.api.person.PersonViewSet._get_non_writable_person_properties",+ return_value=non_writable,+ ):+ response = self.client.post(+ f"/api/person/{person.uuid}/delete_property",+ body,+ format="json",+ )++ self.assertEqual(response.status_code, 400)+ mock_capture.assert_not_called()++ @mock.patch("posthog.api.person.capture_internal")+ def test_delete_property_names_every_forbidden_key(self, mock_capture) -> None:+ person = _create_person(+ team=self.team,+ distinct_ids=["some_distinct_id"],+ properties={"foo": "a", "secret": "b", "hidden": "c"},+ immediate=True,+ )++ with mock.patch(+ "posthog.api.person.PersonViewSet._get_non_writable_person_properties",+ return_value={"secret", "hidden"},+ ):+ response = self.client.post(+ f"/api/person/{person.uuid}/delete_property",+ {"$unset": ["foo", "secret", "hidden"]},+ format="json",+ )++ self.assertEqual(response.status_code, 400)+ self.assertIn("hidden, secret", response.json()["detail"])+ mock_capture.assert_not_called()++ @mock.patch("posthog.api.person.capture_internal")+ @mock.patch("posthog.api.person.get_person_by_pk_or_uuid")+ def test_delete_property_rejects_person_without_distinct_ids(self, mock_get_person, mock_capture) -> None:+ mock_get_person.return_value = mock.Mock(distinct_ids=[])++ response = self.client.post(+ f"/api/person/{uuid4()}/delete_property",+ {"$unset": "foo"},+ format="json",+ )++ self.assertEqual(response.status_code, 400)+ self.assertIn("no distinct IDs", response.json()["detail"])+ mock_capture.assert_not_called()+@mock.patch("posthog.api.person.capture_internal")def test_update_person_property_by_numeric_id(self, mock_capture) -> None:person = _create_person(diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex 1c997e43a773..753cfa02db86 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -242,8 +242,8 @@ export interface PatchedPersonRecordApi {}export interface PersonDeletePropertyRequestApi {- /** The property key to remove from this person. */- $unset: string+ /** A property key, or a list of property keys, to remove from this person. */+ $unset: string | string[]}export interface MessageAssetApi {diff --git a/products/persons/frontend/generated/api.zod.ts b/products/persons/frontend/generated/api.zod.tsindex 220c34818a86..7527eb6d8fa0 100644--- a/products/persons/frontend/generated/api.zod.ts+++ b/products/persons/frontend/generated/api.zod.ts@@ -34,8 +34,16 @@ export const PersonsPartialUpdateBody = /* @__PURE__ */ zod.object({/*** This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.*/++export const personsDeletePropertyCreateBodyUnsetTwoMax = 1000+export const PersonsDeletePropertyCreateBody = /* @__PURE__ */ zod.object({- $unset: zod.string().describe('The property key to remove from this person.'),+ $unset: zod+ .union([+ zod.string().min(1),+ zod.array(zod.string().min(1)).min(1).max(personsDeletePropertyCreateBodyUnsetTwoMax),+ ])+ .describe('A property key, or a list of property keys, to remove from this person.'),})/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4727fe3f405d..4d974976a3a6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55636,8 +55636,8 @@ export namespace Schemas {}export interface PersonDeletePropertyRequest {- /** The property key to remove from this person. */- $unset: string;+ /** A property key, or a list of property keys, to remove from this person. */+ $unset: string | string[];}/**diff --git a/services/mcp/src/generated/persons/api.ts b/services/mcp/src/generated/persons/api.tsindex d4be14fac04e..f5b39a4e1960 100644--- a/services/mcp/src/generated/persons/api.ts+++ b/services/mcp/src/generated/persons/api.ts@@ -171,8 +171,15 @@ export const PersonsDeletePropertyCreateQueryParams = /* @__PURE__ */ zod.objectformat: zod.enum(['csv', 'json']).optional(),})+export const personsDeletePropertyCreateBodyUnsetTwoMax = 1000+export const PersonsDeletePropertyCreateBody = /* @__PURE__ */ zod.object({- $unset: zod.string().describe('The property key to remove from this person.'),+ $unset: zod+ .union([+ zod.string().min(1),+ zod.array(zod.string().min(1)).min(1).max(personsDeletePropertyCreateBodyUnsetTwoMax),+ ])+ .describe('A property key, or a list of property keys, to remove from this person.'),})/**diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-delete.jsonindex 4b0189ef6631..550951a50535 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-delete.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/persons-property-delete.json@@ -6,8 +6,22 @@"type": "string"},"unset": {- "description": "The property key to remove from this person.",- "type": "string"+ "anyOf": [+ {+ "minLength": 1,+ "type": "string"+ },+ {+ "items": {+ "minLength": 1,+ "type": "string"+ },+ "maxItems": 1000,+ "minItems": 1,+ "type": "array"+ }+ ],+ "description": "A property key, or a list of property keys, to remove from this person."}},"required": ["id", "unset"],