: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(data-deletion): drop properties per shard, add hogql predicate support to property drop (#57737)
Paweł Szczur5221e618a124
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex acf47c28662f..d3a86b0f4e6b 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -1,4 +1,5 @@import time+from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom datetime import datetime@@ -9,12 +10,7 @@ import pydanticfrom clickhouse_driver import Clientfrom posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE-from posthog.clickhouse.cluster import (- AlterTableMutationRunner,- ClickhouseCluster,- LightweightDeleteMutationRunner,- Query,-)+from posthog.clickhouse.cluster import AlterTableMutationRunner, ClickhouseCluster, LightweightDeleteMutationRunnerfrom posthog.dags.common import JobOwnersfrom posthog.dags.deletes import deletes_jobfrom posthog.models.data_deletion_request import (@@ -54,6 +50,9 @@ class DeletionRequestContext:execution_mode: str = ExecutionMode.IMMEDIATE.valuedelete_all_events: bool = Falsehogql_predicate: str = ""+ # Set by process_property_removal_per_shard; cleaned re-inserts get this exact value stamped+ # onto inserted_at so the same op's delete pass can exclude them via inserted_at < marker.+ inserted_at_marker: datetime | None = None@dataclass@@ -145,7 +144,93 @@ def _event_removal_where(obj) -> tuple[str, dict]:return " ".join(p for p in parts if p), params-def _get_affected_mat_columns(client: Client, table: str, properties: list[str]) -> list[tuple[str, bool]]:+def _mat_col_presence_clauses(mat_cols: list[tuple[str, bool]]) -> list[str]:+ """Per-column "value is present" checks for DEFAULT-materialized property columns.++ Uses ``<col> != ''`` for both nullable and non-nullable variants:++ - The DEFAULT expression (``JSONExtractRaw(properties, prop)``) returns+ ``''`` for missing keys, regardless of whether the column type is+ Nullable. So rows that never carried the property store ``''``, not+ NULL, and ``IS NOT NULL`` would over-match them and pull control rows+ into the copy/delete set.+ - For nullable columns, ``NULL != ''`` evaluates to NULL (treated as+ false in WHERE), so rows we reset to NULL during cleaning are+ correctly skipped by the delete pass.+ - The mutation reset still differs by nullability (NULL vs ``''``), which+ is why ``is_nullable`` is preserved on the input — only the presence+ check is uniform.+ """+ return [f"`{name}` != ''" for name, _ in mat_cols]+++def _property_removal_where(+ ctx: DeletionRequestContext,+ 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).++ Honors the optional ``hogql_predicate`` on the request the same way+ ``_event_removal_where`` does, so an operator can scope a property removal+ to (e.g.) a specific ``$current_url`` or person property. The compiled+ HogQL fragment uses unqualified column references and is safe to splice+ into queries against either ``events`` or ``sharded_events``. The caller+ must precompile the predicate via ``compile_hogql_predicate`` in the main+ thread (it touches the Django ORM) and pass the result via+ ``hogql_compiled`` — calling it from a per-shard worker thread can fail+ when the worker holds a different DB connection from the test/request+ transaction.++ The delete pass additionally passes ``inserted_at_max``: cleaned re-inserts+ are stamped with that exact value, so ``inserted_at < marker`` skips them.+ 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)]+ if mat_cols:+ presence_clauses.extend(_mat_col_presence_clauses(mat_cols))+ presence = f"({' OR '.join(presence_clauses)})" if len(presence_clauses) > 1 else presence_clauses[0]++ parts = [+ "team_id = %(team_id)s",+ "AND timestamp >= %(start_time)s",+ "AND timestamp < %(end_time)s",+ "AND event IN %(events)s",+ f"AND {presence}",+ ]+ params = _base_params(ctx)+ if hogql_compiled is not None:+ hogql_sql, hogql_values = hogql_compiled+ if hogql_sql:+ parts.append(f"AND ({hogql_sql})")+ params.update(hogql_values)+ if inserted_at_max is not None:+ # Cast explicitly to DateTime64(6) — without it the parameter is parsed as DateTime+ # (second precision), which truncates microseconds and causes the comparison to skip+ # originals whose inserted_at falls in the same second as the marker. The cleaned+ # re-inserts (which stamp inserted_at = marker via the same parameter) suffer the+ # same truncation in the mutation, so both sides must use the cast.+ parts.append("AND (inserted_at IS NULL OR inserted_at < toDateTime64(%(inserted_at_max)s, 6, 'UTC'))")+ params["inserted_at_max"] = inserted_at_max+ return " ".join(parts), params+++QueryLogger = Callable[[str, str], None]+++def _get_affected_mat_columns(+ client: Client,+ table: str,+ properties: list[str],+ log: QueryLogger | None = None,+) -> list[tuple[str, bool]]:"""Query a specific shard for DEFAULT materialized columns matching deleted properties.Returns ``(column_name, is_nullable)`` for DEFAULT columns whose comment follows@@ -155,8 +240,7 @@ def _get_affected_mat_columns(client: Client, table: str, properties: list[str])are excluded — ClickHouse recomputes them automatically at insert time."""database = django_settings.CLICKHOUSE_DATABASE- rows = client.execute(- """+ sql = """SELECT name, comment, type LIKE 'Nullable(%%)'FROM system.columnsWHERE database = %(database)s@@ -164,9 +248,10 @@ def _get_affected_mat_columns(client: Client, table: str, properties: list[str])AND default_kind = 'DEFAULT'AND comment LIKE '%%column_materializer::%%'AND comment NOT LIKE '%%column_materializer::elements_chain::%%'- """,- {"database": database, "table": table},- )+ """+ if log:+ log("discover-mat-cols", sql)+ rows = client.execute(sql, {"database": database, "table": table})target_props = set(properties)result: list[tuple[str, bool]] = []@@ -177,27 +262,35 @@ def _get_affected_mat_columns(client: Client, table: str, properties: list[str])return result-def _create_local_staging_table(client: Client, source_table: str, staging_table: str) -> None:+def _create_local_staging_table(+ client: Client,+ source_table: str,+ staging_table: str,+ log: QueryLogger | None = None,+) -> None:"""Create a non-replicated local copy of the source table schema."""database = django_settings.CLICKHOUSE_DATABASE- rows = client.execute(- "SELECT count() FROM system.tables WHERE database = %(db)s AND name = %(table)s",- {"db": database, "table": staging_table},- )+ exists_sql = "SELECT count() FROM system.tables WHERE database = %(db)s AND name = %(table)s"+ if log:+ log("temp-exists-check", exists_sql)+ rows = client.execute(exists_sql, {"db": database, "table": staging_table})if rows[0][0] > 0:return- rows = client.execute(- "SELECT engine_full FROM system.tables WHERE database = %(db)s AND name = %(table)s",- {"db": database, "table": source_table},- )+ engine_sql = "SELECT engine_full FROM system.tables WHERE database = %(db)s AND name = %(table)s"+ if log:+ log("source-engine-lookup", engine_sql)+ rows = client.execute(engine_sql, {"db": database, "table": source_table})if not rows:raise dagster.Failure(description=f"Source table {database}.{source_table} not found")- client.execute(+ create_sql = (f"CREATE TABLE IF NOT EXISTS {database}.{staging_table} AS {database}.{source_table} ENGINE = MergeTree()")+ if log:+ log("create-temp", create_sql)+ client.execute(create_sql)# ---------------------------------------------------------------------------@@ -403,6 +496,7 @@ def load_property_removal_request("properties": dagster.MetadataValue.text(", ".join(request.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 ""),})@@ -414,90 +508,155 @@ def load_property_removal_request(end_time=request.end_time,events=request.events,properties=request.properties,+ hogql_predicate=request.hogql_predicate or "",)@dagster.op(tags=OWNER_TAG, retry_policy=dagster.RetryPolicy(max_retries=0))-def prepare_and_insert_modified_events(+def process_property_removal_per_shard(context: dagster.OpExecutionContext,cluster: dagster.ResourceParam[ClickhouseCluster],deletion_request: DeletionRequestContext,) -> DeletionRequestContext:- """Create temp table, copy events, drop properties, verify, and insert back — all on the same node per shard.-- The temp table is local MergeTree (non-replicated), so every step that- touches it must execute on the same ClickHouse node. This op runs all- temp-table work within a single callable per shard to guarantee that.-- After this op, sharded_events temporarily has both the original events- (with the target properties) and the modified events (without them).- The next op deletes the originals via a lightweight delete.+ """Run the full property-removal cycle one shard at a time.++ Per shard, on a single host (the temp table is local non-replicated MergeTree):++ 1. Discover affected DEFAULT materialized columns.+ 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``.+ 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+ as the copy, plus ``inserted_at IS NULL OR inserted_at < marker`` so the+ cleaned re-inserts (stamped with that exact marker) are skipped.+ 8. Drop the temp table.++ 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."""+ from django.utils import timezone+source = EVENTS_DATA_TABLE()temp = _temp_table_name(deletion_request.team_id, deletion_request.request_id)db = django_settings.CLICKHOUSE_DATABASE- prop_filter = _property_filter_clause(deletion_request.properties)- params = _base_params(deletion_request)- keys = deletion_request.properties+ properties = deletion_request.properties+ marker = timezone.now()+ deletion_request.inserted_at_marker = marker+ # Format the marker as a string with microseconds — clickhouse-driver serializes Python+ # datetime values with second precision, which causes the cleaned re-inserts to be stamped+ # with a truncated inserted_at and the originals-delete predicate to mismatch by sub-second+ # offsets. Passing as ISO string and casting in SQL preserves the full precision.+ marker_str = marker.strftime("%Y-%m-%d %H:%M:%S.%f")+ # HogQL compilation reaches into the Django ORM (Team lookup); compile once on the main+ # thread before dispatching per-shard work, otherwise the worker thread's DB connection+ # may not see the request/test transaction.+ hogql_compiled = compile_hogql_predicate(deletion_request)++ def _flatten_sql(sql: str) -> str:+ return " ".join(sql.split())def process_shard(client: Client) -> dict:- # 1. Create temp table- _create_local_staging_table(client, source_table=source, staging_table=temp)-- # 2. Copy matching events (truncate first for idempotency)- client.execute(f"TRUNCATE TABLE IF EXISTS {db}.{temp}")- client.execute(- f"""- INSERT INTO {db}.{temp}- SELECT * FROM {db}.{source}- WHERE team_id = %(team_id)s- AND timestamp >= %(start_time)s- AND timestamp < %(end_time)s- AND event IN %(events)s- AND {prop_filter}- """,- params,+ def log_query(label: str, sql: str) -> None:+ context.log.info(f"[{label}] {_flatten_sql(sql)}")++ def execute(label: str, sql: str, params=None, settings=None):+ 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]}")++ _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,+ hogql_compiled=hogql_compiled,+ )+ execute("truncate-temp", f"TRUNCATE TABLE IF EXISTS {db}.{temp}")+ execute(+ "copy-into-temp",+ f"INSERT INTO {db}.{temp} SELECT * FROM {db}.{source} WHERE {copy_predicate}",+ copy_params,settings={"max_execution_time": 1800},)- copied = client.execute(f"SELECT count() FROM {db}.{temp}")[0][0]-- # 3. Mutate properties and reset affected DEFAULT materialized columns.- # Query the distributed table (events) for column comments — sharded_events- # may not carry them. Queried per-shard to handle schema drift.- affected_mat_cols = _get_affected_mat_columns(client, "events", keys)+ copied = execute("count-temp", f"SELECT count() FROM {db}.{temp}")[0][0]update_parts = ["properties = JSONDropKeys(%(keys)s)(properties)",- "inserted_at = now()",+ # 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:default = "NULL" if is_nullable else "''"update_parts.append(f"`{col_name}` = {default}")- runner = AlterTableMutationRunner(+ clean_runner = AlterTableMutationRunner(table=temp,commands={f"UPDATE {', '.join(update_parts)} WHERE 1=1"},- parameters={"keys": keys},+ parameters={"keys": properties, "inserted_at_marker": marker_str},)- waiter = runner(client)- waiter.wait(client)-- # 4. Verify no target properties remain- verify_params = _property_filter_params(keys)- remaining = client.execute(- f"SELECT count() FROM {db}.{temp} WHERE {prop_filter}",+ context.log.info(+ f"[clean-temp-mutation] {_flatten_sql(clean_runner.get_statement(clean_runner.get_all_commands()))}"+ )+ clean_waiter = clean_runner(client)+ clean_waiter.wait(client)++ verify_clauses = [_property_filter_clause(properties), *_mat_col_presence_clauses(affected_mat_cols)]+ verify_predicate = f"({' OR '.join(verify_clauses)})" if len(verify_clauses) > 1 else verify_clauses[0]+ verify_params = _property_filter_params(properties)+ remaining = execute(+ "verify-temp-clean",+ f"SELECT count() FROM {db}.{temp} WHERE {verify_predicate}",verify_params,)[0][0]if remaining > 0:- raise Exception(f"{remaining} events still have target properties after mutation")+ raise Exception(f"{remaining} events still carry target properties after mutation")- # 5. Insert modified events back into sharded_events- client.execute(+ execute(+ "insert-cleaned-back",f"INSERT INTO {db}.{source} SELECT * FROM {db}.{temp}",settings={"max_execution_time": 1800},)- return {"copied": copied, "remaining_after_verify": remaining}+ # Submit the originals delete. Returns a waiter so the outer loop can block on+ # all replicas of this shard before moving on to the next shard.+ delete_predicate, delete_params = _property_removal_where(+ deletion_request,+ mat_cols=affected_mat_cols,+ inserted_at_max=marker_str,+ hogql_compiled=hogql_compiled,+ )+ delete_runner = LightweightDeleteMutationRunner(+ table=source,+ predicate=delete_predicate,+ parameters=delete_params,+ settings={"lightweight_deletes_sync": 2, "mutations_sync": 2},+ )+ context.log.info(+ f"[delete-originals] {_flatten_sql(delete_runner.get_statement(delete_runner.get_all_commands()))}"+ )+ delete_waiter = delete_runner(client)+ # Wait locally so we can be sure the delete is fully applied before this op moves on+ # to the next shard or returns. ``mutations_sync = 2`` makes the runner block on all+ # replicas of the originating shard; the explicit ``wait`` is a defensive backstop.+ delete_waiter.wait(client)++ # Drop the temp table on the SAME host that created it. The temp table is local+ # non-replicated MergeTree; a separate ``map_any_host_in_shards`` call from the outer+ # loop can resolve to a different replica (the schema-qualified name does not+ # influence host selection), which would silently DROP IF EXISTS on the wrong host+ # and leave the staging rows behind on the originating one.+ execute("drop-temp", f"DROP TABLE IF EXISTS {db}.{temp}")++ return {"copied": copied}shards = sorted(cluster.shards)for idx, shard_num in enumerate(shards, 1):@@ -508,62 +667,10 @@ def prepare_and_insert_modified_events(_host, stats = next(iter(result.items()))elapsed = time.monotonic() - shard_start- context.log.info(f"Shard {shard_num}: copied {stats['copied']} events, insert complete in {elapsed:.1f}s")-- return deletion_request--[email protected](tags=OWNER_TAG)-def delete_original_events(- context: dagster.OpExecutionContext,- cluster: dagster.ResourceParam[ClickhouseCluster],- deletion_request: DeletionRequestContext,-) -> DeletionRequestContext:- """Delete the original (unmodified) events that still have the target properties."""- table = EVENTS_DATA_TABLE()- prop_filter = _property_filter_clause(deletion_request.properties)-- for shard_num in sorted(cluster.shards):- context.log.info(f"Deleting originals on shard {shard_num}")- shard_start = time.monotonic()-- runner = LightweightDeleteMutationRunner(- table=table,- predicate=(- f"team_id = %(team_id)s "- f"AND timestamp >= %(start_time)s "- f"AND timestamp < %(end_time)s "- f"AND event IN %(events)s "- f"AND {prop_filter}"- ),- parameters=_base_params(deletion_request),- settings={"lightweight_deletes_sync": 0},+ context.log.info(+ f"Shard {shard_num}: copied {stats['copied']} events, originals deleted, temp dropped in {elapsed:.1f}s")- shard_result = cluster.map_any_host_in_shards({shard_num: runner}).result()- _host, waiter = next(iter(shard_result.items()))- cluster.map_all_hosts_in_shard(shard_num, waiter.wait).result()-- elapsed = time.monotonic() - shard_start- context.log.info(f"Shard {shard_num}: delete complete in {elapsed:.1f}s")-- return deletion_request--[email protected](tags=OWNER_TAG)-def cleanup_temp_tables(- context: dagster.OpExecutionContext,- cluster: dagster.ResourceParam[ClickhouseCluster],- deletion_request: DeletionRequestContext,-) -> DeletionRequestContext:- """Drop the temp tables on all shards."""- temp = _temp_table_name(deletion_request.team_id, deletion_request.request_id)- db = django_settings.CLICKHOUSE_DATABASE-- for shard_num in sorted(cluster.shards):- cluster.map_any_host_in_shards({shard_num: Query(f"DROP TABLE IF EXISTS {db}.{temp}")}).result()- context.log.info(f"Shard {shard_num}: temp table dropped")-return deletion_request@@ -843,7 +950,11 @@ def mark_deletion_failed(context: dagster.HookContext) -> None:context.log.error(f"Deletion request {request_id} marked as failed.")- # Clean up temp tables for property removal jobs+ # Clean up temp tables for property removal jobs. The temp table is local+ # non-replicated MergeTree, so it only exists on whichever host originally ran+ # ``process_shard`` for that shard. We don't know which host that was at this+ # point, so broadcast the DROP to every host in every shard — DROP IF EXISTS+ # is a safe no-op on hosts that don't have it.if ops_config.get("load_property_removal_request"):try:from posthog.clickhouse.cluster import Query, get_cluster@@ -853,7 +964,8 @@ def mark_deletion_failed(context: dagster.HookContext) -> None:temp = _temp_table_name(db_request["team_id"], request_id)db = django_settings.CLICKHOUSE_DATABASEcluster = get_cluster()- cluster.map_one_host_per_shard(Query(f"DROP TABLE IF EXISTS {db}.{temp}")).result()+ drop_sql = f"DROP TABLE IF EXISTS {db}.{temp}"+ cluster.map_all_hosts(Query(drop_sql)).result()context.log.info(f"Cleaned up temp table {temp}")except Exception as e:context.log.warning(f"Failed to clean up temp table: {e}")@@ -879,11 +991,10 @@ def data_deletion_request_event_removal():@dagster.job(tags=OWNER_TAG, hooks={mark_deletion_failed})def data_deletion_request_property_removal():- """Execute an approved property removal request: copy events, drop properties, swap back."""+ """Execute an approved property removal request: per shard, copy events, drop properties,+ re-insert, delete originals, drop temp."""request = load_property_removal_request()- request = prepare_and_insert_modified_events(request)- request = delete_original_events(request)- request = cleanup_temp_tables(request)+ request = process_property_removal_per_shard(request)finalize_deletion_request(request)diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex 6f620488186e..e77fff35aa10 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -721,6 +721,61 @@ def test_full_job_property_removal_single_property(cluster: ClickhouseCluster):assert request.status == RequestStatus.COMPLETED+def test_full_job_property_removal_applies_hogql_predicate(cluster: ClickhouseCluster):+ """A property removal scoped by hogql_predicate must clean only matching events."""+ from posthog.models.organization import Organization+ from posthog.models.team import Team++ org = Organization.objects.create(name="test-org-prop-hogql")+ team = Team.objects.create(organization=org, name="test-team-prop-hogql")++ now = datetime.now()+ start_time = now - timedelta(days=7)+ end_time = now + timedelta(minutes=1)++ chrome_props = json.dumps({"secret": "value", "$browser": "Chrome"})+ firefox_props = json.dumps({"secret": "value", "$browser": "Firefox"})+ chrome_events = [(team.id, "$pageview", uuid4(), now - timedelta(hours=i), chrome_props) for i in range(10)]+ firefox_events = [(team.id, "$pageview", uuid4(), now - timedelta(hours=i), firefox_props) for i in range(5)]++ cluster.any_host(partial(_insert_events_with_properties, chrome_events + firefox_events)).result()++ request = DataDeletionRequest.objects.create(+ team_id=team.id,+ request_type=RequestType.PROPERTY_REMOVAL,+ events=["$pageview"],+ properties=["secret"],+ start_time=start_time,+ end_time=end_time,+ hogql_predicate="properties.$browser = 'Chrome'",+ 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++ # Chrome events: secret cleaned, $browser preserved+ all_props = cluster.any_host(partial(_get_properties, team.id, "$pageview")).result()+ chrome = [p for p in all_props if p.get("$browser") == "Chrome"]+ firefox = [p for p in all_props if p.get("$browser") == "Firefox"]+ assert len(chrome) == 10, f"expected 10 Chrome rows, got {len(chrome)}"+ assert len(firefox) == 5, f"expected 5 Firefox rows untouched, got {len(firefox)}"+ for props in chrome:+ assert "secret" not in props, f"Chrome event still has secret: {props}"+ for props in firefox:+ assert props.get("secret") == "value", f"Firefox event must keep secret: {props}"++def _assert_subfield_removed(props: dict, path: str) -> None:"""Assert a dotted subfield path was removed from props."""parts = path.split(".")