: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): auto-approve small event removal requests (#71762)
Paweł Szczur9f1243bd1806
diff --git a/docs/plans/2026-07-16-auto-approve-small-event-deletions.md b/docs/plans/2026-07-16-auto-approve-small-event-deletions.mdnew file mode 100644index 000000000000..a5b90724be90--- /dev/null+++ b/docs/plans/2026-07-16-auto-approve-small-event-deletions.md@@ -0,0 +1,149 @@+# Auto-approve small event-removal deletion requests++## Context++`DataDeletionRequest` (Django admin only, `posthog/admin/admins/data_deletion_request_admin.py`) requires every+request to walk the full `draft → pending → approved` path, with the APPROVED transition gated on ClickHouse Team+membership. Approval exists because ClickHouse deletes are heavyweight mutations that can degrade production query+performance, but a small event-removal request is not heavyweight, and making a human rubber-stamp it is pure latency.++The goal: approve an `event_removal` request automatically when it matches fewer than 100,000 events, always in+`deferred` execution mode (the `adhoc_events_deletion` queue drained by the scheduled `deletes_job`, which is the+low-impact path). Everything else keeps needing a human.++The decision is made by a scheduled Dagster job, not by the submit page. The distinction matters: the job fetches the+ClickHouse stats itself, immediately before deciding, so it approves against a count it measured rather than one an+operator fetched at some unknown earlier time. Deciding at submit time would mean trusting a stale count, which in+turn needs a freshness gate, a compare-and-swap against the stats the page was rendered from, and a token proving the+page actually offered the opt-out. None of that exists when the measurement and the decision are the same step.++The job is the third sweep over this model, alongside `data_deletion_request_pickup_sensor` (polls APPROVED) and+`verify_queued_deletion_requests_job` (sweeps QUEUED).++The model already carries a `requires_approval` BooleanField that nothing reads. This change gives it meaning as the+"do not auto-approve" opt-out.++## Requirements++Every 30 minutes, for each pending request where `request_type == EVENT_REMOVAL` and `requires_approval` is False:++1. Refresh its ClickHouse stats and persist them.+2. Approve it when `end_time` is in the past and `count < 100_000` — an open time range keeps matching newly ingested+ events, so a count taken now can't bound what the deferred drain deletes when it runs later.+3. Otherwise leave it PENDING for the ClickHouse Team, with the reason logged.++Auto-approved requests go `PENDING → APPROVED` with `execution_mode = DEFERRED`, `approved = True`,+`approved_automatically = True`, `approved_at = now`, and `approved_by` left NULL.++## Decisions++- **`requires_approval` is the opt-out**, repurposed rather than adding a field. The submit page is its only writer,+ and it means "a human must approve this": True for non-event-removals (structural — they are never auto-approvable)+ or when the submitter ticks the box, False otherwise. It is removed from the change form so there is exactly one+ control. Time-dependent conditions are deliberately _not_ baked in at submit: the job re-evaluates the time range+ and the count, so a request whose range closes an hour after submission still qualifies later.+- **`approved_by` stays NULL.** No human approved it, so naming one would be a lie the audit trail can't undo.+- **`approved_automatically`** is a new BooleanField carrying that signal instead. It is filterable in the changelist+ and cleared by "revert to draft" alongside the other approval fields.+- **The threshold is a module constant**, not a setting.+- **Only candidates get their stats refreshed**, not every pending request. A pending request sits until a human acts,+ so refreshing all of them would re-run the same (possibly expensive) ClickHouse query every 30 minutes forever, on+ requests the job can't act on anyway.+- **A failure on one request is logged and skipped**, never raised. One request whose HogQL predicate no longer+ compiles must not stop the sweep from approving the others.+- **The schedule defaults to STOPPED**, like every other schedule and sensor in this feature. An operator enables it+ in the Dagster UI; nothing is auto-approved until they do.+- **`submit_view` deliberately keeps no `CLICKHOUSE_TEAM_GROUP` check**, unlike `approve_view` / `retry_view` / the+ verify path. Any staff user can submit a request that the job may then approve without a ClickHouse Team member+ involved, and the cap is per-request rather than per-user. What bounds the blast radius instead is the combination+ of the 100,000-event cap, the closed-time-range requirement (so the count actually bounds what runs), the fact that+ the job measures rather than trusts, deferred-only execution, and the audit trail on the request.++## Implementation++### `posthog/models/data_deletion_request.py`++Already the shared home for this feature's ClickHouse logic (`event_removal_where`, `count_remaining_for_request`,+`verify_queued_request`), used by both the admin and the dag. The stats-fetch chain moved down here from the admin so+the dag doesn't import from a presentation layer, and the sweep logic lives here alongside `verify_queued_request` for+the same reason — the Dagster op is a thin wrapper over it, and the logic is testable without Dagster.++- `refresh_deletion_stats(request)` — fetch and persist. `STATS_FIELDS` is the single list both writers save, so a new+ stat can't reach one path and skip the other. The write is guarded on `updated_at` and raises+ `StaleDeletionRequestError` if the request moved while the count was running: changing the criteria clears the stats+ precisely because the old numbers no longer describe the request, so writing ours back over that edit would+ resurrect a count nobody measured, which a reviewer could then approve against. Both callers already treat a raise+ as "leave it alone and say so".+- `AUTO_APPROVE_MAX_EVENTS = 100_000` and `AUTO_APPROVE_INTERVAL_MINUTES = 30`. The interval lives here rather than+ beside the schedule so the submit page can tell an operator how long their request will sit before it's looked at,+ without the copy and the cron drifting apart.+- `auto_approve_blocker(request) -> str | None` — why this request can't be auto-approved, or None. Ordered:+ not `EVENT_REMOVAL`; `end_time` missing or in the future; `count` is None; `count >= AUTO_APPROVE_MAX_EVENTS`.+ `requires_approval` and `status` are deliberately not checked here — they're a queryset filter and an update guard,+ not properties of the request's size.+- `auto_approve_pending_requests(max_requests, on_event)` — the sweep. Status-guarded update mirroring+ `approve_view`'s pattern, so a concurrent criteria edit (which resets the request to DRAFT and clears its stats)+ can't be approved against a count that no longer describes it.+- `approved_automatically` field; `requires_approval` help text updated.++### Migration++`AddField` of a boolean with a static default (safe, non-blocking) plus a help-text `AlterField` (a SQL no-op).++### `posthog/dags/data_deletion_requests.py`++`auto_approve_pending_deletion_requests_op` → `auto_approve_deletion_requests_job` →+`auto_approve_deletion_requests_schedule` (`*/30 * * * *`, UTC). The op reports approved/skipped/errored counts plus+`max_requests`, so a tick that hit the cap reads as truncated rather than as "that was all of them". No failure hook —+nothing here transitions a request to IN_PROGRESS.++Registered in `posthog/dags/locations/clickhouse.py`.++### `posthog/admin/admins/data_deletion_request_admin.py`++The submit page stops deciding anything. `submit_view` computes+`requires_approval = not auto_approve_candidate or bool(request.POST.get("requires_approval"))` and hands it to+`_submit_for_approval`, which is back to a plain `DRAFT → PENDING` update. `requires_approval` is removed from+`EDITABLE_FIELDS` and the fieldsets (`ModelAdmin.get_form` builds fields from `flatten_fieldsets`, so that is+sufficient); it stays in `list_filter` and in `duplicate_requests`. `approved_automatically` joins `readonly_fields`,+the Audit trail fieldset, and `list_filter`, and is cleared by `revert_to_draft_view`.++### `posthog/templates/admin/posthog/datadeletionrequest/submit.html`++Orange notice when the request is an event removal, explaining that a job will check it within 30 minutes and what+would disqualify it; grey text otherwise naming the request type. The opt-out checkbox renders unchecked, inside the+form, only for event removals.++## Tests++- `posthog/models/test/test_data_deletion_request.py` — parameterized `auto_approve_blocker` (pure function, no DB).+- `posthog/dags/tests/test_data_deletion_requests.py` — the job against the real cluster fixture: approves a small+ pending event removal (NULL `approved_by`, `approved_automatically`, deferred, stats persisted); ignores an+ opted-out request without even measuring it; leaves an oversized one pending but still refreshes its stats; and+ keeps sweeping when one request's predicate won't compile. Plus job/schedule registration, and that the schedule+ actually yields a run on tick — a schedule function that returns nothing is registered and cronned exactly like a+ working one, but Dagster skips every tick and the sweep never runs.+- `posthog/admin/test_data_deletion_request_admin.py` — submit lands in PENDING and records the opt-out; the checkbox+ is offered only to event removals.++## Verification++```bash+hogli test posthog/admin/test_data_deletion_request_admin.py+hogli test posthog/models/test/test_data_deletion_request.py+hogli test posthog/dags/tests/test_data_deletion_requests.py+uv run python manage.py makemigrations --check --dry-run+uv run python manage.py analyze_migration_risk --fail-on-blocked+ruff check posthog --fix && ruff format posthog+```++End-to-end in the local admin (`hogli start`, then `/admin/posthog/datadeletionrequest/`):++1. Create an `event_removal` draft with a closed time range against a small local team. **Review & Submit** → confirm+ the orange notice and the unchecked checkbox, and that it lands in `pending`, not `approved`.+2. Run the job from the Dagster UI (or `auto_approve_deletion_requests_job.execute_in_process()`) → the request flips+ to `approved` / `deferred` with `approved_automatically` set, `approved_by` empty, and fresh `stats_calculated_at`.+3. Repeat with the checkbox ticked → the job leaves it `pending`.+4. Submit a `property_removal` draft → grey text, no checkbox, `pending` with `requires_approval` true, and the job+ ignores it.+5. Confirm `approved_automatically` filters the changelist and that `requires_approval` still does.diff --git a/posthog/admin/admins/data_deletion_request_admin.py b/posthog/admin/admins/data_deletion_request_admin.pyindex 7ca8a9d6b9e0..a69f577d3cf3 100644--- a/posthog/admin/admins/data_deletion_request_admin.py+++ b/posthog/admin/admins/data_deletion_request_admin.py@@ -3,26 +3,24 @@ import astfrom django import formsfrom django.conf import settingsfrom django.contrib import admin, messages-from django.http import HttpResponseRedirect+from django.http import HttpRequest, HttpResponse, HttpResponseRedirectfrom django.template.response import TemplateResponsefrom django.urls import path, reversefrom django.utils import timezonefrom django.utils.html import format_html-from posthog.clickhouse.client.connection import ClickHouseUser-from posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.clickhouse.workload import Workloadfrom posthog.models.data_deletion_request import (+ AUTO_APPROVE_INTERVAL_MINUTES,+ AUTO_APPROVE_MAX_EVENTS,DataDeletionRequest,ExecutionMode,RequestStatus,RequestType,- cached_compile_hogql_predicate,+ build_deletion_count_query,count_remaining_for_request,- event_match_params,- event_match_sql_fragment,+ fetch_deletion_stats,invalidate_compiled_predicate_cache,- jsonhas_expr,+ refresh_deletion_stats,)CRITERIA_FIELDS = {@@ -67,7 +65,6 @@ EDITABLE_FIELDS = ("person_properties","hogql_predicate","notes",- "requires_approval",)# Dagster Cloud deployment slug per PostHog cloud environment. The admin runs on web pods, which@@ -227,206 +224,6 @@ class DataDeletionRequestForm(forms.ModelForm):]-def _append_hogql_predicate(fragment: str, params: dict, obj) -> tuple[str, dict]:- """Append the compiled HogQL predicate (if any) to ``fragment`` and merge params."""- hogql_sql, hogql_values = cached_compile_hogql_predicate(obj)- if not hogql_sql:- return fragment, params- combined = f"{fragment} AND ({hogql_sql})".strip() if fragment else f"AND ({hogql_sql})"- params.update(hogql_values)- return combined, params---def _build_event_filter(obj) -> tuple[str, dict]:- """Build the WHERE clause and params for matching events."""- return _append_hogql_predicate(event_match_sql_fragment(obj), event_match_params(obj), obj)---def _build_property_filter(obj) -> tuple[str, dict]:- """Build the WHERE clause addition and params for matching properties.-- Covers both ``events.properties`` (using ``fp_`` param prefix) and- ``events.person_properties`` (using ``pp_`` param prefix). The two- presence checks are ORed so the stats count includes every event that- carries at least one target key in either column.- """- event_clause = event_match_sql_fragment(obj)- params: dict = event_match_params(obj)-- presence_clauses: list[str] = []-- properties = obj.properties or []- if properties:- if len(properties) == 1:- presence_clauses.append(jsonhas_expr(properties[0], "fp_0"))- else:- exprs = [jsonhas_expr(prop, f"fp_{i}") for i, prop in enumerate(properties)]- presence_clauses.append(f"({' OR '.join(exprs)})")- for i, prop in enumerate(properties):- for j, part in enumerate(prop.split(".")):- params[f"fp_{i}_{j}"] = part-- person_properties = obj.person_properties or []- if person_properties:- if len(person_properties) == 1:- presence_clauses.append(jsonhas_expr(person_properties[0], "pp_0", column="person_properties"))- else:- exprs = [- jsonhas_expr(prop, f"pp_{i}", column="person_properties") for i, prop in enumerate(person_properties)- ]- presence_clauses.append(f"({' OR '.join(exprs)})")- for i, prop in enumerate(person_properties):- for j, part in enumerate(prop.split(".")):- params[f"pp_{i}_{j}"] = part-- if not presence_clauses:- raise ValueError("Cannot build property filter: both properties and person_properties are empty.")-- property_clause = (- f"AND ({' OR '.join(presence_clauses)})" if len(presence_clauses) > 1 else f"AND {presence_clauses[0]}"- )- filter_clause = f"{event_clause} {property_clause}".strip()- return _append_hogql_predicate(filter_clause, params, obj)---def _event_count_query_template(extra_filter: str) -> str:- # Counts run against the distributed ``events`` table so operators get a- # cluster-wide number; the actual deletions still target ``sharded_events``.- # nosemgrep: clickhouse-fstring-param-audit (extra_filter is built from internal helpers, not user input)- return f"""- SELECT- count() AS events,- count(DISTINCT _part) AS parts,- min(timestamp) AS min_ts,- max(timestamp) AS max_ts- FROM events- WHERE team_id = %(team_id)s- AND timestamp >= %(start_time)s- AND timestamp < %(end_time)s- {extra_filter}- """---def build_deletion_count_query(obj: DataDeletionRequest) -> tuple[str, dict]:- """Return the (SQL template, params) used to count rows matching this request.-- Mirrors ``_fetch_stats`` so admin users can copy the query and run it- independently — ``substitute_params_for_display`` is the companion renderer.- """- if obj.request_type == RequestType.PROPERTY_REMOVAL:- extra_filter, params = _build_property_filter(obj)- else:- extra_filter, params = _build_event_filter(obj)- return _event_count_query_template(extra_filter), params---_STATS_MAX_EXECUTION_TIME = 300---def _fetch_stats(team_id: int, extra_filter: str, params: dict, *, user_id: int | None = None) -> dict:- """Run event count + parts size queries against ClickHouse.-- The same predicate is spliced into both queries: the row count against the- Distributed ``events`` proxy, and the parts inspection against the local- ``sharded_events``. The HogQL predicate emits unqualified column references,- so it works in both contexts.-- ``user_id`` is threaded into the query tag so the acting staff user is- visible in ``system.query_log`` (the kill-switch + tag annotator pick it up- automatically via :class:`QueryTags`).- """- from posthog.clickhouse.client import sync_execute-- with tags_context(- product=Product.INTERNAL,- feature=Feature.DATA_DELETION,- team_id=team_id,- user_id=user_id,- workload=Workload.OFFLINE,- query_type="delete_event_count",- ):- event_result = sync_execute(- _event_count_query_template(extra_filter),- params,- team_id=team_id,- readonly=True,- workload=Workload.OFFLINE,- ch_user=ClickHouseUser.META,- settings={"max_execution_time": _STATS_MAX_EXECUTION_TIME},- )-- with tags_context(- product=Product.INTERNAL,- feature=Feature.DATA_DELETION,- team_id=team_id,- user_id=user_id,- workload=Workload.OFFLINE,- query_type="delete_part_count",- ):- from django.conf import settings as django_settings-- cluster = django_settings.CLICKHOUSE_CLUSTER-- # nosemgrep: clickhouse-fstring-param-audit (filter built from internal helpers; cluster from Django settings)- parts_result = sync_execute(- f"""- SELECT- count() AS part_count,- sum(p.bytes_on_disk) AS total_size_on_disk,- sum(p.rows) AS total_rows_in_those_parts- FROM cluster('{cluster}', system, parts) AS p- INNER JOIN (- SELECT DISTINCT _part AS name- FROM sharded_events- WHERE team_id = %(team_id)s- AND timestamp >= %(start_time)s- AND timestamp < %(end_time)s- {extra_filter}- ) AS matched ON p.name = matched.name- WHERE p.table = 'sharded_events'- AND p.active- """,- params,- team_id=team_id,- readonly=True,- workload=Workload.OFFLINE,- ch_user=ClickHouseUser.META,- settings={"max_execution_time": _STATS_MAX_EXECUTION_TIME},- )-- return {- "count": event_result[0][0] if event_result else 0,- "min_timestamp": event_result[0][2] if event_result and event_result[0][0] else None,- "max_timestamp": event_result[0][3] if event_result and event_result[0][0] else None,- "part_count": parts_result[0][0] if parts_result else 0,- "parts_size": parts_result[0][1] if parts_result else 0,- "parts_row_count": parts_result[0][2] if parts_result else 0,- }---def fetch_event_deletion_stats(obj: DataDeletionRequest, *, user_id: int | None = None):- """Count events and affected parts for an event removal request."""- extra_filter, params = _build_event_filter(obj)- return _fetch_stats(obj.team_id, extra_filter, params, user_id=user_id)---def fetch_property_deletion_stats(obj: DataDeletionRequest, *, user_id: int | None = None):- """Count events with matching properties and affected parts for a property removal request."""- if not obj.properties and not obj.person_properties:- raise ValueError(- "Cannot fetch stats for a property removal request with no properties or person_properties specified."- )- extra_filter, params = _build_property_filter(obj)- return _fetch_stats(obj.team_id, extra_filter, params, user_id=user_id)---def fetch_deletion_stats(obj: DataDeletionRequest, *, user_id: int | None = None):- """Dispatch to the appropriate stats function based on request type."""- if obj.request_type == RequestType.PROPERTY_REMOVAL:- return fetch_property_deletion_stats(obj, user_id=user_id)- return fetch_event_deletion_stats(obj, user_id=user_id)--@admin.register(DataDeletionRequest)class DataDeletionRequestAdmin(admin.ModelAdmin):form = DataDeletionRequestForm@@ -445,7 +242,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"last_executed_at","created_at",)- list_filter = ("request_type", "status", "requires_approval", "approved")+ list_filter = ("request_type", "status", "requires_approval", "approved", "approved_automatically")search_fields = ("team_id", "events", "properties", "person_properties", "notes")readonly_fields = ("status",@@ -462,6 +259,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"criteria_updated_by","criteria_updated_at","approved",+ "approved_automatically","approved_by","approved_at","execution_mode",@@ -490,7 +288,6 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"person_properties","hogql_predicate","notes",- "requires_approval",),},),@@ -520,6 +317,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"criteria_updated_at","updated_at","approved",+ "approved_automatically","approved_by","approved_at","execution_mode",@@ -764,6 +562,10 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):obj.person_drop_profiles or obj.person_drop_events or obj.person_drop_recordings)can_submit = not (missing_properties or missing_person_selectors or missing_person_drop_flag)+ # Only event removals are ever auto-approved, so they're the only ones offered the opt-out.+ # Everything else about eligibility (the time range, the size) is time-dependent and left to+ # the sweep job, which re-evaluates it against stats it fetches itself.+ auto_approve_candidate = obj.request_type == RequestType.EVENT_REMOVALif request.method == "POST":if missing_properties:@@ -784,20 +586,12 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"Cannot submit: person removal request requires at least one drop flag (profiles/events/recordings).",)return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))- updated = DataDeletionRequest.objects.filter(- pk=obj.pk,- status=RequestStatus.DRAFT,- ).update(- status=RequestStatus.PENDING,- updated_at=timezone.now(),- )- if not updated:- messages.error(request, "Request is no longer in draft status.")- return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))- obj.refresh_from_db()- self.log_change(request, obj, "Submitted: status changed from draft to pending.")- messages.success(request, "Request submitted and is now pending.")- return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))+ # The checkbox only posts when ticked. A request that can't be auto-approved at all still+ # gets True: the field means "a human must approve this", and leaving it False would hide+ # the request from the changelist's "requires approval" filter — on precisely the requests+ # a reviewer needs to find.+ requires_approval = not auto_approve_candidate or bool(request.POST.get("requires_approval"))+ return self._submit_for_approval(request, obj, requires_approval=requires_approval)context = {**self.admin_site.each_context(request),@@ -807,11 +601,43 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"missing_person_drop_flag": missing_person_drop_flag,"is_person_removal": obj.request_type == RequestType.PERSON_REMOVAL,"can_submit": can_submit,+ "auto_approve_candidate": auto_approve_candidate,+ # Thousands separators are applied here — django.contrib.humanize isn't installed.+ "auto_approve_max_events": f"{AUTO_APPROVE_MAX_EVENTS:,}",+ "auto_approve_interval_minutes": AUTO_APPROVE_INTERVAL_MINUTES,"opts": self.model._meta,"title": f"Submit deletion request {obj.pk}",}return TemplateResponse(request, "admin/posthog/datadeletionrequest/submit.html", context)+ def _submit_for_approval(+ self, request: HttpRequest, obj: DataDeletionRequest, *, requires_approval: bool+ ) -> HttpResponse:+ """Move the request draft → pending. Approval is somebody else's job, human or scheduled."""+ updated = DataDeletionRequest.objects.filter(+ pk=obj.pk,+ status=RequestStatus.DRAFT,+ ).update(+ status=RequestStatus.PENDING,+ requires_approval=requires_approval,+ updated_at=timezone.now(),+ )+ if not updated:+ messages.error(request, "Request is no longer in draft status.")+ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))+ obj.refresh_from_db()+ self.log_change(request, obj, "Submitted: status changed from draft to pending.")+ if requires_approval:+ messages.success(request, "Request submitted and is now pending ClickHouse Team approval.")+ else:+ messages.success(+ request,+ f"Request submitted and is now pending. The auto-approval job will check it within the next "+ f"{AUTO_APPROVE_INTERVAL_MINUTES} minutes and approve it if it matches fewer than "+ f"{AUTO_APPROVE_MAX_EVENTS:,} events.",+ )+ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))+def fetch_stats_view(self, request, object_id):obj = self.get_object(request, object_id)if not obj:@@ -830,26 +656,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))try:- stats = fetch_deletion_stats(obj, user_id=request.user.id)- obj.count = stats["count"]- obj.part_count = stats["part_count"]- obj.parts_size = stats["parts_size"]- obj.parts_row_count = stats["parts_row_count"]- obj.min_timestamp = stats["min_timestamp"]- obj.max_timestamp = stats["max_timestamp"]- obj.stats_calculated_at = timezone.now()- obj.save(- update_fields=[- "count",- "part_count",- "parts_size",- "parts_row_count",- "min_timestamp",- "max_timestamp",- "stats_calculated_at",- "updated_at",- ]- )+ stats = refresh_deletion_stats(obj, user_id=request.user.id)self.log_change(request, obj, "Fetched ClickHouse stats.")messages.success(request, f"Stats fetched: {stats['count']:,} matching events found.")except Exception as e:@@ -982,6 +789,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):).update(status=RequestStatus.DRAFT,approved=False,+ approved_automatically=False,approved_by=None,approved_at=None,updated_at=timezone.now(),diff --git a/posthog/admin/test_data_deletion_request_admin.py b/posthog/admin/test_data_deletion_request_admin.pyindex 7ed6f57260f7..4301efeaeae7 100644--- a/posthog/admin/test_data_deletion_request_admin.py+++ b/posthog/admin/test_data_deletion_request_admin.py@@ -312,14 +312,27 @@ class TestDataDeletionRequestAdminSubmitView(BaseTest):status=RequestStatus.DRAFT,)- def _call_submit(self, request: DataDeletionRequest, method: str = "POST"):+ def _call_submit(self, request: DataDeletionRequest, method: str = "POST", data: dict | None = None):path = f"/admin/posthog/datadeletionrequest/{request.pk}/submit/"- http_request = self.factory.post(path) if method == "POST" else self.factory.get(path)+ http_request = self.factory.post(path, data or {}) if method == "POST" else self.factory.get(path)http_request.user = self.user_attach_messages(http_request)with patch("posthog.admin.admins.data_deletion_request_admin.reverse", side_effect=_fake_reverse):return self.admin.submit_view(http_request, str(request.pk))+ def _event_removal_request(self, **kwargs):+ now = timezone.now()+ fields = {+ "team_id": self.team.id,+ "request_type": RequestType.EVENT_REMOVAL,+ "events": ["$pageview"],+ "start_time": now - timedelta(days=7),+ "end_time": now - timedelta(minutes=1),+ "status": RequestStatus.DRAFT,+ **kwargs,+ }+ return DataDeletionRequest.objects.create(**fields)+def test_submit_with_properties_only_succeeds(self):request = self._property_removal_request(properties=["$ip"])response = self._call_submit(request)@@ -370,6 +383,39 @@ class TestDataDeletionRequestAdminSubmitView(BaseTest):self.assertFalse(resp_empty.context_data["can_submit"])self.assertTrue(resp_empty.context_data["missing_properties"])+ @parameterized.expand(+ [+ ("event_removal_opted_in", RequestType.EVENT_REMOVAL, {}, False),+ ("event_removal_opted_out", RequestType.EVENT_REMOVAL, {"requires_approval": "on"}, True),+ # No checkbox is rendered for these, and requires_approval must still say a human is needed —+ # False would hide them from the changelist's "requires approval" filter, on precisely the+ # requests a reviewer has to find.+ ("property_removal", RequestType.PROPERTY_REMOVAL, {}, True),+ ]+ )+ def test_submit_leaves_request_pending_and_records_optout(self, _name, request_type, post_data, expected_flag):+ request = (+ self._event_removal_request()+ if request_type == RequestType.EVENT_REMOVAL+ else self._property_removal_request(properties=["$ip"])+ )++ response = self._call_submit(request, data=post_data)++ self.assertEqual(response.status_code, 302)+ request.refresh_from_db()+ # Submitting never approves — the sweep job owns that decision now.+ self.assertEqual(request.status, RequestStatus.PENDING)+ self.assertFalse(request.approved)+ self.assertEqual(request.requires_approval, expected_flag)++ def test_submit_get_offers_the_optout_only_to_event_removals(self):+ event_removal = self._event_removal_request()+ property_removal = self._property_removal_request(properties=["$ip"])++ self.assertTrue(self._call_submit(event_removal, method="GET").context_data["auto_approve_candidate"])+ self.assertFalse(self._call_submit(property_removal, method="GET").context_data["auto_approve_candidate"])+@freeze_time("2025-01-15 12:00:00")@override_settings(STORAGES={"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}})diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex d06dd7208099..fbdef5826de2 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -27,10 +27,12 @@ from posthog.clickhouse.cluster import AlterTableMutationRunner, ClickhouseClustfrom posthog.dags.common import JobOwnersfrom posthog.dags.deletes import deletes_jobfrom posthog.models.data_deletion_request import (+ AUTO_APPROVE_INTERVAL_MINUTES,DataDeletionRequest,ExecutionMode,RequestStatus,RequestType,+ auto_approve_pending_requests,compile_hogql_predicate,event_match_sql_fragment,event_removal_where,@@ -1468,6 +1470,64 @@ def verify_queued_deletion_requests_job():verify_queued_deletion_requests_op()+# ---------------------------------------------------------------------------+# Auto-approve sweep job: approves pending event removals small enough to skip review+# ---------------------------------------------------------------------------+++class AutoApproveConfig(dagster.Config):+ max_requests: int = pydantic.Field(+ default=50,+ ge=1,+ description="Most requests to evaluate in one tick. Each one costs a pair of ClickHouse "+ "queries, so this bounds what a backlog can spend before the next tick.",+ )++[email protected](tags=OWNER_TAG)+def auto_approve_pending_deletion_requests_op(context: dagster.OpExecutionContext, config: AutoApproveConfig) -> None:+ """Refresh stats on pending auto-approve candidates and approve the ones under the size limit."""+ outcome = auto_approve_pending_requests(max_requests=config.max_requests, on_event=context.log.info)+ context.add_output_metadata(+ {+ "approved": dagster.MetadataValue.int(outcome.approved),+ "skipped": dagster.MetadataValue.int(outcome.skipped),+ "errored": dagster.MetadataValue.int(outcome.errored),+ # Surfaced so a tick that hit the cap reads as truncated rather than as "that was all of them".+ "max_requests": dagster.MetadataValue.int(config.max_requests),+ }+ )+ context.log.info(+ f"auto_approve_pending_deletion_requests: {outcome.approved} approved, "+ f"{outcome.skipped} left pending, {outcome.errored} errored."+ )++[email protected](tags=OWNER_TAG)+def auto_approve_deletion_requests_job():+ """Approve pending event removals that are small enough to skip ClickHouse Team review.++ Stats are refreshed inside the job, immediately before the size decision, so the count it+ approves against is one it measured rather than one a person fetched at an unknown earlier time.+ """+ auto_approve_pending_deletion_requests_op()+++ job=auto_approve_deletion_requests_job,+ cron_schedule=f"*/{AUTO_APPROVE_INTERVAL_MINUTES} * * * *",+ execution_timezone="UTC",+ default_status=dagster.DefaultScheduleStatus.STOPPED,+)+def auto_approve_deletion_requests_schedule():+ """Sweep for auto-approvable pending requests.++ Stopped by default like the rest of this feature's schedules and sensors — an operator turns it on+ in the Dagster UI, and nothing is auto-approved until they do.+ """+ return dagster.RunRequest()++# ---------------------------------------------------------------------------# Verifier sensor: launches the sweep job after each deletes_job SUCCESS# ---------------------------------------------------------------------------diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex e057b7b59fad..272893d765ce 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -50,6 +50,7 @@ defs = dagster.Definitions(data_deletion_requests.data_deletion_request_event_removal,data_deletion_requests.data_deletion_request_property_removal,data_deletion_requests.verify_queued_deletion_requests_job,+ data_deletion_requests.auto_approve_deletion_requests_job,part_breaker.break_oversized_parts,],schedules=[@@ -63,6 +64,7 @@ defs = dagster.Definitions(backups.full_non_sharded_backup_schedule,backups.incremental_non_sharded_backup_schedule,part_breaker.break_oversized_parts_schedule,+ data_deletion_requests.auto_approve_deletion_requests_schedule,],sensors=[deletes.run_deletes_after_squash,diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex ebb19a3f987c..d9cd64697809 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -7,6 +7,8 @@ from uuid import uuid4import pytestfrom unittest.mock import patch+from django.utils import timezone+import dagsterfrom clickhouse_driver import Clientfrom dagster import build_op_context@@ -18,6 +20,8 @@ from posthog.dags.data_deletion_requests import (DeletionRequestContext,PersonRemovalContext,_property_removal_where,+ auto_approve_deletion_requests_job,+ auto_approve_deletion_requests_schedule,data_deletion_request_event_removal,data_deletion_request_person_removal,data_deletion_request_pickup_sensor,@@ -33,7 +37,13 @@ from posthog.dags.data_deletion_requests import (process_property_removal_shard,verify_property_removal,)-from posthog.models.data_deletion_request import DataDeletionRequest, ExecutionMode, RequestStatus, RequestType+from posthog.models.data_deletion_request import (+ DataDeletionRequest,+ ExecutionMode,+ RequestStatus,+ RequestType,+ auto_approve_pending_requests,+)from posthog.test.persons import create_personTEAM_ID = 99999@@ -583,6 +593,163 @@ def test_verify_queued_job_registered_in_clickhouse_location():assert defs.get_job_def("verify_queued_deletion_requests_job") is not None+# ---------------------------------------------------------------------------+# Auto-approve sweep tests+# ---------------------------------------------------------------------------++AUTO_APPROVE_TEAM_ID = 77777+++def _pending_event_removal(**overrides) -> DataDeletionRequest:+ now = datetime.now()+ fields = {+ "team_id": AUTO_APPROVE_TEAM_ID,+ "request_type": RequestType.EVENT_REMOVAL,+ "events": ["$pageview"],+ "start_time": now - timedelta(days=7),+ # Closed range: the sweep won't touch a request that is still collecting events.+ "end_time": now - timedelta(minutes=1),+ "status": RequestStatus.PENDING,+ "requires_approval": False,+ **overrides,+ }+ return DataDeletionRequest.objects.create(**fields)+++def test_auto_approve_job_approves_small_pending_event_removal(cluster: ClickhouseCluster):+ cluster.any_host(_truncate_writable_events).result()+ now = datetime.now()+ events = [(AUTO_APPROVE_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i + 1)) for i in range(3)]+ cluster.any_host(partial(_insert_events, events)).result()+ request = _pending_event_removal()++ result = auto_approve_deletion_requests_job.execute_in_process()+ assert result.success++ request.refresh_from_db()+ assert request.status == RequestStatus.APPROVED+ assert request.approved is True+ assert request.approved_automatically is True+ # No human approved it, so the audit trail must not name one.+ assert request.approved_by is None+ assert request.approved_at is not None+ assert request.execution_mode == ExecutionMode.DEFERRED+ # The job decides against a count it measured itself, and persists it.+ assert request.count == 3+ assert request.stats_calculated_at is not None++ cluster.any_host(_truncate_writable_events).result()+++def test_auto_approve_job_ignores_request_that_opted_out(cluster: ClickhouseCluster):+ cluster.any_host(_truncate_writable_events).result()+ request = _pending_event_removal(requires_approval=True)++ result = auto_approve_deletion_requests_job.execute_in_process()+ assert result.success++ request.refresh_from_db()+ assert request.status == RequestStatus.PENDING+ assert request.approved is False+ # Not even measured: the opt-out is a queryset filter, which is what bounds what a backlog of+ # requests the job can never act on costs in ClickHouse queries.+ assert request.count is None+ assert request.stats_calculated_at is None+++def test_auto_approve_job_leaves_oversized_request_pending_but_refreshes_its_stats(cluster: ClickhouseCluster):+ cluster.any_host(_truncate_writable_events).result()+ now = datetime.now()+ events = [(AUTO_APPROVE_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i + 1)) for i in range(3)]+ cluster.any_host(partial(_insert_events, events)).result()+ request = _pending_event_removal()++ with patch("posthog.models.data_deletion_request.AUTO_APPROVE_MAX_EVENTS", 2):+ result = auto_approve_deletion_requests_job.execute_in_process()+ assert result.success++ request.refresh_from_db()+ assert request.status == RequestStatus.PENDING+ assert request.approved is False+ # Measuring is the job's whole point, so the reviewer inherits a fresh count even when the+ # request is too big to approve.+ assert request.count == 3+ assert request.stats_calculated_at is not None++ cluster.any_host(_truncate_writable_events).result()+++def test_auto_approve_job_skips_a_request_it_cannot_measure(cluster: ClickhouseCluster):+ cluster.any_host(_truncate_writable_events).result()+ now = datetime.now()+ events = [(AUTO_APPROVE_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=1))]+ cluster.any_host(partial(_insert_events, events)).result()+ # A predicate that no longer compiles (the referenced property was dropped, the syntax was+ # hand-edited in the DB) makes the stats fetch raise. It must not take the sweep down with it.+ broken = _pending_event_removal(hogql_predicate="this is not ) valid hogql")+ healthy = _pending_event_removal()++ result = auto_approve_deletion_requests_job.execute_in_process()+ assert result.success++ broken.refresh_from_db()+ healthy.refresh_from_db()+ assert broken.status == RequestStatus.PENDING+ assert healthy.status == RequestStatus.APPROVED++ cluster.any_host(_truncate_writable_events).result()+++def test_auto_approve_sweep_does_not_let_stuck_requests_starve_new_ones(cluster: ClickhouseCluster):+ # A request the sweep can never approve stays PENDING with requires_approval False, so it is a+ # candidate on every tick, forever. Ordered by created_at it holds the front of the queue and a+ # newer request behind it is never even measured.+ cluster.any_host(_truncate_writable_events).result()+ now = datetime.now()+ events = [(AUTO_APPROVE_TEAM_ID, "$pageview", uuid4(), now - timedelta(hours=i + 1)) for i in range(3)]+ cluster.any_host(partial(_insert_events, events)).result()++ stuck = _pending_event_removal()+ newer = _pending_event_removal()+ DataDeletionRequest.objects.filter(pk=stuck.pk).update(created_at=timezone.now() - timedelta(days=1))++ # One slot per tick, and a limit that keeps `stuck` permanently over it.+ with patch("posthog.models.data_deletion_request.AUTO_APPROVE_MAX_EVENTS", 2):+ auto_approve_pending_requests(max_requests=1)+ # Second tick: the slot must go to the request that has never been looked at.+ auto_approve_pending_requests(max_requests=1)++ stuck.refresh_from_db()+ newer.refresh_from_db()+ assert stuck.status == RequestStatus.PENDING+ assert newer.status == RequestStatus.APPROVED++ cluster.any_host(_truncate_writable_events).result()+++def test_auto_approve_job_registered_in_clickhouse_location():+ from posthog.dags.locations.clickhouse import defs++ assert defs.get_job_def("auto_approve_deletion_requests_job") is not None+ assert any(schedule.name == "auto_approve_deletion_requests_schedule" for schedule in defs.schedules or [])+++def test_auto_approve_schedule_launches_a_run_on_tick():+ # A schedule function that returns nothing is registered and cronned exactly like a working one,+ # but Dagster skips every tick ("Schedule function returned an empty result") and the sweep never+ # runs. Nothing else here would notice.+ with dagster.build_schedule_context(scheduled_execution_time=None) as context:+ result = auto_approve_deletion_requests_schedule.evaluate_tick(context)++ assert len(result.run_requests or []) == 1+ assert result.skip_message is None++# ---------------------------------------------------------------------------# Property removal tests# ---------------------------------------------------------------------------diff --git a/posthog/migrations/1257_datadeletionrequest_approved_automatically_and_more.py b/posthog/migrations/1257_datadeletionrequest_approved_automatically_and_more.pynew file mode 100644index 000000000000..5a9702d8593c--- /dev/null+++ b/posthog/migrations/1257_datadeletionrequest_approved_automatically_and_more.py@@ -0,0 +1,28 @@+# Generated by Django 5.2.14 on 2026-07-17 11:16++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1256_userproductlist_default_reason"),+ ]++ operations = [+ migrations.AddField(+ model_name="datadeletionrequest",+ name="approved_automatically",+ field=models.BooleanField(+ default=False,+ help_text="Approved by the auto-approval sweep job rather than a person. approved_by is NULL for these.",+ ),+ ),+ migrations.AlterField(+ model_name="datadeletionrequest",+ name="requires_approval",+ field=models.BooleanField(+ default=True,+ help_text="Force manual ClickHouse Team approval, opting out of auto-approval. ClickHouse deletes are heavyweight mutations that can degrade query performance and increase disk usage while running, so approval ensures they are scheduled during low-traffic windows. Small event_removal requests are cheap enough to skip that review, so the auto-approval sweep job approves them unless this is set. Written by the submit page only.",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 769a17f863de..1f9d749e4cec 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1256_userproductlist_default_reason+1257_datadeletionrequest_approved_automatically_and_morediff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.pyindex b719ca85f88f..d37753fdf1b0 100644--- a/posthog/models/data_deletion_request.py+++ b/posthog/models/data_deletion_request.py@@ -1,9 +1,11 @@+from collections.abc import Callablefrom dataclasses import dataclassfrom django.contrib.postgres.fields import ArrayFieldfrom django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.db import models+from django.db.models import Ffrom django.utils import timezonefrom posthog.models.utils import UUIDModel@@ -341,11 +343,18 @@ class DataDeletionRequest(UUIDModel):# Approval workflowrequires_approval = models.BooleanField(default=True,- help_text="ClickHouse deletes are heavyweight mutations that can degrade query performance "- "and increase disk usage while running. Approval ensures deletes are scheduled "- "during low-traffic windows to avoid impacting production workloads.",+ help_text="Force manual ClickHouse Team approval, opting out of auto-approval. "+ "ClickHouse deletes are heavyweight mutations that can degrade query performance "+ "and increase disk usage while running, so approval ensures they are scheduled "+ "during low-traffic windows. Small event_removal requests are cheap enough to skip "+ "that review, so the auto-approval sweep job approves them unless this is set. "+ "Written by the submit page only.",)approved = models.BooleanField(default=False)+ approved_automatically = models.BooleanField(+ default=False,+ help_text="Approved by the auto-approval sweep job rather than a person. approved_by is NULL for these.",+ )approved_by = models.ForeignKey("posthog.User",on_delete=models.SET_NULL,@@ -487,6 +496,251 @@ class DataDeletionRequest(UUIDModel):raise ValidationError({"person_drop_profiles": "person_drop_* flags are only valid for person_removal."})+def _append_hogql_predicate(fragment: str, params: dict, obj) -> tuple[str, dict]:+ """Append the compiled HogQL predicate (if any) to ``fragment`` and merge params."""+ hogql_sql, hogql_values = cached_compile_hogql_predicate(obj)+ if not hogql_sql:+ return fragment, params+ combined = f"{fragment} AND ({hogql_sql})".strip() if fragment else f"AND ({hogql_sql})"+ params.update(hogql_values)+ return combined, params+++def _build_event_filter(obj) -> tuple[str, dict]:+ """Build the WHERE clause and params for matching events."""+ return _append_hogql_predicate(event_match_sql_fragment(obj), event_match_params(obj), obj)+++def _build_property_filter(obj) -> tuple[str, dict]:+ """Build the WHERE clause addition and params for matching properties.++ Covers both ``events.properties`` (using ``fp_`` param prefix) and+ ``events.person_properties`` (using ``pp_`` param prefix). The two+ presence checks are ORed so the stats count includes every event that+ carries at least one target key in either column.+ """+ event_clause = event_match_sql_fragment(obj)+ params: dict = event_match_params(obj)++ presence_clauses: list[str] = []++ properties = obj.properties or []+ if properties:+ if len(properties) == 1:+ presence_clauses.append(jsonhas_expr(properties[0], "fp_0"))+ else:+ exprs = [jsonhas_expr(prop, f"fp_{i}") for i, prop in enumerate(properties)]+ presence_clauses.append(f"({' OR '.join(exprs)})")+ for i, prop in enumerate(properties):+ for j, part in enumerate(prop.split(".")):+ params[f"fp_{i}_{j}"] = part++ person_properties = obj.person_properties or []+ if person_properties:+ if len(person_properties) == 1:+ presence_clauses.append(jsonhas_expr(person_properties[0], "pp_0", column="person_properties"))+ else:+ exprs = [+ jsonhas_expr(prop, f"pp_{i}", column="person_properties") for i, prop in enumerate(person_properties)+ ]+ presence_clauses.append(f"({' OR '.join(exprs)})")+ for i, prop in enumerate(person_properties):+ for j, part in enumerate(prop.split(".")):+ params[f"pp_{i}_{j}"] = part++ if not presence_clauses:+ raise ValueError("Cannot build property filter: both properties and person_properties are empty.")++ property_clause = (+ f"AND ({' OR '.join(presence_clauses)})" if len(presence_clauses) > 1 else f"AND {presence_clauses[0]}"+ )+ filter_clause = f"{event_clause} {property_clause}".strip()+ return _append_hogql_predicate(filter_clause, params, obj)+++def _event_count_query_template(extra_filter: str) -> str:+ # Counts run against the distributed ``events`` table so operators get a+ # cluster-wide number; the actual deletions still target ``sharded_events``.+ # nosemgrep: clickhouse-fstring-param-audit (extra_filter is built from internal helpers, not user input)+ return f"""+ SELECT+ count() AS events,+ count(DISTINCT _part) AS parts,+ min(timestamp) AS min_ts,+ max(timestamp) AS max_ts+ FROM events+ WHERE team_id = %(team_id)s+ AND timestamp >= %(start_time)s+ AND timestamp < %(end_time)s+ {extra_filter}+ """+++def build_deletion_count_query(obj: "DataDeletionRequest") -> tuple[str, dict]:+ """Return the (SQL template, params) used to count rows matching this request.++ Mirrors ``_fetch_stats`` so admin users can copy the query and run it+ independently — ``substitute_params_for_display`` is the companion renderer.+ """+ if obj.request_type == RequestType.PROPERTY_REMOVAL:+ extra_filter, params = _build_property_filter(obj)+ else:+ extra_filter, params = _build_event_filter(obj)+ return _event_count_query_template(extra_filter), params+++_STATS_MAX_EXECUTION_TIME = 300+++def _fetch_stats(team_id: int, extra_filter: str, params: dict, *, user_id: int | None = None) -> dict:+ """Run event count + parts size queries against ClickHouse.++ The same predicate is spliced into both queries: the row count against the+ Distributed ``events`` proxy, and the parts inspection against the local+ ``sharded_events``. The HogQL predicate emits unqualified column references,+ so it works in both contexts.++ ``user_id`` is threaded into the query tag so the acting staff user is+ visible in ``system.query_log`` (the kill-switch + tag annotator pick it up+ automatically via :class:`QueryTags`). The auto-approval sweep job has no+ acting user and passes None.+ """+ from django.conf import settings as django_settings++ 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++ with tags_context(+ product=Product.INTERNAL,+ feature=Feature.DATA_DELETION,+ team_id=team_id,+ user_id=user_id,+ workload=Workload.OFFLINE,+ query_type="delete_event_count",+ ):+ event_result = sync_execute(+ _event_count_query_template(extra_filter),+ params,+ team_id=team_id,+ readonly=True,+ workload=Workload.OFFLINE,+ ch_user=ClickHouseUser.META,+ settings={"max_execution_time": _STATS_MAX_EXECUTION_TIME},+ )++ with tags_context(+ product=Product.INTERNAL,+ feature=Feature.DATA_DELETION,+ team_id=team_id,+ user_id=user_id,+ workload=Workload.OFFLINE,+ query_type="delete_part_count",+ ):+ cluster = django_settings.CLICKHOUSE_CLUSTER++ # nosemgrep: clickhouse-fstring-param-audit (filter built from internal helpers; cluster from Django settings)+ parts_result = sync_execute(+ f"""+ SELECT+ count() AS part_count,+ sum(p.bytes_on_disk) AS total_size_on_disk,+ sum(p.rows) AS total_rows_in_those_parts+ FROM cluster('{cluster}', system, parts) AS p+ INNER JOIN (+ SELECT DISTINCT _part AS name+ FROM sharded_events+ WHERE team_id = %(team_id)s+ AND timestamp >= %(start_time)s+ AND timestamp < %(end_time)s+ {extra_filter}+ ) AS matched ON p.name = matched.name+ WHERE p.table = 'sharded_events'+ AND p.active+ """,+ params,+ team_id=team_id,+ readonly=True,+ workload=Workload.OFFLINE,+ ch_user=ClickHouseUser.META,+ settings={"max_execution_time": _STATS_MAX_EXECUTION_TIME},+ )++ return {+ "count": event_result[0][0] if event_result else 0,+ "min_timestamp": event_result[0][2] if event_result and event_result[0][0] else None,+ "max_timestamp": event_result[0][3] if event_result and event_result[0][0] else None,+ "part_count": parts_result[0][0] if parts_result else 0,+ "parts_size": parts_result[0][1] if parts_result else 0,+ "parts_row_count": parts_result[0][2] if parts_result else 0,+ }+++def fetch_event_deletion_stats(obj: "DataDeletionRequest", *, user_id: int | None = None) -> dict:+ """Count events and affected parts for an event removal request."""+ extra_filter, params = _build_event_filter(obj)+ return _fetch_stats(obj.team_id, extra_filter, params, user_id=user_id)+++def fetch_property_deletion_stats(obj: "DataDeletionRequest", *, user_id: int | None = None) -> dict:+ """Count events with matching properties and affected parts for a property removal request."""+ if not obj.properties and not obj.person_properties:+ raise ValueError(+ "Cannot fetch stats for a property removal request with no properties or person_properties specified."+ )+ extra_filter, params = _build_property_filter(obj)+ return _fetch_stats(obj.team_id, extra_filter, params, user_id=user_id)+++def fetch_deletion_stats(obj: "DataDeletionRequest", *, user_id: int | None = None) -> dict:+ """Dispatch to the appropriate stats function based on request type."""+ if obj.request_type == RequestType.PROPERTY_REMOVAL:+ return fetch_property_deletion_stats(obj, user_id=user_id)+ return fetch_event_deletion_stats(obj, user_id=user_id)+++# The fields ``_fetch_stats`` populates, in the order the model declares them. Both writers — the+# admin's Fetch stats button and the auto-approval sweep job — save exactly this set, so a new stat+# can't reach one path and silently skip the other.+STATS_FIELDS = (+ "count",+ "part_count",+ "parts_size",+ "parts_row_count",+ "min_timestamp",+ "max_timestamp",+)+++class StaleDeletionRequestError(Exception):+ """The request changed while its stats were being computed, so they were not written."""+++def refresh_deletion_stats(request: "DataDeletionRequest", *, user_id: int | None = None) -> dict:+ """Fetch this request's ClickHouse stats and persist them onto the row.++ The counting query takes seconds to minutes, and the write is guarded on ``updated_at`` for that+ window. Changing a request's criteria clears its stats precisely because the old numbers no longer+ describe it, so writing ours back over that edit would resurrect a count for criteria nobody+ measured — one a reviewer could then approve against. Every write to the row bumps ``updated_at``+ (``auto_now``), so a mismatch means the request moved and this fetch is void.+ """+ stats = fetch_deletion_stats(request, user_id=user_id)+ now = timezone.now()+ updated = DataDeletionRequest.objects.filter(pk=request.pk, updated_at=request.updated_at).update(+ stats_calculated_at=now,+ updated_at=now,+ **{field: stats[field] for field in STATS_FIELDS},+ )+ if not updated:+ raise StaleDeletionRequestError(+ f"Deletion request {request.pk} changed while its stats were being computed. Try again."+ )+ request.refresh_from_db()+ return stats++def count_remaining_matching_events(request: "DataDeletionRequest") -> int:"""Count events still matching an event-removal request's criteria in ClickHouse.@@ -683,3 +937,111 @@ def verify_queued_request(request: "DataDeletionRequest") -> VerifyOutcome:status=RequestStatus.COMPLETED, updated_at=timezone.now())return VerifyOutcome(remaining=remaining, promoted=bool(promoted))+++# An event removal below this many events is cheap enough that a dedicated ClickHouse Team review buys+# nothing. The sweep job approves it instead, always deferred so the scheduled deletes_job drains it+# alongside everything else rather than running a mutation of its own.+AUTO_APPROVE_MAX_EVENTS = 100_000+# How often the sweep job runs. Lives here rather than beside the schedule so the admin can tell an+# operator how long their request will sit before it's looked at, without the two drifting apart.+AUTO_APPROVE_INTERVAL_MINUTES = 30+++def auto_approve_blocker(request: "DataDeletionRequest") -> str | None:+ """Why this pending request can't be auto-approved, or None when it can.++ Called by the sweep job immediately after it refreshes the request's stats, so ``count`` is+ current by construction — there is no staleness to defend against here.++ ``requires_approval`` and ``status`` are deliberately not checked: they narrow which requests the+ job considers at all (a queryset filter) and guard the write (a status-guarded update), rather+ than describing whether this request is small enough to skip review.+ """+ if request.request_type != RequestType.EVENT_REMOVAL:+ return (+ f"only event removal requests can be auto-approved, and this is a "+ f"{request.get_request_type_display().lower()} request"+ )+ # A range that hasn't closed keeps matching newly ingested events, so a count taken now says+ # nothing about how much the deferred job will actually delete when it drains later.+ if request.end_time is None or request.end_time > timezone.now():+ return "its time range has not closed yet, so matching events are still arriving"+ if request.count is None:+ return "the stats refresh produced no matching event count"+ if request.count >= AUTO_APPROVE_MAX_EVENTS:+ return f"{request.count:,} matching events is at or above the {AUTO_APPROVE_MAX_EVENTS:,} limit"+ return None+++@dataclass+class AutoApproveOutcome:+ approved: int+ skipped: int+ errored: int+++def auto_approve_pending_requests(+ *,+ max_requests: int,+ on_event: Callable[[str], None] | None = None,+) -> AutoApproveOutcome:+ """Refresh stats on pending auto-approve candidates and approve the ones that qualify.++ Candidates are pending event removals whose submitter didn't opt out. Each one's ClickHouse stats+ are refreshed first, so the size decision is made against a count measured moments earlier rather+ than whatever a person fetched at some unknown past time.++ A failure on one request is reported and skipped rather than raised: one unparseable predicate or+ timed-out count must not stop the other candidates in the same sweep. ``on_event`` receives a+ human-readable line per request for the caller to log.+ """+ log = on_event or (lambda _message: None)+ # Least-recently-measured first, never-measured before that. A request the sweep can't approve —+ # over the limit, range still open, predicate that won't compile — stays pending and stays a+ # candidate forever, so ordering by age would park it at the front of every tick and starve the+ # requests behind it. Ordering by the measurement instead means taking a slot costs you your place.+ candidates = DataDeletionRequest.objects.filter(+ status=RequestStatus.PENDING,+ request_type=RequestType.EVENT_REMOVAL,+ requires_approval=False,+ ).order_by(F("stats_calculated_at").asc(nulls_first=True), "created_at")[:max_requests]++ approved = skipped = errored = 0+ for request in candidates:+ try:+ refresh_deletion_stats(request)+ except Exception as exc:+ errored += 1+ log(f"Request {request.pk}: could not refresh stats, leaving pending: {exc}")+ continue++ blocker = auto_approve_blocker(request)+ if blocker is not None:+ skipped += 1+ log(f"Request {request.pk}: left pending for review because {blocker}.")+ continue++ # Guarded on the same conditions that selected the request. A concurrent criteria edit resets+ # it to DRAFT and clears its stats, so this is what stops the sweep approving criteria whose+ # count no longer describes them.+ updated = DataDeletionRequest.objects.filter(+ pk=request.pk,+ status=RequestStatus.PENDING,+ requires_approval=False,+ ).update(+ status=RequestStatus.APPROVED,+ approved=True,+ approved_automatically=True,+ approved_at=timezone.now(),+ execution_mode=ExecutionMode.DEFERRED,+ updated_at=timezone.now(),+ )+ if not updated:+ skipped += 1+ log(f"Request {request.pk}: changed while being evaluated, left alone.")+ continue+ approved += 1+ log(f"Request {request.pk}: auto-approved (deferred), {request.count:,} matching events.")++ return AutoApproveOutcome(approved=approved, skipped=skipped, errored=errored)diff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.pyindex c2bc2b620a73..e9b390f0d5f4 100644--- a/posthog/models/test/test_data_deletion_request.py+++ b/posthog/models/test/test_data_deletion_request.py@@ -1,6 +1,6 @@import uuid as uuid_libfrom collections.abc import Callable-from datetime import datetime, timedelta+from datetime import UTC, datetime, timedeltaimport pytestfrom freezegun import freeze_time@@ -8,11 +8,14 @@ from unittest.mock import patchfrom django.core.exceptions import ValidationErrorfrom django.test import override_settings+from django.utils import timezonefrom posthog.models import data_deletion_request as ddrfrom posthog.models.data_deletion_request import (DataDeletionRequest,+ RequestStatus,RequestType,+ auto_approve_blocker,cached_compile_hogql_predicate,invalidate_compiled_predicate_cache,)@@ -594,3 +597,76 @@ def test_cached_compile_hogql_predicate_blank_predicate_skips_compile():request = DataDeletionRequest(**_base_kwargs(events=["$pageview"], hogql_predicate=""))with patch.object(ddr, "compile_hogql_predicate", side_effect=AssertionError("should not compile")):assert cached_compile_hogql_predicate(request) == ("", {})+++@freeze_time("2026-06-17T12:00:00Z")+ "overrides,expected_fragment",+ [+ ({}, None),+ ({"request_type": RequestType.PROPERTY_REMOVAL}, "event removal"),+ ({"request_type": RequestType.PERSON_REMOVAL}, "event removal"),+ ({"end_time": None}, "has not closed"),+ # An open range keeps matching newly ingested events, so a count taken now can't bound what+ # the deferred drain deletes when it runs later.+ ({"end_time": datetime(2026, 6, 18, tzinfo=UTC)}, "has not closed"),+ ({"count": None}, "no matching event count"),+ ({"count": 100_000}, "at or above"),+ ({"count": 200_000}, "at or above"),+ ],+)+def test_auto_approve_blocker(overrides, expected_fragment):+ fields = {+ "team_id": TEAM_ID,+ "request_type": RequestType.EVENT_REMOVAL,+ "events": ["$pageview"],+ "start_time": datetime(2026, 6, 10, tzinfo=UTC),+ "end_time": datetime(2026, 6, 16, tzinfo=UTC),+ "status": RequestStatus.PENDING,+ "count": 1_000,+ **overrides,+ }+ blocker = auto_approve_blocker(DataDeletionRequest(**fields))+ if expected_fragment is None:+ assert blocker is None+ else:+ assert blocker is not None+ assert expected_fragment in blocker+++def test_refresh_deletion_stats_does_not_write_over_a_concurrent_criteria_edit(team):+ request = DataDeletionRequest.objects.create(+ team_id=team.id,+ request_type=RequestType.EVENT_REMOVAL,+ events=["$pageview"],+ start_time=datetime(2026, 6, 10, tzinfo=UTC),+ end_time=datetime(2026, 6, 16, tzinfo=UTC),+ status=RequestStatus.PENDING,+ )+ stale = DataDeletionRequest.objects.get(pk=request.pk)+ # Another operator broadens the criteria while the count is running. Saving that clears the stats,+ # because the numbers no longer describe the request.+ DataDeletionRequest.objects.filter(pk=request.pk).update(+ delete_all_events=True,+ events=[],+ count=None,+ stats_calculated_at=None,+ status=RequestStatus.DRAFT,+ updated_at=timezone.now(),+ )+ counted = {+ "count": 42,+ "part_count": 1,+ "parts_size": 1,+ "parts_row_count": 42,+ "min_timestamp": None,+ "max_timestamp": None,+ }++ with patch.object(ddr, "fetch_deletion_stats", return_value=counted):+ with pytest.raises(ddr.StaleDeletionRequestError):+ ddr.refresh_deletion_stats(stale)++ request.refresh_from_db()+ assert request.count is None+ assert request.stats_calculated_at is Nonediff --git a/posthog/templates/admin/posthog/datadeletionrequest/submit.html b/posthog/templates/admin/posthog/datadeletionrequest/submit.htmlindex 98f31652a55d..224dd9d231fd 100644--- a/posthog/templates/admin/posthog/datadeletionrequest/submit.html+++ b/posthog/templates/admin/posthog/datadeletionrequest/submit.html@@ -74,8 +74,7 @@<tr><th style="text-align: left; padding: 8px; border-bottom: 1px solid #ddd; vertical-align: top;">Notes</th><td style="padding: 8px; border-bottom: 1px solid #ddd;">{{ obj.notes }}</td></tr>{% endif %}<tr><th style="text-align: left; padding: 8px; border-bottom: 1px solid #ddd;">Created by</th><td style="padding: 8px; border-bottom: 1px solid #ddd;">{{ obj.created_by|default:"—" }}</td></tr>- <tr><th style="text-align: left; padding: 8px; border-bottom: 1px solid #ddd;">Created at</th><td style="padding: 8px; border-bottom: 1px solid #ddd;">{{ obj.created_at }}</td></tr>- <tr><th style="text-align: left; padding: 8px;">Requires approval</th><td style="padding: 8px;">{{ obj.requires_approval|yesno:"Yes,No" }}</td></tr>+ <tr><th style="text-align: left; padding: 8px;">Created at</th><td style="padding: 8px;">{{ obj.created_at }}</td></tr></table>{% if missing_properties %}@@ -94,8 +93,35 @@</div>{% endif %}+{% if can_submit %}+ {% if auto_approve_candidate %}+ <div style="margin: 16px 0; padding: 12px 16px; border: 1px solid #f0ad4e; border-radius: 4px; background: #fcf8e3; color: #8a6d3b;">+ <strong>This request may be approved automatically.</strong>+ A job checks pending event removals every {{ auto_approve_interval_minutes }} minutes. It refreshes the+ ClickHouse stats, and if the request+ matches fewer than {{ auto_approve_max_events }} events and its time range has already ended, it approves the+ request and queues it for the scheduled deletes job. Anything larger, or still collecting events, waits for the+ ClickHouse Team.+ </div>+ {% else %}+ <p style="margin: 16px 0; color: #666;">+ Only event removal requests can be approved automatically. This is a+ {{ obj.get_request_type_display|lower }} request, so submitting sends it to the ClickHouse Team for manual+ approval.+ </p>+ {% endif %}+{% endif %}+<form method="post">{% csrf_token %}+ {% if can_submit and auto_approve_candidate %}+ <div style="margin-top: 16px;">+ <label>+ <input type="checkbox" name="requires_approval" />+ Do not auto-approve. Send this to the ClickHouse Team for manual review instead.+ </label>+ </div>+ {% endif %}<div style="margin-top: 20px; display: flex; gap: 10px; align-items: center;"><input type="submit" value="Confirm & Submit" class="default" style="padding: 10px 15px;"{% if not can_submit %} disabled{% endif %} /><a href="{% url 'admin:posthog_datadeletionrequest_change' obj.pk %}" style="padding: 10px 15px;">Back</a>