: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(hogql): guard groups-join prefilter against group-type-name aliases (#71614)
Xanderbf1c84d40054
diff --git a/posthog/hogql/database/schema/groups.py b/posthog/hogql/database/schema/groups.pyindex ab4b24a12352..9c813cb338ac 100644--- a/posthog/hogql/database/schema/groups.py+++ b/posthog/hogql/database/schema/groups.py@@ -8,6 +8,7 @@ from posthog.hogql.database.lazy_join_tags import GROUPS_REVENUE_ANALYTICSfrom posthog.hogql.database.models import (DateTimeDatabaseField,FieldOrTable,+ FieldTraverser,IntegerDatabaseField,LazyJoin,LazyJoinToAdd,@@ -171,7 +172,7 @@ def join_with_group_n_table(# blob row by row — on high-volume teams that's enough to OOM the whole query even when# only a handful of events are actually being selected. With the filter, the hash table is# bounded by the distinct `$group_N` values present in the matched events.- events_prefilter = _outer_events_prefilter(node)+ events_prefilter = _outer_events_prefilter(node, context)if events_prefilter is not None:key_subquery = ast.SelectQuery(select=[ast.Field(chain=[f"$group_{group_index}"])],@@ -204,13 +205,10 @@ def join_with_group_n_table(return join_expr-# Aliases on the events table that resolve to lazy joins or traversers. If the outer WHERE-# references any of these (e.g. `WHERE group_0.properties.X = 'Y'`, `WHERE person.id = ...`),-# cloning that WHERE into the inner `SELECT $group_N FROM events WHERE ...` subquery would-# carry the typed `Field` for the lazy join, and the resolver would recursively try to-# resolve the same lazy join inside our inner subquery — producing unbounded recursion or a-# `ResolutionError: Select query must have a type`. Skip the optimization in that case;-# we'd rather pay the original groups-hash-table cost than crash.+# Static events-table aliases that resolve to a lazy join. Cloning a WHERE that references one+# into the inner `SELECT $group_N FROM events` subquery re-triggers the same lazy join during+# resolution and recurses, so the prefilter is skipped in that case (see `_guarded_events_aliases`,+# which also picks up the per-project group-type-name aliases dynamically).EVENTS_LAZY_JOIN_ALIASES = frozenset({"person",@@ -233,7 +231,22 @@ EVENTS_LAZY_JOIN_ALIASES = frozenset()-def _outer_events_prefilter(node: SelectQuery):+def _guarded_events_aliases(context: HogQLContext) -> frozenset[str]:+ """Events-table aliases whose reference must skip the prefilter: the static lazy joins,+ plus every FieldTraverser on events (this catches the per-project group-type-name aliases+ like `organization`; the always-present `person`/`person_id` traversers are already in the+ static set, so the union just dedupes them)."""+ if context.database is None:+ return EVENTS_LAZY_JOIN_ALIASES+ try:+ events_table = context.database.get_table(["events"])+ except Exception:+ return EVENTS_LAZY_JOIN_ALIASES+ traversers = frozenset(name for name, field in events_table.fields.items() if isinstance(field, FieldTraverser))+ return EVENTS_LAZY_JOIN_ALIASES | traversers+++def _outer_events_prefilter(node: SelectQuery, context: HogQLContext):"""Extract a clone of the outer query's WHERE that we can safely embed inside the groupsjoin subquery. We only return it when:@@ -247,9 +260,11 @@ def _outer_events_prefilter(node: SelectQuery):set is bounded by a date range." Without that guard, a query whose WHERE is only`team_id = X` (or empty) would push a key subquery that scans every event for theteam, which is strictly worse than no filter at all.- 3. The WHERE does not reference any lazy-join alias on the events table. Cloning a- `group_N.X` / `person.X` reference into the inner subquery would re-trigger the- resolver on the same lazy join during inner-subquery resolution.+ 3. The WHERE does not reference any lazy-join alias on the events table — including the+ per-project group-type-name aliases (e.g. `organization`) that resolve to `group_N`.+ Cloning a `group_N.X` / `organization.X` / `person.X` reference into the inner+ subquery would re-trigger the resolver on the same lazy join during inner-subquery+ resolution."""# Deferred: lazy_tables imports the resolver, which imports database schema modules — circular.from posthog.hogql.transforms.lazy_tables import find_field_chains # noqa: PLC0415@@ -269,14 +284,21 @@ def _outer_events_prefilter(node: SelectQuery):if not _references_timestamp(where):return None- if any(- chain and isinstance(chain[0], str) and chain[0] in EVENTS_LAZY_JOIN_ALIASES- for chain in find_field_chains(where)- ):+ guarded_aliases = _guarded_events_aliases(context)+ if any(_chain_hits_guarded_alias(chain, guarded_aliases) for chain in find_field_chains(where)):return Nonereturn clone_expr(where)+def _chain_hits_guarded_alias(chain: list, guarded: frozenset[str]) -> bool:+ # Condition #1 guarantees the outer FROM's qualifier is literally `events`, so a leading+ # `events` segment is transparent: `events.organization.x` names the same lazy join as+ # `organization.x`. Peel it before matching, or the qualified form slips past the guard.+ if len(chain) > 1 and chain[0] == "events":+ chain = chain[1:]+ return bool(chain) and isinstance(chain[0], str) and chain[0] in guarded++class _TimestampReferenceFinder(TraversingVisitor):"""Walks an expression to see whether it touches the `timestamp` field."""diff --git a/posthog/hogql/database/schema/test/test_groups_join_prefilter.py b/posthog/hogql/database/schema/test/test_groups_join_prefilter.pyindex 2eeb5bfc8711..54a73b06c8e3 100644--- a/posthog/hogql/database/schema/test/test_groups_join_prefilter.py+++ b/posthog/hogql/database/schema/test/test_groups_join_prefilter.py@@ -2,6 +2,8 @@ from datetime import UTC, datetimefrom posthog.test.base import APIBaseTest+from parameterized import parameterized+from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.parser import parse_select@@ -72,27 +74,27 @@ class TestGroupsJoinPrefilter(APIBaseTest):sql = self._print("SELECT group_0.properties FROM events")self.assertNotIn("in(key,", sql)- def test_skips_filter_when_outer_where_references_lazy_join(self):- # Cloning a WHERE that references a lazy-join column (e.g. `group_0.properties.X`)- # into the inner `SELECT $group_N FROM events ...` subquery would re-trigger the- # same lazy join inside that inner subquery during resolution — producing unbounded- # recursion or a `ResolutionError`. The guard skips the optimization in that case;- # the outer group join still resolves and prints normally, just without the key- # prefilter pushed into its WHERE.- sql = self._print(- "SELECT group_0.properties FROM events "- "WHERE group_0.properties.industry = 'tech' "- "AND timestamp > toDateTime('2026-01-01')"- )- self.assertIn("events__group_0", sql)- self.assertNotIn("in(key,", sql)-- def test_skips_filter_when_outer_where_references_person_lazy_join(self):- # Same recursive-resolution risk for `person.*` references on the events table.+ @parameterized.expand(+ [+ # Physical group_N alias, its per-project group-type-name alias (`company` →+ # group_0, a FieldTraverser), and person.* — each references a lazy join on+ # events. Cloning that reference into the inner `SELECT $group_N FROM events ...`+ # subquery would re-trigger the same lazy join during resolution — unbounded+ # recursion or a `ResolutionError`. The guard skips the prefilter; the outer+ # group join still resolves and prints normally, just without the key prefilter.+ ("physical_group_alias", "group_0.properties.industry = 'tech'"),+ ("group_type_name_alias", "company.properties.industry = 'tech'"),+ ("person_lazy_join", "person.properties.plan = 'pro'"),+ # Table-qualified forms (`events.<alias>...`) are legal hand-written HogQL and name+ # the same lazy joins; the guard must peel the leading `events` segment or they crash.+ ("qualified_physical_group_alias", "events.group_0.properties.industry = 'tech'"),+ ("qualified_group_type_name_alias", "events.company.properties.industry = 'tech'"),+ ("qualified_person_lazy_join", "events.person.properties.plan = 'pro'"),+ ]+ )+ def test_skips_filter_when_outer_where_references_lazy_join(self, _name: str, where_predicate: str):sql = self._print(- "SELECT group_0.properties FROM events "- "WHERE person.properties.plan = 'pro' "- "AND timestamp > toDateTime('2026-01-01')"+ f"SELECT group_0.properties FROM events WHERE {where_predicate} AND timestamp > toDateTime('2026-01-01')")self.assertIn("events__group_0", sql)self.assertNotIn("in(key,", sql)