:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-deletion): drop table qualifier on materialized columns in HogQL predicates (#57554)
Paweł Szczurdeef3b1b430b
diff --git a/posthog/admin/admins/data_deletion_request_admin.py b/posthog/admin/admins/data_deletion_request_admin.pyindex dbc24627ad0a..12e0f8a59cf6 100644--- a/posthog/admin/admins/data_deletion_request_admin.py+++ b/posthog/admin/admins/data_deletion_request_admin.py@@ -178,9 +178,9 @@ class DataDeletionRequestForm(forms.ModelForm):fields = "__all__"-def _append_hogql_predicate(fragment: str, params: dict, obj, *, target_data_table: bool) -> tuple[str, dict]:+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 = compile_hogql_predicate(obj, target_data_table=target_data_table)+ hogql_sql, hogql_values = compile_hogql_predicate(obj)if not hogql_sql:return fragment, paramscombined = f"{fragment} AND ({hogql_sql})".strip() if fragment else f"AND ({hogql_sql})"@@ -188,14 +188,12 @@ def _append_hogql_predicate(fragment: str, params: dict, obj, *, target_data_tabreturn combined, params-def _build_event_filter(obj, *, target_data_table: bool = False) -> tuple[str, dict]:+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, target_data_table=target_data_table- )+ return _append_hogql_predicate(event_match_sql_fragment(obj), event_match_params(obj), obj)-def _build_property_filter(obj, *, target_data_table: bool = False) -> tuple[str, dict]:+def _build_property_filter(obj) -> tuple[str, dict]:"""Build the WHERE clause addition and params for matching properties."""event_clause = event_match_sql_fragment(obj)params: dict = event_match_params(obj)@@ -211,7 +209,7 @@ def _build_property_filter(obj, *, target_data_table: bool = False) -> tuple[strparams[f"fp_{i}_{j}"] = partfilter_clause = f"{event_clause} {property_clause}".strip()- return _append_hogql_predicate(filter_clause, params, obj, target_data_table=target_data_table)+ return _append_hogql_predicate(filter_clause, params, obj)def _event_count_query_template(extra_filter: str) -> str:@@ -245,18 +243,13 @@ def build_deletion_count_query(obj: DataDeletionRequest) -> tuple[str, dict]:return _event_count_query_template(extra_filter), params-def _fetch_stats(- team_id: int,- events_filter: str,- events_params: dict,- sharded_filter: str,- sharded_params: dict,-) -> dict:+def _fetch_stats(team_id: int, extra_filter: str, params: dict) -> dict:"""Run event count + parts size queries against ClickHouse.- The two filters share the same ``hogql_val_*`` keys but are qualified for- their respective tables (``events`` vs ``sharded_events``), so any- materialized-column references resolve correctly in each query.+ 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."""from posthog.clickhouse.client import sync_execute@@ -268,8 +261,8 @@ def _fetch_stats(query_type="delete_event_count",):event_result = sync_execute(- _event_count_query_template(events_filter),- events_params,+ _event_count_query_template(extra_filter),+ params,team_id=team_id,readonly=True,workload=Workload.OFFLINE,@@ -301,12 +294,12 @@ def _fetch_stats(WHERE team_id = %(team_id)sAND timestamp >= %(start_time)sAND timestamp < %(end_time)s- {sharded_filter}+ {extra_filter}) AS matched ON p.name = matched.nameWHERE p.table = 'sharded_events'AND p.active""",- sharded_params,+ params,team_id=team_id,readonly=True,workload=Workload.OFFLINE,@@ -325,18 +318,16 @@ def _fetch_stats(def fetch_event_deletion_stats(obj: DataDeletionRequest):"""Count events and affected parts for an event removal request."""- events_filter, events_params = _build_event_filter(obj)- sharded_filter, sharded_params = _build_event_filter(obj, target_data_table=True)- return _fetch_stats(obj.team_id, events_filter, events_params, sharded_filter, sharded_params)+ extra_filter, params = _build_event_filter(obj)+ return _fetch_stats(obj.team_id, extra_filter, params)def fetch_property_deletion_stats(obj: DataDeletionRequest):"""Count events with matching properties and affected parts for a property removal request."""if not obj.properties:raise ValueError("Cannot fetch stats for a property removal request with no properties specified.")- events_filter, events_params = _build_property_filter(obj)- sharded_filter, sharded_params = _build_property_filter(obj, target_data_table=True)- return _fetch_stats(obj.team_id, events_filter, events_params, sharded_filter, sharded_params)+ extra_filter, params = _build_property_filter(obj)+ return _fetch_stats(obj.team_id, extra_filter, params)def fetch_deletion_stats(obj: DataDeletionRequest):diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex 4ec81c2cef5f..2f99e27c3f33 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -106,20 +106,18 @@ def _base_params(ctx: DeletionRequestContext) -> dict:_EVENT_REMOVAL_TIME_PREDICATE = "team_id = %(team_id)s AND timestamp >= %(start_time)s AND timestamp < %(end_time)s"-def _event_removal_where(obj, *, target_data_table: bool = False) -> tuple[str, dict]:+def _event_removal_where(obj) -> tuple[str, dict]:"""Full WHERE predicate + params for event-removal queries.Combines the mandatory team/timestamp bounds, the events filter (skipped- when ``delete_all_events`` is set), and any compiled HogQL predicate.-- ``target_data_table`` is forwarded to ``compile_hogql_predicate`` — pass- ``True`` for queries running against ``sharded_events`` (DELETE, deferred- queueing) and leave ``False`` for the Distributed ``events`` proxy- (cluster-wide read counts).+ when ``delete_all_events`` is set), and any compiled HogQL predicate. The+ compiled HogQL fragment uses unqualified column references, so the result+ is safe to splice into queries against either the Distributed ``events``+ proxy or the local ``sharded_events`` MergeTree."""parts = [_EVENT_REMOVAL_TIME_PREDICATE, event_match_sql_fragment(obj)]params = event_match_params(obj)- hogql_sql, hogql_values = compile_hogql_predicate(obj, target_data_table=target_data_table)+ hogql_sql, hogql_values = compile_hogql_predicate(obj)if hogql_sql:parts.append(f"AND ({hogql_sql})")params.update(hogql_values)@@ -262,7 +260,7 @@ def _run_immediate_event_deletion(context.log.info(f"Processing shard {shard_num} ({idx}/{len(shards)})")shard_start = time.monotonic()- predicate, parameters = _event_removal_where(deletion_request, target_data_table=True)+ predicate, parameters = _event_removal_where(deletion_request)runner = LightweightDeleteMutationRunner(table=table,predicate=predicate,@@ -290,7 +288,7 @@ def _queue_events_for_deferred_deletion(source_table = EVENTS_DATA_TABLE()db = django_settings.CLICKHOUSE_DATABASEshards = sorted(cluster.shards)- predicate, params = _event_removal_where(deletion_request, target_data_table=True)+ predicate, params = _event_removal_where(deletion_request)# nosemgrep: clickhouse-fstring-param-audit (all interpolated values are internal constants/settings)insert_sql = (f"INSERT INTO {db}.{ADHOC_EVENTS_DELETION_TABLE} (team_id, uuid) "diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.pyindex afeaa7fa5a9d..cc82d9b37ac0 100644--- a/posthog/hogql/printer/base.py+++ b/posthog/hogql/printer/base.py@@ -1275,10 +1275,20 @@ class BasePrinter(Visitor[str]):raise QueryError(f"Can't resolve field {field_type.name} on table {table_name}")field_name = cast(Union[Literal["properties"], Literal["person_properties"]], field.name)+ # In non-HogQL contexts (legacy queries, data deletion predicates) the consumer splices+ # this fragment into a query whose table scope is fixed and known (e.g. ``events e``,+ # ``DELETE FROM sharded_events``). Mirror what visit_field_type already does for regular+ # columns at line 1201: drop the table prefix. In particular, lightweight DELETE rewrites+ # the predicate into a mutation, whose expression analyzer rejects table-qualified+ # references like ``sharded_events.mat_$current_url`` even when the column exists.+ table_prefix: str | None = (+ None if self.context.within_non_hogql_query else self.visit(field_type.table_type)+ )+materialized_column = self._get_materialized_column(table_name, property_name, field_name)if materialized_column is not None:yield PrintableMaterializedColumn(- self.visit(field_type.table_type),+ table_prefix,self._print_identifier(materialized_column.name),is_nullable=materialized_column.is_nullable,has_minmax_index=materialized_column.has_minmax_index,@@ -1289,7 +1299,7 @@ class BasePrinter(Visitor[str]):# Check for dmat (dynamic materialized) columnsif dmat_column := self._get_dmat_column(table_name, field_name, property_name):yield PrintableMaterializedColumn(- self.visit(field_type.table_type),+ table_prefix,self._print_identifier(dmat_column),is_nullable=True,has_minmax_index=False,diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.pyindex a805a5bde720..60f00ca2da22 100644--- a/posthog/models/data_deletion_request.py+++ b/posthog/models/data_deletion_request.py@@ -17,7 +17,7 @@ def jsonhas_expr(prop: str, param_prefix: str) -> str:return f"JSONHas(properties, {args})"-def compile_hogql_predicate(obj, *, target_data_table: bool = False) -> tuple[str, dict]:+def compile_hogql_predicate(obj) -> tuple[str, dict]:"""Parse and compile ``obj.hogql_predicate`` into a ClickHouse SQL fragment.Returns ``(sql_fragment, extra_params)``. Both are empty when the predicate@@ -26,14 +26,12 @@ def compile_hogql_predicate(obj, *, target_data_table: bool = False) -> tuple[st:class:`~django.core.exceptions.ValidationError` on parse, resolution orsubquery errors — suitable for use inside ``Model.clean()``.- ``target_data_table`` selects the ClickHouse table the fragment will be- spliced against:-- - ``False`` (default): emit ``events.<col>`` qualifiers — for read queries- against the Distributed ``events`` proxy (e.g. cluster-wide row counts).- - ``True``: emit ``sharded_events.<col>`` qualifiers — for the local- ``sharded_events`` MergeTree (DELETE mutations, parts inspection, deferred- uuid extraction).+ The fragment uses unqualified column references (no ``events.``/``sharded_events.``+ prefix), so it can be spliced into queries against either the Distributed+ ``events`` proxy or the local ``sharded_events`` MergeTree. This matters for+ lightweight DELETE: ClickHouse rewrites it into a mutation whose expression+ analyzer rejects table-qualified references like ``sharded_events.mat_$current_url``+ even when the column exists on every replica."""predicate = (getattr(obj, "hogql_predicate", "") or "").strip()if not predicate:@@ -64,13 +62,11 @@ def compile_hogql_predicate(obj, *, target_data_table: bool = False) -> tuple[stif obj.team_id is None:raise ValidationError({"hogql_predicate": "team_id must be set before validating the predicate."})+ # ``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)- # Default leaves the events table un-aliased so qualified column references (e.g. mat-column- # shortcuts) print as ``events.<col>`` — the right shape for the Distributed proxy used by- # read queries. Only the data-table case needs an alias swap.- table_alias = "sharded_events" if target_data_table else Nonetry:- sql = translate_hogql(predicate, context, dialect="clickhouse", events_table_alias=table_alias)+ sql = translate_hogql(predicate, context, dialect="clickhouse")except Exception as exc:raise ValidationError({"hogql_predicate": f"Could not compile HogQL: {exc}"}) from excdiff --git a/posthog/models/test/__snapshots__/test_data_deletion_request.ambr b/posthog/models/test/__snapshots__/test_data_deletion_request.ambrindex c3c7a5807351..d5236c7fa4a4 100644--- a/posthog/models/test/__snapshots__/test_data_deletion_request.ambr+++ b/posthog/models/test/__snapshots__/test_data_deletion_request.ambr@@ -1,10 +1,7 @@# serializer version: 1-# name: test_compile_hogql_predicate_emits_sharded_events_for_materialized_column- dict({- 'events': 'like(events.`mat_$current_url`, %(hogql_val_0)s)',- 'sharded': 'like(sharded_events.`mat_$current_url`, %(hogql_val_0)s)',- })-# ----# name: test_compile_hogql_predicate_targets_sharded_events+# name: test_compile_hogql_predicate_emits_no_table_qualifier'and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, %(hogql_val_0)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_1)s), 0), equals(event, %(hogql_val_2)s))'# ---+# name: test_compile_hogql_predicate_emits_unqualified_materialized_column+ 'like(`mat_$current_url`, %(hogql_val_0)s)'+# ---diff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.pyindex e0c0cab1789c..d1aeb7e64e57 100644--- a/posthog/models/test/test_data_deletion_request.py+++ b/posthog/models/test/test_data_deletion_request.py@@ -114,12 +114,13 @@ def test_compile_hogql_predicate_empty_returns_empty():assert compile_hogql_predicate(request) == ("", {})-def test_compile_hogql_predicate_targets_sharded_events(team, snapshot):- """Predicate is spliced into ``DELETE FROM sharded_events WHERE …``, so the- compiled SQL must not reference the Distributed ``events`` proxy.+def test_compile_hogql_predicate_emits_no_table_qualifier(team, snapshot):+ """Predicate is spliced into both ``SELECT … FROM events`` and ``DELETE FROM+ sharded_events WHERE …``, so the compiled SQL must use unqualified column+ references — neither ``events.`` nor ``sharded_events.``.- Snapshots the full SQL fragment so any regression that re-introduces an- ``events.`` table prefix (or any other shape change) is caught.+ Snapshots the full SQL fragment so any regression that re-introduces a table+ prefix is caught."""from posthog.models.data_deletion_request import compile_hogql_predicate@@ -134,11 +135,12 @@ def test_compile_hogql_predicate_targets_sharded_events(team, snapshot):assert sql == snapshot-def test_compile_hogql_predicate_emits_sharded_events_for_materialized_column(team, snapshot):- """When a property has a materialized column, the printer emits ``{table}.mat_{prop}``.- With ``target_data_table=True`` that qualifier must be ``sharded_events`` — without- the flag it would point at the Distributed ``events`` proxy, mismatched with a DELETE- against the local table.+def test_compile_hogql_predicate_emits_unqualified_materialized_column(team, snapshot):+ """When a property has a materialized column, the printer emits the ``mat_<prop>``+ column without a table prefix. ClickHouse's lightweight DELETE rewrites the+ predicate into a mutation whose expression analyzer rejects table-qualified+ references, so ``sharded_events.mat_$current_url`` would fail with "Missing+ columns" even when the column exists on every replica."""from posthog.models.data_deletion_request import compile_hogql_predicate@@ -153,11 +155,11 @@ def test_compile_hogql_predicate_emits_sharded_events_for_materialized_column(tehogql_predicate="properties.$current_url LIKE '%message=%'",))- events_sql, _ = compile_hogql_predicate(request)- sharded_sql, _ = compile_hogql_predicate(request, target_data_table=True)- assert "events.`mat_$current_url`" in events_sql- assert "sharded_events.`mat_$current_url`" in sharded_sql- assert {"events": events_sql, "sharded": sharded_sql} == snapshot+ sql, _ = compile_hogql_predicate(request)+ assert "events.`mat_$current_url`" not in sql+ assert "sharded_events.`mat_$current_url`" not in sql+ assert "`mat_$current_url`" in sql+ assert sql == snapshotdef test_rendered_count_query_substitutes_parameters():