: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(deletions): stop crashing on person-property deletion requests (#97009)
Phil Haackbf0a72478453
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 2c78e00ec339..d4f5ef5f5a52 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -109,9 +109,12 @@ The events property-removal path rewrites rows in a staging table and resets eacThat works because `materialize()` creates columns as `DEFAULT <expr>`, which is assignable.All of that machinery (column discovery, staging rewrite, shard walk) is scoped to `events`; none of it reaches `flag_evaluations`.-Until it does, `get_property_removal_shards` refuses to start when the table holds rows matching the request, so a request cannot complete while data it named survives.+Until it does, `get_property_removal_shards` refuses to start when the table holds rows matching a request's event `properties`, so such a request cannot complete while data it named survives.The check costs nothing while the table is empty.+The person-property half of a request is different, whether or not it also names event properties: `DeletionTarget.stores_person_properties` is `False` on `FLAG_EVALUATIONS`, so the gate does not build a `person_properties` predicate against the table at all, and that half of the request completes regardless of what the column holds.+That is accurate for rows written since the producer stopped sending `person_properties` (2026-09-05, #95693), and a deliberate blind spot for whatever a row written before then still carries: those values are out of the gate's reach until the row's TTL passes.+The schema stopped being a second obstacle with migration `0301_flag_evaluations_default_columns`, which recreated the nine typed columns as `DEFAULT <expr>`, the kind `materialize()` mints on events; they were true ClickHouse `MATERIALIZED` before, which is not assignable at all.Measured against ClickHouse 26.6.2 on the `DEFAULT` shape:@@ -137,8 +140,9 @@ The remaining fix is pointing the events rewrite machinery at this table, with t#### If a request arrives before the fix landsToday the refusal costs nothing, because the table is empty.-Once it holds rows, a property removal with `delete_all_events` refuses whenever a single flag-evaluation row carries the named property, and the operator has no way through: `delete_all_events` and `events` are mutually exclusive on the model, so the request cannot be narrowed to exclude `$feature_flag_called`, and the admin Retry button replays the same failure.+Once it holds rows, a property removal with `delete_all_events` refuses whenever a single flag-evaluation row carries the named event property, and the operator has no way through: `delete_all_events` and `events` are mutually exclusive on the model, so the request cannot be narrowed to exclude `$feature_flag_called`, and the admin Retry button replays the same failure.The only exits are waiting out the TTL or shipping the fix above. The table partitions by month with `ttl_only_drop_parts = 1`, so a part drops only once its newest row expires: the real wait is up to about 120 days, not the 90-day TTL. `posthog/models/flag_evaluations/sql.py` says the same thing next to the partition clause.+A person-property-only request is not stuck this way: as above, the gate does not check `flag_evaluations` for one at all.Refusing beats silently under-deleting, so the gate is the right default.If the fix has not landed by the time real traffic hits, the cheaper stopgaps are letting a request exclude event names so an operator can scope around the table, or recording an explicit, audited acknowledgement on the request so an operator can accept the residue rather than being stuck.@@ -166,7 +170,7 @@ Keeping the fork downstream of person resolution is the contract, tracked on #81## Adding a table-Register it in `PERSONAL_DATA_TARGETS`, with capability flags reflecting what its schema can actually take and what the sweep code actually implements: `accepts_property_rewrite` needs the rewrite machinery to reach the table, not just assignable columns.+Register it in `PERSONAL_DATA_TARGETS`, with capability flags reflecting what its schema can actually take and what the sweep code actually implements: `accepts_property_rewrite` needs the rewrite machinery to reach the table, not just assignable columns; `stores_person_properties` needs the table's `person_properties` column to actually hold reachable data, not just exist in the schema; see `FLAG_EVALUATIONS` for a table where those diverged.If it is not going to be swept, add it to `TTL_ONLY_TABLES` with the window you are accepting.If its storage lives on a cluster other than the one the deletion jobs connect to, give it a `cluster_setting` naming that cluster and mark it `optional`; see "Reach" and "Dispatching" above for which sweeps then reach it and which refuse.diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex 3e6146ed856f..e6b4810fdcd2 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -1,6 +1,6 @@import timefrom collections.abc import Callable-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom datetime import UTC, datetime, timedeltafrom functools import partial@@ -446,8 +446,7 @@ def _refuse_unsweepable(cluster: ClickhouseCluster,targets: list[DeletionTarget],deletion_request: DeletionRequestContext,- predicate: str,- params: dict,+ predicate_for: Callable[[DeletionTarget], tuple[str, dict] | None],*,reason: str,) -> None:@@ -456,8 +455,7 @@ def _refuse_unsweepable(assert_no_unsweepable_rows(cluster,targets,- predicate,- params,+ predicate_for,events=[] if deletion_request.delete_all_events else deletion_request.events,reason=reason,)@@ -465,6 +463,34 @@ def _refuse_unsweepable(raise dagster.Failure(description=f"Deletion request {deletion_request.request_id}: {exc}") from exc+def _refuse_property_removal_unsweepable(+ cluster: ClickhouseCluster,+ unsweepable: list[DeletionTarget],+ deletion_request: DeletionRequestContext,+ marker_str: str,+) -> None:+ """Gate a property-removal request against every unsweepable target.++ A target without ``stores_person_properties`` (today only flag_evaluations) drops the+ request's ``person_properties`` half from its presence check, since the gate cannot query that+ column there; see the field's own comment on ``DeletionTarget`` for what that costs. A target+ left with no criteria at all, nothing in ``properties`` either, is skipped rather than+ queried.+ """++ def predicate_for(target: DeletionTarget) -> tuple[str, dict] | None:+ request = (+ deletion_request if target.stores_person_properties else replace(deletion_request, person_properties=[])+ )+ if not request.properties and not request.person_properties:+ return None+ return _property_removal_where(request, inserted_at_max=marker_str)++ _refuse_unsweepable(+ cluster, unsweepable, deletion_request, predicate_for, reason=_PROPERTY_REWRITE_UNSWEEPABLE_REASON+ )++def _verify_swept(cluster: ClickhouseCluster,targets: list[DeletionTarget],@@ -496,8 +522,10 @@ def _event_removal_placements(unsweepable = [p.target for p in placements if not p.target.accepts_hogql_predicate]if unsweepable:- predicate, params = portable_event_removal_where(deletion_request)- _refuse_unsweepable(cluster, unsweepable, deletion_request, predicate, params, reason=_HOGQL_UNSWEEPABLE_REASON)+ criteria = portable_event_removal_where(deletion_request)+ _refuse_unsweepable(+ cluster, unsweepable, deletion_request, lambda _target: criteria, reason=_HOGQL_UNSWEEPABLE_REASON+ )return [p for p in placements if p.target.accepts_hogql_predicate]@@ -755,15 +783,7 @@ def get_property_removal_shards(marker_str = marker.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S.%f")# Bound by the same marker as the sweep and the verify gate, so a row ingested after the# marker — which the sweep would never touch — can't refuse the request forever.- presence, presence_params = _property_removal_where(deletion_request, inserted_at_max=marker_str)- _refuse_unsweepable(- cluster,- unsweepable,- deletion_request,- presence,- presence_params,- reason=_PROPERTY_REWRITE_UNSWEEPABLE_REASON,- )+ _refuse_property_removal_unsweepable(cluster, unsweepable, deletion_request, marker_str)shards = sorted(cluster.shards)context.log.info(f"Fanning out property removal {deletion_request.request_id} to {len(shards)} shard op(s)")@@ -1087,15 +1107,7 @@ def verify_property_removal(# Bounded by the same marker as the checks below so post-marker ingestion can't wedge the run.unsweepable = [t for t in resolve_targets_here(cluster) if not t.accepts_property_rewrite]if unsweepable:- presence, presence_params = _property_removal_where(deletion_request, inserted_at_max=marker_str)- _refuse_unsweepable(- cluster,- unsweepable,- deletion_request,- presence,- presence_params,- reason=_PROPERTY_REWRITE_UNSWEEPABLE_REASON,- )+ _refuse_property_removal_unsweepable(cluster, unsweepable, deletion_request, marker_str)properties = deletion_request.propertiesperson_properties = deletion_request.person_propertiesdiff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex 4c5583447b04..6562a398f40b 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -102,14 +102,15 @@ def _truncate_writable_events(client: Client) -> None:client.execute("TRUNCATE TABLE IF EXISTS sharded_events")-def _insert_flag_evaluations_with_properties(rows: list[tuple], client: Client) -> None:- # Rows of (team_id, distinct_id, properties_json, uuid, timestamp, inserted_at). The event name- # is stamped here because a property-removal request narrows on it. inserted_at is set- # explicitly rather than left to its `DEFAULT timestamp` so a test can place a row before or- # after the removal marker, which is what the marker-bounded gate keys on.+def _insert_flag_evaluations_with_properties(rows: list[tuple], client: Client, column: str = "properties") -> None:+ # Rows of (team_id, distinct_id, <column>_json, uuid, timestamp, inserted_at). The event name is+ # stamped here because a property-removal request narrows on it. inserted_at is set explicitly+ # rather than left to its `DEFAULT timestamp` so a test can place a row before or after the+ # removal marker, which is what the marker-bounded gate keys on. `column` selects which JSON blob+ # column the row's properties land in: `properties` (event) or `person_properties`.client.execute(- "INSERT INTO writable_flag_evaluations "- "(team_id, distinct_id, properties, uuid, timestamp, inserted_at, event) VALUES",+ f"INSERT INTO writable_flag_evaluations "+ f"(team_id, distinct_id, {column}, uuid, timestamp, inserted_at, event) VALUES",[(*row, FLAG_EVALUATIONS_SOURCE_EVENT) for row in rows],)@@ -2202,6 +2203,103 @@ def test_get_property_removal_shards_refuses_when_flag_evaluations_holds_matchinassert list(get_property_removal_shards(build_op_context(), cluster, deletion_request))+ "properties, person_properties, insert_column, insert_value, expect_refusal",+ [+ pytest.param(+ [], ["email"], "person_properties", '{"email": "[email protected]"}', False, id="person_properties_only"+ ),+ pytest.param(+ ["$ip"],+ ["email"],+ "person_properties",+ '{"email": "[email protected]"}',+ False,+ id="mixed_matches_person_property",+ ),+ pytest.param(["$ip"], ["email"], "properties", '{"$ip": "1.2.3.4"}', True, id="mixed_matches_event_property"),+ ],+)+def test_get_property_removal_shards_narrows_person_properties_on_flag_evaluations(+ cluster: ClickhouseCluster,+ properties: list[str],+ person_properties: list[str],+ insert_column: str,+ insert_value: str,+ expect_refusal: bool,+) -> None:+ # flag_evaluations' person_properties column no longer receives real data (#95693), so the gate+ # drops the person_properties half of its check: a row matching only that half now survives,+ # which is the accepted cost. The target itself is still checked, so a row matching the request's+ # event property must still refuse.+ request = DataDeletionRequest.objects.create(+ team_id=PROP_TEAM_ID,+ request_type=RequestType.PROPERTY_REMOVAL,+ events=[FLAG_EVALUATIONS_SOURCE_EVENT],+ properties=properties,+ person_properties=person_properties,+ start_time=datetime.now() - timedelta(days=7),+ end_time=datetime.now() + timedelta(days=1),+ status=RequestStatus.APPROVED,+ )+ config = DataDeletionRequestConfig(request_id=str(request.pk))+ deletion_request = load_property_removal_request(build_op_context(), config)+ marker = deletion_request.inserted_at_marker+ assert marker is not None+ before_marker = marker - timedelta(minutes=1)++ cluster.any_host(_truncate_flag_evaluations).result()+ cluster.any_host(+ partial(+ _insert_flag_evaluations_with_properties,+ [(PROP_TEAM_ID, "someone", insert_value, str(uuid4()), before_marker, before_marker)],+ column=insert_column,+ )+ ).result()++ if expect_refusal:+ with pytest.raises(dagster.Failure, match="cannot be deleted"):+ list(get_property_removal_shards(build_op_context(), cluster, deletion_request))+ else:+ assert list(get_property_removal_shards(build_op_context(), cluster, deletion_request))++ cluster.any_host(_truncate_flag_evaluations).result()+++def test_execute_event_deletion_refuses_hogql_predicate_when_flag_evaluations_holds_matching_rows(+ cluster: ClickhouseCluster,+) -> None:+ # flag_evaluations has no HogQL table definition, so it cannot accept the compiled predicate+ # and falls into the unsweepable branch of _event_removal_placements. A matching row there must+ # refuse the request rather than let it complete while HogQL-matched rows survive.+ now = datetime.now()+ start_time = now - timedelta(days=7)+ end_time = now + timedelta(minutes=1)++ cluster.any_host(_truncate_flag_evaluations).result()+ cluster.any_host(+ partial(+ _insert_flag_evaluations_with_properties,+ [(PROP_TEAM_ID, "someone", '{"$browser": "Chrome"}', str(uuid4()), now, now)],+ )+ ).result()++ deletion_ctx = DeletionRequestContext(+ request_id=str(uuid4()),+ team_id=PROP_TEAM_ID,+ start_time=start_time,+ end_time=end_time,+ events=[FLAG_EVALUATIONS_SOURCE_EVENT],+ hogql_predicate="properties.$browser = 'Chrome'",+ )+ with pytest.raises(dagster.Failure, match="cannot be deleted"):+ execute_event_deletion(build_op_context(), cluster, deletion_ctx)++ cluster.any_host(_truncate_flag_evaluations).result()++@pytest.mark.django_dbdef test_delete_person_events_op_resolves_distinct_ids_to_uuids(cluster: ClickhouseCluster):# When the request was submitted by distinct_id, the events op must resolve to UUIDsdiff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.pyindex 477db7a7d656..6c34c65ce4a4 100644--- a/posthog/models/deletion_targets.py+++ b/posthog/models/deletion_targets.py@@ -103,6 +103,16 @@ class DeletionTarget:# table, which today is hardcoded to the events tables. flag_evaluations satisfies only the# schema half, so flipping this without extending the sweep silently under-deletes.accepts_property_rewrite: bool = False+ # Whether the property-removal gate may build a person_properties predicate here. False where+ # the column has been dropped out of band on PostHog Cloud, which makes the predicate an+ # unknown-identifier error rather than a count. The flag narrows the gate on every deployment+ # regardless of whether the column is actually present there. The cost is a blind spot: rows+ # this table stored before its producer stopped sending person_properties hold real values+ # wherever the column survives, and this gate no longer sees them. Bounded by the table's TTL;+ # see COVERAGE_DOC.+ # accepts_property_rewrite=True implies this must stay True too, since the rewrite assumes the+ # column holds real data; __post_init__ below enforces that pairing.+ stores_person_properties: bool = True# Read uuids from this table when queueing a deferred deletion. False where the rows duplicate# another target's uuids, which would queue each one twice.queue_uuid_candidates: bool = True@@ -110,6 +120,13 @@ class DeletionTarget:# events skip this table without querying it.stored_events: frozenset[str] | None = None+ def __post_init__(self) -> None:+ if self.accepts_property_rewrite and not self.stores_person_properties:+ raise ValueError(+ f"{self.data_table}: accepts_property_rewrite needs stores_person_properties, "+ f"because the rewrite writes the person_properties column back. See {COVERAGE_DOC}."+ )+@propertydef cluster_name(self) -> str:return getattr(settings, self.cluster_setting)@@ -166,15 +183,17 @@ EVENTS_JSON = DeletionTarget(queue_uuid_candidates=False,)-# Flag-evaluation telemetry carries the same person and group payload as events, so person, team-# and queued-uuid sweeps must reach it. It takes neither of the richer sweeps; both exclusions are-# explained in docs/internal/clickhouse-deletion-coverage.md. Its producer populates person_id-# exactly as the events pipeline does, so a person sweep matches on person_id like every other-# events-shaped table.+# Flag-evaluation telemetry carries the same person_id and group payload as events, so team and+# queued-uuid sweeps must reach it, and a person sweep matches on person_id like every other+# events-shaped table. Its producer stopped sending person_properties on 2026-09-05 (#95693); a row+# the table stored before then is out of the property-removal gate's reach until its TTL passes. It+# takes neither of the richer sweeps; both exclusions are explained in+# docs/internal/clickhouse-deletion-coverage.md.FLAG_EVALUATIONS = DeletionTarget(data_table=FLAG_EVALUATIONS_DATA_TABLE,read_table=FLAG_EVALUATIONS_TABLE,optional=True,+ stores_person_properties=False,stored_events=frozenset({FLAG_EVALUATIONS_SOURCE_EVENT}),)@@ -387,8 +406,7 @@ def count_surviving_rows(cluster: ClickhouseCluster, target: DeletionTarget, predef assert_no_unsweepable_rows(cluster: ClickhouseCluster,targets: Sequence[DeletionTarget],- predicate: str,- params: dict,+ predicate_for: Callable[[DeletionTarget], tuple[str, dict] | None],*,events: Sequence[str],reason: str,@@ -397,8 +415,10 @@ def assert_no_unsweepable_rows(Pass targets already narrowed by ``resolve_targets``; this does not re-check presence.- ``predicate`` must be the portable part of the criteria — no HogQL fragment, no- materialized-column arms — so the count is a superset of what the deletion would have removed.+ ``predicate_for`` returns the criteria to count on a target, or ``None`` to skip it.+ The criteria carry no HogQL fragment and no materialized-column arms, so each count is a+ superset of what the deletion would have removed. A caller may drop a criterion the target+ cannot hold, and the count is then a superset of the remainder.``events`` is the request's event filter, empty meaning every event.Deliberately gated on rows existing rather than on the request's shape: an unconditional@@ -409,6 +429,11 @@ def assert_no_unsweepable_rows(if not target.may_hold_any_of(events):continue+ criteria = predicate_for(target)+ if criteria is None:+ continue+ predicate, params = criteria+count = count_surviving_rows(cluster, target, predicate, params)if count:raise UnsweepableRowsError(