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.

perf(hogql): prefilter groups JOIN by event keys to avoid OOM on huge teams (#65784)

Meikel Ratzecf4acda4303
diff --git a/posthog/hogql/database/schema/groups.py b/posthog/hogql/database/schema/groups.py
index 60e15c7c9a1d..ab4b24a12352 100644
--- a/posthog/hogql/database/schema/groups.py
+++ b/posthog/hogql/database/schema/groups.py
@@ -20,7 +20,7 @@ from posthog.hogql.database.models import (
from posthog.hogql.database.schema.groups_revenue_analytics import GroupsRevenueAnalyticsTable
from posthog.hogql.errors import ResolutionError
from posthog.hogql.parser import parse_select
-from posthog.hogql.visitor import TraversingVisitor
+from posthog.hogql.visitor import TraversingVisitor, clone_expr
GROUPS_TABLE_FIELDS: dict[str, FieldOrTable] = {
"index": IntegerDatabaseField(
@@ -163,6 +163,32 @@ def join_with_group_n_table(
right=ast.Constant(value=group_index),
)
+ # If the outer query has a bounded prefilter on `events` (one that references `timestamp` —
+ # which is the strongest signal we have that the matched set is small), push an additional
+ # `group_key IN (SELECT $group_N FROM events WHERE <outer prefilter>)` predicate into the
+ # groups subquery. Without this filter, the LEFT JOIN materializes a hash table containing
+ # every group of this type for the team, decompressing the (very wide) `group_properties`
+ # 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)
+ if events_prefilter is not None:
+ key_subquery = ast.SelectQuery(
+ select=[ast.Field(chain=[f"$group_{group_index}"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=events_prefilter,
+ )
+ select_query.where = ast.And(
+ exprs=[
+ select_query.where,
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["key"]),
+ right=key_subquery,
+ ),
+ ]
+ )
+
join_expr = ast.JoinExpr(table=select_query)
join_expr.join_type = "LEFT JOIN"
join_expr.alias = join_to_add.to_table
@@ -178,6 +204,97 @@ 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.
+EVENTS_LAZY_JOIN_ALIASES = frozenset(
+ {
+ "person",
+ "person_id",
+ "pdi",
+ "poe",
+ "group_0",
+ "group_1",
+ "group_2",
+ "group_3",
+ "group_4",
+ "goe_0",
+ "goe_1",
+ "goe_2",
+ "goe_3",
+ "goe_4",
+ "session",
+ "revenue_analytics",
+ }
+)
+
+
+def _outer_events_prefilter(node: SelectQuery):
+ """
+ Extract a clone of the outer query's WHERE that we can safely embed inside the groups
+ join subquery. We only return it when:
+
+ 1. The outer's `FROM` is a plain unaliased `events` reference. Anything else (custom
+ alias like `FROM events AS e` in funnels, JOINed tables on the outer, or a subquery)
+ means the WHERE may reference symbols (`e.timestamp`, `p.id`, …) that don't exist
+ in our inner `SELECT $group_N FROM events` subquery — cloning a WHERE that names
+ them would raise `Unable to resolve field` when the resolver walks the clone.
+ 2. The WHERE references the `timestamp` field — cheap heuristic for "the matched event
+ 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 the
+ team, 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.
+ """
+ # Deferred: lazy_tables imports the resolver, which imports database schema modules — circular.
+ from posthog.hogql.transforms.lazy_tables import find_field_chains # noqa: PLC0415
+
+ where = node.where
+ if where is None:
+ return None
+
+ select_from = node.select_from
+ if select_from is None:
+ return None
+ table = select_from.table
+ if not isinstance(table, ast.Field) or table.chain != ["events"]:
+ return None
+ if select_from.alias is not None and select_from.alias != "events":
+ return None
+
+ 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)
+ ):
+ return None
+ return clone_expr(where)
+
+
+class _TimestampReferenceFinder(TraversingVisitor):
+ """Walks an expression to see whether it touches the `timestamp` field."""
+
+ def __init__(self):
+ super().__init__()
+ self.found = False
+
+ def visit_field(self, node):
+ if node.chain and node.chain[-1] == "timestamp":
+ self.found = True
+
+
+def _references_timestamp(expr) -> bool:
+ finder = _TimestampReferenceFinder()
+ finder.visit(expr)
+ return finder.found
+
+
class RawGroupsTable(Table):
description: str = (
"Raw, un-deduplicated groups rows (one per update). Query `groups` instead unless you need to "
diff --git a/posthog/hogql/database/schema/test/test_groups_join_prefilter.py b/posthog/hogql/database/schema/test/test_groups_join_prefilter.py
new file mode 100644
index 000000000000..2eeb5bfc8711
--- /dev/null
+++ b/posthog/hogql/database/schema/test/test_groups_join_prefilter.py
@@ -0,0 +1,108 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import APIBaseTest
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+
+from posthog.models.group_type_mapping import invalidate_group_types_cache
+from posthog.test.persons import create_group_type_mapping
+
+
+class TestGroupsJoinPrefilter(APIBaseTest):
+ """
+ Each `LEFT JOIN groups` subquery generated for `group_N.<field>` access should also be
+ constrained by `group_key IN (SELECT $group_N FROM events WHERE <outer prefilter>)` when
+ the outer query has a `timestamp`-bounded WHERE. Without that constraint the join hash
+ table contains every group of that type for the team, decompressing the wide
+ `group_properties` blob row-by-row — enough to OOM the query on a high-volume team even
+ when only a handful of events are actually selected.
+
+ The optimization is gated on `timestamp` appearing in the outer WHERE, so unbounded
+ queries (no WHERE, or WHERE without a date range) still go through the original path.
+ """
+
+ def setUp(self):
+ super().setUp()
+ create_group_type_mapping(
+ team=self.team,
+ project=self.team.project,
+ group_type="company",
+ group_type_index=0,
+ created_at=datetime(2020, 1, 1, tzinfo=UTC),
+ )
+ invalidate_group_types_cache(self.team.project_id)
+ self.database = Database.create_for(team=self.team)
+ self.context = HogQLContext(team=self.team, database=self.database, enable_select_queries=True)
+
+ def _print(self, query: str) -> str:
+ sql, _ = prepare_and_print_ast(parse_select(query), context=self.context, dialect="clickhouse")
+ return sql
+
+ def test_pushes_group_key_filter_when_outer_where_has_timestamp(self):
+ sql = self._print("SELECT group_0.properties FROM events WHERE timestamp > toDateTime('2026-01-01') LIMIT 10")
+ # Groups subquery now constrains group_key to the keys present in the matched events.
+ # The `$group_0` field reference can be wrapped by the resolver (timestamp clamping
+ # against the GroupTypeMapping created_at, etc.), so we only assert the column ref
+ # appears in the printed SQL — not the exact SELECT prefix.
+ self.assertIn("in(key,", sql)
+ self.assertIn("events.`$group_0`", sql)
+ self.assertIn("FROM events", sql)
+
+ def test_pushes_group_key_filter_with_uuid_and_timestamp_where(self):
+ # Mirrors the prod test-event-fetch shape: uuid set plus a tight timestamp window.
+ sql = self._print(
+ "SELECT group_0.properties FROM events "
+ "WHERE uuid IN ('019ef62f-21be-7867-9939-e0723c27efc2') "
+ "AND timestamp > toDateTime('2026-06-23 02:48:28') "
+ "AND timestamp < toDateTime('2026-06-23 13:32:26')"
+ )
+ self.assertIn("in(key,", sql)
+ self.assertIn("events.`$group_0`", sql)
+
+ def test_skips_filter_when_outer_where_lacks_timestamp(self):
+ # No timestamp reference → the optimization would push a key subquery that scans every
+ # event for the team, which is strictly worse than no filter. Guard skips it.
+ sql = self._print("SELECT group_0.properties FROM events WHERE event = '$pageview'")
+ self.assertNotIn("in(key,", sql)
+
+ def test_skips_filter_when_outer_has_no_where(self):
+ 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.
+ sql = self._print(
+ "SELECT group_0.properties FROM events "
+ "WHERE person.properties.plan = 'pro' "
+ "AND timestamp > toDateTime('2026-01-01')"
+ )
+ self.assertIn("events__group_0", sql)
+ self.assertNotIn("in(key,", sql)
+
+ def test_skips_filter_when_outer_from_events_is_aliased(self):
+ # Funnel queries (and others) build `FROM events AS e ... WHERE e.timestamp > X`.
+ # Cloning that WHERE into the inner `SELECT $group_N FROM events` subquery would
+ # carry references to `e.X` that have no scope in the inner subquery, raising
+ # `Unable to resolve field: e`. Guard skips the optimization for aliased FROMs.
+ sql = self._print("SELECT group_0.properties FROM events AS e WHERE e.timestamp > toDateTime('2026-01-01')")
+ # The lazy join is named after the FROM alias, so `e__group_0` rather than `events__group_0`.
+ self.assertIn("e__group_0", sql)
+ self.assertNotIn("in(key,", sql)