: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(worker): delete soft-deleted persons via a dictHas dictionary ins… (#73743)
Bryan Ciaraldi0dda3fbdb144
diff --git a/posthog/models/async_deletion/delete_person.py b/posthog/models/async_deletion/delete_person.pyindex dad4dc07b634..7ff038d5f045 100644--- a/posthog/models/async_deletion/delete_person.py+++ b/posthog/models/async_deletion/delete_person.py@@ -1,14 +1,84 @@+import time+import uuid+from posthog.clickhouse.client import sync_execute-from posthog.clickhouse.client.connection import Workload---def remove_deleted_person_data(mutations_sync=False):- settings = {"lightweight_deletes_sync": 1 if mutations_sync else 0}- sync_execute(- """- DELETE FROM person- WHERE id IN (SELECT id FROM person WHERE is_deleted > 0)- """,- settings=settings,- workload=Workload.OFFLINE,- )+from posthog.clickhouse.client.connection import ClickHouseUser, Workload, get_clickhouse_creds+from posthog.clickhouse.cluster import ON_CLUSTER_CLAUSE+from posthog.settings.data_stores import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE++# Prefix for the transient, per-run dictionary of person ids pending deletion.+DELETED_PERSON_IDS_DICTIONARY = "deleted_person_ids_dictionary"+++def _wait_until_dictionary_loaded(name: str, timeout_seconds: int = 600) -> None:+ deadline = time.monotonic() + timeout_seconds+ while True:+ statuses = [+ status+ for (status,) in sync_execute(+ f"SELECT status FROM clusterAllReplicas('{CLICKHOUSE_CLUSTER}', system.dictionaries) "+ "WHERE database = %(database)s AND name = %(name)s",+ {"database": CLICKHOUSE_DATABASE, "name": name},+ workload=Workload.OFFLINE,+ )+ ]+ if statuses and all(status == "LOADED" for status in statuses):+ return+ if "FAILED" in statuses or time.monotonic() > deadline:+ raise Exception(f"{name} not loaded on all replicas: {statuses}")+ time.sleep(2.0)+++def remove_deleted_person_data():+ """Hard-delete persons whose current (latest-version) state is deleted from ClickHouse.++ `person` is a ReplacingMergeTree keyed on (team_id, id); a person can be soft-deleted and+ later revived by a newer version, so whether to remove one is decided by the latest version+ -- argMax(is_deleted, version) > 0 -- not by any version having is_deleted > 0. The keys are+ loaded into a dictionary once and deleted with dictHas(), so each part is scanned a single+ time instead of re-running a whole-table subquery per affected part.+ """+ dict_reader_user, dict_reader_password = get_clickhouse_creds(ClickHouseUser.DICT_READER)++ # Unique per invocation so overlapping runs never create, consume, or drop a shared+ # cluster-wide dictionary out from under each other.+ name = f"{DELETED_PERSON_IDS_DICTIONARY}_{uuid.uuid4().hex}"+ qualified = f"{CLICKHOUSE_DATABASE}.{name}"++ # Create inside the try so a partial cluster-wide create is still cleaned up by the finally.+ try:+ # Credentials are passed as query parameters so they are not interpolated into the+ # traced statement. `present` is an unused attribute; the dictionary is only probed+ # with dictHas().+ sync_execute(+ f"""+ CREATE OR REPLACE DICTIONARY {qualified} {ON_CLUSTER_CLAUSE()} (team_id Int64, id UUID, present UInt8)+ PRIMARY KEY team_id, id+ SOURCE(CLICKHOUSE(+ QUERY 'SELECT team_id, id, toUInt8(1) AS present FROM {CLICKHOUSE_DATABASE}.person WHERE (team_id, id) IN (SELECT team_id, id FROM {CLICKHOUSE_DATABASE}.person WHERE is_deleted > 0) GROUP BY team_id, id HAVING argMax(is_deleted, version) > 0'+ USER %(dict_reader_user)s PASSWORD %(dict_reader_password)s+ ))+ LAYOUT(COMPLEX_KEY_HASHED())+ LIFETIME(0)+ """,+ {"dict_reader_user": dict_reader_user, "dict_reader_password": dict_reader_password},+ workload=Workload.OFFLINE,+ )++ sync_execute(+ f"SYSTEM RELOAD DICTIONARY {ON_CLUSTER_CLAUSE()} {qualified}",+ workload=Workload.OFFLINE,+ )+ _wait_until_dictionary_loaded(name)++ # Synchronous so the dictionary is dropped only after the mutation is applied everywhere.+ sync_execute(+ f"DELETE FROM person WHERE dictHas('{qualified}', (team_id, id))",+ settings={"lightweight_deletes_sync": 2},+ workload=Workload.OFFLINE,+ )+ finally:+ sync_execute(+ f"DROP DICTIONARY IF EXISTS {qualified} {ON_CLUSTER_CLAUSE()} SYNC",+ workload=Workload.OFFLINE,+ )diff --git a/posthog/models/async_deletion/test_delete_person.py b/posthog/models/async_deletion/test_delete_person.pyindex 9dc4788586b6..36b811e68844 100644--- a/posthog/models/async_deletion/test_delete_person.py+++ b/posthog/models/async_deletion/test_delete_person.py@@ -1,25 +1,91 @@import pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin+from django.conf import settings+from posthog.clickhouse.client import sync_execute-from posthog.models.async_deletion.delete_person import remove_deleted_person_data+from posthog.models.async_deletion.delete_person import DELETED_PERSON_IDS_DICTIONARY, remove_deleted_person_datafrom posthog.models.person.util import create_person+def _visible_person_count(team_id: int) -> int:+ # SELECT excludes lightweight-deleted rows (_row_exists = 0). Scope to the test's team:+ # the ClickHouse person table is shared across the worker's tests and only truncated at+ # package teardown, so a whole-table count would see other tests' rows.+ return sync_execute("SELECT count() FROM person WHERE team_id = %(team_id)s", {"team_id": team_id})[0][0]+++def _dictionaries_exist() -> bool:+ # per-run dictionaries share a name prefix; none should remain after a run+ [[count]] = sync_execute(+ "SELECT count() FROM system.dictionaries WHERE database = %(db)s AND name LIKE %(prefix)s",+ {"db": settings.CLICKHOUSE_DATABASE, "prefix": f"{DELETED_PERSON_IDS_DICTIONARY}%"},+ )+ return count > 0++@pytest.mark.eeclass TestDeletePerson(BaseTest, ClickhouseTestMixin):CLASS_DATA_LEVEL_SETUP = False- def test_delete_person(self):+ def test_deletes_all_versions_of_soft_deleted_persons(self):+ # person A: a later version flips is_deleted -> every version of A must be removed,+ # which is why the delete keys on id rather than on is_deleted directly.uuid = create_person(team_id=self.team.pk, version=0, is_deleted=False)create_person(uuid=uuid, team_id=self.team.pk, version=1, is_deleted=True)+ # person B: single soft-deleted versioncreate_person(team_id=self.team.pk, version=0, is_deleted=True)+ # person C: not deleted -> must remaincreate_person(team_id=self.team.pk, version=0)- remove_deleted_person_data(mutations_sync=True)+ remove_deleted_person_data()++ # only person C remains visible (both versions of A + B are tombstoned)+ assert _visible_person_count(self.team.pk) == 1++ def test_preserves_persons_that_are_not_soft_deleted(self):+ create_person(team_id=self.team.pk, version=0)+ create_person(team_id=self.team.pk, version=0)++ remove_deleted_person_data()++ assert _visible_person_count(self.team.pk) == 2++ def test_preserves_revived_persons(self):+ # Soft-deleted at v0 then revived at v1 (newer version, not deleted): the person is+ # currently live -- argMax(is_deleted, version) = 0 -- so neither version may be removed.+ uuid = create_person(team_id=self.team.pk, version=0, is_deleted=True)+ create_person(uuid=uuid, team_id=self.team.pk, version=1, is_deleted=False)++ remove_deleted_person_data()++ # both versions of the revived person survive (the delete keys on the whole person)+ assert _visible_person_count(self.team.pk) == 2++ def test_no_op_when_nothing_is_soft_deleted(self):+ # Dictionary source query returns no rows -> dictHas is always false ->+ # nothing is deleted and the mutation must not error.+ create_person(team_id=self.team.pk, version=0)++ remove_deleted_person_data()++ assert _visible_person_count(self.team.pk) == 1++ def test_drops_the_dictionary_after_running(self):+ create_person(team_id=self.team.pk, version=0, is_deleted=True)++ remove_deleted_person_data()++ # the transient dictionary must not linger (it holds the id set in memory)+ assert not _dictionaries_exist()++ def test_is_idempotent(self):+ # After the first run the deleted rows are tombstoned (_row_exists = 0) and so+ # no longer appear in the dictionary source SELECT, so a second run is a no-op.+ create_person(team_id=self.team.pk, version=0, is_deleted=True)+ create_person(team_id=self.team.pk, version=0)- # Scope to this test's team: the ClickHouse person table is shared across the worker's- # tests and only truncated at package teardown, so a whole-table count sees other rows.- count = sync_execute("SELECT count() FROM person WHERE team_id = %(team_id)s", {"team_id": self.team.pk})[0][0]+ remove_deleted_person_data()+ remove_deleted_person_data()- assert count == 1+ assert _visible_person_count(self.team.pk) == 1