: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): verify anytime, deferred default, hide person (#71009)
Paweł Szczur3c7bddc7aa66
diff --git a/posthog/admin/admins/data_deletion_request_admin.py b/posthog/admin/admins/data_deletion_request_admin.pyindex 87a55e91283b..7ca8a9d6b9e0 100644--- a/posthog/admin/admins/data_deletion_request_admin.py+++ b/posthog/admin/admins/data_deletion_request_admin.py@@ -13,17 +13,16 @@ from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.clickhouse.workload import Workloadfrom posthog.models.data_deletion_request import (- VERIFIABLE_STATUSES,DataDeletionRequest,ExecutionMode,RequestStatus,RequestType,cached_compile_hogql_predicate,+ count_remaining_for_request,event_match_params,event_match_sql_fragment,invalidate_compiled_predicate_cache,jsonhas_expr,- verify_queued_request,)CRITERIA_FIELDS = {@@ -43,6 +42,14 @@ CRITERIA_FIELDS = {}CLICKHOUSE_TEAM_GROUP = "ClickHouse Team"+PERSON_REMOVAL_FIELDS = (+ "person_uuids",+ "person_distinct_ids",+ "person_drop_profiles",+ "person_drop_events",+ "person_drop_recordings",+)+# Requests can only be edited while draft or pending. Once approved (or later), the# criteria are locked — operators must explicitly "revert to draft" to change them.EDITABLE_STATUSES = {RequestStatus.DRAFT, RequestStatus.PENDING}@@ -61,11 +68,6 @@ EDITABLE_FIELDS = ("hogql_predicate","notes","requires_approval",- "person_uuids",- "person_distinct_ids",- "person_drop_profiles",- "person_drop_events",- "person_drop_recordings",)# Dagster Cloud deployment slug per PostHog cloud environment. The admin runs on web pods, which@@ -211,20 +213,18 @@ class DataDeletionRequestForm(forms.ModelForm):help_text="Optional HogQL boolean expression (validated against the events table). ""Combined with the other filters via AND. Example: properties.$browser = 'Chrome'.",)- person_uuids = ArrayTextareaField(- required=False,- help_text="One person UUID per line. You can also paste a JSON array. "- "Combined with person_distinct_ids; total ≤ 1000.",- )- person_distinct_ids = ArrayTextareaField(- required=False,- help_text="One person distinct ID per line. You can also paste a JSON array. "- "Combined with person_uuids; total ≤ 1000.",- )class Meta:model = DataDeletionRequest- fields = "__all__"+ exclude = PERSON_REMOVAL_FIELDS++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ request_type = self.fields.get("request_type")+ if isinstance(request_type, forms.ChoiceField):+ request_type.choices = [+ (value, label) for value, label in RequestType.choices if value != RequestType.PERSON_REMOVAL+ ]def _append_hogql_predicate(fragment: str, params: dict, obj) -> tuple[str, dict]:@@ -494,20 +494,6 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):),},),- (- "Person targets",- {- "fields": (- "person_uuids",- "person_distinct_ids",- "person_drop_profiles",- "person_drop_events",- "person_drop_recordings",- ),- "classes": ("data-deletion-person-fields",),- "description": "Only used for person_removal requests.",- },- ),("ClickHouse stats",{@@ -696,14 +682,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):obj.status == RequestStatus.FAILED and request.user.groups.filter(name=CLICKHOUSE_TEAM_GROUP).exists())extra_context["retry_url"] = reverse("admin:posthog_datadeletionrequest_retry", args=[obj.pk])- # Verify works for QUEUED (the normal deferred path) and FAILED (a job that errored- # after the events were already deleted). Both rely on counting matching events, which- # is only meaningful for event_removal requests.- extra_context["can_verify"] = (- obj.status in VERIFIABLE_STATUSES- and obj.request_type == RequestType.EVENT_REMOVAL- and request.user.groups.filter(name=CLICKHOUSE_TEAM_GROUP).exists()- )+ extra_context["can_verify"] = request.user.groups.filter(name=CLICKHOUSE_TEAM_GROUP).exists()extra_context["verify_url"] = reverse("admin:posthog_datadeletionrequest_verify", args=[obj.pk])# ClickHouse stats are calculated from this page (works for any status).@@ -938,9 +917,10 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))supports_deferred = obj.request_type == RequestType.EVENT_REMOVAL+ default_execution_mode = ExecutionMode.DEFERRED if supports_deferred else ExecutionMode.IMMEDIATEif request.method == "POST":- execution_mode = request.POST.get("execution_mode", ExecutionMode.IMMEDIATE)+ execution_mode = request.POST.get("execution_mode", default_execution_mode)if obj.request_type == RequestType.PERSON_REMOVAL:# person_removal is always IMMEDIATE — ignore any submitted value.execution_mode = ExecutionMode.IMMEDIATE@@ -982,7 +962,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"supports_deferred": supports_deferred,"is_person_removal": obj.request_type == RequestType.PERSON_REMOVAL,"execution_mode_choices": ExecutionMode.choices,- "default_execution_mode": ExecutionMode.IMMEDIATE,+ "default_execution_mode": default_execution_mode,"opts": self.model._meta,"title": f"Approve deletion request {obj.pk}",}@@ -1061,24 +1041,37 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):messages.error(request, "Only ClickHouse Team members can verify deletion requests.")return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))- if obj.request_type != RequestType.EVENT_REMOVAL:- messages.error(request, "Only event removal requests can be verified.")+ if obj.request_type == RequestType.PERSON_REMOVAL:+ messages.warning(+ request,+ "Automated verification isn't available for person removal requests — verify manually.",+ )return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))- if obj.status not in VERIFIABLE_STATUSES:- messages.error(request, "Only queued or failed requests can be verified.")+ try:+ remaining = count_remaining_for_request(obj)+ except Exception as e:+ messages.error(request, f"Failed to verify: {e}")return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))- prior_status = obj.status- outcome = verify_queued_request(obj)- if outcome.promoted:- obj.refresh_from_db()- self.log_change(request, obj, f"Verified: 0 matching events remain, status {prior_status} → completed.")- messages.success(request, "Verified — no matching events remain. Marked completed.")- else:+ if remaining:messages.warning(request,- f"{outcome.remaining} matching event(s) still present in ClickHouse. "- f"Left {obj.status} — re-run after the next scheduled deletion.",+ f"{remaining} matching row(s) still present in ClickHouse. "+ f"Left {obj.get_status_display().lower()} — re-run after the next scheduled deletion.",)+ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))++ prior_status = obj.status+ promoted = (+ DataDeletionRequest.objects.filter(pk=obj.pk)+ .exclude(status=RequestStatus.COMPLETED)+ .update(status=RequestStatus.COMPLETED, updated_at=timezone.now())+ )+ if promoted:+ obj.refresh_from_db()+ self.log_change(request, obj, f"Verified: 0 matching rows remain, status {prior_status} → completed.")+ messages.success(request, "Verified — no matching rows remain. Marked completed.")+ else:+ messages.info(request, "Verified — no matching rows remain. Already completed.")return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))diff --git a/posthog/admin/test_data_deletion_request_admin.py b/posthog/admin/test_data_deletion_request_admin.pyindex 00f07584ad8b..7ed6f57260f7 100644--- a/posthog/admin/test_data_deletion_request_admin.py+++ b/posthog/admin/test_data_deletion_request_admin.py@@ -69,7 +69,7 @@ class TestDataDeletionRequestAdminApprovalFlow(BaseTest):self.assertEqual(response.status_code, 200)context = response.context_dataself.assertTrue(context["supports_deferred"])- self.assertEqual(context["default_execution_mode"], ExecutionMode.IMMEDIATE)+ self.assertEqual(context["default_execution_mode"], ExecutionMode.DEFERRED)def test_approve_view_get_hides_picker_for_property_removal(self):request = self._pending_request(request_type=RequestType.PROPERTY_REMOVAL, properties=["$ip"])@@ -94,6 +94,15 @@ class TestDataDeletionRequestAdminApprovalFlow(BaseTest):self.assertEqual(request.execution_mode, execution_mode)self.assertTrue(request.approved)+ def test_approve_view_post_defaults_event_removal_to_deferred(self):+ request = self._pending_request()+ response = self._call_approve("POST", request, {})++ self.assertEqual(response.status_code, 302)+ request.refresh_from_db()+ self.assertEqual(request.status, RequestStatus.APPROVED)+ self.assertEqual(request.execution_mode, ExecutionMode.DEFERRED)+def test_approve_view_post_deferred_rejected_for_property_removal(self):request = self._pending_request(request_type=RequestType.PROPERTY_REMOVAL, properties=["$ip"])response = self._call_approve("POST", request, {"execution_mode": ExecutionMode.DEFERRED.value})@@ -783,13 +792,14 @@ class TestDataDeletionRequestAdminVerify(BaseTest):request.refresh_from_db()self.assertEqual(request.status, RequestStatus.QUEUED)- def test_verify_view_rejects_non_verifiable_status(self):+ def test_verify_view_promotes_from_any_status_when_events_gone(self):request = self._queued_request()request.status = RequestStatus.APPROVEDrequest.save(update_fields=["status"])- self._call_verify(request)+ with patch("posthog.models.data_deletion_request.count_remaining_matching_events", return_value=0):+ self._call_verify(request)request.refresh_from_db()- self.assertEqual(request.status, RequestStatus.APPROVED)+ self.assertEqual(request.status, RequestStatus.COMPLETED)def test_verify_view_promotes_failed_when_events_gone(self):request = self._queued_request()@@ -809,12 +819,23 @@ class TestDataDeletionRequestAdminVerify(BaseTest):request.refresh_from_db()self.assertEqual(request.status, RequestStatus.FAILED)- def test_verify_view_rejects_non_event_removal(self):+ def test_verify_view_verifies_property_removal(self):request = self._queued_request()request.request_type = RequestType.PROPERTY_REMOVAL+ request.properties = ["$ip"]+ request.status = RequestStatus.FAILED+ request.save(update_fields=["request_type", "properties", "status"])+ with patch("posthog.models.data_deletion_request.count_remaining_property_events", return_value=0):+ self._call_verify(request)+ request.refresh_from_db()+ self.assertEqual(request.status, RequestStatus.COMPLETED)++ def test_verify_view_reports_person_removal_unsupported(self):+ request = self._queued_request()+ request.request_type = RequestType.PERSON_REMOVALrequest.status = RequestStatus.FAILEDrequest.save(update_fields=["request_type", "status"])- with patch("posthog.models.data_deletion_request.count_remaining_matching_events", return_value=0) as counted:+ with patch("posthog.admin.admins.data_deletion_request_admin.count_remaining_for_request") as counted:self._call_verify(request)counted.assert_not_called()request.refresh_from_db()@@ -918,3 +939,23 @@ class TestDagsterRunLink(SimpleTestCase):def test_admin_renders_placeholder_when_never_executed(self):admin_obj = DataDeletionRequestAdmin(DataDeletionRequest, AdminSite())self.assertEqual(admin_obj.last_dagster_run(DataDeletionRequest()), "—")+++class TestDataDeletionRequestFormHidesPersonRemoval(SimpleTestCase):+ def test_person_removal_hidden_from_type_picker_and_fields(self):+ from typing import cast++ from django import forms++ from posthog.admin.admins.data_deletion_request_admin import PERSON_REMOVAL_FIELDS, DataDeletionRequestForm++ form = DataDeletionRequestForm()+ request_type = form.fields["request_type"]+ assert isinstance(request_type, forms.ChoiceField)+ choices = cast("list[tuple[str, str]]", request_type.choices)+ type_values = [value for value, _ in choices]+ self.assertNotIn(RequestType.PERSON_REMOVAL, type_values)+ self.assertIn(RequestType.EVENT_REMOVAL, type_values)+ self.assertIn(RequestType.PROPERTY_REMOVAL, type_values)+ for field in PERSON_REMOVAL_FIELDS:+ self.assertNotIn(field, form.fields)diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.pyindex b12dd8ea6732..a9c4b6e2f190 100644--- a/posthog/models/data_deletion_request.py+++ b/posthog/models/data_deletion_request.py@@ -503,6 +503,137 @@ def count_remaining_matching_events(request: "DataDeletionRequest") -> int:return int(result[0][0]) if result else 0+def _mat_col_presence_clauses(mat_cols: list[tuple[str, bool]]) -> list[str]:+ """ "Value is present" checks for DEFAULT-materialized property columns: ``col != ''``.++ Matches the deletion path in posthog/dags/data_deletion_requests.py: the DEFAULT expression+ stores ``''`` for missing keys, so ``!= ''`` (not ``IS NOT NULL``) is the correct presence test.+ """+ return [f"`{name}` != ''" for name, _ in mat_cols]+++def discover_affected_mat_columns(properties: list[str], table_column: str) -> list[tuple[str, bool]]:+ """DEFAULT-materialized columns on the distributed ``events`` table for the given properties.++ Returns ``(column_name, is_nullable)`` for columns whose comment follows the+ ``column_materializer::<table_column>::<prop>`` convention. Mirrors ``_get_affected_mat_columns``+ in the deletion job so verification counts a row as dirty on the same terms the deletion does — a+ value left in a materialized column after its JSON key is gone still counts.+ """+ if not properties:+ return []++ from django.conf import settings as django_settings++ from posthog.clickhouse.client import sync_execute+ from posthog.clickhouse.client.connection import ClickHouseUser++ from ee.clickhouse.materialized_columns.columns import MaterializedColumnDetails++ rows = sync_execute(+ """+ SELECT name, comment, type LIKE 'Nullable(%%)'+ FROM system.columns+ WHERE database = %(database)s+ AND table = 'events'+ AND comment LIKE '%%column_materializer::%%'+ AND comment NOT LIKE '%%column_materializer::elements_chain::%%'+ """,+ {"database": django_settings.CLICKHOUSE_DATABASE},+ readonly=True,+ ch_user=ClickHouseUser.META,+ )+ target = set(properties)+ result: list[tuple[str, bool]] = []+ for name, comment, is_nullable in rows:+ details = MaterializedColumnDetails.from_column_comment(comment)+ if details.table_column == table_column and details.property_name in target:+ result.append((name, bool(is_nullable)))+ return result+++def _property_presence_where(+ request: "DataDeletionRequest",+ mat_cols: list[tuple[str, bool]] | None = None,+ person_mat_cols: list[tuple[str, bool]] | None = None,+) -> tuple[str, dict]:+ """WHERE predicate + params matching events that still carry any target (person_)property.++ Mirrors ``event_removal_where`` but swaps the events filter for a presence check over+ ``properties`` / ``person_properties`` and their DEFAULT-materialized columns. Used to verify a+ property_removal request: once the property has been stripped from the JSON and its materialized+ column reset on every matching event, this count reaches zero. The presence set must match the+ deletion path (``_property_removal_where``) or a row it still considers dirty reads as clean here.+ """+ parts = [_EVENT_REMOVAL_TIME_PREDICATE, event_match_sql_fragment(request)]+ params = event_match_params(request)++ presence: list[str] = []+ for i, prop in enumerate(request.properties or []):+ presence.append(jsonhas_expr(prop, f"fp_{i}"))+ for j, part in enumerate(prop.split(".")):+ params[f"fp_{i}_{j}"] = part+ if mat_cols:+ presence.extend(_mat_col_presence_clauses(mat_cols))+ 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+ if person_mat_cols:+ presence.extend(_mat_col_presence_clauses(person_mat_cols))+ if presence:+ parts.append(f"AND ({' OR '.join(presence)})")++ hogql_sql, hogql_values = compile_hogql_predicate(request)+ if hogql_sql:+ parts.append(f"AND ({hogql_sql})")+ params.update(hogql_values)+ return " ".join(p for p in parts if p), params+++def count_remaining_property_events(request: "DataDeletionRequest") -> int:+ """Count events that still carry any of a property-removal request's target properties."""+ from posthog.clickhouse.client import sync_execute+ from posthog.clickhouse.client.connection import ClickHouseUser+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context+ from posthog.clickhouse.workload import Workload++ mat_cols = discover_affected_mat_columns(request.properties or [], "properties")+ person_mat_cols = discover_affected_mat_columns(request.person_properties or [], "person_properties")+ predicate, params = _property_presence_where(request, mat_cols, person_mat_cols)+ with tags_context(+ product=Product.INTERNAL,+ feature=Feature.DATA_DELETION,+ team_id=request.team_id,+ workload=Workload.OFFLINE,+ query_type="data_deletion_request_verify_property",+ ):+ # nosemgrep: clickhouse-fstring-param-audit (predicate built from internal helper, not user input)+ result = sync_execute(+ f"SELECT count() FROM events WHERE {predicate} AND _row_exists = 1",+ params,+ team_id=request.team_id,+ readonly=True,+ workload=Workload.OFFLINE,+ ch_user=ClickHouseUser.META,+ )+ return int(result[0][0]) if result else 0+++def count_remaining_for_request(request: "DataDeletionRequest") -> int | None:+ """Count rows still matching a deletion request's criteria in ClickHouse.++ Dispatches on request type: matching events for event_removal, events still carrying the+ target property for property_removal. Returns ``None`` for person_removal, which has no+ automated remaining-count.+ """+ if request.request_type == RequestType.EVENT_REMOVAL:+ return count_remaining_matching_events(request)+ if request.request_type == RequestType.PROPERTY_REMOVAL:+ return count_remaining_property_events(request)+ return None++@dataclassclass VerifyOutcome:remaining: intdiff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.pyindex d071e208feb0..c2bc2b620a73 100644--- a/posthog/models/test/test_data_deletion_request.py+++ b/posthog/models/test/test_data_deletion_request.py@@ -378,6 +378,51 @@ def test_rendered_count_query_includes_hogql_predicate(team):assert "%(" not in rendered+def test_property_presence_where_scopes_and_matches_property_columns(team):+ from posthog.clickhouse.client.escape import substitute_params_for_display++ request = DataDeletionRequest(+ **_base_kwargs(+ team_id=team.id,+ request_type=RequestType.PROPERTY_REMOVAL,+ events=["$pageview"],+ properties=["$ip"],+ person_properties=["email"],+ start_time=datetime(2026, 4, 1),+ end_time=datetime(2026, 4, 15),+ )+ )+ predicate, params = ddr._property_presence_where(request)+ rendered = substitute_params_for_display(predicate, params)++ assert f"team_id = {team.id}" in rendered+ assert "timestamp >= '2026-04-01 00:00:00'" in rendered+ assert "timestamp < '2026-04-15 00:00:00'" in rendered+ assert "JSONHas(properties, '$ip')" in rendered+ assert "JSONHas(person_properties, 'email')" in rendered+ assert "%(" not in rendered+++def test_property_presence_where_includes_materialized_columns(team):+ from posthog.clickhouse.client.escape import substitute_params_for_display++ request = DataDeletionRequest(+ **_base_kwargs(+ team_id=team.id,+ request_type=RequestType.PROPERTY_REMOVAL,+ events=["$pageview"],+ properties=["$ip"],+ start_time=datetime(2026, 4, 1),+ end_time=datetime(2026, 4, 15),+ )+ )+ predicate, params = ddr._property_presence_where(request, mat_cols=[("mat_$ip", False)])+ rendered = substitute_params_for_display(predicate, params)++ assert "JSONHas(properties, '$ip')" in rendered+ assert "`mat_$ip` != ''" in rendered++def _person_kwargs(**overrides) -> dict:kwargs = {"team_id": TEAM_ID,diff --git a/posthog/templates/admin/posthog/datadeletionrequest/change_form.html b/posthog/templates/admin/posthog/datadeletionrequest/change_form.htmlindex e7927a4e48a9..fae21792cbbb 100644--- a/posthog/templates/admin/posthog/datadeletionrequest/change_form.html+++ b/posthog/templates/admin/posthog/datadeletionrequest/change_form.html@@ -1,40 +1,6 @@{% extends "admin/change_form.html" %}{% load i18n %}-{% block extrahead %}- {{ block.super }}- <script>- (function () {- // Toggle event/property fields and the "Person targets" fieldset based on request_type.- // Event fields are scoped via the form-row CSS classes Django renders (.field-<name>);- // the person fieldset has the explicit class "data-deletion-person-fields".- var EVENT_FIELDS = ["events", "delete_all_events", "properties", "hogql_predicate"];-- function applyToggle() {- var select = document.getElementById("id_request_type");- if (!select) return;- var isPerson = select.value === "person_removal";-- EVENT_FIELDS.forEach(function (name) {- var row = document.querySelector(".form-row.field-" + name);- if (row) row.style.display = isPerson ? "none" : "";- });-- document.querySelectorAll("fieldset.data-deletion-person-fields").forEach(function (fs) {- fs.style.display = isPerson ? "" : "none";- });- }-- document.addEventListener("DOMContentLoaded", function () {- var select = document.getElementById("id_request_type");- if (!select) return;- applyToggle();- select.addEventListener("change", applyToggle);- });- })();- </script>-{% endblock %}-{% block after_field_sets %}{{ block.super }}@@ -145,8 +111,12 @@{% if can_verify %}<div class="submit-row" style="margin-top: 20px; padding: 20px; border-radius: 5px; border: 1px solid #417690; display: flex; align-items: center; gap: 10px;"><div class="info">- This request is <strong>{{ original.get_status_display|lower }}</strong>. Verify to re-check ClickHouse now —- if no matching events remain, it will be marked completed{% if original.status == "failed" %} (use this when the job errored after the events were already deleted){% endif %}.+ This request is <strong>{{ original.get_status_display|lower }}</strong>.+ {% if original.request_type == "person_removal" %}+ Automated verification isn't available for person removal requests — verifying will report that a manual check is required.+ {% else %}+ Verify to re-check ClickHouse now — if no matching rows remain, it will be marked completed{% if original.status == "failed" %} (use this when the job errored after the data was already deleted){% endif %}.+ {% endif %}</div><button type="submit" formaction="{{ verify_url }}" formmethod="post" formnovalidate class="button" style="padding: 10px 15px; background: #417690; color: white;" onclick="return confirm('Verify this request against ClickHouse now?');">Verify deletion</button></div>