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.

perf(persons): batch bulk deletion and skip query on distinct_id miss (#72578)

José Sequeira6a87b9149b6f
diff --git a/posthog/api/person.py b/posthog/api/person.py
index a3c2261def2f..afa5c15c5af4 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -550,7 +550,19 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if filter.distinct_id:
# Exact match on any of the person's distinct IDs; no matching person => no results.
matched = get_person_by_distinct_id(team.pk, filter.distinct_id)
- person_properties.append({"type": "hogql", "key": f"id = toUUID('{matched.uuid}')" if matched else "1 = 2"})
+ if matched is None:
+ # Return early: a constant-false predicate can't be pushed into the persons
+ # lazy table, so ClickHouse would still aggregate every person row for the
+ # team before filtering everything out.
+ return Response(
+ {
+ "results": [],
+ "next": None,
+ "previous": None,
+ **({"count": 0} if "include_total" in request.GET else {}),
+ }
+ )
+ person_properties.append({"type": "hogql", "key": f"id = toUUID('{matched.uuid}')"})
actors_query = ActorsQuery(
select=["id"],
properties=person_properties,
diff --git a/posthog/api/test/__snapshots__/test_person.ambr b/posthog/api/test/__snapshots__/test_person.ambr
index 6268df541736..1bf95770eba9 100644
--- a/posthog/api/test/__snapshots__/test_person.ambr
+++ b/posthog/api/test/__snapshots__/test_person.ambr
@@ -176,40 +176,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPerson.test_filter_person_list.4
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT person.id AS id,
- toTimeZone(person.created_at, 'UTC') AS created_at
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons
- WHERE 0
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestPerson.test_filter_person_prop
'''
/* user_id:0 request:_snapshot_ */
@@ -689,40 +655,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPersonFromClickhouse.test_filter_person_list.4
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT persons.id AS id
- FROM
- (SELECT person.id AS id,
- toTimeZone(person.created_at, 'UTC') AS created_at
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons
- WHERE 0
- ORDER BY persons.created_at DESC,
- persons.id DESC
- LIMIT 101
- OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto',
- readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- optimize_rewrite_aggregate_function_with_if=0,
- optimize_min_inequality_conjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestPersonFromClickhouse.test_filter_person_prop
'''
/* user_id:0 request:_snapshot_ */
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index d801a749c3ce..a4b816548c00 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -317,6 +317,10 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 0)
+ response = self.client.get("/api/person/?distinct_id=inexistent&include_total")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"results": [], "next": None, "previous": None, "count": 0})
+
def test_cant_see_another_organization_pii_with_filters(self):
# Completely different organization
another_org: Organization = Organization.objects.create()
diff --git a/posthog/hogql_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.py
index 6253eab4d649..8d62f1f5b67d 100644
--- a/posthog/hogql_queries/actor_strategies.py
+++ b/posthog/hogql_queries/actor_strategies.py
@@ -109,7 +109,7 @@ class PersonStrategy(ActorStrategy):
"is_identified": p.is_identified,
"created_at": datetime.fromtimestamp(p.created_at / 1000, tz=UTC) if p.created_at else None,
"last_seen_at": datetime.fromtimestamp(p.last_seen_at / 1000, tz=UTC) if p.last_seen_at else None,
- "distinct_ids": distinct_ids_by_person.get(p.id, []),
+ "distinct_ids": [d.id for d in distinct_ids_by_person.get(p.id, [])],
}
for p in all_persons
}
diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.py
index c9825a5235a1..7f190e62c2c5 100644
--- a/posthog/models/person/bulk_delete.py
+++ b/posthog/models/person/bulk_delete.py
@@ -12,10 +12,12 @@ import structlog
from temporalio import common
from posthog.helpers.impersonation import is_impersonated
-from posthog.models.activity_logging.activity_log import Detail, log_activity
+from posthog.models.activity_logging.activity_log import Detail, LogActivityEntry, bulk_log_activity
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person import Person
from posthog.models.person.util import (
+ DistinctIdForPerson,
+ _batched_get_distinct_ids_for_persons,
_fetch_persons_by_distinct_ids_via_personhog,
_fetch_persons_by_uuids_via_personhog,
delete_person,
@@ -67,27 +69,46 @@ def delete_persons_profile(
Activity logging is performed only when both ``request`` and ``organization_id``
are provided (i.e. from a DRF endpoint). Dagster ops should leave them as None.
"""
+ from posthog.personhog_client.client import personhog_call
+
deleted: builtins.list[Person] = []
errors: builtins.list[uuid_lib.UUID] = []
+ # A missing map entry (or a failed batch fetch) passes None below, making delete_person
+ # fall back to its own per-person lookup so failure isolation is preserved.
+ distinct_ids_by_person: dict[int, builtins.list[DistinctIdForPerson]] = {}
+ try:
+ distinct_ids_by_person = personhog_call(
+ "get_distinct_ids_for_deletion",
+ lambda: _batched_get_distinct_ids_for_persons(team_id, [person.pk for person in persons]),
+ caller_tag="persons/deletion-distinct-ids",
+ )
+ except Exception:
+ logger.exception("Batched distinct-id fetch failed, falling back to per-person lookups")
for person in persons:
try:
- delete_person(person=person)
+ delete_person(person=person, distinct_ids=distinct_ids_by_person.get(person.pk))
deleted.append(person)
except Exception:
logger.exception("Failed to delete person", person_uuid=str(person.uuid))
errors.append(person.uuid)
- continue
- if request is not None and organization_id is not None and actor is not None:
- log_activity(
- organization_id=organization_id,
- team_id=team_id,
- user=cast(User, actor),
- was_impersonated=is_impersonated(request),
- item_id=person.pk,
- scope="Person",
- activity="deleted",
- detail=Detail(name=str(person.uuid)),
- )
+
+ if request is not None and organization_id is not None and actor is not None:
+ was_impersonated = is_impersonated(request)
+ bulk_log_activity(
+ [
+ LogActivityEntry(
+ organization_id=organization_id,
+ team_id=team_id,
+ user=cast(User, actor),
+ was_impersonated=was_impersonated,
+ item_id=person.pk,
+ scope="Person",
+ activity="deleted",
+ detail=Detail(name=str(person.uuid)),
+ )
+ for person in deleted
+ ]
+ )
if deleted:
delete_persons_from_postgres(team_id, deleted)
diff --git a/posthog/models/person/test/test_batched_personhog_helpers.py b/posthog/models/person/test/test_batched_personhog_helpers.py
index 2566527acaa5..822697cd19c2 100644
--- a/posthog/models/person/test/test_batched_personhog_helpers.py
+++ b/posthog/models/person/test/test_batched_personhog_helpers.py
@@ -281,7 +281,7 @@ class TestBatchedGetDistinctIdsForPersons(SimpleTestCase):
assert len(result) == n_persons
for i in range(n_persons):
- assert result[i + 1] == [f"d{i}"]
+ assert [d.id for d in result[i + 1]] == [f"d{i}"]
fake.assert_called("get_distinct_ids_for_persons", times=expected_calls)
def test_empty_input(self):
@@ -322,7 +322,7 @@ class TestBatchedGetDistinctIdsForPersons(SimpleTestCase):
result = _batched_get_distinct_ids_for_persons(1, [1, 999])
- assert result[1] == ["d1"]
+ assert [d.id for d in result[1]] == ["d1"]
assert result[999] == []
diff --git a/posthog/models/person/test/test_bulk_delete_helpers.py b/posthog/models/person/test/test_bulk_delete_helpers.py
index d2f7f679684e..b58810575459 100644
--- a/posthog/models/person/test/test_bulk_delete_helpers.py
+++ b/posthog/models/person/test/test_bulk_delete_helpers.py
@@ -76,7 +76,28 @@ class DeletePersonsProfileTests(BaseTest):
result = delete_persons_profile(self.team.pk, [p], actor=self.user)
assert result.deleted_count == 1
assert result.errors == []
- ch_delete.assert_called_once_with(person=p)
+ ch_delete.assert_called_once()
+ assert ch_delete.call_args.kwargs["person"] == p
+ assert [d.id for d in ch_delete.call_args.kwargs["distinct_ids"]] == ["a"]
+ pg_delete.assert_called_once_with(self.team.pk, [p])
+
+ @parameterized.expand(
+ [
+ ("batch_fetch_fails", {"side_effect": RuntimeError("personhog down")}),
+ ("person_missing_from_batch", {"return_value": {}}),
+ ]
+ )
+ def test_falls_back_to_per_person_lookup(self, _name, batch_behavior):
+ p = create_person(team=self.team, distinct_ids=["a"], properties={})
+ with (
+ patch("posthog.models.person.bulk_delete._batched_get_distinct_ids_for_persons", **batch_behavior),
+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,
+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,
+ ):
+ result = delete_persons_profile(self.team.pk, [p], actor=self.user)
+ assert result.deleted_count == 1
+ assert result.errors == []
+ assert ch_delete.call_args.kwargs["distinct_ids"] is None
pg_delete.assert_called_once_with(self.team.pk, [p])
def test_collects_errors_and_skips_failed_persons_in_pg_batch(self):
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index 3ee73f391594..3ea3ed61efd3 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -4,6 +4,7 @@ import json
import datetime
import contextvars
from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional, Union
from uuid import UUID
from zoneinfo import ZoneInfo
@@ -159,13 +160,20 @@ def _batched_get_persons_by_distinct_ids(
return valid_results
+@dataclass
+class DistinctIdForPerson:
+ id: str
+ version: int
+
+
def _batched_get_distinct_ids_for_persons(
team_id: int,
person_ids: list[int],
limit_per_person: int | None = None,
-) -> dict[int, list[str]]:
+) -> dict[int, list[DistinctIdForPerson]]:
+ """Fetch each person's distinct_ids with their versions, one RPC per PERSONHOG_BATCH_SIZE batch."""
client = _get_client()
- distinct_ids_by_person: dict[int, list[str]] = {}
+ distinct_ids_by_person: dict[int, list[DistinctIdForPerson]] = {}
for i in range(0, len(person_ids), PERSONHOG_BATCH_SIZE):
batch_ids = person_ids[i : i + PERSONHOG_BATCH_SIZE]
did_request = GetDistinctIdsForPersonsRequest(team_id=team_id, person_ids=batch_ids)
@@ -173,7 +181,9 @@ def _batched_get_distinct_ids_for_persons(
did_request.limit_per_person = limit_per_person
did_resp = client.get_distinct_ids_for_persons(did_request)
for pd in did_resp.person_distinct_ids:
- distinct_ids_by_person[pd.person_id] = [d.distinct_id for d in pd.distinct_ids]
+ distinct_ids_by_person[pd.person_id] = [
+ DistinctIdForPerson(id=d.distinct_id, version=int(d.version or 0)) for d in pd.distinct_ids
+ ]
return distinct_ids_by_person
@@ -315,7 +325,8 @@ def _fetch_persons_by_distinct_ids_via_personhog(
)
return [
- proto_person_to_model(r.person, distinct_ids=distinct_ids_by_person.get(r.person.id, [])) for r in valid_results
+ proto_person_to_model(r.person, distinct_ids=[d.id for d in distinct_ids_by_person.get(r.person.id, [])])
+ for r in valid_results
]
@@ -373,10 +384,11 @@ def get_distinct_ids_for_persons(
if not person_ids:
return {}
- return personhog_call(
+ distinct_ids_by_person = personhog_call(
"get_distinct_ids_for_persons",
lambda: _batched_get_distinct_ids_for_persons(team_id, person_ids, limit_per_person=limit_per_person),
)
+ return {person_id: [d.id for d in distinct_ids] for person_id, distinct_ids in distinct_ids_by_person.items()}
def _fetch_persons_by_uuids_via_personhog(
@@ -398,7 +410,10 @@ def _fetch_persons_by_uuids_via_personhog(
team_id, person_ids, limit_per_person=distinct_id_limit
)
- return [proto_person_to_model(p, distinct_ids=distinct_ids_by_person.get(p.id, [])) for p in valid_persons]
+ return [
+ proto_person_to_model(p, distinct_ids=[d.id for d in distinct_ids_by_person.get(p.id, [])])
+ for p in valid_persons
+ ]
def get_persons_by_uuids(team_id: int, uuids: list[str], *, distinct_id_limit: int | None = None) -> list[Person]:
@@ -600,12 +615,18 @@ def delete_persons_from_postgres(team_id: int, persons: list[Person]) -> None:
personhog_call("delete_persons", personhog_fn)
-def delete_person(person: Person) -> None:
+def delete_person(person: Person, distinct_ids: list[DistinctIdForPerson] | None = None) -> None:
+ """Produce ClickHouse deletion tombstones for a person and its distinct_ids.
+
+ ``distinct_ids`` can be prefetched in batch (see ``delete_persons_profile``) to
+ avoid one RPC per person; when omitted it is fetched here.
+ """
# This is racy https://github.com/PostHog/posthog/issues/11590
- distinct_ids_to_version = _get_distinct_ids_with_version(person)
+ if distinct_ids is None:
+ distinct_ids = _get_distinct_ids_with_version(person)
_delete_person(person.team_id, person.uuid, int(person.version or 0), person.created_at)
- for distinct_id, version in distinct_ids_to_version.items():
- _delete_ch_distinct_id(person.team_id, person.uuid, distinct_id, version)
+ for distinct_id in distinct_ids:
+ _delete_ch_distinct_id(person.team_id, person.uuid, distinct_id.id, distinct_id.version)
def _delete_person(
@@ -627,12 +648,12 @@ def _delete_person(
)
-def _get_distinct_ids_with_version(person: Person) -> dict[str, int]:
- def personhog_fn() -> dict[str, int]:
+def _get_distinct_ids_with_version(person: Person) -> list[DistinctIdForPerson]:
+ def personhog_fn() -> list[DistinctIdForPerson]:
resp = _get_client().get_distinct_ids_for_person(
GetDistinctIdsForPersonRequest(team_id=person.team_id, person_id=person.pk)
)
- return {d.distinct_id: int(d.version or 0) for d in resp.distinct_ids}
+ return [DistinctIdForPerson(id=d.distinct_id, version=int(d.version or 0)) for d in resp.distinct_ids]
return personhog_call("get_distinct_ids_with_version", personhog_fn)
diff --git a/posthog/queries/actor_base_query.py b/posthog/queries/actor_base_query.py
index fea03cbd8230..af1d115ec0b1 100644
--- a/posthog/queries/actor_base_query.py
+++ b/posthog/queries/actor_base_query.py
@@ -84,7 +84,10 @@ def _fetch_people_via_personhog(
team_id, person_ids, limit_per_person=distinct_id_limit
)
- persons = [proto_person_to_model(p, distinct_ids=distinct_ids_by_person.get(p.id, [])) for p in valid_persons]
+ persons = [
+ proto_person_to_model(p, distinct_ids=[d.id for d in distinct_ids_by_person.get(p.id, [])])
+ for p in valid_persons
+ ]
persons.sort(key=lambda p: (-(p.created_at.timestamp() if p.created_at else 0), str(p.uuid)))
return persons