Skip to content

: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.

fix(data-deletion): compile predicate like a regular HogQL query (#64250)

Paweł Szczur938b219499d1
diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.py
index eca3d8663b71..47321ff63829 100644
--- a/posthog/models/data_deletion_request.py
+++ b/posthog/models/data_deletion_request.py
@@ -42,10 +42,15 @@ 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.schema import PersonsOnEventsMode
+
from posthog.hogql.context import HogQLContext
from posthog.hogql.hogql import translate_hogql
+ from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr
+ from posthog.models.team import Team
+
try:
parse_expr(predicate)
except Exception as exc:
@@ -61,7 +66,32 @@ def compile_hogql_predicate(obj) -> tuple[str, dict]:
# ``within_non_hogql_query=True`` instructs the printer to emit unqualified column
# 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)
+ #
+ # Resolve the team's modifiers (``propertyGroupsMode`` et al.) so the predicate compiles
+ # like a regular HogQL query. Without them the property-group optimizer is off, and a typed
+ # property comparison such as ``person.properties.isEnterprise = 'yes'`` falls back to a
+ # coerced JSONExtract that casts the value to Bool — turning the stored string into NULL so
+ # the predicate silently matches nothing. With them it becomes the index-eligible
+ # ``person_properties_map_custom['isEnterprise'] = 'yes'`` map read.
+ #
+ # Force on-events person resolution regardless of the team's general query default: the
+ # fragment is spliced bare into the ``events`` SELECT and the ``sharded_events`` DELETE, so
+ # ``person.properties`` must read the on-events ``person_properties`` column — a joined
+ # persons table (the ``..._joined`` / ``disabled`` modes) would reference an alias that does
+ # not exist in either splice site.
+ try:
+ team = Team.objects.get(id=obj.team_id)
+ except Team.DoesNotExist as exc:
+ raise ValidationError({"hogql_predicate": "team no longer exists; cannot validate the predicate."}) from exc
+ modifiers = create_default_modifiers_for_team(team)
+ modifiers.personsOnEventsMode = PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
+ context = HogQLContext(
+ team_id=obj.team_id,
+ team=team,
+ modifiers=modifiers,
+ 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.py
index 41a4155c5708..d3f446d9a173 100644
--- a/posthog/models/test/test_data_deletion_request.py
+++ b/posthog/models/test/test_data_deletion_request.py
@@ -2,6 +2,7 @@ import uuid as uuid_lib
from datetime import datetime, timedelta
import pytest
+from freezegun import freeze_time
from django.core.exceptions import ValidationError
@@ -218,6 +219,55 @@ def test_compile_hogql_predicate_emits_unqualified_materialized_column(team, sna
assert sql == snapshot
+def test_compile_hogql_predicate_missing_team_raises_validation_error(db):
+ """If the team no longer exists, compilation must raise ``ValidationError`` (not
+ ``Team.DoesNotExist``) so ``Model.clean()`` callers keep their contract.
+ """
+ from posthog.models.data_deletion_request import compile_hogql_predicate
+
+ request = DataDeletionRequest(
+ **_base_kwargs(team_id=2**31 - 1, events=["$pageview"], hogql_predicate="properties.$browser = 'Chrome'")
+ )
+ with pytest.raises(ValidationError, match="team no longer exists"):
+ compile_hogql_predicate(request)
+
+
+@freeze_time("2026-06-17T12:00:00Z")
+def test_compile_hogql_predicate_boolean_person_property_not_coerced(team):
+ """A boolean-typed person property compared to a non-``true``/``false`` string must not be
+ coerced to Bool. The coercion (``accurateCastOrNull(transform(...), 'Bool')``) maps the
+ stored value to NULL, so ``person.properties.isEnterprise = 'yes'`` would silently match
+ nothing. Compiling with the team's modifiers routes it through the property-group map read
+ instead, exactly as a regular HogQL query would.
+ """
+ from posthog.models.data_deletion_request import compile_hogql_predicate
+
+ from products.event_definitions.backend.models import PropertyDefinition
+
+ team.modifiers = {"propertyGroupsMode": "optimized"}
+ team.save()
+
+ PropertyDefinition.objects.create(
+ team=team,
+ name="isEnterprise",
+ type=PropertyDefinition.Type.PERSON,
+ property_type="Boolean",
+ )
+
+ request = DataDeletionRequest(
+ **_base_kwargs(
+ team_id=team.id,
+ events=["$pageview"],
+ hogql_predicate="person.properties.isEnterprise = 'yes'",
+ )
+ )
+ sql, _ = compile_hogql_predicate(request)
+
+ assert "person_properties_map_custom" in sql
+ assert "accurateCastOrNull" not in sql
+ assert "transform(" not in sql
+
+
def test_rendered_count_query_substitutes_parameters():
from posthog.admin.admins.data_deletion_request_admin import build_deletion_count_query
from posthog.clickhouse.client.escape import substitute_params_for_display