: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): run immediate event deletes as one dagster step per shard (#109048)
Paweł Szczur47f1318d09ff
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 44efa60ebfdf..138c219dbf73 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -15,7 +15,7 @@ It is a property of every table that stores rows attributable to a person.| Event deletion (async) | `deletes_job` → `delete_events` | `team_id`, `uuid` || Queued uuid drain | `deletes_job` → `delete_events` | `team_id`, `uuid`, `inserted_at` || Person removal request | `delete_person_events_op` | `team_id`, `person_id`, `timestamp` |-| Event removal request | `execute_event_deletion` | `team_id`, `timestamp`, `event`, + HogQL |+| Event removal request | `delete_event_removal_shard` | `team_id`, `timestamp`, `event`, + HogQL || Property removal request | `process_property_removal_shard` | `properties`, `person_properties`, + HogQL |The first five use only columns every target declares, so they apply unchanged to any registered table.@@ -59,7 +59,7 @@ The handle in hand is probed first, so a deployment whose tables are all on oneSweeps that iterate placements dispatch each target over `placement.cluster.shards`:- `delete_person_events_op`-- `execute_event_deletion`, immediate mode+- `get_event_removal_shards`, which fans out one `delete_event_removal_shard` op per table and shard, so a failed delete re-executes on its own- `deletes_job` → `delete_events`, which also has to put its dictionaries on the second cluster; see belowThe rest are bound to a single handle and refuse rather than skip when a target has moved off it (`dispatchable_here`, `UnreachableTargetError`):@@ -221,7 +221,7 @@ Doing nothing means the first affected GDPR request becomes an escalation.### Immediate event removal skips `flag_evaluations`-`_run_immediate_event_deletion` leaves `flag_evaluations` out of its targets, so an immediate request neither sweeps the table nor checks it for matching rows.+`get_event_removal_shards` leaves `flag_evaluations` out of its targets, so an immediate request neither sweeps the table nor checks it for matching rows.The rows age out with the table's TTL, which in practice is up to about 120 days (see above).Deferred event removal still queues the table's uuids, and `deletes_job` removes them.The skip exists because of the HogQL gap below: before it, the gate refused every immediate request with a predicate whose team had matching `$feature_flag_called` rows.diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex 5dc8716c89dc..e99e5f27d72b 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -1,5 +1,5 @@import time-from collections.abc import Callable, Collection+from collections.abc import Callable, Collection, Iteratorfrom dataclasses import dataclass, field, replacefrom datetime import UTC, datetime, timedeltafrom functools import partial@@ -32,6 +32,7 @@ from posthog.clickhouse.workload import Workloadfrom posthog.dags.common import JobOwnersfrom posthog.dags.deletes import deletes_jobfrom posthog.data_deletion import compile_event_uuid_query+from posthog.dataclasses import frozenfrom posthog.models.data_deletion_request import (AUTO_APPROVE_INTERVAL_MINUTES,DataDeletionRequest,@@ -674,47 +675,30 @@ def _event_removal_placements(_IMMEDIATE_SKIP_TARGETS = (FLAG_EVALUATIONS,)-def _run_immediate_event_deletion(- context: dagster.OpExecutionContext,- cluster: ClickhouseCluster,- deletion_request: DeletionRequestContext,-) -> None:- placements = _event_removal_placements(cluster, deletion_request, skip_targets=_IMMEDIATE_SKIP_TARGETS)- targets = [p.target for p in placements]+@frozen+class EventRemovalShard:+ """One immediate delete: a table, and a shard number on the cluster that carries that table."""- context.log.info(f"Starting immediate event deletion on tables {[t.data_table for t in targets]}")+ data_table: str+ shard_num: int- swept_shards = 0- for placement in placements:- target = placement.target- # The HogQL fragment compiles differently per schema: materialized-column/JSONExtract- # reads on the legacy table, JSON subcolumn reads on the native-JSON table.- predicate, parameters = event_removal_where(- deletion_request, use_new_events_schema=target.uses_new_events_schema- )- # placement.cluster, not the job's handle: shard numbers are per cluster.- shards = sorted(placement.cluster.shards)- swept_shards += len(shards)+def _placement_for_table(cluster: ClickhouseCluster, data_table: str) -> TargetPlacement:+ target = next(t for t in PERSONAL_DATA_TARGETS if t.data_table == data_table)+ placements = resolve_placements(cluster, [target])+ if not placements:+ raise dagster.Failure(description=f"{data_table} is not present on any reachable cluster")+ return placements[0]- for idx, shard_num in enumerate(shards, 1):- context.log.info(f"Processing {target.data_table} shard {shard_num} ({idx}/{len(shards)})")- shard_start = time.monotonic()-- runner = LightweightDeleteMutationRunner(- table=target.data_table,- predicate=predicate,- parameters=parameters,- settings={"lightweight_deletes_sync": 0},- )-- shard_result = placement.cluster.map_any_host_in_shards({shard_num: runner}).result()- _host, mutation_waiter = next(iter(shard_result.items()))- placement.cluster.map_all_hosts_in_shard(shard_num, mutation_waiter.wait).result()-- elapsed = time.monotonic() - shard_start- context.log.info(f"{target.data_table} shard {shard_num} complete in {elapsed:.1f}s")+def _verify_immediate_event_deletion(+ context: dagster.OpExecutionContext,+ cluster: ClickhouseCluster,+ deletion_request: DeletionRequestContext,+ deleted_shards: list[EventRemovalShard],+) -> None:+ tables = list(dict.fromkeys(shard.data_table for shard in deleted_shards))+ targets = [next(t for t in PERSONAL_DATA_TARGETS if t.data_table == table) for table in tables]_verify_swept(cluster,targets,@@ -729,8 +713,8 @@ def _run_immediate_event_deletion(context.add_output_metadata({"mode": dagster.MetadataValue.text("immediate"),- "shards_processed": dagster.MetadataValue.int(swept_shards),- "swept_tables": dagster.MetadataValue.text(", ".join(t.data_table for t in targets)),+ "shards_processed": dagster.MetadataValue.int(len(deleted_shards)),+ "swept_tables": dagster.MetadataValue.text(", ".join(tables)),})@@ -800,17 +784,78 @@ def _queue_events_for_deferred_deletion()[email protected](out=dagster.DynamicOut(EventRemovalShard), tags=OWNER_TAG)+def get_event_removal_shards(+ context: dagster.OpExecutionContext,+ cluster: dagster.ResourceParam[ClickhouseCluster],+ deletion_request: DeletionRequestContext,+) -> Iterator[dagster.DynamicOutput[EventRemovalShard]]:+ """Fan out one delete_event_removal_shard op per table and shard; a deferred request fans out nothing.++ The mapping key makes each delete re-executable on its own from the Dagster UI.+ """+ if deletion_request.execution_mode == ExecutionMode.DEFERRED.value:+ return++ placements = _event_removal_placements(cluster, deletion_request, skip_targets=_IMMEDIATE_SKIP_TARGETS)+ # placement.cluster, not the job's handle: shard numbers are per cluster.+ shards = [+ EventRemovalShard(data_table=placement.target.data_table, shard_num=shard_num)+ for placement in placements+ for shard_num in sorted(placement.cluster.shards)+ ]+ context.log.info(f"Fanning out event removal {deletion_request.request_id} to {len(shards)} shard op(s)")+ for shard in shards:+ yield dagster.DynamicOutput(shard, mapping_key=f"{shard.data_table}_shard_{shard.shard_num}")++[email protected](tags=OWNER_TAG, retry_policy=dagster.RetryPolicy(max_retries=0))+def delete_event_removal_shard(+ context: dagster.OpExecutionContext,+ cluster: dagster.ResourceParam[ClickhouseCluster],+ shard: EventRemovalShard,+ deletion_request: DeletionRequestContext,+) -> EventRemovalShard:+ """Run the lightweight delete for one table on one shard, and wait until it finishes.++ A re-execution waits on the matching mutation in system.mutations if ClickHouse still lists it,+ and enqueues it again otherwise.+ """+ placement = _placement_for_table(cluster, shard.data_table)+ # The HogQL fragment compiles differently per schema: materialized-column/JSONExtract+ # reads on the legacy table, JSON subcolumn reads on the native-JSON table.+ predicate, parameters = event_removal_where(+ deletion_request, use_new_events_schema=placement.target.uses_new_events_schema+ )+ runner = LightweightDeleteMutationRunner(+ table=shard.data_table,+ predicate=predicate,+ parameters=parameters,+ settings={"lightweight_deletes_sync": 0},+ )++ shard_start = time.monotonic()+ shard_result = placement.cluster.map_any_host_in_shards({shard.shard_num: runner}).result()+ _host, mutation_waiter = next(iter(shard_result.items()))+ placement.cluster.map_all_hosts_in_shard(shard.shard_num, mutation_waiter.wait).result()++ elapsed = time.monotonic() - shard_start+ context.log.info(f"{shard.data_table} shard {shard.shard_num} complete in {elapsed:.1f}s")+ return shard++@dagster.op(tags=OWNER_TAG)-def execute_event_deletion(+def complete_event_deletion(context: dagster.OpExecutionContext,cluster: dagster.ResourceParam[ClickhouseCluster],deletion_request: DeletionRequestContext,+ deleted_shards: list[EventRemovalShard],) -> DeletionRequestContext:- """Dispatch event deletion based on execution_mode."""+ """Verify an immediate request after every shard op (a Dagster fan-in), or queue a deferred one."""if deletion_request.execution_mode == ExecutionMode.DEFERRED.value:_queue_events_for_deferred_deletion(context, cluster, deletion_request)else:- _run_immediate_event_deletion(context, cluster, deletion_request)+ _verify_immediate_event_deletion(context, cluster, deletion_request, deleted_shards)return deletion_request@@ -1690,12 +1735,17 @@ def mark_deletion_failed(context: dagster.HookContext) -> None:def data_deletion_request_event_removal():"""Execute an approved event deletion request.- Immediate mode runs a lightweight delete mutation shard by shard.- Deferred mode queues event UUIDs into adhoc_events_deletion for the+ Immediate mode: load → dynamic fan-out (one delete op per table and shard, parallel under the+ run executor) → verify (fan-in) → finalize. A failed shard is re-executed on its own with the+ Dagster UI's "Re-execute from failure"; finalize accepts the FAILED status the failure hook set,+ so the re-executed run completes the request.+ Deferred mode fans out nothing and queues event UUIDs into adhoc_events_deletion for thescheduled deletes_job to drain later."""request = load_deletion_request()- result = execute_event_deletion(request)+ shards = get_event_removal_shards(request)+ deleted = shards.map(lambda shard: delete_event_removal_shard(shard, request))+ result = complete_event_deletion(request, deleted.collect())finalize_deletion_request(result)diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex 4793bbd32158..ffe5d248a47b 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -23,6 +23,7 @@ from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutatfrom posthog.dags.data_deletion_requests import (DataDeletionRequestConfig,DeletionRequestContext,+ EventRemovalShard,HogQLEventDeletionExecutor,HogQLEventRemovalContext,PersonRemovalContext,@@ -30,16 +31,18 @@ from posthog.dags.data_deletion_requests import (_refuse_property_removal_unsweepable,auto_approve_deletion_requests_job,auto_approve_deletion_requests_schedule,+ complete_event_deletion,data_deletion_request_event_removal,data_deletion_request_hogql_event_removal,data_deletion_request_person_removal,data_deletion_request_pickup_sensor,data_deletion_request_property_removal,+ delete_event_removal_shard,delete_person_events_op,delete_person_profiles_op,delete_person_recordings_op,- execute_event_deletion,finalize_deletion_request,+ get_event_removal_shards,get_property_removal_shards,load_deletion_request,load_hogql_event_removal_request,@@ -65,6 +68,7 @@ from posthog.models.deletion_targets import (placement_for,)from posthog.models.event.sql import (+ EVENTS_DATA_TABLE,EVENTS_PROPERTIES_JSON_TYPE,PERSON_PROPERTIES_JSON_TYPE,json_property_presence_expr,@@ -432,6 +436,14 @@ def test_finalize_deletion_request_transitions_status(execution_mode, start_statassert request.status == expected_status+def _run_event_deletion(cluster: ClickhouseCluster, deletion_ctx: DeletionRequestContext) -> None:+ fan_out = get_event_removal_shards(build_op_context(), cluster, deletion_ctx)+ deleted = [+ delete_event_removal_shard(build_op_context(), cluster, output.value, deletion_ctx) for output in fan_out+ ]+ complete_event_deletion(build_op_context(), cluster, deletion_ctx, deleted)++@pytest.mark.django_dbdef test_execute_event_deletion_deletes_matching_events(cluster: ClickhouseCluster):now = datetime.now()@@ -455,8 +467,7 @@ def test_execute_event_deletion_deletes_matching_events(cluster: ClickhouseClustend_time=end_time,events=["$pageview"],)- context = build_op_context()- execute_event_deletion(context, cluster, deletion_ctx)+ _run_event_deletion(cluster, deletion_ctx)# Matching events should be deletedassert cluster.any_host(partial(_count_events_by_name, TEAM_ID, "$pageview")).result() == 10 # only outside_range@@ -492,8 +503,7 @@ def test_execute_event_deletion_delete_all_events_drops_every_event_for_team(cluevents=[],delete_all_events=True,)- context = build_op_context()- execute_event_deletion(context, cluster, deletion_ctx)+ _run_event_deletion(cluster, deletion_ctx)# Every event for the team within the time range is gone (only outside_range survives).assert cluster.any_host(partial(_count_events, TEAM_ID)).result() == 5@@ -531,8 +541,7 @@ def test_execute_event_deletion_applies_hogql_predicate(cluster: ClickhouseClustevents=["$pageview"],hogql_predicate="properties.$browser = 'Chrome'",)- context = build_op_context()- execute_event_deletion(context, cluster, deletion_ctx)+ _run_event_deletion(cluster, deletion_ctx)# Only the Chrome events should be deleted; Firefox events remain.assert cluster.any_host(partial(_count_events_by_name, team.id, "$pageview")).result() == 5@@ -557,8 +566,7 @@ def test_execute_event_deletion_multiple_event_names(cluster: ClickhouseCluster)end_time=end_time,events=["$pageview", "$screen"],)- context = build_op_context()- execute_event_deletion(context, cluster, deletion_ctx)+ _run_event_deletion(cluster, deletion_ctx)assert cluster.any_host(partial(_count_events_by_name, TEAM_ID, "$pageview")).result() == 0assert cluster.any_host(partial(_count_events_by_name, TEAM_ID, "$screen")).result() == 0@@ -596,6 +604,7 @@ def test_full_job_event_deletion(cluster: ClickhouseCluster):resources={"cluster": cluster},)assert result.success+ assert "delete_event_removal_shard[sharded_events_shard_1]" in {event.step_key for event in result.all_events}# Target events deletedassert cluster.any_host(partial(_count_events_by_name, TEAM_ID, "$pageview")).result() == 0@@ -607,6 +616,67 @@ def test_full_job_event_deletion(cluster: ClickhouseCluster):assert request.status == RequestStatus.COMPLETED+def test_event_removal_reexecutes_only_the_failed_shard(cluster: ClickhouseCluster) -> None:+ now = datetime.now()+ events = [(TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i)) for i in range(10)]+ cluster.any_host(partial(_insert_events, events)).result()++ request = DataDeletionRequest.objects.create(+ team_id=TEAM_ID,+ request_type=RequestType.EVENT_REMOVAL,+ events=["$pageview"],+ start_time=now - timedelta(days=7),+ end_time=now + timedelta(minutes=1),+ status=RequestStatus.APPROVED,+ )+ run_config = {"ops": {"load_deletion_request": {"config": {"request_id": str(request.pk)}}}}++ original_call = LightweightDeleteMutationRunner.__call__++ def fail_on_events_table(runner: LightweightDeleteMutationRunner, client: Client):+ if runner.table == EVENTS_DATA_TABLE():+ raise Exception("delete failed")+ return original_call(runner, client)++ with patch.object(LightweightDeleteMutationRunner, "__call__", autospec=True, side_effect=fail_on_events_table):+ failed = data_deletion_request_event_removal.execute_in_process(+ run_config=run_config, resources={"cluster": cluster}, raise_on_error=False+ )+ assert not failed.success+ failed_shard_step = f"delete_event_removal_shard[{EVENTS_DATA_TABLE()}_shard_1]"+ shard_outcomes = {+ event.step_key: event.event_type_value+ for event in failed.all_events+ if event.step_key+ and event.step_key.startswith("delete_event_removal_shard[")+ and event.event_type_value in ("STEP_SUCCESS", "STEP_FAILURE")+ }+ assert shard_outcomes.pop(failed_shard_step) == "STEP_FAILURE"+ assert all(outcome == "STEP_SUCCESS" for outcome in shard_outcomes.values())+ request.refresh_from_db()+ assert request.status == RequestStatus.FAILED++ # Re-execute from failure reuses the cached load and fan-out outputs and reruns only the failed shard.+ assert request.start_time is not None and request.end_time is not None+ ctx = DeletionRequestContext(+ request_id=str(request.pk),+ team_id=request.team_id,+ start_time=request.start_time,+ end_time=request.end_time,+ events=request.events,+ )+ retried = delete_event_removal_shard(+ build_op_context(), cluster, EventRemovalShard(data_table=EVENTS_DATA_TABLE(), shard_num=1), ctx+ )+ completed = complete_event_deletion(build_op_context(), cluster, ctx, [retried])+ finalize_deletion_request(build_op_context(), completed)++ request.refresh_from_db()+ assert request.status == RequestStatus.COMPLETED+ assert cluster.any_host(partial(_count_events_by_name, TEAM_ID, "$pageview")).result() == 0++# ---------------------------------------------------------------------------# Deferred event-removal tests# ---------------------------------------------------------------------------@@ -638,8 +708,7 @@ def test_execute_event_deletion_deferred_queues_into_adhoc_table(cluster: Clickhevents=["$pageview"],execution_mode=ExecutionMode.DEFERRED.value,)- context = build_op_context()- execute_event_deletion(context, cluster, deletion_ctx)+ _run_event_deletion(cluster, deletion_ctx)# Events NOT deleted.assert cluster.any_host(partial(_count_events_by_name, DEFERRED_TEAM_ID, "$pageview")).result() == 25@@ -2292,7 +2361,7 @@ def test_deferred_event_removal_queues_flag_evaluations_and_blocks_promotion(cluevents=[FLAG_EVALUATIONS_SOURCE_EVENT],execution_mode=ExecutionMode.DEFERRED.value,)- execute_event_deletion(build_op_context(), cluster, deletion_ctx)+ _run_event_deletion(cluster, deletion_ctx)queued = cluster.any_host(partial(_adhoc_pending_uuids, DEFERRED_TEAM_ID)).result()assert flag_uuid in queued@@ -2443,7 +2512,7 @@ def test_immediate_event_deletion_skips_flag_evaluations(cluster: ClickhouseClusevents=[FLAG_EVALUATIONS_SOURCE_EVENT],hogql_predicate="properties.$browser = 'Chrome'",)- execute_event_deletion(build_op_context(), cluster, deletion_ctx)+ _run_event_deletion(cluster, deletion_ctx)assert cluster.any_host(partial(_count_events_by_name, team.id, FLAG_EVALUATIONS_SOURCE_EVENT)).result() == 0assert len(cluster.any_host(partial(_flag_evaluation_person_ids, team.id)).result()) == 1