: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(flags): remove person properties from flag_evaluations on request (#114276)
Phil Haackf8b18ea2e53e
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex a686362a796e..ccba08021729 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -95,7 +95,7 @@ Leaving one out stays possible, and `PERSON_ID_REWRITE_EXEMPT` is where that dec- `sharded_events` — all sweeps.- `sharded_events_json` — all sweeps, on the events cluster, through patch parts instead of mutations (`uses_patch_parts`). Optional: only present after the native-JSON migration.-- `sharded_flag_evaluations` — person, team, queued-uuid, immediate and deferred event removal, and property removal of event `properties` (below). Neither event removal nor property removal sweeps it when the request carries a HogQL predicate. Optional.+- `sharded_flag_evaluations` — person, team, queued-uuid, immediate and deferred event removal, and property removal of event and person properties (below). Neither event removal nor property removal sweeps it when the request carries a HogQL predicate. Optional.- `sharded_posthog_document_embeddings_<model>` — event and team deletion, through `delete_event_documents`. An embedded document is keyed by the id of the thing it describes (`document_id`), and an Event deletion's key is that same id, so the pending dictionary is joined on `(team_id, Event, document_id)`. Every per-model table listed by the error tracking facade's `document_embedding_tables` is swept and counted.Native property-removal requests fail when the selected rows retain a requested permanent or temporary property, or a matching person `$set`/`$set_once` instruction.@@ -156,8 +156,7 @@ That works because `materialize()` creates columns as `DEFAULT <expr>`, so an in`group0..group4_properties` no longer exist on the table: no Insight or Hog function used them as a breakdown or a filter, so the ClickHouse team dropped them directly on both prod clusters, and `posthog/models/flag_evaluations/sql.py` no longer declares them. Event `properties` and `person_id` are still sent.`person_properties` is on the table again, so test-account filters can read person properties off the row the way they do on `events`.The column defaults to `'{}'`, and no row holds real person properties until the producer sends them.-Until then `DeletionTarget.stores_person_properties` stays `False` on `FLAG_EVALUATIONS`, so the job drops the `person_properties` half for this table, and a request that names only person properties does not touch it.-`stores_person_properties` has to turn on before or with the producer change, or a person-property removal skips real values on this table and still reports success.+Property removal treats `person_properties` here as it does on `events`: the gate counts it, the copy drops the named keys from it, and the per-shard verify, the final verify and the admin Verify count all check it.#### Typed columns@@ -276,7 +275,7 @@ A manual run can narrow the plan with `team_ids` and `partitions`. A listed team## 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` makes the property-removal job sweep the table, so it needs a rewrite that cleans every copy the table keeps, 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 that rewrites event properties without person properties.+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` makes the property-removal job sweep the table, so it needs a rewrite that cleans every copy the table keeps, not just assignable columns, and a `person_properties` column, because the job reads and rewrites that column on every table it sweeps.Set `accepts_person_id_rewrite` unless you mean to leave the table out of the squash, which needs `person_id` outside the table's sorting and partition keys; skipping it is what stranded `flag_evaluations` rows on a merged-away person (#93035).A table you do leave out goes in `PERSON_ID_REWRITE_EXEMPT` with the reason.If it is not going to be swept, add it to `TTL_ONLY_TABLES` with the window you are accepting.diff --git a/posthog/clickhouse/test/test_deletion_coverage.py b/posthog/clickhouse/test/test_deletion_coverage.pyindex aa8491ceb3f7..0c88b562b613 100644--- a/posthog/clickhouse/test/test_deletion_coverage.py+++ b/posthog/clickhouse/test/test_deletion_coverage.py@@ -52,8 +52,9 @@ class TestDeletionCoverage(ClickhouseTestMixin, BaseTest):def test_every_personal_data_target_is_squashed_or_exempt(self):# A merge moves a distinct_id to another person, and a later deletion names only the# survivor, so a target the squash skips keeps its rows on the absorbed person until the- # TTL drops them (#93035). The test above cannot catch that: it keys on person_properties,- # which flag_evaluations does not declare, which is how flag_evaluations slipped through.+ # TTL drops them (#93035). The test above cannot catch that, because it checks only that the+ # deletion sweep reaches a table, and only for a table that declares person_properties. This+ # test reads the registered targets instead, because a target need not declare that column.skipped = {target.data_table for target in PERSONAL_DATA_TARGETS if not target.accepts_person_id_rewrite}unaccounted = sorted(skipped - PERSON_ID_REWRITE_EXEMPT)diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex d106eb01b10f..7908d1b3a3a6 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -2,7 +2,7 @@ import jsonimport timeimport loggingfrom collections.abc import Callable, Collection, Iterator-from dataclasses import dataclass, field, replace+from dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom functools import partialfrom typing import TypeVar@@ -556,27 +556,10 @@ def _refuse_unsweepable(raise dagster.Failure(description=f"Deletion request {deletion_request.request_id}: {exc}") from exc-_STORES_NONE_OF_THE_PROPERTIES = "the request names only person properties, and this table stores none"--def _deletion_target(data_table: str) -> DeletionTarget:return next(target for target in PERSONAL_DATA_TARGETS if target.data_table == data_table)-def _scoped_to(target: DeletionTarget, deletion_request: DeletionRequestContext) -> DeletionRequestContext:- """The property-removal request narrowed to the property columns ``target`` stores.-- A target without ``stores_person_properties`` (today only flag_evaluations) drops the- request's ``person_properties`` half, since that column cannot be queried or assigned there;- see the field's own comment on ``DeletionTarget`` for what that costs.- """- return deletion_request if target.stores_person_properties else replace(deletion_request, person_properties=[])---def _names_any_property(request: DeletionRequestContext) -> bool:- return bool(request.properties or request.person_properties)--def _hogql_excludes(target: DeletionTarget, deletion_request: DeletionRequestContext) -> bool:"""Whether the request carries a HogQL predicate that does not compile against ``target``."""return bool(deletion_request.hogql_predicate) and not target.accepts_hogql_predicate@@ -596,11 +579,10 @@ def _refuse_property_removal_unsweepable(which ``_property_rewrite_targets`` leaves out of the sweep."""- def predicate_for(target: DeletionTarget) -> tuple[str, dict] | NotCounted:- request = _scoped_to(target, deletion_request)- if not _names_any_property(request):- return NotCounted(reason=_STORES_NONE_OF_THE_PROPERTIES)- return _property_removal_where(request, inserted_at_max=marker_str, json_schema=target.uses_new_events_schema)+ def predicate_for(target: DeletionTarget) -> tuple[str, dict]:+ return _property_removal_where(+ deletion_request, inserted_at_max=marker_str, json_schema=target.uses_new_events_schema+ )_refuse_unsweepable(cluster,@@ -1165,6 +1147,14 @@ def _with_copied_inserted_at_bound(predicate: _ShardPredicate, copied_inserted_a)+def _drop_keys_expr(source: str, keys_param: str) -> str:+ # JSONDropKeysPool fails on an empty string. A legacy events row stores '' in a JSON column its+ # producer omitted, because those columns have no DEFAULT. An insert can also set '' explicitly.+ # Such a row has no key to drop, so it keeps its value. ClickHouse can evaluate both branches of+ # `if`, so the UDF gets '{}' in place of '' and the outer `if` discards that result.+ return f"if(empty({source}), {source}, JSONDropKeysPool(if(empty({source}), '{{}}', {source}), %({keys_param})s))"++@frozenclass _CleanedSelect:"""How the copy reads cleaned rows out of the source table."""@@ -1211,11 +1201,11 @@ def _cleaned_select_list(# let the cast below turn the cleaned string back into the JSON column type.if deletion_request.properties:source = "toJSONString(properties)" if target.json_schema else "properties"- replacements["properties"] = f"JSONDropKeysPool({source}, %(keys)s)"+ replacements["properties"] = _drop_keys_expr(source, "keys")params["keys"] = deletion_request.propertiesif deletion_request.person_properties:source = "toJSONString(person_properties)" if target.json_schema else "person_properties"- replacements["person_properties"] = f"JSONDropKeysPool({source}, %(person_keys)s)"+ replacements["person_properties"] = _drop_keys_expr(source, "person_keys")params["person_keys"] = deletion_request.person_propertiesfor name, is_nullable in mat_cols:replacements[name] = "NULL" if is_nullable else "''"@@ -1288,9 +1278,6 @@ def _property_rewrite_targets(if not target.may_hold_any_of(events):log.info(f"{target.read_table}: not rewritten, because it stores none of the request's events")continue- if not _names_any_property(_scoped_to(target, deletion_request)):- log.info(f"{target.read_table}: not rewritten, because {_STORES_NONE_OF_THE_PROPERTIES}")- continueswept.append(target)return swept@@ -1423,12 +1410,11 @@ def copy_property_removal_shard("""marker_str = _marker_str(deletion_request)hogql_compiled = _compile_predicate(deletion_request, target.json_schema)- request = _scoped_to(target.deletion_target, deletion_request)staging = _ShardStaging(request_id=deletion_request.request_id, target=target)log = _query_logger(context, target)def copy(client: Client) -> dict:- return _copy_property_removal_target(client, request, target, marker_str, hogql_compiled, staging, log)+ return _copy_property_removal_target(client, deletion_request, target, marker_str, hogql_compiled, staging, log)copied = _run_on_shard(_cluster_for(cluster, target), target, copy)context.add_output_metadata({"copied": dagster.MetadataValue.int(copied["rows"])})@@ -1449,7 +1435,6 @@ def delete_property_removal_shard(db = django_settings.CLICKHOUSE_DATABASEmarker_str = _marker_str(deletion_request)hogql_compiled = _compile_predicate(deletion_request, target.json_schema)- request = _scoped_to(target.deletion_target, deletion_request)staging = _ShardStaging(request_id=deletion_request.request_id, target=target)log = _query_logger(context, target)@@ -1473,7 +1458,7 @@ def delete_property_removal_shard()_sync_replica(client, target, log)- predicate = _shard_predicate(client, request, target.deletion_target, marker_str, hogql_compiled, log)+ predicate = _shard_predicate(client, deletion_request, target.deletion_target, marker_str, hogql_compiled, log)predicate = _with_copied_inserted_at_bound(predicate, copied["inserted_at_max"])count_sql = (f"SELECT toString(toYYYYMM(timestamp)) AS month, uniqExact(uuid) "@@ -1649,7 +1634,6 @@ def verify_property_removal_shard(db = django_settings.CLICKHOUSE_DATABASEmarker_str = _marker_str(deletion_request)hogql_compiled = _compile_predicate(deletion_request, target.json_schema)- request = _scoped_to(target.deletion_target, deletion_request)staging = _ShardStaging(request_id=deletion_request.request_id, target=target)log = _query_logger(context, target)@@ -1669,7 +1653,7 @@ def verify_property_removal_shard(return stats_sync_replica(client, target, log)- predicate = _shard_predicate(client, request, target.deletion_target, marker_str, hogql_compiled, log)+ predicate = _shard_predicate(client, deletion_request, target.deletion_target, marker_str, hogql_compiled, log)predicate = _with_copied_inserted_at_bound(predicate, copied["inserted_at_max"])remaining = client.execute(f"SELECT count() FROM {db}.{target.table} WHERE {predicate.sql}",@@ -1685,9 +1669,9 @@ def verify_property_removal_shard("start_time": deletion_request.start_time,"end_time": deletion_request.end_time,"marker": marker_str,- **_presence_params(request),+ **_presence_params(deletion_request),}- presence = _target_presence_clause(request, target, predicate.mat_cols)+ presence = _target_presence_clause(deletion_request, target, predicate.mat_cols)unexpired_sql, unexpired_params = _unexpired_rows(client, target.deletion_target)expected_months = staging.unexpired_uuids(client, copied["months"], unexpired_sql, unexpired_params)cleaned_stats = client.execute(@@ -1774,8 +1758,7 @@ def verify_property_removal()def check(client: Client, target: DeletionTarget, hogql_compiled: tuple[str, dict]) -> int:- request = _scoped_to(target, deletion_request)- predicate = _shard_predicate(client, request, target, marker_str, hogql_compiled)+ predicate = _shard_predicate(client, deletion_request, target, marker_str, hogql_compiled)return client.execute(surviving_rows_sql(target.read_table, predicate.sql),predicate.params,diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex dac40d204529..d8e88bf209bb 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -139,17 +139,19 @@ 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[, _timestamp]). 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, **row_values: object) -> None:+ # Rows of (team_id, distinct_id, properties_json, uuid, timestamp, inserted_at[, _timestamp]).+ # Each keyword in row_values sets that column to the same value on every row. 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.columns = "team_id, distinct_id, properties, uuid, timestamp, inserted_at"if rows and len(rows[0]) == 7:columns += ", _timestamp"+ stamped = {"event": FLAG_EVALUATIONS_SOURCE_EVENT, **row_values}client.execute(- f"INSERT INTO writable_flag_evaluations ({columns}, event) VALUES",- [(*row, FLAG_EVALUATIONS_SOURCE_EVENT) for row in rows],+ f"INSERT INTO writable_flag_evaluations ({columns}, {', '.join(stamped)}) VALUES",+ [(*row, *stamped.values()) for row in rows],)@@ -1069,10 +1071,14 @@ def test_property_removal_cleaning_uses_unversioned_pool_udf() -> None:"2026-10-05 13:03:36.419459",)- assert "CAST(JSONDropKeysPool(properties, %(keys)s) AS String) AS `properties`" in cleaned.expressionsassert (- "CAST(JSONDropKeysPool(person_properties, %(person_keys)s) AS String) AS `person_properties`"- in cleaned.expressions+ "CAST(if(empty(properties), properties, JSONDropKeysPool(if(empty(properties), '{}', properties), %(keys)s)) "+ "AS String) AS `properties`" in cleaned.expressions+ )+ assert (+ "CAST(if(empty(person_properties), person_properties, "+ "JSONDropKeysPool(if(empty(person_properties), '{}', person_properties), %(person_keys)s)) "+ "AS String) AS `person_properties`" in cleaned.expressions)@@ -2600,17 +2606,32 @@ def test_get_property_removal_shards_refuses_a_hogql_predicate_when_flag_evaluat@pytest.mark.django_db@pytest.mark.parametrize(- "hogql_predicate, properties, person_properties, insert_value, error",+ "hogql_predicate, properties, person_properties, stored_properties, stored_person_properties, error",[- pytest.param("", [], ["email"], '{"email": "[email protected]"}', None, id="person_properties_only"),pytest.param(- "", ["$ip"], ["email"], '{"email": "[email protected]"}', None, id="mixed_row_holds_only_the_person_key"+ "",+ [],+ ["email"],+ "{}",+ '{"email": "[email protected]"}',+ "still match the removal predicate",+ id="person_properties_only",+ ),+ pytest.param(+ "",+ ["$ip"],+ ["email"],+ "{}",+ '{"email": "[email protected]"}',+ "still match the removal predicate",+ id="mixed_row_holds_only_the_person_key",),pytest.param("",["$ip"],["email"],'{"$ip": "1.2.3.4"}',+ "{}","still match the removal predicate",id="mixed_matches_event_property",),@@ -2618,8 +2639,9 @@ def test_get_property_removal_shards_refuses_a_hogql_predicate_when_flag_evaluat"properties.$browser = 'Chrome'",[],["email"],+ "{}",'{"email": "[email protected]"}',- None,+ "cannot be deleted",id="gated_person_properties_only",),pytest.param(@@ -2627,25 +2649,24 @@ def test_get_property_removal_shards_refuses_a_hogql_predicate_when_flag_evaluat["$ip"],["email"],'{"$ip": "1.2.3.4"}',+ "{}","cannot be deleted",id="gated_mixed_matches_event_property",),],)-def test_verify_property_removal_narrows_person_properties_on_flag_evaluations(+def test_verify_property_removal_counts_person_properties_on_flag_evaluations(cluster: ClickhouseCluster,team,hogql_predicate: str,properties: list[str],person_properties: list[str],- insert_value: str,- error: str | None,+ stored_properties: str,+ stored_person_properties: str,+ error: str,) -> None:- # verify runs after the shard ops have rewritten rows, so a query error here leaves an erasure- # half done. flag_evaluations has no person_properties column (#95693), so both of its checks on- # the table drop that half, and a row matching the event-property half still fails the request.- # The admin Verify button marks a request completed when its count is zero, so that count must- # hold the same rows the job's verify does.+ # The admin Verify button marks a request completed when its count is zero, so that count must see+ # the same surviving rows the job's verify does. It counts this table without the HogQL fragment.request = DataDeletionRequest.objects.create(team_id=team.id,request_type=RequestType.PROPERTY_REMOVAL,@@ -2667,43 +2688,50 @@ def test_verify_property_removal_narrows_person_properties_on_flag_evaluations(cluster.any_host(partial(_insert_flag_evaluations_with_properties,- [(team.id, "someone", insert_value, str(uuid4()), before_marker, before_marker)],+ [(team.id, "someone", stored_properties, str(uuid4()), before_marker, before_marker)],+ person_properties=stored_person_properties,)).result()- with pytest.raises(dagster.Failure, match=error) if error else nullcontext():+ with pytest.raises(dagster.Failure, match=error):verify_property_removal(build_op_context(), cluster, deletion_request, [])- assert count_remaining_for_request(request) == (1 if error else 0)+ assert count_remaining_for_request(request) == 1cluster.any_host(_truncate_flag_evaluations).result()-def _flag_evaluation_rows(team_id: int, client: Client) -> list[tuple[str, dict, str, str, int]]:+def _flag_evaluation_rows(team_id: int, client: Client) -> list[tuple[str, dict, dict | None, str, str, str, str, int]]:rows = client.execute(- "SELECT toString(uuid), properties, flag_key, session_id, toUnixTimestamp(_timestamp) FROM flag_evaluations "- "WHERE team_id = %(team_id)s AND _row_exists = 1",+ "SELECT toString(uuid), properties, person_properties, toString(person_created_at), person_mode, flag_key, "+ "session_id, toUnixTimestamp(_timestamp) FROM flag_evaluations WHERE team_id = %(team_id)s AND _row_exists = 1",{"team_id": team_id},)return sorted((- (uuid, json.loads(properties), flag_key, session_id, kafka_time)- for uuid, properties, flag_key, session_id, kafka_time in rows+ (uuid, json.loads(properties), json.loads(person_properties or "null"), *rest)+ for uuid, properties, person_properties, *rest in rows),key=lambda row: row[0],)+_STORED_PERSON = {"email": "[email protected]", "plan": "pro"}++@pytest.mark.django_db@pytest.mark.parametrize(- "properties, person_properties",+ "properties, person_properties, stored_person",[- pytest.param(["$session_id"], [], id="typed_column"),- pytest.param(["$feature_flag"], [], id="sort_key_column"),- pytest.param(["$session_id"], ["email"], id="with_person_properties"),+ pytest.param(["$session_id"], [], _STORED_PERSON, id="typed_column"),+ pytest.param(["$feature_flag"], [], _STORED_PERSON, id="sort_key_column"),+ pytest.param(["$session_id"], ["email"], _STORED_PERSON, id="with_person_properties"),+ # An insert that sets person_properties to '' stores '', and the event-property half still+ # selects the row, so the copy must leave the empty value alone.+ pytest.param(["$session_id"], ["email"], None, id="empty_person_properties"),],)def test_full_job_property_removal_rewrites_flag_evaluations(- cluster: ClickhouseCluster, properties: list[str], person_properties: list[str]+ cluster: ClickhouseCluster, properties: list[str], person_properties: list[str], stored_person: dict | None) -> None:now = timezone.now()ingested = now - timedelta(hours=1)@@ -2715,7 +2743,16 @@ def test_full_job_property_removal_rewrites_flag_evaluations(for uuid in (replayed_uuid, replayed_uuid, single_uuid)]cluster.any_host(_truncate_flag_evaluations).result()- cluster.any_host(partial(_insert_flag_evaluations_with_properties, rows)).result()+ # Non-default values, so a copy that reset the person columns would fail the comparison below.+ cluster.any_host(+ partial(+ _insert_flag_evaluations_with_properties,+ rows,+ person_properties=json.dumps(stored_person) if stored_person else "",+ person_created_at=datetime(2026, 1, 2, 3, 4, 5, 678000),+ person_mode="propertyless",+ )+ ).result()request = DataDeletionRequest.objects.create(team_id=PROP_TEAM_ID,@@ -2732,11 +2769,24 @@ def test_full_job_property_removal_rewrites_flag_evaluations(resources={"cluster": cluster},)assert result.success+ assert count_remaining_for_request(request) == 0cleaned = {key: value for key, value in stored.items() if key not in properties}+ cleaned_person = (+ None if stored_person is None else {k: v for k, v in stored_person.items() if k not in person_properties}+ )# _timestamp keeps the Kafka message time, which flag_evaluations_backfill reads as the consumer position.expected = [- (uuid, cleaned, cleaned.get("$feature_flag", ""), cleaned.get("$session_id", ""), int(kafka_time.timestamp()))+ (+ uuid,+ cleaned,+ cleaned_person,+ "2026-01-02 03:04:05.678",+ "propertyless",+ cleaned.get("$feature_flag", ""),+ cleaned.get("$session_id", ""),+ int(kafka_time.timestamp()),+ )for uuid in sorted((replayed_uuid, replayed_uuid, single_uuid))]assert cluster.any_host(partial(_flag_evaluation_rows, PROP_TEAM_ID)).result() == expecteddiff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.pyindex 2722d8bdebea..c73f41c093f7 100644--- a/posthog/models/data_deletion_request.py+++ b/posthog/models/data_deletion_request.py@@ -914,7 +914,6 @@ def _property_presence_where(mat_cols: list[tuple[str, bool]] | None = None,person_mat_cols: list[tuple[str, bool]] | None = None,*,- with_person_properties: bool = True,with_hogql: bool = True,) -> tuple[str, dict]:"""WHERE predicate + params matching events that still carry any target (person_)property.@@ -925,8 +924,8 @@ def _property_presence_where(column reset on every matching event, this count reaches zero. The presence set must match thedeletion path (``_property_removal_where``) or a row it still considers dirty reads as clean here.- ``with_person_properties`` and ``with_hogql`` drop the parts a table without the events schema- cannot run: its ``person_properties`` column and the compiled HogQL fragment.+ ``with_hogql`` drops the compiled HogQL fragment, which a table without the events schema cannot+ run."""parts = [_EVENT_REMOVAL_TIME_PREDICATE, event_match_sql_fragment(request)]params = event_match_params(request)@@ -938,7 +937,7 @@ def _property_presence_where(params[f"fp_{i}_{j}"] = partif mat_cols:presence.extend(_mat_col_presence_clauses(mat_cols))- for i, prop in enumerate((request.person_properties or []) if with_person_properties else []):+ for i, prop in enumerate(request.person_properties or []):presence.append(jsonhas_expr(prop, f"pp_{i}", column="person_properties"))for j, part in enumerate(prop.split(".")):params[f"pp_{i}_{j}"] = part@@ -958,10 +957,9 @@ def count_remaining_property_events(request: "DataDeletionRequest") -> int:"""Count rows that still carry any of a property-removal request's target properties.Counts across every default deletion target the property-removal job rewrites, because a request- is only complete once each of those tables is clean. A target without ``stores_person_properties``- is checked for the event ``properties`` only, and skipped when the request names only person- properties, as the job does. A target that cannot take the compiled HogQL fragment is counted- without it, which matches a superset. That can only hold a request open, never complete it early.+ is only complete once each of those tables is clean. A target that cannot take the compiled HogQL+ fragment is counted without it, which matches a superset. That can only hold a request open,+ never complete it early.The presence predicate is built for the legacy schema, so the native-JSON table is left to thejob's own verification."""@@ -975,6 +973,9 @@ def count_remaining_property_events(request: "DataDeletionRequest") -> int:surviving_rows_sql,)+ if not request.properties and not request.person_properties:+ return 0+events = [] if request.delete_all_events else request.eventstotal = 0with tags_context(@@ -991,17 +992,12 @@ def count_remaining_property_events(request: "DataDeletionRequest") -> int:or not target.may_hold_any_of(events)):continue- person_properties = (request.person_properties or []) if target.stores_person_properties else []- if not request.properties and not person_properties:- continuemat_cols = discover_affected_mat_columns(request.properties or [], "properties", target.read_table)- person_mat_cols = discover_affected_mat_columns(person_properties, "person_properties", target.read_table)+ person_mat_cols = discover_affected_mat_columns(+ request.person_properties or [], "person_properties", target.read_table+ )predicate, params = _property_presence_where(- request,- mat_cols,- person_mat_cols,- with_person_properties=target.stores_person_properties,- with_hogql=target.accepts_hogql_predicate,+ request, mat_cols, person_mat_cols, with_hogql=target.accepts_hogql_predicate)result = sync_execute(surviving_rows_sql(target.read_table, predicate),diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.pyindex af95317779d9..6ac40dfa44c2 100644--- a/posthog/models/deletion_targets.py+++ b/posthog/models/deletion_targets.py@@ -105,14 +105,6 @@ class DeletionTarget:# a named property that the table keeps survives the rewrite. A property removal refuses while a# target without it holds rows the request names.accepts_property_rewrite: bool = False- # Whether property removal may build a person_properties predicate or replacement 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 and the rewrite 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 property removal no longer sees them. Bounded- # by the table's TTL; see COVERAGE_DOC.- stores_person_properties: bool = True# Whether the person-overrides squash rewrites person_id here. A merge moves a distinct_id to# another person, and a later deletion names only the survivor, so a table the squash skips# keeps its rows on the absorbed person and no sweep ever matches them (#93035).@@ -133,15 +125,6 @@ class DeletionTarget:# MutationRunner.patch_parts.uses_patch_parts: bool = False- def __post_init__(self) -> None:- # A table that takes a HogQL predicate has the events schema, including person_properties.- if self.accepts_property_rewrite and self.accepts_hogql_predicate and not self.stores_person_properties:- raise ValueError(- f"{self.data_table}: accepts_property_rewrite on an events-schema table needs "- f"stores_person_properties, because the rewrite must clean its person_properties "- f"column too. See {COVERAGE_DOC}."- )-@propertydef cluster_name(self) -> str:return getattr(settings, self.cluster_setting)@@ -225,19 +208,16 @@ EVENTS_JSON = DeletionTarget(# 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. Property removal rewrites its event properties. Its producer stopped sending-# person_properties on 2026-09-05 (#95693); a row the table stored before then is out of property-# removal's reach until its TTL passes. A HogQL predicate does not compile against the table, so a-# request that carries one never sweeps it. Immediate event removal with a predicate leaves the-# matching rows to the TTL. Deferred event removal and property removal with a predicate refuse-# while the table holds matching rows. docs/internal/clickhouse-deletion-coverage.md explains these-# limits.+# events-shaped table. Property removal rewrites its event properties and its person properties. A+# HogQL predicate does not compile against the table, so a request that carries one never sweeps it.+# Immediate event removal with a predicate leaves the matching rows to the TTL. Deferred event+# removal and property removal with a predicate refuse while the table holds matching rows.+# docs/internal/clickhouse-deletion-coverage.md explains these limits.FLAG_EVALUATIONS = DeletionTarget(data_table=FLAG_EVALUATIONS_DATA_TABLE,read_table=FLAG_EVALUATIONS_TABLE,optional=True,accepts_property_rewrite=True,- stores_person_properties=False,accepts_person_id_rewrite=True,stored_events=frozenset({FLAG_EVALUATIONS_SOURCE_EVENT}),ttl_days=FLAG_EVALUATIONS_TTL_DAYS,diff --git a/posthog/models/test/test_deletion_targets.py b/posthog/models/test/test_deletion_targets.pyindex c1b3acaca30b..675873aa2b28 100644--- a/posthog/models/test/test_deletion_targets.py+++ b/posthog/models/test/test_deletion_targets.py@@ -10,7 +10,6 @@ from posthog.clickhouse.client.connection import NodeRolefrom posthog.clickhouse.cluster import ClickhouseCluster, HostInfofrom posthog.models.deletion_targets import (DeletionTarget,- HogQLSchema,UnreachableTargetError,dispatchable_here,placement_for,@@ -135,14 +134,3 @@ def test_a_sibling_shards_over_the_role_its_target_declares() -> None:assert placement is not Noneassert sorted(placement.cluster.shards) == [1, 2]assert placement.cluster.shard_role == NodeRole.EVENTS---def test_an_events_schema_target_cannot_take_the_property_rewrite_without_person_properties() -> None:- with pytest.raises(ValueError, match="stores_person_properties"):- DeletionTarget(- data_table="sharded_events",- read_table="events",- hogql_schema=HogQLSchema.LEGACY,- accepts_property_rewrite=True,- stores_person_properties=False,- )