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.

feat(data-deletion): person properties dagster (#60048)

Paweł Szczurc0602a22159f
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index 5d0628438525..d2443cde506c 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -47,6 +47,7 @@ class DeletionRequestContext:
end_time: datetime
events: list[str]
properties: list[str] = field(default_factory=list)
+ person_properties: list[str] = field(default_factory=list)
execution_mode: str = ExecutionMode.IMMEDIATE.value
delete_all_events: bool = False
hogql_predicate: str = ""
@@ -98,29 +99,32 @@ def _temp_table_name(team_id: int, request_id: str) -> str:
return f"tmp_dag_team_{team_id}_prop_rm_{request_id[:8]}"
-def _property_filter_clause(properties: list[str]) -> str:
- if len(properties) == 1:
- return jsonhas_expr(properties[0], "fp_0")
- exprs = [jsonhas_expr(prop, f"fp_{i}") for i, prop in enumerate(properties)]
+def _property_filter_clause(props: list[str], prefix: str = "fp_", column: str = "properties") -> str:
+ if len(props) == 1:
+ return jsonhas_expr(props[0], f"{prefix}0", column=column)
+ exprs = [jsonhas_expr(prop, f"{prefix}{i}", column=column) for i, prop in enumerate(props)]
return f"({' OR '.join(exprs)})"
-def _property_filter_params(properties: list[str]) -> dict:
+def _property_filter_params(props: list[str], prefix: str = "fp_") -> dict:
params: dict[str, str] = {}
- for i, prop in enumerate(properties):
+ for i, prop in enumerate(props):
for j, part in enumerate(prop.split(".")):
- params[f"fp_{i}_{j}"] = part
+ params[f"{prefix}{i}_{j}"] = part
return params
def _base_params(ctx: DeletionRequestContext) -> dict:
- return {
+ params: dict = {
"team_id": ctx.team_id,
"start_time": ctx.start_time,
"end_time": ctx.end_time,
"events": ctx.events,
**_property_filter_params(ctx.properties),
}
+ if ctx.person_properties:
+ params.update(_property_filter_params(ctx.person_properties, prefix="pp_"))
+ return params
_EVENT_REMOVAL_TIME_PREDICATE = "team_id = %(team_id)s AND timestamp >= %(start_time)s AND timestamp < %(end_time)s"
@@ -167,15 +171,17 @@ def _mat_col_presence_clauses(mat_cols: list[tuple[str, bool]]) -> list[str]:
def _property_removal_where(
ctx: DeletionRequestContext,
mat_cols: list[tuple[str, bool]] | None = None,
+ person_mat_cols: list[tuple[str, bool]] | None = None,
inserted_at_max: str | None = None,
hogql_compiled: tuple[str, dict] | None = None,
) -> tuple[str, dict]:
"""Full WHERE predicate + params for property-removal queries.
Used both to copy candidate events into the staging table and to delete the
- originals afterward. The presence check (JSON ``properties`` plus DEFAULT
- materialized columns) MUST match between the two passes — drift causes
- either data loss (delete > copy) or duplication (copy > delete).
+ originals afterward. The presence check (JSON ``properties`` and/or
+ ``person_properties`` plus DEFAULT materialized columns) MUST match between
+ the two passes — drift causes either data loss (delete > copy) or duplication
+ (copy > delete).
Honors the optional ``hogql_predicate`` on the request the same way
``_event_removal_where`` does, so an operator can scope a property removal
@@ -193,9 +199,21 @@ def _property_removal_where(
Legacy rows may have ``inserted_at IS NULL`` and are still originals to
delete — the NULL branch keeps them in scope.
"""
- presence_clauses = [_property_filter_clause(ctx.properties)]
+ presence_clauses: list[str] = []
+ if ctx.properties:
+ presence_clauses.append(_property_filter_clause(ctx.properties))
if mat_cols:
presence_clauses.extend(_mat_col_presence_clauses(mat_cols))
+ if ctx.person_properties:
+ presence_clauses.append(
+ _property_filter_clause(ctx.person_properties, prefix="pp_", column="person_properties")
+ )
+ if person_mat_cols:
+ presence_clauses.extend(_mat_col_presence_clauses(person_mat_cols))
+ if not presence_clauses:
+ raise ValueError(
+ "_property_removal_where requires at least one of properties or person_properties to be non-empty"
+ )
presence = f"({' OR '.join(presence_clauses)})" if len(presence_clauses) > 1 else presence_clauses[0]
parts = [
@@ -229,15 +247,18 @@ def _get_affected_mat_columns(
client: Client,
table: str,
properties: list[str],
+ table_column: str = "properties",
log: QueryLogger | None = None,
) -> list[tuple[str, bool]]:
"""Query a specific shard for materialized columns matching deleted properties.
Returns ``(column_name, is_nullable)`` for columns whose comment follows the
- ``column_materializer::properties::<prop>`` convention. Comments live on the
- distributed ``events`` table while the DEFAULT expression lives on
- ``sharded_events`` (see ``materialize()`` in ee/clickhouse/materialized_columns),
- so we cannot filter by ``default_kind`` on the same row that carries the comment.
+ ``column_materializer::<table_column>::<prop>`` convention. Pass
+ ``table_column="person_properties"`` to discover columns materialised from
+ ``events.person_properties``. Comments live on the distributed ``events``
+ table while the DEFAULT expression lives on ``sharded_events`` (see
+ ``materialize()`` in ee/clickhouse/materialized_columns), so we cannot
+ filter by ``default_kind`` on the same row that carries the comment.
The comment itself is a sufficient identifier — it is PostHog-specific and the
``elements_chain::*`` family is excluded explicitly.
"""
@@ -258,7 +279,7 @@ def _get_affected_mat_columns(
result: list[tuple[str, bool]] = []
for col_name, comment, is_nullable in rows:
details = MaterializedColumnDetails.from_column_comment(comment)
- if details.table_column == "properties" and details.property_name in target_props:
+ if details.table_column == table_column and details.property_name in target_props:
result.append((col_name, bool(is_nullable)))
return result
@@ -477,9 +498,10 @@ def load_property_removal_request(
f"Request {config.request_id} is not an approved property_removal request.",
)
- if not request.properties:
+ person_properties = list(request.person_properties or [])
+ if not request.properties and not person_properties:
raise dagster.Failure(
- f"Request {config.request_id} has no properties specified.",
+ f"Request {config.request_id} has no properties or person_properties specified.",
)
_record_execution_attempt(request)
@@ -487,7 +509,7 @@ def load_property_removal_request(
context.log.info(
f"Processing property removal {request.pk}: "
f"team_id={request.team_id}, events={request.events}, "
- f"properties={request.properties}, "
+ f"properties={request.properties}, person_properties={person_properties}, "
f"time_range={request.start_time} to {request.end_time}"
)
context.add_output_metadata(
@@ -495,6 +517,7 @@ def load_property_removal_request(
"team_id": dagster.MetadataValue.int(request.team_id),
"events": dagster.MetadataValue.text(", ".join(request.events)),
"properties": dagster.MetadataValue.text(", ".join(request.properties)),
+ "person_properties": dagster.MetadataValue.text(", ".join(person_properties)),
"start_time": dagster.MetadataValue.text(str(request.start_time)),
"end_time": dagster.MetadataValue.text(str(request.end_time)),
"hogql_predicate": dagster.MetadataValue.text(request.hogql_predicate or ""),
@@ -509,6 +532,7 @@ def load_property_removal_request(
end_time=request.end_time,
events=request.events,
properties=request.properties,
+ person_properties=person_properties,
hogql_predicate=request.hogql_predicate or "",
)
@@ -523,13 +547,15 @@ def process_property_removal_per_shard(
Per shard, on a single host (the temp table is local non-replicated MergeTree):
- 1. Discover affected DEFAULT materialized columns.
+ 1. Discover affected DEFAULT materialized columns for both ``properties``
+ and ``person_properties``.
2. Create the temp table.
3. Copy matching events from sharded_events into temp. Presence check covers
- JSON ``properties`` AND materialized columns — a row can carry the value
- in the column alone, and ``SELECT *`` would otherwise leave it behind.
- 4. Mutate the temp table: drop JSON keys, reset materialized columns to their
- defaults, stamp ``inserted_at = marker``.
+ JSON ``properties`` and/or ``person_properties`` AND their materialized
+ columns — a row can carry the value in the column alone, and ``SELECT *``
+ would otherwise leave it behind.
+ 4. Mutate the temp table: drop JSON keys from each targeted column, reset
+ materialized columns to their defaults, stamp ``inserted_at = marker``.
5. Verify no target presence remains in temp (JSON or materialized columns).
6. Re-insert cleaned events into sharded_events.
7. Lightweight-delete the originals from sharded_events. Same presence check
@@ -539,7 +565,7 @@ def process_property_removal_per_shard(
Steps 3 and 7 use the same predicate (modulo the ``inserted_at`` clause on
delete), generated by ``_property_removal_where`` from the same per-shard
- ``mat_cols`` list, so they cannot drift.
+ ``mat_cols`` / ``person_mat_cols`` lists, so they cannot drift.
"""
from django.utils import timezone
@@ -547,6 +573,7 @@ def process_property_removal_per_shard(
temp = _temp_table_name(deletion_request.team_id, deletion_request.request_id)
db = django_settings.CLICKHOUSE_DATABASE
properties = deletion_request.properties
+ person_properties = deletion_request.person_properties
marker = timezone.now()
deletion_request.inserted_at_marker = marker
# Format the marker as a string with microseconds — clickhouse-driver serializes Python
@@ -570,14 +597,29 @@ def process_property_removal_per_shard(
log_query(label, sql)
return client.execute(sql, params, settings=settings)
- affected_mat_cols = _get_affected_mat_columns(client, "events", properties, log=log_query)
- context.log.info(f"affected materialized columns: {[c[0] for c in affected_mat_cols]}")
+ affected_mat_cols = (
+ _get_affected_mat_columns(client, "events", properties, table_column="properties", log=log_query)
+ if properties
+ else []
+ )
+ affected_person_mat_cols = (
+ _get_affected_mat_columns(
+ client, "events", person_properties, table_column="person_properties", log=log_query
+ )
+ if person_properties
+ else []
+ )
+ context.log.info(
+ f"affected materialized columns: properties={[c[0] for c in affected_mat_cols]}, "
+ f"person_properties={[c[0] for c in affected_person_mat_cols]}"
+ )
_create_local_staging_table(client, source_table=source, staging_table=temp, log=log_query)
copy_predicate, copy_params = _property_removal_where(
deletion_request,
mat_cols=affected_mat_cols,
+ person_mat_cols=affected_person_mat_cols,
hogql_compiled=hogql_compiled,
)
execute("truncate-temp", f"TRUNCATE TABLE IF EXISTS {db}.{temp}")
@@ -589,20 +631,25 @@ def process_property_removal_per_shard(
)
copied = execute("count-temp", f"SELECT count() FROM {db}.{temp}")[0][0]
- update_parts = [
- "properties = JSONDropKeys(%(keys)s)(properties)",
- # Cast to DateTime64(6) so microseconds survive the parameter binding —
- # mirrors the cast in the delete predicate so both sides agree on the marker.
- "inserted_at = toDateTime64(%(inserted_at_marker)s, 6, 'UTC')",
- ]
- for col_name, is_nullable in affected_mat_cols:
+ update_parts: list[str] = []
+ mutation_params: dict = {"inserted_at_marker": marker_str}
+ if properties:
+ update_parts.append("properties = JSONDropKeys(%(keys)s)(properties)")
+ mutation_params["keys"] = properties
+ if person_properties:
+ update_parts.append("person_properties = JSONDropKeys(%(person_keys)s)(person_properties)")
+ mutation_params["person_keys"] = person_properties
+ # Cast to DateTime64(6) so microseconds survive the parameter binding —
+ # mirrors the cast in the delete predicate so both sides agree on the marker.
+ update_parts.append("inserted_at = toDateTime64(%(inserted_at_marker)s, 6, 'UTC')")
+ for col_name, is_nullable in affected_mat_cols + affected_person_mat_cols:
default = "NULL" if is_nullable else "''"
update_parts.append(f"`{col_name}` = {default}")
clean_runner = AlterTableMutationRunner(
table=temp,
commands={f"UPDATE {', '.join(update_parts)} WHERE 1=1"},
- parameters={"keys": properties, "inserted_at_marker": marker_str},
+ parameters=mutation_params,
)
context.log.info(
f"[clean-temp-mutation] {_flatten_sql(clean_runner.get_statement(clean_runner.get_all_commands()))}"
@@ -610,9 +657,17 @@ def process_property_removal_per_shard(
clean_waiter = clean_runner(client)
clean_waiter.wait(client)
- verify_clauses = [_property_filter_clause(properties), *_mat_col_presence_clauses(affected_mat_cols)]
+ verify_clauses: list[str] = []
+ if properties:
+ verify_clauses.append(_property_filter_clause(properties))
+ verify_clauses.extend(_mat_col_presence_clauses(affected_mat_cols))
+ if person_properties:
+ verify_clauses.append(_property_filter_clause(person_properties, prefix="pp_", column="person_properties"))
+ verify_clauses.extend(_mat_col_presence_clauses(affected_person_mat_cols))
verify_predicate = f"({' OR '.join(verify_clauses)})" if len(verify_clauses) > 1 else verify_clauses[0]
- verify_params = _property_filter_params(properties)
+ verify_params: dict = {**_property_filter_params(properties)}
+ if person_properties:
+ verify_params.update(_property_filter_params(person_properties, prefix="pp_"))
remaining = execute(
"verify-temp-clean",
f"SELECT count() FROM {db}.{temp} WHERE {verify_predicate}",
@@ -632,6 +687,7 @@ def process_property_removal_per_shard(
delete_predicate, delete_params = _property_removal_where(
deletion_request,
mat_cols=affected_mat_cols,
+ person_mat_cols=affected_person_mat_cols,
inserted_at_max=marker_str,
hogql_compiled=hogql_compiled,
)
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index df04a95893f9..ea0c1035418d 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -598,10 +598,391 @@ def test_load_property_removal_request_rejects_empty_properties():
config = DataDeletionRequestConfig(request_id=str(request.pk))
context = build_op_context()
- with pytest.raises(Exception, match="no properties specified"):
+ with pytest.raises(Exception, match="no properties or person_properties specified"):
load_property_removal_request(context, config)
+def _insert_events_with_person_properties(events: list[tuple], client: Client) -> None:
+ """Insert events with (team_id, event, uuid, timestamp, person_properties_json)."""
+ client.execute(
+ "INSERT INTO writable_events (team_id, event, uuid, timestamp, person_properties) VALUES",
+ events,
+ )
+
+
+def _get_person_properties(team_id: int, event_name: str, client: Client) -> list[dict]:
+ result = client.execute(
+ "SELECT person_properties FROM events WHERE team_id = %(team_id)s AND event = %(event)s",
+ {"team_id": team_id, "event": event_name},
+ )
+ return [json.loads(row[0]) if row[0] else {} for row in result]
+
+
+def test_full_job_person_property_removal(cluster: ClickhouseCluster):
+ """Keys in person_properties are removed; the event itself is preserved."""
+ now = datetime.now()
+ start_time = now - timedelta(days=7)
+ end_time = now + timedelta(minutes=1)
+
+ person_props_to_drop = json.dumps({"email": "[email protected]", "keep": "yes"})
+ no_target_person_props = json.dumps({"keep": "yes", "other": "value"})
+
+ target_events = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i), person_props_to_drop) for i in range(10)
+ ]
+ events_without_target = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i), no_target_person_props) for i in range(5)
+ ]
+
+ cluster.any_host(partial(_insert_events_with_person_properties, target_events + events_without_target)).result()
+
+ assert cluster.any_host(partial(_count_events_by_name, PROP_TEAM_ID, "$pageview")).result() == 15
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=[],
+ person_properties=["email"],
+ start_time=start_time,
+ end_time=end_time,
+ status=RequestStatus.APPROVED,
+ )
+
+ result = data_deletion_request_property_removal.execute_in_process(
+ run_config={
+ "ops": {
+ "load_property_removal_request": {
+ "config": {"request_id": str(request.pk)},
+ },
+ },
+ },
+ resources={"cluster": cluster},
+ )
+ assert result.success
+
+ # Events still exist (properties removed, not deleted)
+ assert cluster.any_host(partial(_count_events_by_name, PROP_TEAM_ID, "$pageview")).result() == 15
+
+ # Target key removed from person_properties
+ all_person_props = cluster.any_host(partial(_get_person_properties, PROP_TEAM_ID, "$pageview")).result()
+ for pprops in all_person_props:
+ assert "email" not in pprops, f"email should be removed, got {pprops}"
+ # Non-target key preserved on the events that had it
+ events_with_keep = [p for p in all_person_props if "keep" in p]
+ assert len(events_with_keep) == 15, "keep key should survive on all events"
+
+ request.refresh_from_db()
+ assert request.status == RequestStatus.COMPLETED
+
+
+def test_full_job_both_properties_and_person_properties(cluster: ClickhouseCluster):
+ """When both properties and person_properties are specified, both columns are cleaned."""
+ now = datetime.now()
+ start_time = now - timedelta(days=7)
+ end_time = now + timedelta(minutes=1)
+
+ props = json.dumps({"$ip": "1.2.3.4", "keep": "yes"})
+ person_props = json.dumps({"email": "[email protected]", "keep_person": "yes"})
+
+ events: list[tuple] = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i), props, person_props) for i in range(8)
+ ]
+
+ cluster.any_host(
+ lambda client: client.execute(
+ "INSERT INTO writable_events (team_id, event, uuid, timestamp, properties, person_properties) VALUES",
+ events,
+ )
+ ).result()
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=["$ip"],
+ person_properties=["email"],
+ start_time=start_time,
+ end_time=end_time,
+ status=RequestStatus.APPROVED,
+ )
+
+ result = data_deletion_request_property_removal.execute_in_process(
+ run_config={
+ "ops": {
+ "load_property_removal_request": {
+ "config": {"request_id": str(request.pk)},
+ },
+ },
+ },
+ resources={"cluster": cluster},
+ )
+ assert result.success
+
+ # Events preserved
+ assert cluster.any_host(partial(_count_events_by_name, PROP_TEAM_ID, "$pageview")).result() == 8
+
+ # $ip removed from properties
+ all_props = cluster.any_host(partial(_get_properties, PROP_TEAM_ID, "$pageview")).result()
+ for p in all_props:
+ assert "$ip" not in p, f"$ip should be removed, got {p}"
+ assert "keep" in p, f"keep should survive, got {p}"
+
+ # email removed from person_properties
+ all_person_props = cluster.any_host(partial(_get_person_properties, PROP_TEAM_ID, "$pageview")).result()
+ for pp in all_person_props:
+ assert "email" not in pp, f"email should be removed, got {pp}"
+ assert "keep_person" in pp, f"keep_person should survive, got {pp}"
+
+ request.refresh_from_db()
+ assert request.status == RequestStatus.COMPLETED
+
+
+def test_load_property_removal_request_loads_person_properties_only():
+ """load_property_removal_request succeeds when properties=[] and person_properties is non-empty."""
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=[],
+ person_properties=["email", "phone"],
+ start_time=datetime.now() - timedelta(days=7),
+ end_time=datetime.now(),
+ status=RequestStatus.APPROVED,
+ )
+
+ config = DataDeletionRequestConfig(request_id=str(request.pk))
+ result = load_property_removal_request(build_op_context(), config)
+
+ assert result.properties == []
+ assert result.person_properties == ["email", "phone"]
+ assert result.team_id == PROP_TEAM_ID
+ request.refresh_from_db()
+ assert request.status == RequestStatus.IN_PROGRESS
+
+
+def test_full_job_person_property_removal_ignores_out_of_range_events(cluster: ClickhouseCluster):
+ """Events outside the request time range must not have their person_properties modified."""
+ now = datetime.now()
+ start_time = now - timedelta(days=7)
+ end_time = now + timedelta(minutes=1)
+
+ person_props_with_key = json.dumps({"email": "[email protected]", "keep": "yes"})
+
+ in_range = [(PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i), person_props_with_key) for i in range(5)]
+ out_of_range = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(days=30), person_props_with_key) for _ in range(3)
+ ]
+
+ cluster.any_host(partial(_insert_events_with_person_properties, in_range + out_of_range)).result()
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=[],
+ person_properties=["email"],
+ start_time=start_time,
+ end_time=end_time,
+ status=RequestStatus.APPROVED,
+ )
+
+ result = data_deletion_request_property_removal.execute_in_process(
+ run_config={
+ "ops": {
+ "load_property_removal_request": {
+ "config": {"request_id": str(request.pk)},
+ },
+ },
+ },
+ resources={"cluster": cluster},
+ )
+ assert result.success
+
+ all_person_props = cluster.any_host(partial(_get_person_properties, PROP_TEAM_ID, "$pageview")).result()
+
+ emails_present = [p for p in all_person_props if "email" in p]
+ emails_absent = [p for p in all_person_props if "email" not in p]
+ # The 3 out-of-range events still have the email key
+ assert len(emails_present) == 3, f"expected 3 out-of-range events to still have email, got {len(emails_present)}"
+ # The 5 in-range events have had email removed
+ assert len(emails_absent) == 5, f"expected 5 in-range events with email removed, got {len(emails_absent)}"
+
+
+def test_full_job_person_property_removal_ignores_other_event_names(cluster: ClickhouseCluster):
+ """Events with a different event name than requested must not have their person_properties modified."""
+ now = datetime.now()
+ start_time = now - timedelta(days=7)
+ end_time = now + timedelta(minutes=1)
+
+ person_props_with_key = json.dumps({"email": "[email protected]", "keep": "yes"})
+
+ pageview_events = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i), person_props_with_key) for i in range(5)
+ ]
+ identify_events = [
+ (PROP_TEAM_ID, "$identify", uuid4(), now - timedelta(hours=i), person_props_with_key) for i in range(4)
+ ]
+
+ cluster.any_host(partial(_insert_events_with_person_properties, pageview_events + identify_events)).result()
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=[],
+ person_properties=["email"],
+ start_time=start_time,
+ end_time=end_time,
+ status=RequestStatus.APPROVED,
+ )
+
+ result = data_deletion_request_property_removal.execute_in_process(
+ run_config={
+ "ops": {
+ "load_property_removal_request": {
+ "config": {"request_id": str(request.pk)},
+ },
+ },
+ },
+ resources={"cluster": cluster},
+ )
+ assert result.success
+
+ pageview_props = cluster.any_host(partial(_get_person_properties, PROP_TEAM_ID, "$pageview")).result()
+ for pprops in pageview_props:
+ assert "email" not in pprops, f"$pageview should have email removed: {pprops}"
+
+ identify_props = cluster.any_host(partial(_get_person_properties, PROP_TEAM_ID, "$identify")).result()
+ for pprops in identify_props:
+ assert "email" in pprops, f"$identify email should be untouched: {pprops}"
+
+
+def _add_person_property_mat_columns(col_defs: list[tuple[str, str, str]], client: Client) -> None:
+ """Add materialized columns sourced from person_properties for testing.
+
+ Comment uses ``column_materializer::person_properties::<prop_name>`` so
+ ``_get_affected_mat_columns(..., table_column="person_properties")`` picks them up.
+ """
+ from django.conf import settings
+
+ db = settings.CLICKHOUSE_DATABASE
+ for col_name, prop_name, col_type in col_defs:
+ comment = f"column_materializer::person_properties::{prop_name}"
+ client.execute(
+ f"ALTER TABLE {db}.sharded_events "
+ f"ADD COLUMN IF NOT EXISTS `{col_name}` {col_type} "
+ f"DEFAULT JSONExtractRaw(person_properties, '{prop_name}')"
+ )
+ client.execute(f"ALTER TABLE {db}.events ADD COLUMN IF NOT EXISTS `{col_name}` {col_type} COMMENT '{comment}'")
+
+
+ "col_defs, person_properties_to_delete, expected_empty_cols",
+ [
+ pytest.param(
+ [("mat_pp_email", "email", "String")],
+ ["email"],
+ ["mat_pp_email"],
+ id="single_person_property",
+ ),
+ pytest.param(
+ [
+ ("mat_pp_phone", "phone", "String"),
+ ("mat_pp_city", "city", "Nullable(String)"),
+ ],
+ ["phone", "city"],
+ ["mat_pp_phone", "mat_pp_city"],
+ id="multiple_person_properties_mixed_nullable",
+ ),
+ ],
+)
+def test_full_job_person_property_removal_clears_mat_columns(
+ cluster: ClickhouseCluster,
+ col_defs: list[tuple[str, str, str]],
+ person_properties_to_delete: list[str],
+ expected_empty_cols: list[str],
+):
+ """Materialized columns sourced from person_properties are zeroed when those keys are deleted."""
+ cluster.any_host(partial(_add_person_property_mat_columns, col_defs)).result()
+
+ try:
+ now = datetime.now()
+ start_time = now - timedelta(days=7)
+ end_time = now + timedelta(minutes=1)
+
+ target_person_props = {prop: "secret" for _, prop, _ in col_defs}
+ target_person_props["keep"] = "yes"
+ pp_with_target = json.dumps(target_person_props)
+ pp_without_target = json.dumps({"keep": "yes", "other": "value"})
+
+ target_events = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i), pp_with_target) for i in range(20)
+ ]
+ control_events = [
+ (PROP_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i), pp_without_target) for i in range(10)
+ ]
+
+ cluster.any_host(partial(_insert_events_with_person_properties, target_events + control_events)).result()
+
+ # Precondition: mat columns have values populated from person_properties
+ for col_name in expected_empty_cols:
+ mat_values = cluster.any_host(partial(_get_mat_column_values, PROP_TEAM_ID, "$pageview", col_name)).result()
+ assert any(v and "secret" in v for v in mat_values), (
+ f"expected 'secret' in {col_name} before deletion, got {set(mat_values)}"
+ )
+
+ request = DataDeletionRequest.objects.create(
+ team_id=PROP_TEAM_ID,
+ request_type=RequestType.PROPERTY_REMOVAL,
+ events=["$pageview"],
+ properties=[],
+ person_properties=person_properties_to_delete,
+ start_time=start_time,
+ end_time=end_time,
+ status=RequestStatus.APPROVED,
+ )
+
+ result = data_deletion_request_property_removal.execute_in_process(
+ run_config={
+ "ops": {
+ "load_property_removal_request": {
+ "config": {"request_id": str(request.pk)},
+ },
+ },
+ },
+ resources={"cluster": cluster},
+ )
+ assert result.success
+
+ # Events still exist — only person_properties mutated
+ assert cluster.any_host(partial(_count_events_by_name, PROP_TEAM_ID, "$pageview")).result() == 30
+
+ # Target keys removed from person_properties JSON
+ all_pp = cluster.any_host(partial(_get_person_properties, PROP_TEAM_ID, "$pageview")).result()
+ for pp in all_pp:
+ for prop in person_properties_to_delete:
+ assert prop not in pp, f"{prop} should be removed from person_properties, got {pp}"
+ assert "keep" in pp, f"keep should be preserved, got {pp}"
+
+ # Materialized columns zeroed out
+ for col_name in expected_empty_cols:
+ mat_values = cluster.any_host(partial(_get_mat_column_values, PROP_TEAM_ID, "$pageview", col_name)).result()
+ non_empty = [v for v in mat_values if v and v not in ("", None)]
+ assert not non_empty, f"{col_name} should be empty after deletion, got non-empty: {set(non_empty)}"
+
+ request.refresh_from_db()
+ assert request.status == RequestStatus.COMPLETED
+ finally:
+ cluster.any_host(partial(_drop_default_mat_columns, col_defs)).result()
+
+
@pytest.mark.django_db
def test_full_job_property_removal(cluster: ClickhouseCluster):
now = datetime.now()