:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-deletion): skip flag_evaluations in immediate event removal (#108308)
Paweł Szczur696542f620d4
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 9143b96c8f50..a73820bab9d8 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` — person, team, queued-uuid and event removal, but `deletes_job` skips it by default today. Not a squash target. Property rewriting is unsupported: temporary properties and quarantine diagnostics retain additional copies that the legacy property-removal machinery does not rewrite. Optional: only present after the native-JSON migration. See the known gap below.-- `sharded_flag_evaluations` — person, team, queued-uuid and event removal. Not property removal (below). Optional.+- `sharded_flag_evaluations` — person, team, queued-uuid and deferred event removal. Not immediate event removal or property removal (below). 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.@@ -221,6 +221,13 @@ Refusing beats silently under-deleting, so the gate is the right default.If the fix has not landed by the time real traffic hits, the cheaper stopgaps are letting a request exclude event names so an operator can scope around the table, or recording an explicit, audited acknowledgement on the request so an operator can accept the residue rather than being stuck.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.+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.+### Event removal with a HogQL predicate does not reach `flag_evaluations``compile_hogql_predicate` resolves every predicate against the events HogQL table and emits events-specific physical columns.@@ -228,7 +235,7 @@ Its only axis of variation is legacy vs native-JSON events, so while the dag doeWhether a given fragment would run against `flag_evaluations` depends on the predicate and the team's modifiers: one naming only `event` or `distinct_id` would, one reaching a `mat_*` column or a property-group map would not, and nothing validates which.The dag refuses rather than guessing.A HogQL table definition for `flag_evaluations` does not change that, because nothing routes compilation to a table.-Requests without a predicate are swept normally; requests with one are refused if the table holds matching rows.+Deferred requests without a predicate are swept normally; deferred requests with one are refused if the table holds matching rows.## Producer prerequisite: person_id paritydiff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex 524b24d30d9d..af90621d5f84 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+from collections.abc import Callable, Collectionfrom dataclasses import dataclass, field, replacefrom datetime import UTC, datetime, timedeltafrom functools import partial@@ -48,6 +48,8 @@ from posthog.models.data_deletion_request import ()from posthog.models.deletion_targets import (COVERAGE_DOC,+ FLAG_EVALUATIONS,+ PERSONAL_DATA_TARGETS,DeletionTarget,TargetPlacement,UnsweepableRowsError,@@ -641,13 +643,19 @@ def _verify_swept(def _event_removal_placements(- cluster: ClickhouseCluster, deletion_request: DeletionRequestContext+ cluster: ClickhouseCluster,+ deletion_request: DeletionRequestContext,+ *,+ skip_targets: Collection[DeletionTarget] = (),) -> list[TargetPlacement]:"""Targets this event-removal request can sweep, each with the handle that reaches it."""events = [] if deletion_request.delete_all_events else deletion_request.events# A target that can't hold any of the named events has nothing to sweep, and mutations serialize# per table, so enqueueing a no-op one would queue in front of real work.- placements = [p for p in resolve_placements(cluster) if p.target.may_hold_any_of(events)]+ # Skipped targets are dropped before resolve_placements, which raises for an unreachable target+ # that still holds rows.+ targets = [t for t in PERSONAL_DATA_TARGETS if t not in skip_targets]+ placements = [p for p in resolve_placements(cluster, targets) if p.target.may_hold_any_of(events)]if not deletion_request.hogql_predicate:return placements@@ -660,12 +668,18 @@ def _event_removal_placements(return [p for p in placements if p.target.accepts_hogql_predicate]+# Immediate deletion leaves flag_evaluations rows to the table's TTL. A HogQL predicate does not+# compile against that table, so gating on it refused every such request whose team had matching+# $feature_flag_called rows. Deferred deletion still queues the table's uuids.+_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)+ placements = _event_removal_placements(cluster, deletion_request, skip_targets=_IMMEDIATE_SKIP_TARGETS)targets = [p.target for p in placements]context.log.info(f"Starting immediate event deletion on tables {[t.data_table for t in targets]}")diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex ef971d338b35..4793bbd32158 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -2413,34 +2413,40 @@ def test_get_property_removal_shards_narrows_person_properties_on_flag_evaluatio@pytest.mark.django_db-def test_execute_event_deletion_refuses_hogql_predicate_when_flag_evaluations_holds_matching_rows(- cluster: ClickhouseCluster,-) -> None:- # flag_evaluations has no HogQL table definition, so it cannot accept the compiled predicate- # and falls into the unsweepable branch of _event_removal_placements. A matching row there must- # refuse the request rather than let it complete while HogQL-matched rows survive.+def test_immediate_event_deletion_skips_flag_evaluations(cluster: ClickhouseCluster) -> None:+ from posthog.models.organization import Organization+ from posthog.models.team import Team++ org = Organization.objects.create(name="test-org-immediate-flag-evaluations")+ team = Team.objects.create(organization=org, name="test-team-immediate-flag-evaluations")now = datetime.now()- start_time = now - timedelta(days=7)- end_time = now + timedelta(minutes=1)cluster.any_host(_truncate_flag_evaluations).result()+ cluster.any_host(+ partial(+ _insert_events_with_properties,+ [(team.id, FLAG_EVALUATIONS_SOURCE_EVENT, uuid4(), now, '{"$browser": "Chrome"}')],+ )+ ).result()cluster.any_host(partial(_insert_flag_evaluations_with_properties,- [(PROP_TEAM_ID, "someone", '{"$browser": "Chrome"}', str(uuid4()), now, now)],+ [(team.id, "someone", '{"$browser": "Chrome"}', str(uuid4()), now, now)],)).result()deletion_ctx = DeletionRequestContext(request_id=str(uuid4()),- team_id=PROP_TEAM_ID,- start_time=start_time,- end_time=end_time,+ team_id=team.id,+ start_time=now - timedelta(days=7),+ end_time=now + timedelta(minutes=1),events=[FLAG_EVALUATIONS_SOURCE_EVENT],hogql_predicate="properties.$browser = 'Chrome'",)- with pytest.raises(dagster.Failure, match="cannot be deleted"):- execute_event_deletion(build_op_context(), cluster, deletion_ctx)+ execute_event_deletion(build_op_context(), cluster, deletion_ctx)++ assert cluster.any_host(partial(_count_events_by_name, team.id, FLAG_EVALUATIONS_SOURCE_EVENT)).result() == 0+ assert len(cluster.any_host(partial(_flag_evaluation_person_ids, team.id)).result()) == 1cluster.any_host(_truncate_flag_evaluations).result()