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.

feat(hogql): add opt-in persons join pushdown modifier (#110392)

Phil Haackf81311a88e30
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 0a37bb305466..8d51dfd2b28a 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -29338,6 +29338,10 @@
],
"type": "string"
},
+ "personIdPushdown": {
+ "description": "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table.",
+ "type": "boolean"
+ },
"personsArgMaxVersion": {
"enum": ["auto", "v1", "v2"],
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 42da5dbda274..135079266256 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -521,6 +521,8 @@ export interface HogQLQueryModifiers {
sessionIdPushdown?: boolean
/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */
sessionPropertyPreAggregation?: boolean
+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
+ personIdPushdown?: boolean
dataWarehouseEventsModifiers?: DataWarehouseEventsModifier[]
debug?: boolean
timings?: boolean
diff --git a/posthog/hogql/database/schema/persons.py b/posthog/hogql/database/schema/persons.py
index 19e9a21b7527..1fb3c766e718 100644
--- a/posthog/hogql/database/schema/persons.py
+++ b/posthog/hogql/database/schema/persons.py
@@ -24,10 +24,10 @@ from posthog.hogql.database.models import (
)
from posthog.hogql.database.schema.persons_pdi import PersonsPDITable
from posthog.hogql.database.schema.persons_revenue_analytics import PersonsRevenueAnalyticsTable
-from posthog.hogql.database.schema.util.where_clause_extractor import WhereClauseExtractor
+from posthog.hogql.database.schema.util.where_clause_extractor import WhereClauseExtractor, top_level_conjuncts
from posthog.hogql.errors import ResolutionError
from posthog.hogql.parser import parse_select
-from posthog.hogql.visitor import CloningVisitor, clone_expr
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
from posthog.schema_enums import PersonsArgMaxVersion
@@ -268,6 +268,105 @@ def select_from_persons_table(
return select
+# These return different values in the subquery and in the outer query.
+_NONDETERMINISTIC_FUNCTIONS = frozenset({"rand", "rownumberinblock", "rownumberinallblocks", "nowinblock"})
+
+
+class _CopyableConjunctVisitor(TraversingVisitor):
+ def __init__(self, table_type: ast.Type):
+ super().__init__()
+ self.table_type = table_type
+ self.reads_table = False
+ self.copyable = True
+
+ def visit_field(self, node: ast.Field):
+ field_type = node.type.field_type if isinstance(node.type, ast.PropertyType) else node.type
+ if isinstance(field_type, ast.FieldType) and field_type.table_type is self.table_type:
+ self.reads_table = True
+ else:
+ self.copyable = False
+
+ # A nested subquery already has its lazy joins expanded. A copy of it would also run a second time.
+ def visit_select_query(self, node: ast.SelectQuery):
+ self.copyable = False
+
+ def visit_select_set_query(self, node: ast.SelectSetQuery):
+ self.copyable = False
+
+ def visit_call(self, node: ast.Call):
+ if node.name.lower() in _NONDETERMINISTIC_FUNCTIONS:
+ self.copyable = False
+ super().visit_call(node)
+
+
+# The copy drops the hidden alias that the resolver puts on every field. The resolver adds it back.
+class _AliasStrippingCloner(CloningVisitor):
+ def visit_alias(self, node: ast.Alias) -> Expr:
+ return self.visit(node.expr)
+
+
+def _is_relative_sample(sample: Optional[ast.SampleExpr]) -> bool:
+ """True for `SAMPLE k` with k at most 1, which SAMPLE BY applies to the same rows in the subquery and the outer query.
+
+ ClickHouse turns `SAMPLE n` (a row count) into a ratio from each query's own row estimate.
+ The subquery reads with fewer terms, so its ratio can be smaller and skip rows that the outer query keeps.
+ """
+ if sample is None:
+ return False
+ ratio = sample.sample_value
+ return ratio.left.value <= (ratio.right.value if ratio.right is not None else 1)
+
+
+def build_person_id_pushdown_predicate(join_to_add: LazyJoinToAdd, node: SelectQuery) -> Optional[Expr]:
+ """Build `id IN (SELECT person_id FROM <left table> WHERE <conjuncts>)` for the joined persons subquery.
+
+ The conjuncts are the top-level AND terms of the outer WHERE and PREWHERE that read only the left table.
+ A term must read at least one left-table column, because a constant term narrows nothing.
+ Every row that the outer query keeps satisfies all of them. Its person stays in the set. The join returns the same
+ rows. A term is copied whole or left out. Leaving a term out only widens the set.
+ The subquery reads the left table before the outer scan does. A row that arrives between the two reads can lack
+ its person columns.
+ Returns None unless the left table is the query's own FROM table and at least one term qualifies.
+ """
+ left = node.select_from
+ if (
+ left is None
+ or not isinstance(left.table, ast.Field)
+ or left.table_args
+ or left.type is not join_to_add.lazy_join_type.table_type
+ ):
+ return None
+
+ cloner = _AliasStrippingCloner(clear_types=True, clear_locations=True)
+ conjuncts: list[Expr] = []
+ for where in (node.where, node.prewhere):
+ if where is None:
+ continue
+ for conjunct in top_level_conjuncts(where):
+ visitor = _CopyableConjunctVisitor(left.type)
+ visitor.visit(conjunct)
+ if visitor.copyable and visitor.reads_table:
+ conjuncts.append(cloner.visit(conjunct))
+ if not conjuncts:
+ return None
+
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["id"]),
+ # The resolver turns this into GLOBAL IN. GLOBAL IN does not deduplicate the set that it ships to each shard.
+ right=ast.SelectQuery(
+ distinct=True,
+ select=[ast.Field(chain=[join_to_add.from_table, "person_id"])],
+ select_from=ast.JoinExpr(
+ table=ast.Field(chain=list(left.table.chain)),
+ alias=left.alias,
+ sample=cloner.visit(left.sample) if _is_relative_sample(left.sample) else None,
+ ),
+ where=conjuncts[0] if len(conjuncts) == 1 else ast.And(exprs=conjuncts),
+ ),
+ )
+
+
def join_with_persons_table(
join_to_add: LazyJoinToAdd,
context: HogQLContext,
@@ -277,7 +376,8 @@ def join_with_persons_table(
if not join_to_add.fields_accessed:
raise ResolutionError("No fields requested from persons table")
- join_expr = ast.JoinExpr(table=select_from_persons_table(join_to_add, context, node))
+ pushdown = build_person_id_pushdown_predicate(join_to_add, node) if context.modifiers.personIdPushdown else None
+ join_expr = ast.JoinExpr(table=select_from_persons_table(join_to_add, context, node, filter=pushdown))
organization: Organization | None = context.team.organization if context.team else None
if organization is None:
diff --git a/posthog/hogql/database/schema/sessions_v2.py b/posthog/hogql/database/schema/sessions_v2.py
index 8f528e87e9af..ae07cc4125ec 100644
--- a/posthog/hogql/database/schema/sessions_v2.py
+++ b/posthog/hogql/database/schema/sessions_v2.py
@@ -29,6 +29,7 @@ from posthog.hogql.database.schema.util.where_clause_extractor import (
build_session_id_literal_pushdown_predicate,
build_session_id_v7_pushdown_predicate,
build_session_property_pre_aggregation_predicate,
+ top_level_conjuncts,
)
from posthog.hogql.errors import ResolutionError
from posthog.hogql.modifiers import create_default_modifiers_for_team
@@ -516,14 +517,7 @@ def build_direct_session_id_in_pushdown(
if occurrence_type is None:
return None
- def flatten_and(expr: ast.Expr) -> list[ast.Expr]:
- if isinstance(expr, ast.And):
- return [t for sub in expr.exprs for t in flatten_and(sub)]
- if isinstance(expr, ast.Call) and expr.name == "and":
- return [t for sub in expr.args for t in flatten_and(sub)]
- return [expr]
-
- for term in flatten_and(node.where):
+ for term in top_level_conjuncts(node.where):
if not isinstance(term, ast.CompareOperation) or term.op not in (
ast.CompareOperationOp.In,
ast.CompareOperationOp.GlobalIn,
diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr
index 0303215ee682..5ee020bf4265 100644
--- a/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr
+++ b/posthog/hogql/database/schema/test/__snapshots__/test_persons.ambr
@@ -118,6 +118,53 @@
use_hive_partitioning=0
'''
# ---
+# name: TestPersonIdPushdown.test_pushdown_restricts_persons_subquery_to_events_in_window
+ '''
+ SELECT events.event AS event,
+ events__person.properties___plan AS plan
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '') AS properties___plan
+ FROM person
+ WHERE and(equals(person.team_id, 99999), globalIn(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE and(equals(person.team_id, 99999), globalIn(person.id,
+ (SELECT DISTINCT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), less(events.timestamp, toDateTime64(%(hogql_val_3)s, 6, %(hogql_val_4)s))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, %(hogql_val_5)s), person.version), plus(now64(6, %(hogql_val_6)s), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_7)s, 6, %(hogql_val_8)s)), less(events.timestamp, toDateTime64(%(hogql_val_9)s, 6, %(hogql_val_10)s)), ifNull(equals(events__person.properties___plan, %(hogql_val_11)s), 0))
+ ORDER BY events.event ASC
+ 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: TestPersonOptimization.test_joins_are_left_alone_for_now
'''
SELECT events.uuid AS uuid
diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_persons.new_events_schema.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_persons.new_events_schema.ambr
index 096640ee7fc7..e60a71b48208 100644
--- a/posthog/hogql/database/schema/test/__snapshots__/test_persons.new_events_schema.ambr
+++ b/posthog/hogql/database/schema/test/__snapshots__/test_persons.new_events_schema.ambr
@@ -30,6 +30,54 @@
json_type_escape_dots_in_keys=1
'''
# ---
+# name: TestPersonIdPushdown.test_pushdown_restricts_persons_subquery_to_events_in_window[new_events_schema]
+ '''
+ SELECT events.event AS event,
+ events__person.properties___plan AS plan
+ FROM events_json AS events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '') AS properties___plan
+ FROM person
+ WHERE and(equals(person.team_id, 99999), globalIn(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE and(equals(person.team_id, 99999), globalIn(person.id,
+ (SELECT DISTINCT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id
+ FROM events_json AS events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), less(events.timestamp, toDateTime64(%(hogql_val_3)s, 6, %(hogql_val_4)s))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, %(hogql_val_5)s), person.version), plus(now64(6, %(hogql_val_6)s), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_7)s, 6, %(hogql_val_8)s)), less(events.timestamp, toDateTime64(%(hogql_val_9)s, 6, %(hogql_val_10)s)), ifNull(equals(events__person.properties___plan, %(hogql_val_11)s), 0))
+ ORDER BY events.event ASC
+ 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,
+ json_type_escape_dots_in_keys=1
+ '''
+# ---
# name: TestPersonOptimization.test_joins_are_left_alone_for_now[new_events_schema]
'''
SELECT events.uuid AS uuid
diff --git a/posthog/hogql/database/schema/test/test_persons.py b/posthog/hogql/database/schema/test/test_persons.py
index 463f467b51b8..d4dc933d8400 100644
--- a/posthog/hogql/database/schema/test/test_persons.py
+++ b/posthog/hogql/database/schema/test/test_persons.py
@@ -5,6 +5,7 @@ from posthog.test.base import (
ClickhouseTestMixin,
_create_event,
_create_person,
+ create_person_id_override_by_distinct_id,
flush_persons_and_events,
snapshot_clickhouse_queries,
)
@@ -22,6 +23,7 @@ from posthog.schema import (
EventsNode,
FilterLogicalOperator,
HogQLQueryModifiers,
+ HogQLQueryResponse,
InCohortVia,
InsightActorsQuery,
PersonsArgMaxVersion,
@@ -30,9 +32,11 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
from posthog.hogql.database.schema.persons import _is_virtual_field_requiring_join
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.execute import sync_execute
@@ -238,6 +242,153 @@ class TestPersonOptimization(ClickhouseTestMixin, APIBaseTest):
self.assertNotIn("in(tuple(person.id, person.version)", response.clickhouse)
+IN_WINDOW = datetime(2024, 1, 2, 12)
+BEFORE_WINDOW = datetime(2023, 12, 15, 12)
+WINDOW_AND_PAID = "timestamp >= '2024-01-01' AND timestamp < '2024-01-03' AND person.properties.plan = 'paid'"
+
+
+def _persons_semi_join(clickhouse: str) -> str:
+ sql = " ".join(clickhouse.split())
+ end = sql.index(" AS events__person ON")
+ # The last events scan before the persons alias is the semi-join.
+ return sql[sql.rindex("FROM events", 0, end) : end]
+
+
+class TestPersonIdPushdown(ClickhouseTestMixin, APIBaseTest):
+ FIXTURE = [
+ ("in_window_paid", "paid_in_window", "paid", IN_WINDOW),
+ ("in_window_free", "free_in_window", "free", IN_WINDOW),
+ ("before_window_paid", "paid_before_window", "paid", BEFORE_WINDOW),
+ ("before_window_free", "free_before_window", "free", BEFORE_WINDOW),
+ # Only the override-corrected person_id gives in_window_merged the paid plan.
+ ("in_window_merged", "merged_from", "free", IN_WINDOW),
+ ("before_window_merge_target", "merged_to", "paid", BEFORE_WINDOW),
+ ]
+
+ def setUp(self):
+ super().setUp()
+ for event, distinct_id, plan, timestamp in self.FIXTURE:
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id], properties={"plan": plan})
+ _create_event(event=event, distinct_id=distinct_id, team=self.team, timestamp=timestamp)
+ create_person_id_override_by_distinct_id("merged_from", "merged_to", self.team.pk)
+
+ def _execute(self, where: str | None, mode: PersonsOnEventsMode, pushdown: bool) -> HogQLQueryResponse:
+ where_clause = f"WHERE {where}" if where else ""
+ return execute_hogql_query(
+ f"SELECT event, person.properties.plan FROM events {where_clause} ORDER BY event",
+ self.team,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode=mode, personIdPushdown=pushdown),
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "window_and_person_property",
+ WINDOW_AND_PAID,
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,
+ {"in_window_paid", "in_window_merged"},
+ ),
+ (
+ "or_mixing_window_and_person_property",
+ "timestamp < '2024-01-03' AND (timestamp >= '2024-01-01' OR person.properties.plan = 'paid')",
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,
+ {
+ "in_window_paid",
+ "in_window_free",
+ "in_window_merged",
+ "before_window_paid",
+ "before_window_merge_target",
+ },
+ ),
+ (
+ "person_property_alone",
+ "person.properties.plan = 'paid'",
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,
+ {"in_window_paid", "in_window_merged", "before_window_paid", "before_window_merge_target"},
+ ),
+ (
+ "no_where",
+ None,
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,
+ {event for event, *_ in FIXTURE},
+ ),
+ (
+ "disabled_mode_window_and_person_property",
+ WINDOW_AND_PAID,
+ PersonsOnEventsMode.DISABLED,
+ {"in_window_paid"},
+ ),
+ ]
+ )
+ def test_pushdown_returns_same_rows_as_without(
+ self, _name: str, where: str | None, mode: PersonsOnEventsMode, expected_events: set[str]
+ ):
+ without_pushdown = self._execute(where, mode, pushdown=False).results
+
+ with_pushdown = self._execute(where, mode, pushdown=True).results
+
+ assert {row[0] for row in without_pushdown} == expected_events
+ assert with_pushdown == without_pushdown
+
+ def test_pushdown_restricts_persons_subquery_to_events_in_window(self):
+ response = self._execute(
+ WINDOW_AND_PAID, PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED, pushdown=True
+ )
+
+ assert response.clickhouse is not None
+ assert "timestamp" in _persons_semi_join(response.clickhouse)
+ self.assertQueryMatchesSnapshot(response.clickhouse)
+
+
+class TestPersonIdPushdownPrinting(APIBaseTest):
+ def _print(self, query: str) -> str:
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ enable_select_queries=True,
+ modifiers=create_default_modifiers_for_team(
+ self.team,
+ HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED, personIdPushdown=True
+ ),
+ ),
+ )
+ sql, _ = prepare_and_print_ast(parse_select(query), context, dialect="clickhouse")
+ return sql
+
+ @parameterized.expand(
+ [
+ ("aliased_from", "FROM events AS e WHERE e.timestamp >= '2024-01-01'", True),
+ ("event_property_term", "FROM events WHERE properties.$host != 'localhost'", True),
+ ("rand_term", "FROM events WHERE (timestamp >= '2024-01-01' OR rand() = 0)", False),
+ (
+ "block_position_term",
+ "FROM events WHERE (timestamp >= '2024-01-01' OR rowNumberInAllBlocks() < 100)",
+ False,
+ ),
+ ]
+ )
+ def test_pushdown_copies_only_terms_that_evaluate_the_same_in_the_subquery(
+ self, _name: str, from_where: str, pushed: bool
+ ):
+ sql = self._print(f"SELECT event {from_where} AND person.properties.plan = 'paid'")
+
+ assert ("SELECT DISTINCT" in " ".join(sql.split())) == pushed
+
+ @parameterized.expand(
+ [
+ ("relative_sample", "SAMPLE 1/2 OFFSET 1/2", True),
+ ("absolute_sample", "SAMPLE 10000", False),
+ ]
+ )
+ def test_pushdown_copies_only_a_relative_sample(self, _name: str, sample: str, copied: bool):
+ sql = self._print(
+ f"SELECT event FROM events {sample} WHERE timestamp >= '2024-01-01' AND person.properties.plan = 'paid'"
+ )
+
+ assert (sample in _persons_semi_join(sql)) == copied
+
+
class TestPersonsV2LimitPushDown(ClickhouseTestMixin, APIBaseTest):
"""Tests for the V2 argmax ORDER BY / LIMIT push-down into the inner subquery.
diff --git a/posthog/hogql/database/schema/util/where_clause_extractor.py b/posthog/hogql/database/schema/util/where_clause_extractor.py
index 7deef3cd8070..4c53284270e3 100644
--- a/posthog/hogql/database/schema/util/where_clause_extractor.py
+++ b/posthog/hogql/database/schema/util/where_clause_extractor.py
@@ -654,6 +654,14 @@ def extract_uuid_constants(node: ast.Expr) -> list[ast.Constant]:
return []
+def top_level_conjuncts(expr: ast.Expr) -> list[ast.Expr]:
+ if isinstance(expr, ast.And):
+ return [conjunct for sub in expr.exprs for conjunct in top_level_conjuncts(sub)]
+ if isinstance(expr, ast.Call) and expr.name == "and":
+ return [conjunct for sub in expr.args for conjunct in top_level_conjuncts(sub)]
+ return [expr]
+
+
def build_session_id_literal_pushdown_predicate(
outer_node: ast.SelectQuery,
join_to_add: LazyJoinToAdd,
@@ -674,14 +682,7 @@ def build_session_id_literal_pushdown_predicate(
if events_table_type is None:
return None
- def flatten_and(expr: ast.Expr) -> list[ast.Expr]:
- if isinstance(expr, ast.And):
- return [t for sub in expr.exprs for t in flatten_and(sub)]
- if isinstance(expr, ast.Call) and expr.name == "and":
- return [t for sub in expr.args for t in flatten_and(sub)]
- return [expr]
-
- for term in flatten_and(outer_node.where):
+ for term in top_level_conjuncts(outer_node.where):
if not isinstance(term, ast.CompareOperation) or term.op not in (
CompareOperationOp.In,
CompareOperationOp.Eq,
diff --git a/posthog/schema.py b/posthog/schema.py
index ff1094201222..5ca6ede20b1d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5790,6 +5790,15 @@ class HogQLQueryModifiers(BaseModel):
" dataclass instances directly via PyO3, skipping the JSON round-trip."
),
)
+ personIdPushdown: bool | None = Field(
+ default=None,
+ description=(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate"
+ " into the joined persons subquery, so the latest-version lookup only reads"
+ " persons that the outer query's left-table filters can reach. Applies only"
+ " to a persons join from the query's own FROM table."
+ ),
+ )
personsArgMaxVersion: PersonsArgMaxVersion | None = None
personsJoinMode: PersonsJoinMode | None = None
personsOnEventsMode: PersonsOnEventsMode | None = None
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index 9be55908e032..e22fdec13cdc 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -845,6 +845,8 @@ export interface HogQLQueryModifiersApi {
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserModeApi | null
+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
+ personIdPushdown?: boolean | null
personsArgMaxVersion?: PersonsArgMaxVersionApi | null
personsJoinMode?: PersonsJoinModeApi | null
personsOnEventsMode?: PersonsOnEventsModeApi | null
diff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.ts
index d6f68298ed9f..d9e1326cce53 100644
--- a/products/batch_exports/frontend/generated/api.zod.ts
+++ b/products/batch_exports/frontend/generated/api.zod.ts
@@ -611,6 +611,12 @@ export const BatchExportsCreateBody = /* @__PURE__ */ zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -1556,6 +1562,12 @@ export const BatchExportsUpdateBody = /* @__PURE__ */ zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -2260,6 +2272,12 @@ export const BatchExportsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -2956,6 +2974,12 @@ export const BatchExportsRunTestStepCreateBody = /* @__PURE__ */ zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -3671,6 +3695,12 @@ export const BatchExportsRunTestStepNewCreateBody = /* @__PURE__ */ zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -4096,6 +4126,12 @@ export const FileDownloadBatchExportsCreateBody = /* @__PURE__ */ zod.union([
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -4344,6 +4380,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = /* @__PURE__ */ zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index bd783386e41e..26505328e018 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1767,6 +1767,8 @@ export interface HogQLQueryModifiersApi {
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserModeApi | null
+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
+ personIdPushdown?: boolean | null
personsArgMaxVersion?: PersonsArgMaxVersionApi | null
personsJoinMode?: PersonsJoinModeApi | null
personsOnEventsMode?: PersonsOnEventsModeApi | null
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 9726233d2198..00f455e59a8d 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1594,6 +1594,8 @@ export interface HogQLQueryModifiersApi {
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserModeApi | null
+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
+ personIdPushdown?: boolean | null
personsArgMaxVersion?: PersonsArgMaxVersionApi | null
personsJoinMode?: PersonsJoinModeApi | null
personsOnEventsMode?: PersonsOnEventsModeApi | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 0e3586c02589..12d522a468d9 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -651,6 +651,8 @@ export interface HogQLQueryModifiersApi {
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserModeApi | null
+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
+ personIdPushdown?: boolean | null
personsArgMaxVersion?: PersonsArgMaxVersionApi | null
personsJoinMode?: PersonsJoinModeApi | null
personsOnEventsMode?: PersonsOnEventsModeApi | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 382a4b808935..620291a811f3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2599,6 +2599,8 @@ export namespace Schemas {
optimizeProjections?: boolean | null;
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserMode | null;
+ /** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
+ personIdPushdown?: boolean | null;
personsArgMaxVersion?: PersonsArgMaxVersion | null;
personsJoinMode?: PersonsJoinMode | null;
personsOnEventsMode?: PersonsOnEventsMode | null;
diff --git a/services/mcp/src/generated/batch_exports/api.ts b/services/mcp/src/generated/batch_exports/api.ts
index 418a36a0e593..79c09f235f36 100644
--- a/services/mcp/src/generated/batch_exports/api.ts
+++ b/services/mcp/src/generated/batch_exports/api.ts
@@ -623,6 +623,12 @@ export const BatchExportsCreateBody = () => zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -1331,6 +1337,12 @@ export const BatchExportsPartialUpdateBody = () => zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -1770,6 +1782,12 @@ export const FileDownloadBatchExportsCreateBody = () => zod.union([
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
@@ -2054,6 +2072,12 @@ export const FileDownloadBatchExportsCountRowsCreateBody = () => zod
.describe(
'HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `\*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_\*` modes drive the same hand-rolled Rust parser as `rust_\*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.'
),
+ personIdPushdown: zod
+ .union([zod.boolean(), zod.null()])
+ .optional()
+ .describe(
+ "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ ),
personsArgMaxVersion: zod.union([zod.enum(['auto', 'v1', 'v2']), zod.null()]).optional(),
personsJoinMode: zod.union([zod.enum(['inner', 'left']), zod.null()]).optional(),
personsOnEventsMode: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
index c3cdb9c9c49a..9e08527041ca 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-create.json
@@ -899,6 +899,17 @@
],
"description": "HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip."
},
+ "personIdPushdown": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ },
"personsArgMaxVersion": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
index ae01b32d68cd..deca174e2521 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/batch-export-update.json
@@ -898,6 +898,17 @@
],
"description": "HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip."
},
+ "personIdPushdown": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ },
"personsArgMaxVersion": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
index c5d37042dd69..4bcd2e3965ea 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-count-rows-create.json
@@ -374,6 +374,17 @@
],
"description": "HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip."
},
+ "personIdPushdown": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ },
"personsArgMaxVersion": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
index 6a9cded8c25b..1aad18a83562 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/file-download-batch-exports-create.json
@@ -603,6 +603,17 @@
],
"description": "HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip."
},
+ "personIdPushdown": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table."
+ },
"personsArgMaxVersion": {
"anyOf": [
{