: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): stop v2 persons limit pushdown breaking aggregates (#87323)
Sandy Spicerc54fec2163ad
diff --git a/posthog/hogql/database/schema/groups.py b/posthog/hogql/database/schema/groups.pyindex 9c813cb338ac..3519812c674f 100644--- a/posthog/hogql/database/schema/groups.py+++ b/posthog/hogql/database/schema/groups.py@@ -87,30 +87,9 @@ def _is_nonneg_int_constant(expr) -> bool:return isinstance(expr, ast.Constant) and isinstance(expr.value, int) and expr.value >= 0-class _WindowFunctionFinder(TraversingVisitor):- # Window functions evade the order_by and has_aggregation guards but must see every group, so bail on them too.- found: bool = False-- def visit(self, node):- if not self.found:- super().visit(node)-- def visit_select_query(self, node: ast.SelectQuery):- pass # a window inside a scalar subquery doesn't change this query's rows-- def visit_window_function(self, node: ast.WindowFunction):- self.found = True---def _has_window_function(expr: ast.Expr) -> bool:- finder = _WindowFunctionFinder()- finder.visit(expr)- return finder.found--def _bare_limit_key_count(node: SelectQuery) -> int | None:# Deferred: posthog.hogql.property imports database schema modules, so a top-level import here is circular.- from posthog.hogql.property import has_aggregation # noqa: PLC0415+ from posthog.hogql.property import has_aggregation, has_window_function # noqa: PLC0415# Only safe for a bare `from groups limit N`; bail to the full dedup on anything that changes the surviving rows.if (@@ -131,7 +110,7 @@ def _bare_limit_key_count(node: SelectQuery) -> int | None:or node.limit_percentor any(has_aggregation(expr) for expr in node.select)or node.window_exprs- or any(_has_window_function(expr) for expr in node.select)+ or any(has_window_function(expr) for expr in node.select)or not isinstance(_resolved_table(node.select_from.type), GroupsTable)):return Nonediff --git a/posthog/hogql/database/schema/persons.py b/posthog/hogql/database/schema/persons.pyindex d5f6c0278e9e..d4c9dd61c98f 100644--- a/posthog/hogql/database/schema/persons.py+++ b/posthog/hogql/database/schema/persons.py@@ -171,9 +171,17 @@ def select_from_persons_table(if filter is not None:cast(ast.SelectQuery, cast(ast.CompareOperation, select.where).right).where = filter+ # Deferred: posthog.hogql.property imports database schema modules, so a top-level import here is circular.+ from posthog.hogql.property import has_aggregation, has_window_function # noqa: PLC0415+# Push ORDER BY + LIMIT into the inner deduplication subquery so ClickHouse can stop early.# Skip when there's an outer WHERE -- a premature inner LIMIT would exclude valid rows# before the filter runs (e.g. cohort members dropped because LIMIT grabbed other rows first).+ # Skip aggregate, DISTINCT, and window-function selects too: they must see every person, and+ # the executor stamps a default LIMIT on every query, so pushing it down would cap+ # e.g. `SELECT count() FROM persons` at the page size instead of counting the whole team.+ # HAVING, QUALIFY, ARRAY JOIN, LIMIT BY, and WITH TIES / PERCENT also filter or reshape+ # rows after deduplication, so they need the full person set as well.can_push_to_inner = (node.select_fromand node.select_from.type@@ -184,6 +192,16 @@ def select_from_persons_table(and node.limitand not node.whereand not node.prewhere+ and not node.having+ and not node.qualify+ and not node.array_join_op+ and not node.limit_by+ and not node.limit_with_ties+ and not node.limit_percent+ and not node.distinct+ and not any(has_aggregation(expr) for expr in node.select)+ and not node.window_exprs+ and not any(has_window_function(expr) for expr in node.select))if can_push_to_inner:compare = cast(ast.CompareOperation, select.where)diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambrindex f6476998a350..b0ace07b0efa 100644--- a/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr+++ b/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr@@ -264,6 +264,114 @@use_hive_partitioning=0'''# ---+# name: TestPersonsV2LimitPushDown.test_v2_full_row_set_selects_do_not_push_limit_down_0_aggregate+ '''+ SELECT count() AS `count()`+ FROM+ (SELECT person.id AS id+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonsV2LimitPushDown.test_v2_full_row_set_selects_do_not_push_limit_down_1_distinct+ '''+ SELECT DISTINCT persons.is_identified AS is_identified+ FROM+ (SELECT person.id AS id,+ person.is_identified AS is_identified+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 2 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonsV2LimitPushDown.test_v2_full_row_set_selects_do_not_push_limit_down_2_window+ '''+ SELECT persons.id AS id,+ count() OVER ()+ FROM+ (SELECT person.id AS id+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons+ LIMIT 10 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonsV2LimitPushDown.test_v2_full_row_set_selects_do_not_push_limit_down_3_having+ '''+ SELECT persons.id AS id+ FROM+ (SELECT person.id AS id,+ person.is_identified AS is_identified+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons+ HAVING equals(persons.is_identified, 0)+ LIMIT 5 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestPersonsV2LimitPushDown.test_v2_order_by_and_limit_pushed_down'''SELECT persons.id AS id,diff --git a/posthog/hogql/database/schema/test/test_persons.py b/posthog/hogql/database/schema/test/test_persons.pyindex 592f374d8388..ff6dc1d2ff69 100644--- a/posthog/hogql/database/schema/test/test_persons.py+++ b/posthog/hogql/database/schema/test/test_persons.py@@ -244,6 +244,44 @@ class TestPersonsV2LimitPushDown(ClickhouseTestMixin, APIBaseTest):assert len(response.results) == 1assert response.results[0][1] == "[email protected]"+ @parameterized.expand(+ [+ # (name, query, LIMIT that a wrongly pushed-down limit+offset+1 would print in the inner subquery)+ ("aggregate", "SELECT count() FROM persons", "LIMIT 101"),+ ("distinct", "SELECT DISTINCT is_identified FROM persons LIMIT 2", "LIMIT 3"),+ ("window", "SELECT id, count() OVER () FROM persons LIMIT 10", "LIMIT 11"),+ # HAVING acts as a post-dedup filter, like the WHERE case test_v2_cohort_where covers.+ ("having", "SELECT id FROM persons HAVING is_identified = 0 LIMIT 5", "LIMIT 6"),+ ]+ )+ @snapshot_clickhouse_queries+ def test_v2_full_row_set_selects_do_not_push_limit_down(self, _name, query, pushed_down_limit):+ response = execute_hogql_query(query, self.team, modifiers=self._v2_modifiers(), pretty=False)+ assert response.clickhouse is not None+ assert "in(tuple(person.id, person.version)" in response.clickhouse+ assert pushed_down_limit not in response.clickhouse++ @parameterized.expand(+ [+ # (name, query, pin v2 modifiers, index of the total in the result row)+ ("count_v2", "SELECT count() FROM persons LIMIT 1", True, 0),+ ("count_default", "SELECT count() FROM persons LIMIT 1", False, 0),+ ("window_total_v2", "SELECT id, count() OVER () AS total FROM persons LIMIT 1", True, 1),+ ]+ )+ def test_totals_over_persons_are_not_capped_by_limit(self, _name, query, pin_v2, result_index):+ for i in range(3):+ _create_person(team_id=self.team.pk, distinct_ids=[f"count_person_{i}"])+ flush_persons_and_events()++ response = execute_hogql_query(+ query,+ self.team,+ modifiers=self._v2_modifiers() if pin_v2 else None,+ pretty=False,+ )+ assert response.results[0][result_index] == 3+class TestPersons(ClickhouseTestMixin, APIBaseTest):person_properties = {"$initial_referring_domain": "https://google.com"}diff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex 9fa8a419f56d..5df17decebe8 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -290,6 +290,28 @@ class AggregationFinder(TraversingVisitor):self.visit(arg)+class WindowFunctionFinder(TraversingVisitor):+ # Window functions evade the order_by and has_aggregation guards but must see every input row,+ # so limit pushdowns bail on them too.+ found: bool = False++ def visit(self, node):+ if not self.found:+ super().visit(node)++ def visit_select_query(self, node: ast.SelectQuery):+ pass # a window inside a scalar subquery doesn't change this query's rows++ def visit_window_function(self, node: ast.WindowFunction):+ self.found = True+++def has_window_function(expr: AST) -> bool:+ finder = WindowFunctionFinder()+ finder.visit(expr)+ return finder.found++def _handle_bool_values(value: ValueT, expr: ast.Expr, property: Property, team: Team) -> ValueT | bool:if value is True:value = "true"