: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
chore(data-deletion): bound stats queries, allow predicate subqueries, add ephemeral preview button (#60020)
Paweł Szczur6013e2c71e67
diff --git a/posthog/admin/admins/data_deletion_request_admin.py b/posthog/admin/admins/data_deletion_request_admin.pyindex 7d16a8638fd6..8fdb3f4aa030 100644--- a/posthog/admin/admins/data_deletion_request_admin.py+++ b/posthog/admin/admins/data_deletion_request_admin.py@@ -277,13 +277,20 @@ def build_deletion_count_query(obj: DataDeletionRequest) -> tuple[str, dict]:return _event_count_query_template(extra_filter), params-def _fetch_stats(team_id: int, extra_filter: str, params: dict) -> dict:+_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 theDistributed ``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@@ -291,6 +298,7 @@ def _fetch_stats(team_id: int, extra_filter: str, params: dict) -> dict:product=Product.INTERNAL,feature=Feature.DATA_DELETION,team_id=team_id,+ user_id=user_id,workload=Workload.OFFLINE,query_type="delete_event_count",):@@ -301,12 +309,14 @@ def _fetch_stats(team_id: int, extra_filter: str, params: dict) -> dict: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",):@@ -338,6 +348,7 @@ def _fetch_stats(team_id: int, extra_filter: str, params: dict) -> dict:readonly=True,workload=Workload.OFFLINE,ch_user=ClickHouseUser.META,+ settings={"max_execution_time": _STATS_MAX_EXECUTION_TIME},)return {@@ -350,27 +361,27 @@ def _fetch_stats(team_id: int, extra_filter: str, params: dict) -> dict:}-def fetch_event_deletion_stats(obj: DataDeletionRequest):+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)+ return _fetch_stats(obj.team_id, extra_filter, params, user_id=user_id)-def fetch_property_deletion_stats(obj: DataDeletionRequest):+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)+ return _fetch_stats(obj.team_id, extra_filter, params, user_id=user_id)-def fetch_deletion_stats(obj: DataDeletionRequest):+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)- return fetch_event_deletion_stats(obj)+ return fetch_property_deletion_stats(obj, user_id=user_id)+ return fetch_event_deletion_stats(obj, user_id=user_id)@admin.register(DataDeletionRequest)@@ -598,6 +609,11 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):self.admin_site.admin_view(self.fetch_stats_view),name="posthog_datadeletionrequest_fetch_stats",),+ path(+ "<path:object_id>/preview-stats/",+ self.admin_site.admin_view(self.preview_stats_view),+ name="posthog_datadeletionrequest_preview_stats",+ ),path("<path:object_id>/approve/",self.admin_site.admin_view(self.approve_view),@@ -670,6 +686,12 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):messages.success(request, "Request submitted and is now pending.")return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_change", args=[obj.pk]))+ is_clickhouse_team = request.user.groups.filter(name=CLICKHOUSE_TEAM_GROUP).exists()+ preview_stats = request.session.pop("data_deletion_preview_stats", None)+ if preview_stats and str(preview_stats.get("obj_pk")) != str(obj.pk):+ # Belongs to a different request — drop it rather than mislead the operator.+ preview_stats = None+context = {**self.admin_site.each_context(request),"obj": obj,@@ -679,6 +701,9 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):"is_person_removal": obj.request_type == RequestType.PERSON_REMOVAL,"can_submit": can_submit,"fetch_stats_url": reverse("admin:posthog_datadeletionrequest_fetch_stats", args=[obj.pk]),+ "preview_stats_url": reverse("admin:posthog_datadeletionrequest_preview_stats", args=[obj.pk]),+ "is_clickhouse_team": is_clickhouse_team,+ "preview_stats": preview_stats,"opts": self.model._meta,"title": f"Submit deletion request {obj.pk}",}@@ -702,7 +727,7 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_submit", args=[obj.pk]))try:- stats = fetch_deletion_stats(obj)+ 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"]@@ -729,6 +754,56 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_submit", args=[obj.pk]))+ def preview_stats_view(self, request, object_id):+ """ClickHouse-Team-only ephemeral stats run.++ Runs the same ClickHouse queries as ``fetch_stats_view`` but does **not**+ persist anything to the model — useful while iterating on a predicate.+ Results are stashed in the session and rendered on the next submit page+ render under a separate "Preview (not saved)" block.+ """+ obj = self.get_object(request, object_id)+ if not obj:+ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_changelist"))++ if not request.user.groups.filter(name=CLICKHOUSE_TEAM_GROUP).exists():+ messages.error(request, "Only ClickHouse Team members can preview stats.")+ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_submit", args=[obj.pk]))++ if request.method != "POST":+ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_submit", args=[obj.pk]))++ if obj.request_type == RequestType.PERSON_REMOVAL:+ count = len(obj.person_uuids) + len(obj.person_distinct_ids)+ request.session["data_deletion_preview_stats"] = {+ "obj_pk": str(obj.pk),+ "count": count,+ "calculated_at": timezone.now().isoformat(),+ }+ messages.info(request, f"Preview selector count: {count} person target(s). Not saved.")+ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_submit", args=[obj.pk]))++ try:+ stats = fetch_deletion_stats(obj, user_id=request.user.id)+ request.session["data_deletion_preview_stats"] = {+ "obj_pk": str(obj.pk),+ "count": stats["count"],+ "part_count": stats["part_count"],+ "parts_size": stats["parts_size"],+ "parts_row_count": stats["parts_row_count"],+ "min_timestamp": stats["min_timestamp"].isoformat() if stats["min_timestamp"] else None,+ "max_timestamp": stats["max_timestamp"].isoformat() if stats["max_timestamp"] else None,+ "calculated_at": timezone.now().isoformat(),+ }+ messages.info(+ request,+ f"Preview stats: {stats['count']:,} matching events. Not saved to the request.",+ )+ except Exception as e:+ messages.error(request, f"Failed to preview stats: {e}")++ return HttpResponseRedirect(reverse("admin:posthog_datadeletionrequest_submit", args=[obj.pk]))+def approve_view(self, request, object_id):obj = self.get_object(request, object_id)if not obj:diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.pyindex 81fcea49e7c2..42d5879ca2a3 100644--- a/posthog/models/data_deletion_request.py+++ b/posthog/models/data_deletion_request.py@@ -40,32 +40,26 @@ def compile_hogql_predicate(obj) -> tuple[str, dict]:# Imported lazily: HogQL pulls in the full schema graph, which we don't want# to load for every model import (admin registration, migrations, etc.).- from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.hogql import translate_hogqlfrom posthog.hogql.parser import parse_expr- from posthog.hogql.visitor import TraversingVisitor-- class _RejectSubqueries(TraversingVisitor):- def visit_select_query(self, node: ast.SelectQuery) -> None:- raise ValidationError({"hogql_predicate": "Subqueries are not allowed in a data deletion predicate."})-- def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:- raise ValidationError({"hogql_predicate": "Subqueries are not allowed in a data deletion predicate."})try:- parsed = parse_expr(predicate)+ parse_expr(predicate)except Exception as exc:raise ValidationError({"hogql_predicate": f"Could not parse HogQL: {exc}"}) from exc- _RejectSubqueries().visit(parsed)-if obj.team_id is None:raise ValidationError({"hogql_predicate": "team_id must be set before validating the predicate."})+ # Subqueries are allowed (e.g. ``person_id IN (SELECT id FROM persons WHERE …)``).+ # HogQL's table resolver injects ``team_id`` guards into each referenced table,+ # so cross-team data cannot leak through a subquery — the team-scoping test+ # in test_data_deletion_request.py is the regression net for that invariant.# ``within_non_hogql_query=True`` instructs the printer to emit unqualified column- # references — both for regular fields and for materialized-column shortcuts.- context = HogQLContext(team_id=obj.team_id, within_non_hogql_query=True, enable_select_queries=False)+ # references for the outer expression so the fragment splices into both the+ # Distributed ``events`` SELECT and the ``sharded_events`` DELETE mutation.+ context = HogQLContext(team_id=obj.team_id, within_non_hogql_query=True, enable_select_queries=True)try:sql = translate_hogql(predicate, context, dialect="clickhouse")except Exception as exc:diff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.pyindex d1aeb7e64e57..41a4155c5708 100644--- a/posthog/models/test/test_data_deletion_request.py+++ b/posthog/models/test/test_data_deletion_request.py@@ -74,9 +74,9 @@ def test_non_event_removal_cannot_set_delete_all_events():("", None),("this is not hogql", "hogql_predicate"),("nonexistent_column = 1", "hogql_predicate"),- ("event IN (SELECT event FROM events)", "Subqueries"),+ ("event IN (SELECT event FROM events)", None),],- ids=["valid", "blank", "invalid_syntax", "unknown_field", "subquery"],+ ids=["valid", "blank", "invalid_syntax", "unknown_field", "subquery_allowed"],)def test_hogql_predicate_validation(team, predicate, error_match):request = DataDeletionRequest(@@ -89,6 +89,62 @@ def test_hogql_predicate_validation(team, predicate, error_match):request.clean()+ "predicate",+ [+ "person_id IN (SELECT id FROM persons WHERE properties.email = '[email protected]')",+ "event IN (SELECT event FROM events WHERE timestamp > now() - INTERVAL 1 DAY)",+ ],+ ids=["person_subquery", "events_subquery"],+)+def test_hogql_predicate_allows_subqueries(team, predicate):+ """Subqueries against persons / events / cohorts are allowed in deletion predicates.++ HogQL's table resolver injects the ``team_id`` guard into each subquery, so+ cross-team data cannot leak through; the team-scoping test below is the+ regression net for that invariant.+ """+ from posthog.models.data_deletion_request import compile_hogql_predicate++ request = DataDeletionRequest(+ **_base_kwargs(team_id=team.id, events=["$pageview"], hogql_predicate=predicate),+ )+ request.clean()+ sql, _ = compile_hogql_predicate(request)+ assert sql+++def test_hogql_predicate_subquery_is_team_scoped(db):+ """Compiling the same person-subquery predicate for two different teams must+ splice each team's id into the inner WHERE clause — that's how HogQL prevents+ cross-team leaks via subqueries.+ """+ from posthog.models.data_deletion_request import compile_hogql_predicate++ org = Organization.objects.create(name="scoping-org")+ team_a = Team.objects.create(organization=org, name="team-a")+ team_b = Team.objects.create(organization=org, name="team-b")+ assert team_a.id != team_b.id++ predicate = "person_id IN (SELECT id FROM persons WHERE properties.email = '[email protected]')"++ req_a = DataDeletionRequest(**_base_kwargs(team_id=team_a.id, events=["$pageview"], hogql_predicate=predicate))+ req_b = DataDeletionRequest(**_base_kwargs(team_id=team_b.id, events=["$pageview"], hogql_predicate=predicate))++ sql_a, _ = compile_hogql_predicate(req_a)+ sql_b, _ = compile_hogql_predicate(req_b)++ # HogQL inlines ``team_id`` as a literal int (not a parameter), so the bare+ # team id appears directly in the SQL. Confirm each team's id shows up in+ # its own SQL but not in the other's, and the standard ``equals(team_id, …)``+ # guard shape is present — that's HogQL's table resolver wrapping the+ # ``persons`` subquery with the team scope.+ assert f"equals(team_id, {team_a.id})" in sql_a+ assert f"equals(team_id, {team_b.id})" in sql_b+ assert f"equals(team_id, {team_b.id})" not in sql_a+ assert f"equals(team_id, {team_a.id})" not in sql_b++def test_compile_hogql_predicate_returns_sql_and_values(team):from posthog.models.data_deletion_request import compile_hogql_predicatediff --git a/posthog/templates/admin/posthog/datadeletionrequest/submit.html b/posthog/templates/admin/posthog/datadeletionrequest/submit.htmlindex 76bf76067d15..17c128e565d5 100644--- a/posthog/templates/admin/posthog/datadeletionrequest/submit.html+++ b/posthog/templates/admin/posthog/datadeletionrequest/submit.html@@ -93,11 +93,34 @@{% else %}<p style="color: #666; margin: 4px 0;">No stats have been fetched yet.</p>{% endif %}- <form method="post" action="{{ fetch_stats_url }}" style="margin-top: 12px;">+ <form method="post" action="{{ fetch_stats_url }}" style="margin-top: 12px; display: inline-block;">{% csrf_token %}<input type="submit" value="{% if obj.stats_calculated_at %}Refresh stats{% else %}Fetch stats{% endif %}" style="padding: 8px 14px;" /></form>+ {% if is_clickhouse_team %}+ <form method="post" action="{{ preview_stats_url }}" style="margin-top: 12px; display: inline-block; margin-left: 8px;">+ {% csrf_token %}+ <input type="submit" value="Show stats now (don't save)" style="padding: 8px 14px;" />+ </form>+ {% endif %}+</fieldset>++{% if preview_stats %}+<fieldset style="margin: 20px 0; padding: 16px; border: 1px dashed #0c5460; border-radius: 4px; background: #d1ecf1; color: #0c5460;">+ <legend style="font-weight: bold; padding: 0 8px;">Preview (not saved)</legend>+ <table style="border-collapse: collapse; width: 100%;">+ <tr><th style="text-align: left; padding: 6px 8px; border-bottom: 1px solid #bee5eb;">Matching events</th><td style="padding: 6px 8px; border-bottom: 1px solid #bee5eb;">{{ preview_stats.count|default:"0" }}</td></tr>+ {% if preview_stats.min_timestamp is not None %}+ <tr><th style="text-align: left; padding: 6px 8px; border-bottom: 1px solid #bee5eb;">Min timestamp</th><td style="padding: 6px 8px; border-bottom: 1px solid #bee5eb;">{{ preview_stats.min_timestamp|default:"—" }}</td></tr>+ <tr><th style="text-align: left; padding: 6px 8px; border-bottom: 1px solid #bee5eb;">Max timestamp</th><td style="padding: 6px 8px; border-bottom: 1px solid #bee5eb;">{{ preview_stats.max_timestamp|default:"—" }}</td></tr>+ <tr><th style="text-align: left; padding: 6px 8px; border-bottom: 1px solid #bee5eb;">Part count</th><td style="padding: 6px 8px; border-bottom: 1px solid #bee5eb;">{{ preview_stats.part_count|default:"0" }}</td></tr>+ <tr><th style="text-align: left; padding: 6px 8px; border-bottom: 1px solid #bee5eb;">Parts size</th><td style="padding: 6px 8px; border-bottom: 1px solid #bee5eb;">{{ preview_stats.parts_size|default:"0" }} bytes</td></tr>+ <tr><th style="text-align: left; padding: 6px 8px; border-bottom: 1px solid #bee5eb;">Total rows in affected parts</th><td style="padding: 6px 8px; border-bottom: 1px solid #bee5eb;">{{ preview_stats.parts_row_count|default:"0" }}</td></tr>+ {% endif %}+ <tr><th style="text-align: left; padding: 6px 8px;">Previewed at</th><td style="padding: 6px 8px;">{{ preview_stats.calculated_at }}</td></tr>+ </table></fieldset>+{% endif %}{% if missing_properties %}<div style="margin: 16px 0; padding: 12px 16px; border: 1px solid #dc3545; border-radius: 4px; background: #f8d7da; color: #721c24;">