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): push down events predicates through lazy joins (#61129)

Robbie2c01924bb340
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 434272283305..83c33e7891ff 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -22318,6 +22318,9 @@
"enum": ["enabled", "disabled", "optimized"],
"type": "string"
},
+ "pushDownPredicates": {
+ "type": "boolean"
+ },
"s3TableUseInvalidColumns": {
"type": "boolean"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index ef9a4bc700ac..4757f9d62b2d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -449,6 +449,7 @@ export interface HogQLQueryModifiers {
usePreaggregatedTableTransforms?: boolean
usePreaggregatedIntermediateResults?: boolean
optimizeProjections?: boolean
+ pushDownPredicates?: boolean
/** If these are provided, the query will fail if these skip indexes are not used */
forceClickhouseDataSkippingIndexes?: string[]
inlineCohortCalculation?: 'off' | 'auto' | 'always'
diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambr
index e7927ea4347f..9717b03b07ba 100644
--- a/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambr
+++ b/posthog/hogql/database/schema/test/__snapshots__/test_sessions_v3.ambr
@@ -555,14 +555,18 @@
# name: TestSessionsV3.test_session_dot_channel_type
'''
SELECT events__session.`$channel_type` AS `$channel_type`
- FROM events
+ FROM
+ (SELECT events.`$session_id` AS `$session_id`,
+ events.`$session_id_uuid` AS `$session_id_uuid`
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.`$session_id_uuid`, toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID'))))
+ LIMIT 100) AS events
LEFT JOIN
(SELECT multiIf(match(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 3), ''), 'null')), 'cross-network'), 'Cross Network', or(in(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 2), ''), 'null')), tuple('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')), startsWith(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 2), ''), 'null')), 'paid'), tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 5), isNotNull(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 7), ''), 'null'))), coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 1), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 1), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 3), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Paid Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 2), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (coalesce(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 4), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_paid', (cutToFirstSignificantSubdomain(coalesce(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 4), '')), 'source'))), multiIf(ifNull(equals(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 7), ''), 'null'), '1'), 0), 'Paid Search', match(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 3), ''), 'null')), '^(.*video.*)$'), 'Paid Video', tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 6), 'Paid Social', 'Paid Unknown')), and(ifNull(equals(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 4), '$direct'), 0), isNull(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 2), ''), 'null'))), or(isNull(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 1), ''), 'null'))), in(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 1), ''), 'null')), tuple('(direct)', 'direct', '$direct'))), not(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 6))), 'Direct', coalesce(coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 1), ''), 'null')), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 1), ''), 'null')), '')), 'source'))), if(match(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 3), ''), 'null')), '^(.*(([^a-df-z]|^)shop|shopping).*)$'), 'Organic Shopping', NULL), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 2), ''), 'null')), ''), 'medium')), coalesce(dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (coalesce(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 4), ''), 'source')), dictGetOrNull('posthog_test.channel_definition_dict', 'type_if_organic', (cutToFirstSignificantSubdomain(coalesce(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 4), '')), 'source'))), multiIf(match(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 3), ''), 'null')), '^(.*video.*)$'), 'Organic Video', match(lower(nullIf(nullIf(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 2), ''), 'null')), 'push$'), 'Push', tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 6), 'Organic Social', ifNull(equals(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 4), '$direct'), 0), 'Direct', isNotNull(tupleElement(argMinMerge(raw_sessions_v3.entry_channel_type_properties), 4)), 'Referral', 'Unknown'))) AS `$channel_type`,
raw_sessions_v3.session_id_v7 AS session_id_v7
FROM raw_sessions_v3
WHERE and(equals(raw_sessions_v3.team_id, 99999), equals(raw_sessions_v3.session_timestamp, fromUnixTimestamp64Milli(toUInt64(bitShiftRight(toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), 80)))))
GROUP BY raw_sessions_v3.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(equals(events.team_id, 99999), equals(events.`$session_id_uuid`, toUInt128(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID'))))
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
diff --git a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambr b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambr
index 2e82b682f6d4..3d0922d9d1de 100644
--- a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambr
+++ b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v2_where_clause_extractor.ambr
@@ -189,9 +189,16 @@
SELECT
events__session.`$session_duration` AS duration
FROM
- events
+ (SELECT
+ events.`$session_id_uuid` AS `$session_id_uuid`,
+ toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM
+ events
+ WHERE
+ and(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))
+ LIMIT 50000) AS events
LEFT JOIN (SELECT
- dateDiff(%(hogql_val_0)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`,
+ dateDiff(%(hogql_val_1)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_2)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_3)s))) AS `$session_duration`,
raw_sessions.session_id_v7 AS session_id_v7
FROM
raw_sessions
@@ -199,8 +206,6 @@
and(equals(raw_sessions.team_id, <TEAM_ID>), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(today(), toIntervalDay(3))))
GROUP BY
raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE
- and(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))
LIMIT 50000
'''
# ---
diff --git a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambr b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambr
index 6d04546652c4..ad585ab0c849 100644
--- a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambr
+++ b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_v3_where_clause_extractor.ambr
@@ -204,9 +204,16 @@
SELECT
events__session.`$session_duration` AS duration
FROM
- events
+ (SELECT
+ events.`$session_id_uuid` AS `$session_id_uuid`,
+ toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM
+ events
+ WHERE
+ and(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))
+ LIMIT 50000) AS events
LEFT JOIN (SELECT
- dateDiff(%(hogql_val_0)s, min(toTimeZone(raw_sessions_v3.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(raw_sessions_v3.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`,
+ dateDiff(%(hogql_val_1)s, min(toTimeZone(raw_sessions_v3.min_timestamp, %(hogql_val_2)s)), max(toTimeZone(raw_sessions_v3.max_timestamp, %(hogql_val_3)s))) AS `$session_duration`,
raw_sessions_v3.session_id_v7 AS session_id_v7
FROM
raw_sessions_v3
@@ -214,8 +221,6 @@
and(equals(raw_sessions_v3.team_id, <TEAM_ID>), lessOrEquals(raw_sessions_v3.session_timestamp, plus(today(), toIntervalDay(3))))
GROUP BY
raw_sessions_v3.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE
- and(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))
LIMIT 50000
'''
# ---
diff --git a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambr b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambr
index 91098b3c6d98..4a5d9a9e1526 100644
--- a/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambr
+++ b/posthog/hogql/database/schema/util/test/__snapshots__/test_session_where_clause_extractor.ambr
@@ -118,9 +118,16 @@
SELECT
events__session.`$session_duration` AS duration
FROM
- events
+ (SELECT
+ events.`$session_id` AS `$session_id`,
+ toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM
+ events
+ WHERE
+ and(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))
+ LIMIT 50000) AS events
LEFT JOIN (SELECT
- dateDiff(%(hogql_val_0)s, min(toTimeZone(sessions.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(sessions.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`,
+ dateDiff(%(hogql_val_1)s, min(toTimeZone(sessions.min_timestamp, %(hogql_val_2)s)), max(toTimeZone(sessions.max_timestamp, %(hogql_val_3)s))) AS `$session_duration`,
sessions.session_id AS session_id
FROM
sessions
@@ -129,8 +136,6 @@
GROUP BY
sessions.session_id,
sessions.session_id) AS events__session ON equals(events.`$session_id`, events__session.session_id)
- WHERE
- and(equals(events.team_id, <TEAM_ID>), less(events.timestamp, today()))
LIMIT 50000
'''
# ---
diff --git a/posthog/hogql/database/schema/util/test/test_predicate_pushdown.py b/posthog/hogql/database/schema/util/test/test_predicate_pushdown.py
new file mode 100644
index 000000000000..94d2cc32194d
--- /dev/null
+++ b/posthog/hogql/database/schema/util/test/test_predicate_pushdown.py
@@ -0,0 +1,263 @@
+from typing import Optional
+
+from parameterized import parameterized
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.models import LazyJoin
+from posthog.hogql.database.schema.events import EventsTable
+from posthog.hogql.database.schema.util.where_clause_extractor import (
+ EventsPredicatePushdownExtractor,
+ JoinedTableReferenceFinder,
+ contains_subquery,
+ references_joined_table,
+)
+from posthog.hogql.parser import parse_expr
+from posthog.hogql.printer import print_prepared_ast
+
+
+def make_field(chain: list[str | int], table_type: Optional[ast.TableType] = None) -> ast.Field:
+ """Create a field with optional type information."""
+ field_type = None
+ if table_type is not None and len(chain) > 0:
+ last = chain[-1]
+ field_type = ast.FieldType(name=str(last), table_type=table_type)
+ return ast.Field(chain=chain, type=field_type)
+
+
+def make_events_table_type() -> ast.TableType:
+ """Create a TableType for the events table."""
+ return ast.TableType(table=EventsTable())
+
+
+def make_lazy_join_type(field: str) -> ast.LazyJoinType:
+ """Create a mock LazyJoinType for testing."""
+ return ast.LazyJoinType(
+ table_type=make_events_table_type(),
+ field=field,
+ lazy_join=LazyJoin(from_field=["id"], join_table=EventsTable(), join_function=lambda *args: None),
+ )
+
+
+def make_select_query_alias_type(alias: str) -> ast.SelectQueryAliasType:
+ """Create a SelectQueryAliasType for testing."""
+ return ast.SelectQueryAliasType(alias=alias, select_query_type=None) # type: ignore[arg-type]
+
+
+class TestJoinedTableReferenceFinder:
+ @parameterized.expand(
+ [
+ # (test_name, field_chain, joined_aliases, expected_found)
+ ("field_in_joined_aliases", ["session", "duration"], {"session"}, True),
+ ("field_not_in_joined_aliases", ["events", "timestamp"], {"session"}, False),
+ ("nested_field_in_joined_aliases", ["events__session", "id"], {"events__session"}, True),
+ ("empty_joined_aliases", ["session", "duration"], set(), False),
+ ("multiple_aliases_match_first", ["person", "id"], {"person", "session"}, True),
+ ("multiple_aliases_no_match", ["events", "id"], {"person", "session"}, False),
+ ]
+ )
+ def test_field_chain_detection(self, _name, field_chain, joined_aliases, expected_found):
+ field = make_field(field_chain)
+ finder = JoinedTableReferenceFinder(joined_aliases)
+ finder.visit(field)
+ assert finder.found_joined_reference == expected_found
+
+ def test_lazy_join_type_detected_via_type_system(self):
+ """Fields typed with LazyJoinType should be detected even if chain doesn't match."""
+ lazy_join_type = make_lazy_join_type("session")
+ field = ast.Field(
+ chain=["custom_alias", "duration"],
+ type=ast.FieldType(name="duration", table_type=lazy_join_type),
+ )
+ finder = JoinedTableReferenceFinder(set()) # Empty set - rely on type system
+ finder.visit(field)
+ assert finder.found_joined_reference is True
+
+ def test_select_query_alias_type_detected_via_type_system(self):
+ """Fields typed with SelectQueryAliasType should be detected."""
+ subquery_type = make_select_query_alias_type("subquery")
+ field = ast.Field(
+ chain=["subquery", "id"],
+ type=ast.FieldType(name="id", table_type=subquery_type),
+ )
+ finder = JoinedTableReferenceFinder(set())
+ finder.visit(field)
+ assert finder.found_joined_reference is True
+
+ def test_property_type_with_lazy_join_detected(self):
+ """PropertyType wrapping a LazyJoinType should be detected."""
+ lazy_join_type = make_lazy_join_type("person")
+ field_type = ast.FieldType(name="properties", table_type=lazy_join_type)
+ property_type = ast.PropertyType(chain=["email"], field_type=field_type)
+ field = ast.Field(chain=["person", "properties", "email"], type=property_type)
+
+ finder = JoinedTableReferenceFinder(set())
+ finder.visit(field)
+ assert finder.found_joined_reference is True
+
+ def test_table_type_not_detected_as_joined(self):
+ """Fields typed with plain TableType should not be detected as joined."""
+ table_type = make_events_table_type()
+ field = ast.Field(
+ chain=["events", "timestamp"],
+ type=ast.FieldType(name="timestamp", table_type=table_type),
+ )
+ finder = JoinedTableReferenceFinder(set())
+ finder.visit(field)
+ assert finder.found_joined_reference is False
+
+
+class TestReferencesJoinedTable:
+ @parameterized.expand(
+ [
+ # (test_name, expr_str, joined_aliases, expected)
+ ("comparison_with_joined_field", "session.duration > 0", {"session"}, True),
+ ("comparison_without_joined_field", "timestamp > '2024-01-01'", {"session"}, False),
+ ("and_with_joined_field", "timestamp > '2024-01-01' AND session.duration > 0", {"session"}, True),
+ ("nested_function_with_joined_field", "ifNull(session.duration, 0) > 0", {"session"}, True),
+ ]
+ )
+ def test_references_joined_table(self, _name, expr_str, joined_aliases, expected):
+ expr = parse_expr(expr_str)
+ assert references_joined_table(expr, joined_aliases) is expected
+
+
+def print_expr(expr: Optional[ast.Expr]) -> Optional[str]:
+ """Print an expression to HogQL string for comparison."""
+ if expr is None:
+ return None
+ context = HogQLContext(team_id=1)
+ return print_prepared_ast(node=expr, context=context, dialect="hogql")
+
+
+class TestEventsPredicatePushdownExtractor:
+ @parameterized.expand(
+ [
+ # (test_name, expr_str, joined_aliases, expected_inner, expected_outer)
+ (
+ "simple_timestamp_filter_pushable",
+ "timestamp >= '2024-01-01'",
+ set(),
+ "greaterOrEquals(timestamp, '2024-01-01')",
+ None,
+ ),
+ (
+ "joined_field_not_pushable",
+ "session.duration > 0",
+ {"session"},
+ None,
+ "greater(session.duration, 0)",
+ ),
+ (
+ "and_with_all_pushable",
+ "timestamp >= '2024-01-01' AND event = 'click'",
+ set(),
+ "and(greaterOrEquals(timestamp, '2024-01-01'), equals(event, 'click'))",
+ None,
+ ),
+ (
+ "and_splits_pushable_from_joined",
+ "timestamp >= '2024-01-01' AND session.duration > 0",
+ {"session"},
+ "greaterOrEquals(timestamp, '2024-01-01')",
+ "greater(session.duration, 0)",
+ ),
+ (
+ "or_with_joined_stays_in_outer",
+ "timestamp >= '2024-01-01' OR session.duration > 0",
+ {"session"},
+ None,
+ "or(greaterOrEquals(timestamp, '2024-01-01'), greater(session.duration, 0))",
+ ),
+ (
+ "multiple_pushable_predicates",
+ "timestamp >= '2024-01-01' AND timestamp < '2024-02-01' AND event = 'click'",
+ set(),
+ "and(greaterOrEquals(timestamp, '2024-01-01'), less(timestamp, '2024-02-01'), equals(event, 'click'))",
+ None,
+ ),
+ (
+ "nested_and_with_joined",
+ "(timestamp >= '2024-01-01' AND event = 'click') AND session.duration > 0",
+ {"session"},
+ "and(greaterOrEquals(timestamp, '2024-01-01'), equals(event, 'click'))",
+ "greater(session.duration, 0)",
+ ),
+ (
+ "function_with_joined_field_not_pushable",
+ "ifNull(session.duration, 0) > 0",
+ {"session"},
+ None,
+ "greater(ifNull(session.duration, 0), 0)",
+ ),
+ ]
+ )
+ def test_predicate_splitting(self, _name, expr_str, joined_aliases, expected_inner, expected_outer):
+ expr = parse_expr(expr_str)
+
+ extractor = EventsPredicatePushdownExtractor(joined_aliases)
+ inner_where, outer_where = extractor.get_pushdown_predicates(expr)
+
+ assert print_expr(inner_where) == expected_inner
+ assert print_expr(outer_where) == expected_outer
+
+ def test_empty_joined_aliases_relies_on_type_system(self):
+ """With empty joined_aliases, detection relies entirely on type system."""
+ # Create a field with LazyJoinType
+ lazy_join_type = make_lazy_join_type("session")
+ field = ast.Field(
+ chain=["session", "duration"],
+ type=ast.FieldType(name="duration", table_type=lazy_join_type),
+ )
+ comparison = ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=field,
+ right=ast.Constant(value=0),
+ )
+
+ extractor = EventsPredicatePushdownExtractor(set())
+ inner_where, outer_where = extractor.get_pushdown_predicates(comparison)
+
+ # Should detect via type system even with empty joined_aliases
+ assert inner_where is None
+ assert outer_where is not None
+
+ def test_in_cohort_predicate_stays_outer(self):
+ """An unresolved IN COHORT op (inCohortVia=LEFTJOIN) becomes a cohort LEFT JOIN after pushdown, so it
+ must not be pushed into the events subquery; the events-only timestamp predicate still pushes."""
+ timestamp = ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value="2024-01-01"),
+ )
+ in_cohort = ast.CompareOperation(
+ op=ast.CompareOperationOp.InCohort,
+ left=ast.Field(chain=["person_id"]),
+ right=ast.Constant(value=1),
+ )
+ extractor = EventsPredicatePushdownExtractor(set())
+ inner_where, outer_where = extractor.get_pushdown_predicates(ast.And(exprs=[timestamp, in_cohort]))
+
+ assert isinstance(inner_where, ast.CompareOperation) and inner_where.op == ast.CompareOperationOp.GtEq
+ assert isinstance(outer_where, ast.CompareOperation) and outer_where.op == ast.CompareOperationOp.InCohort
+
+ def test_in_cohort_only_predicate_not_pushable(self):
+ """A standalone IN COHORT / NOT IN COHORT predicate is non-pushable (nothing left to push)."""
+ for op in (ast.CompareOperationOp.InCohort, ast.CompareOperationOp.NotInCohort):
+ in_cohort = ast.CompareOperation(op=op, left=ast.Field(chain=["person_id"]), right=ast.Constant(value=1))
+ extractor = EventsPredicatePushdownExtractor(set())
+ inner_where, outer_where = extractor.get_pushdown_predicates(in_cohort)
+
+ assert inner_where is None, f"{op}: should not be pushable"
+ assert isinstance(outer_where, ast.CompareOperation) and outer_where.op == op
+
+ def test_subquery_predicate_stays_outer(self):
+ """A predicate with a nested subquery (e.g. inCohortVia=SUBQUERY's IN (SELECT ...)) is not pushable;
+ a plain events predicate alongside it still pushes."""
+ expr = parse_expr("event = 'x' AND person_id IN (SELECT person_id FROM raw_cohortpeople)")
+ extractor = EventsPredicatePushdownExtractor(set())
+ inner_where, outer_where = extractor.get_pushdown_predicates(expr)
+
+ # the bare `event = 'x'` pushes; the IN (SELECT ...) stays outer
+ assert inner_where is not None and not contains_subquery(inner_where)
+ assert outer_where is not None and contains_subquery(outer_where)
diff --git a/posthog/hogql/database/schema/util/where_clause_extractor.py b/posthog/hogql/database/schema/util/where_clause_extractor.py
index db20b0936cb4..ca1a22737f02 100644
--- a/posthog/hogql/database/schema/util/where_clause_extractor.py
+++ b/posthog/hogql/database/schema/util/where_clause_extractor.py
@@ -845,3 +845,384 @@ def is_not_truthy(value):
def is_truthy(value):
return not is_not_truthy(value)
+
+
+class _FieldNodeCollector(TraversingVisitor):
+ """Collects every Field node in an expression (used to inspect what a SELECT alias references)."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.fields: list[ast.Field] = []
+
+ def visit_field(self, node: ast.Field) -> None:
+ self.fields.append(node)
+ super().visit_field(node)
+
+
+# ClickHouse functions that emit more than one output row per input row. A predicate containing one of
+# these cannot be pushed into the events subquery: it would multiply rows in a different scope than the
+# same call in the outer SELECT/GROUP BY, changing the result set (the on-vs-off pushdown invariant).
+# `arrayJoin` is the only such function reachable inside a WHERE predicate: `untuple` expands a tuple into
+# columns (not rows), and the clause-level `ARRAY JOIN` lives on the SelectQuery, not in a predicate. Add
+# any future array-expanding function HogQL lowers into WHERE here.
+_ROW_MULTIPLYING_FUNCTIONS = {"arrayJoin"}
+
+
+class _RowMultiplyingFunctionFinder(TraversingVisitor):
+ """Detects any row-multiplying function call (e.g. arrayJoin) anywhere in an expression."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_call(self, node: ast.Call) -> None:
+ if node.name in _ROW_MULTIPLYING_FUNCTIONS:
+ self.found = True
+ super().visit_call(node)
+
+
+def contains_row_multiplying_function(expr: ast.Expr) -> bool:
+ finder = _RowMultiplyingFunctionFinder()
+ finder.visit(expr)
+ return finder.found
+
+
+class _InCohortFinder(TraversingVisitor):
+ """Detects an unresolved IN COHORT / NOT IN COHORT comparison anywhere in an expression."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_compare_operation(self, node: ast.CompareOperation) -> None:
+ if node.op in (ast.CompareOperationOp.InCohort, ast.CompareOperationOp.NotInCohort):
+ self.found = True
+ super().visit_compare_operation(node)
+
+
+def contains_in_cohort(expr: ast.Expr) -> bool:
+ """An unresolved IN COHORT op (inCohortVia=LEFTJOIN) is rewritten to a cohort LEFT JOIN *after* pushdown
+ runs. Pushing it would move that join inside the synthetic events subquery; keep it out so the pushdown
+ declines. (inCohortVia=SUBQUERY resolves to `IN (subquery)` before pushdown, caught by contains_subquery.)
+ """
+ finder = _InCohortFinder()
+ finder.visit(expr)
+ return finder.found
+
+
+class _SubqueryFinder(TraversingVisitor):
+ """Detects a nested SELECT (e.g. an `IN (SELECT …)`) anywhere in an expression."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.found = False
+
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ self.found = True
+
+ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:
+ self.found = True
+
+
+def contains_subquery(expr: ast.Expr) -> bool:
+ """A predicate with a nested SELECT (e.g. `person_id IN (SELECT … FROM cohortpeople)`, the inCohortVia=
+ SUBQUERY form of IN COHORT) is kept out of the events subquery: rebuilding the hand-typed subquery around
+ an already-resolved nested query is a correctness risk, and these are rare in pushable filters.
+ """
+ finder = _SubqueryFinder()
+ finder.visit(expr)
+ return finder.found
+
+
+class JoinedTableReferenceFinder(TraversingVisitor):
+ """Checks if an expression references fields that should not be pushed down into an events subquery.
+
+ Supports two modes:
+
+ Allowlist mode (when events_table_type is provided):
+ Only fields whose type resolves to the events table are pushable.
+ Untyped fields and fields resolving to non-events types are blocked.
+ This catches SELECT-level aliases like step_0 that expand to expressions
+ referencing the outer scope.
+
+ Blocklist mode (when events_table_type is None):
+ Fields are blocked only if they reference joined table aliases or have
+ lazy join / subquery types. Used in tests with untyped expressions.
+ """
+
+ def __init__(
+ self,
+ joined_table_aliases: set[str],
+ events_table_type: ast.TableType | ast.TableAliasType | None = None,
+ select_aliases: dict[str, ast.Expr] | None = None,
+ ):
+ super().__init__()
+ self.joined_table_aliases = joined_table_aliases
+ self.events_table_type = events_table_type
+ # Map of SELECT-list alias name -> its expression, used to classify a WHERE field that
+ # resolves to a SELECT alias by what the alias actually references (not just its name).
+ self.select_aliases = select_aliases or {}
+ self.found_joined_reference = False
+
+ def visit_field(self, node: ast.Field):
+ # Check 1: Field chain references a known joined table alias
+ if node.chain and len(node.chain) > 0:
+ first_part = node.chain[0]
+ if isinstance(first_part, str) and first_part in self.joined_table_aliases:
+ self.found_joined_reference = True
+ return
+
+ # Check 2: Type-based check
+ if self.events_table_type is not None:
+ # Allowlist mode: field must resolve to the events table
+ if node.type is None:
+ self.found_joined_reference = True
+ return
+ if not self._is_events_field(node.type):
+ self.found_joined_reference = True
+ else:
+ # Blocklist mode: check for lazy join/subquery types
+ if node.type is not None and self._type_references_lazy_join(node.type):
+ self.found_joined_reference = True
+
+ def _is_events_field(self, type_node: ast.Type) -> bool:
+ """Check if a type resolves to a field on the events table (allowlist check)."""
+ visited: set[int] = set()
+ alias_names: list[str] = []
+ to_check: list[ast.Type] = [type_node]
+
+ while to_check:
+ current = to_check.pop()
+ if current is None or id(current) in visited:
+ continue
+ visited.add(id(current))
+
+ if isinstance(current, ast.FieldAliasType):
+ alias_names.append(current.alias)
+ to_check.append(current.type)
+ continue
+ if isinstance(current, ast.PropertyType):
+ to_check.append(current.field_type)
+ continue
+
+ if isinstance(current, ast.FieldType):
+ if not self._table_type_matches_events(current.table_type):
+ return False
+ # Reaching the events FieldType through an alias whose name isn't an events column means a
+ # SELECT-level alias (e.g. `events.$group_0 AS aggregation_target`) the subquery won't expose.
+ if any(not self._is_events_column_name(a) for a in alias_names):
+ return False
+ return True
+
+ # Non-field type (e.g. a CallType from `toTimeZone(timestamp, 'UTC') AS timestamp`). Pushable only
+ # if the alias name is an events column AND the alias body is events-only (checked below). Trusting
+ # the name alone would wrongly push `f(session.x) AS event` or `'x' AS event`.
+ if alias_names and self._is_events_column_name(alias_names[0]):
+ alias_expr = self.select_aliases.get(alias_names[0])
+ if alias_expr is not None and self._alias_expr_only_events(alias_expr):
+ return True
+
+ return False
+
+ return False
+
+ def _alias_expr_only_events(self, expr: ast.Expr) -> bool:
+ """A SELECT-alias expression is safe to push only if it references at least one events column
+ and no non-events (joined / other) column, so re-binding the alias name to the inner events
+ column is correct. The field's type alone is lossy for call expressions, so we walk the actual
+ expression and check each referenced field's table."""
+ # An arrayJoin hidden in the alias body can't be pushed: the WHERE field is the bare alias (so the
+ # top-level row-multiplying check misses it), but SelectAliasInliner later expands it into the
+ # subquery, multiplying rows in a scope independent of the outer SELECT's copy and changing results.
+ if contains_row_multiplying_function(expr):
+ return False
+ collector = _FieldNodeCollector()
+ collector.visit(expr)
+ if not collector.fields:
+ return False # constant or no column reference -> re-binding the alias name would be wrong
+ return all(self._table_type_matches_events(self._field_table_type(f.type)) for f in collector.fields)
+
+ def _field_table_type(self, type_node: ast.Type | None) -> ast.Type | None:
+ """Unwrap FieldAliasType / PropertyType to the underlying field's table_type, or None for a
+ non-column expression (e.g. a nested CallType) which we treat conservatively as non-events."""
+ seen: set[int] = set()
+ current = type_node
+ while current is not None and id(current) not in seen:
+ seen.add(id(current))
+ if isinstance(current, ast.FieldType):
+ return current.table_type
+ if isinstance(current, ast.PropertyType):
+ current = current.field_type
+ continue
+ if isinstance(current, ast.FieldAliasType):
+ current = current.type
+ continue
+ return None
+ return None
+
+ def _is_events_column_name(self, name: str) -> bool:
+ """Check if a name matches a column on the events table."""
+ if self.events_table_type is None:
+ return False
+ target: ast.TableType | ast.TableAliasType | ast.LazyTableType = self.events_table_type
+ if isinstance(target, ast.TableAliasType):
+ target = target.table_type
+ if isinstance(target, ast.TableType) and hasattr(target.table, "fields"):
+ return name in target.table.fields
+ return False
+
+ def _table_type_matches_events(self, table_type: ast.Type | None) -> bool:
+ """Check if a table type matches the events table."""
+ if table_type is None or self.events_table_type is None:
+ return False
+
+ unwrapped: ast.Type = table_type
+ if isinstance(unwrapped, ast.TableAliasType):
+ unwrapped = unwrapped.table_type
+ if isinstance(unwrapped, ast.VirtualTableType):
+ unwrapped = unwrapped.table_type
+ if isinstance(unwrapped, ast.TableAliasType):
+ unwrapped = unwrapped.table_type
+
+ target: ast.Type = self.events_table_type
+ if isinstance(target, ast.TableAliasType):
+ target = target.table_type
+
+ if isinstance(unwrapped, ast.TableType) and isinstance(target, ast.TableType):
+ return unwrapped.table is target.table
+
+ return table_type is self.events_table_type
+
+ def _type_references_lazy_join(self, type_node) -> bool:
+ """Blocklist check: returns True if type resolves to a lazy join or subquery."""
+ visited: set[int] = set()
+ to_check = [type_node]
+
+ while to_check:
+ current = to_check.pop()
+ if current is None or id(current) in visited:
+ continue
+ visited.add(id(current))
+
+ if isinstance(current, ast.LazyJoinType):
+ return True
+ if isinstance(current, ast.SelectQueryAliasType):
+ return True
+
+ if isinstance(current, ast.FieldAliasType):
+ to_check.append(current.type)
+ continue
+ if isinstance(current, ast.VirtualTableType):
+ to_check.append(current.table_type)
+ continue
+ if isinstance(current, ast.TableAliasType):
+ to_check.append(current.table_type)
+ continue
+
+ if isinstance(current, ast.PropertyType):
+ to_check.append(current.field_type)
+ elif isinstance(current, ast.FieldType):
+ to_check.append(current.table_type)
+
+ return False
+
+
+def references_joined_table(
+ expr: ast.Expr,
+ joined_table_aliases: set[str],
+ events_table_type: ast.TableType | ast.TableAliasType | None = None,
+ select_aliases: dict[str, ast.Expr] | None = None,
+) -> bool:
+ """Check if an expression references any field that should not be pushed down."""
+ finder = JoinedTableReferenceFinder(joined_table_aliases, events_table_type, select_aliases)
+ finder.visit(expr)
+ return finder.found_joined_reference
+
+
+class EventsPredicatePushdownExtractor:
+ """
+ Extracts predicates from a WHERE clause that can be pushed down into an events subquery.
+
+ This class analyzes WHERE clauses and splits them into:
+ - inner_where: Predicates that only reference the events table (can be pushed down)
+ - outer_where: Predicates that reference joined tables (must stay in outer query)
+
+ The design is fail-safe: if we can't determine whether a predicate is pushable,
+ we keep it in the outer WHERE (may scan more data but never incorrect).
+ """
+
+ def __init__(
+ self,
+ joined_table_aliases: set[str],
+ events_table_type: ast.TableType | ast.TableAliasType | None = None,
+ select_aliases: dict[str, ast.Expr] | None = None,
+ ):
+ self.joined_table_aliases = joined_table_aliases
+ self.events_table_type = events_table_type
+ self.select_aliases = select_aliases or {}
+
+ def get_pushdown_predicates(self, where: ast.Expr) -> tuple[Optional[ast.Expr], Optional[ast.Expr]]:
+ """
+ Split a WHERE expression into inner (pushable) and outer (non-pushable) parts.
+
+ Returns:
+ (inner_where, outer_where) tuple where:
+ - inner_where: Predicates to push into events subquery (or None if none)
+ - outer_where: Predicates to keep in outer query (or None if none)
+ """
+ inner_exprs, outer_exprs = self._split_expression(where)
+
+ inner_where = self._combine_with_and(inner_exprs)
+ outer_where = self._combine_with_and(outer_exprs)
+
+ return (inner_where, outer_where)
+
+ def _split_expression(self, expr: ast.Expr) -> tuple[list[ast.Expr], list[ast.Expr]]:
+ """
+ Recursively split an expression into inner (pushable) and outer (non-pushable) parts.
+
+ Returns:
+ (inner_exprs, outer_exprs) - lists of expressions for inner and outer WHERE
+ """
+ if isinstance(expr, ast.And):
+ # For AND: we can split - pushable parts go inner, non-pushable stay outer
+ inner_exprs: list[ast.Expr] = []
+ outer_exprs: list[ast.Expr] = []
+ for sub_expr in flatten_ands(expr.exprs):
+ sub_inner, sub_outer = self._split_expression(sub_expr)
+ inner_exprs.extend(sub_inner)
+ outer_exprs.extend(sub_outer)
+ return (inner_exprs, outer_exprs)
+
+ elif isinstance(expr, ast.Call):
+ # Handle function calls like and(), or(), not(), equals(), etc.
+ if expr.name == "and":
+ return self._split_expression(ast.And(exprs=expr.args))
+ elif expr.name == "or":
+ return self._split_expression(ast.Or(exprs=expr.args))
+
+ cloned = clone_expr(expr, clear_types=False, clear_locations=True)
+ # Keep in the outer query (fail-safe), same as a joined-table reference, when the predicate:
+ # - contains a row-multiplying call (arrayJoin): pushing it would expand rows in a different scope
+ # than the same call in the outer SELECT/GROUP BY, changing the result set;
+ # - contains an unresolved IN COHORT op (inCohortVia=LEFTJOIN): it becomes a cohort LEFT JOIN after
+ # pushdown, which must not land inside the synthetic events subquery; or
+ # - contains a nested subquery (e.g. the inCohortVia=SUBQUERY `IN (SELECT …)` form, or any other
+ # `x IN (SELECT …)`): rebuilding the hand-typed subquery around it is a correctness risk.
+ if (
+ references_joined_table(expr, self.joined_table_aliases, self.events_table_type, self.select_aliases)
+ or contains_row_multiplying_function(expr)
+ or contains_in_cohort(expr)
+ or contains_subquery(expr)
+ ):
+ return ([], [cloned])
+ return ([cloned], [])
+
+ def _combine_with_and(self, exprs: list[ast.Expr]) -> Optional[ast.Expr]:
+ """Combine a list of expressions with AND, or return None if empty."""
+ if len(exprs) == 0:
+ return None
+ elif len(exprs) == 1:
+ return exprs[0]
+ else:
+ return ast.And(exprs=exprs)
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index 376d46cb483f..6ba3d79a9085 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -21,6 +21,7 @@ from posthog.hogql.printer.duckdb import DuckDBPrinter
from posthog.hogql.printer.hogql import HogQLPrinter
from posthog.hogql.printer.postgres import PostgresPrinter
from posthog.hogql.resolver import ResolverFactory, resolve_types
+from posthog.hogql.transforms.events_predicate_pushdown import apply_events_predicate_pushdown, events_pushdown_enabled
from posthog.hogql.transforms.in_cohort import resolve_in_cohorts, resolve_in_cohorts_conjoined
from posthog.hogql.transforms.lazy_tables import resolve_lazy_tables
from posthog.hogql.transforms.projection_pushdown import pushdown_projections
@@ -176,6 +177,10 @@ def prepare_ast_for_printing(
with context.timings.measure("resolve_lazy_tables"):
resolve_lazy_tables(node, dialect, stack, context, resolver_factory=resolver_factory)
+ if events_pushdown_enabled(context.modifiers):
+ with context.timings.measure("events_predicate_pushdown"):
+ node = apply_events_predicate_pushdown(node, context)
+
with context.timings.measure("swap_properties"):
node = PropertySwapper(
timezone=context.property_swapper.timezone,
diff --git a/posthog/hogql/test/__snapshots__/test_query.ambr b/posthog/hogql/test/__snapshots__/test_query.ambr
index 07a15f8fc920..c6099eb77aec 100644
--- a/posthog/hogql/test/__snapshots__/test_query.ambr
+++ b/posthog/hogql/test/__snapshots__/test_query.ambr
@@ -271,12 +271,15 @@
'''
-- ClickHouse
SELECT e.event AS event, s.session_id AS session_id
- FROM events AS e LEFT JOIN (
+ FROM (
+ SELECT e.event AS event, e.`$session_id` AS `$session_id`
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), isNotNull(nullIf(nullIf(e.`$session_id`, ''), 'null')))
+ LIMIT 10) AS e LEFT JOIN (
SELECT session_replay_events.session_id AS session_id
FROM session_replay_events
WHERE equals(session_replay_events.team_id, 99999)
GROUP BY session_replay_events.session_id) AS s ON equals(s.session_id, nullIf(nullIf(e.`$session_id`, ''), 'null'))
- WHERE and(equals(e.team_id, 99999), isNotNull(nullIf(nullIf(e.`$session_id`, ''), 'null')))
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, allow_experimental_join_condition=1, use_hive_partitioning=0
@@ -300,12 +303,15 @@
'''
-- ClickHouse
SELECT e.event AS event, s.session_id AS session_id
- FROM events AS e LEFT JOIN (
+ FROM (
+ SELECT e.event AS event, e.properties AS properties
+ FROM events AS e
+ WHERE and(equals(e.team_id, 99999), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '')))
+ LIMIT 10) AS e LEFT JOIN (
SELECT session_replay_events.session_id AS session_id
FROM session_replay_events
WHERE equals(session_replay_events.team_id, 99999)
- GROUP BY session_replay_events.session_id) AS s ON equals(s.session_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''))
- WHERE and(equals(e.team_id, 99999), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_1)s), ''), 'null'), '^"|"$', '')))
+ GROUP BY session_replay_events.session_id) AS s ON equals(s.session_id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, %(hogql_val_1)s), ''), 'null'), '^"|"$', ''))
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, allow_experimental_join_condition=1, use_hive_partitioning=0
diff --git a/posthog/hogql/transforms/events_predicate_pushdown.py b/posthog/hogql/transforms/events_predicate_pushdown.py
new file mode 100644
index 000000000000..679f346985db
--- /dev/null
+++ b/posthog/hogql/transforms/events_predicate_pushdown.py
@@ -0,0 +1,670 @@
+from typing import cast
+
+import structlog
+
+from posthog.schema import HogQLQueryModifiers, PropertyGroupsMode
+
+from posthog.hogql import ast
+from posthog.hogql.base import _T_AST
+from posthog.hogql.constants import LimitContext, get_max_limit_for_context
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.models import DatabaseField, FieldTraverser
+from posthog.hogql.database.schema.events import EventsTable
+from posthog.hogql.database.schema.util.where_clause_extractor import EventsPredicatePushdownExtractor
+from posthog.hogql.functions.mapping import find_hogql_aggregation
+from posthog.hogql.printer.base import resolve_field_type
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
+
+from posthog.clickhouse.materialized_columns import TablesWithMaterializedColumns, get_materialized_column_for_property
+from posthog.clickhouse.property_groups import property_groups
+from posthog.models.property import PropertyName, TableColumn
+from posthog.settings import TEST
+
+logger = structlog.get_logger(__name__)
+
+
+def events_pushdown_enabled(modifiers: HogQLQueryModifiers) -> bool:
+ """Enabled when explicitly on, or unset under TEST. Shared by the call site and the transform."""
+ return bool(modifiers.pushDownPredicates or (modifiers.pushDownPredicates is None and TEST))
+
+
+def _printer_top_level_select_ids(node: _T_AST) -> set[int]:
+ """Selects the printer will inject a top-level LIMIT into: the root, or the direct SelectQuery branches of
+ the outermost union. Nested-union branches are excluded; they'd get an inner LIMIT with no outer cap."""
+ if isinstance(node, ast.SelectQuery):
+ return {id(node)}
+ if isinstance(node, ast.SelectSetQuery):
+ return {id(branch) for branch in node.select_queries() if isinstance(branch, ast.SelectQuery)}
+ return set()
+
+
+def apply_events_predicate_pushdown(
+ node: _T_AST,
+ context: HogQLContext,
+) -> _T_AST:
+ """Apply predicate pushdown to events tables with lazy joins. Mutates the AST in place; returns it."""
+ top_level_select_ids = _printer_top_level_select_ids(node)
+ EventsPredicatePushdownTransform(context=context, top_level_select_ids=top_level_select_ids).visit(node)
+ return node
+
+
+class SelectAliasInliner(CloningVisitor):
+ """Inlines SELECT-alias references in a pushed predicate so the full aliased expression is carried into the
+ subquery, not the bare name (which would re-bind to the raw column and drop the wrapper)."""
+
+ def __init__(self, select_aliases: dict[str, ast.Expr]):
+ super().__init__(clear_types=False)
+ self.select_aliases = select_aliases
+ self._resolving: set[str] = set()
+
+ def visit_field(self, node: ast.Field):
+ alias = node.type.alias if isinstance(node.type, ast.FieldAliasType) else None
+ if alias is not None and alias in self.select_aliases and alias not in self._resolving:
+ self._resolving.add(alias)
+ try:
+ return self.visit(clone_expr(self.select_aliases[alias], clear_types=False))
+ finally:
+ self._resolving.discard(alias)
+ return super().visit_field(node)
+
+
+class LazyTypeDetector(TraversingVisitor):
+ """Detects any unresolved LazyJoinType / LazyTableType; pushdown bails if found (the subquery won't have those joins)."""
+
+ def __init__(self):
+ super().__init__()
+ self.found_lazy_type = False
+
+ def visit_field(self, node: ast.Field):
+ super().visit_field(node)
+ if node.type is not None and self._check_type_for_lazy(node.type):
+ self.found_lazy_type = True
+
+ def visit_join_expr(self, node: ast.JoinExpr):
+ super().visit_join_expr(node)
+ if node.type is not None and self._check_type_for_lazy(node.type):
+ self.found_lazy_type = True
+
+ def visit_alias(self, node: ast.Alias):
+ super().visit_alias(node)
+ if node.type is not None and self._check_type_for_lazy(node.type):
+ self.found_lazy_type = True
+
+ def _check_type_for_lazy(self, field_type: ast.Type) -> bool:
+ if isinstance(field_type, ast.LazyJoinType):
+ return True
+ if isinstance(field_type, ast.LazyTableType):
+ return True
+ if isinstance(field_type, ast.FieldType):
+ return self._check_table_type_for_lazy(field_type.table_type)
+ if isinstance(field_type, ast.PropertyType):
+ return self._check_type_for_lazy(field_type.field_type)
+ if isinstance(field_type, ast.SelectQueryAliasType):
+ if field_type.select_query_type is not None:
+ return self._check_select_query_type_for_lazy(field_type.select_query_type)
+ return False
+
+ def _check_table_type_for_lazy(self, table_type: ast.Type | None) -> bool:
+ if table_type is None:
+ return False
+ if isinstance(table_type, ast.LazyJoinType):
+ return True
+ if isinstance(table_type, ast.LazyTableType):
+ return True
+ if isinstance(table_type, ast.TableAliasType):
+ return self._check_table_type_for_lazy(table_type.table_type)
+ if isinstance(table_type, ast.SelectQueryAliasType):
+ if table_type.select_query_type is not None:
+ return self._check_select_query_type_for_lazy(table_type.select_query_type)
+ return False
+
+ def _check_select_query_type_for_lazy(self, query_type: ast.SelectQueryType | ast.SelectSetQueryType) -> bool:
+ if isinstance(query_type, ast.SelectSetQueryType):
+ return False
+ for table_type in query_type.tables.values():
+ if self._check_table_type_for_lazy(table_type):
+ return True
+ for table_type in query_type.anonymous_tables:
+ if self._check_table_type_for_lazy(table_type):
+ return True
+ return False
+
+
+class EventsFieldCollector(TraversingVisitor):
+ """Collects the direct events columns a query references (with resolved FieldTypes, so the subquery can be
+ built without re-running resolve_types) and flags non-direct fields / lazy joins that block pushdown."""
+
+ def __init__(self, target_table: ast.TableType | ast.TableAliasType, context: HogQLContext):
+ super().__init__()
+ self.target_table = target_table
+ self.context = context
+ self.collected_fields: dict[str, ast.FieldType] = {}
+ self.materialized_columns: set[str] = set()
+ self._group_covered_field_ids: set[int] = set()
+ self.has_non_direct_fields = False
+
+ def visit_field(self, node: ast.Field):
+ super().visit_field(node)
+
+ # Already exposed via its property-group Map column (see visit_call), so skip the redundant blob.
+ if id(node) in self._group_covered_field_ids:
+ return
+
+ field_type = node.type
+
+ # events.properties.$foo: unwrap to the base column so we collect/re-type it for the inner table.
+ property_type = field_type if isinstance(field_type, ast.PropertyType) else None
+ if property_type is not None:
+ field_type = property_type.field_type
+
+ if isinstance(field_type, ast.FieldType):
+ table_type = field_type.table_type
+
+ if self._type_references_lazy_join(table_type):
+ self.has_non_direct_fields = True
+ return
+
+ if self._matches_target_table(table_type):
+ # Expose the physical mat/dmat/group column the printer reads, not the slow `properties` blob;
+ # falls through to the blob if the property isn't materialized.
+ if property_type is not None and self._collect_materialized_column(property_type, field_type):
+ return
+
+ db_column_name = self._get_database_column_name(field_type)
+ if db_column_name:
+ self.collected_fields[db_column_name] = field_type
+ else:
+ self.has_non_direct_fields = True
+
+ def visit_call(self, node: ast.Call):
+ # Expose the property-group Map column for an OPTIMIZED JSONHas(properties, 'k') before recursing, so
+ # visit_field can skip the redundant blob. Mirrors ClickHousePrinter._get_optimized_property_group_call.
+ group_column = self._optimized_json_has_group_column(node)
+ if group_column is not None:
+ self.materialized_columns.add(group_column)
+ covered = node.args[0]
+ while isinstance(covered, ast.Alias):
+ covered = covered.expr
+ if isinstance(covered, ast.Field):
+ self._group_covered_field_ids.add(id(covered))
+ super().visit_call(node)
+
+ def _optimized_json_has_group_column(self, node: ast.Call) -> str | None:
+ """The property-group Map column an OPTIMIZED `JSONHas(<events properties>, <const>)` reads, else None."""
+ if self.context.modifiers.propertyGroupsMode != PropertyGroupsMode.OPTIMIZED:
+ return None
+ if node.name != "JSONHas" or len(node.args) != 2 or not isinstance(node.args[1], ast.Constant):
+ return None
+ field_type = resolve_field_type(node.args[0])
+ if not isinstance(field_type, ast.FieldType) or not self._matches_target_table(field_type.table_type):
+ return None
+ resolved = self._resolve_events_table_and_column(field_type)
+ if resolved is None:
+ return None
+ table_name, field_name = resolved
+ for group_column in property_groups.get_property_group_columns(table_name, field_name, str(node.args[1].value)):
+ return group_column
+ return None
+
+ def _resolve_events_table_and_column(self, field_type: ast.FieldType) -> tuple[str, str] | None:
+ """(events table name, db column name) for a direct column on the target events table, else None."""
+ field_name = self._get_database_column_name(field_type)
+ if field_name is None:
+ return None
+ table = field_type.table_type
+ while isinstance(table, (ast.TableAliasType, ast.VirtualTableType)):
+ table = table.table_type
+ if not isinstance(table, ast.TableType):
+ return None
+ return table.table.to_printed_hogql(), field_name
+
+ def _collect_materialized_column(self, property_type: ast.PropertyType, base_field_type: ast.FieldType) -> bool:
+ """Record the physical column the printer reads for this event property; False (collect the raw blob) when none."""
+ if self.context.modifiers.materializationMode == "disabled" or not property_type.chain:
+ return False
+ resolved = self._resolve_events_table_and_column(base_field_type)
+ if resolved is None:
+ return False
+ table_name, field_name = resolved
+ column = self._materialized_column_for_property(table_name, field_name, str(property_type.chain[0]))
+ if column is None:
+ return False
+ self.materialized_columns.add(column)
+ return True
+
+ def _materialized_column_for_property(self, table_name: str, field_name: str, property_name: str) -> str | None:
+ """The single physical column the printer reads for events.<field>.<property>, or None. Mirrors
+ BasePrinter._get_all_materialized_property_sources' priority (static column, dmat slot, first group column)."""
+ materialized_column = get_materialized_column_for_property(
+ cast(TablesWithMaterializedColumns, table_name),
+ cast(TableColumn, field_name),
+ cast(PropertyName, property_name),
+ )
+ if materialized_column is not None:
+ return materialized_column.name
+
+ if self.context.property_swapper is not None and table_name == "events" and field_name == "properties":
+ prop_info = self.context.property_swapper.event_properties.get(property_name)
+ if prop_info and prop_info.get("dmat"):
+ return prop_info["dmat"]
+
+ if self.context.modifiers.propertyGroupsMode in (PropertyGroupsMode.ENABLED, PropertyGroupsMode.OPTIMIZED):
+ for group_column in property_groups.get_property_group_columns(table_name, field_name, property_name):
+ return group_column
+
+ return None
+
+ def _type_references_lazy_join(self, table_type: ast.Type | None) -> bool:
+ if table_type is None:
+ return False
+ if isinstance(table_type, ast.LazyJoinType):
+ return True
+ if isinstance(table_type, ast.TableAliasType):
+ return self._type_references_lazy_join(table_type.table_type)
+ if isinstance(table_type, ast.LazyTableType):
+ return True
+ if isinstance(table_type, ast.VirtualTableType):
+ return self._type_references_lazy_join(table_type.table_type)
+ return False
+
+ def _get_database_column_name(self, field_type: ast.FieldType) -> str | None:
+ try:
+ resolved = field_type.resolve_database_field(self.context)
+ if isinstance(resolved, FieldTraverser):
+ return None
+ if isinstance(resolved, DatabaseField):
+ return resolved.name
+ return None
+ except Exception as err:
+ # Fail-safe: treat any resolution failure as non-direct and decline; debug-logged so a resolver
+ # regression silently disabling pushdown stays visible.
+ logger.debug("events_predicate_pushdown_field_resolution_failed", error=str(err))
+ return None
+
+ def _matches_target_table(self, table_type: ast.Type | None) -> bool:
+ if table_type is None:
+ return False
+
+ unwrapped: ast.Type = table_type
+ if isinstance(unwrapped, ast.TableAliasType):
+ unwrapped = unwrapped.table_type
+ if isinstance(unwrapped, ast.VirtualTableType):
+ unwrapped = unwrapped.table_type
+ if isinstance(unwrapped, ast.TableAliasType):
+ unwrapped = unwrapped.table_type
+
+ target: ast.Type = self.target_table
+ if isinstance(target, ast.TableAliasType):
+ target = target.table_type
+
+ if isinstance(unwrapped, ast.TableType) and isinstance(target, ast.TableType):
+ return unwrapped.table is target.table
+ return table_type is self.target_table or unwrapped is target
+
+
+class _ShortCircuitBlockerFinder(TraversingVisitor):
+ """Finds aggregate or window functions, which consume the whole result before a LIMIT applies. Does not
+ recurse into subqueries: only this query level's own expressions matter for its own LIMIT."""
+
+ def __init__(self):
+ super().__init__()
+ self.found = False
+
+ def visit(self, node):
+ if not self.found:
+ super().visit(node)
+
+ def visit_select_query(self, node: ast.SelectQuery):
+ pass
+
+ def visit_window_function(self, node: ast.WindowFunction):
+ self.found = True
+
+ def visit_call(self, node: ast.Call):
+ if find_hogql_aggregation(node.name):
+ self.found = True
+ else:
+ super().visit_call(node)
+
+
+class EventsPredicatePushdownTransform(TraversingVisitor):
+ """Pushes events WHERE/PREWHERE predicates into a pre-filtering subquery:
+ `FROM events` -> `FROM (SELECT <needed cols> FROM events WHERE <predicates>) AS events`.
+
+ Runs after resolve_lazy_tables and applies bottom-up so nested `FROM events` subqueries benefit too."""
+
+ # Join types across which moving an events PREDICATE is result-safe (they preserve the events/left side).
+ # Broader than _all_joins_preserve_every_row (LEFT only): INNER / CROSS are predicate-safe but can drop an
+ # events row, so they pass here yet decline at _safe_inner_limit (the single-rule gate always needs it).
+ _SAFE_JOIN_TYPES = {"JOIN", "INNER JOIN", "LEFT JOIN", "LEFT OUTER JOIN", "CROSS JOIN"}
+
+ def __init__(
+ self,
+ context: HogQLContext,
+ top_level_select_ids: set[int] | None = None,
+ ):
+ super().__init__()
+ self.context = context
+ self.top_level_select_ids = top_level_select_ids or set()
+
+ def visit_select_query(self, node: ast.SelectQuery):
+ super().visit_select_query(node) # bottom-up: visit subqueries first
+
+ if self._should_apply_pushdown(node):
+ try:
+ decline_reason = self._apply_pushdown(node)
+ except Exception as err:
+ # Pure optimization: any unexpected failure must leave the query untouched, not break it.
+ # _apply_pushdown mutates node only after every check passes, so a raise leaves it unchanged.
+ logger.warning("events_predicate_pushdown_unexpected_error", error=str(err), exc_info=True)
+ return
+ if decline_reason is not None:
+ logger.debug("events_predicate_pushdown_declined", reason=decline_reason)
+
+ def _apply_pushdown(self, node: ast.SelectQuery) -> str | None:
+ """Apply predicate pushdown to an eligible query. Returns a decline reason, or None if applied."""
+ assert node.select_from is not None
+
+ joined_aliases = self._collect_joined_aliases(node)
+ if not joined_aliases:
+ return "no_safe_joined_aliases"
+
+ events_table_type = node.select_from.type
+ if not isinstance(events_table_type, (ast.TableType, ast.TableAliasType)):
+ return "from_not_table_type"
+
+ # Collect needed columns before extracting/mutating predicates, so we can bail before touching
+ # node.where and never drop a pushable predicate.
+ collector = self._collect_needed_columns(node, events_table_type)
+ if collector is None or (not collector.collected_fields and not collector.materialized_columns):
+ return "no_collectable_columns"
+
+ # Classify a WHERE field that resolves to an alias by what the alias references (e.g. `f(session.x) AS
+ # event` must not be pushed by name).
+ select_aliases = {expr.alias: expr.expr for expr in node.select if isinstance(expr, ast.Alias)}
+
+ # Split without mutating node yet, so any bail below leaves the original predicates intact.
+ extractor = EventsPredicatePushdownExtractor(
+ joined_table_aliases=joined_aliases,
+ events_table_type=events_table_type,
+ select_aliases=select_aliases,
+ )
+
+ inner_from_where: ast.Expr | None = None
+ inner_from_prewhere: ast.Expr | None = None
+ new_where = node.where
+ new_prewhere = node.prewhere
+
+ if node.where is not None:
+ inner_from_where, new_where = extractor.get_pushdown_predicates(node.where)
+ if node.prewhere is not None:
+ inner_from_prewhere, new_prewhere = extractor.get_pushdown_predicates(node.prewhere)
+
+ # PREWHERE is valid only on a physical scan, not a subquery. A fully-pushable PREWHERE moves into the
+ # inner scan; a residual one would have to stay on the outer subquery (invalid), so bail.
+ if new_prewhere is not None:
+ return "prewhere_not_fully_pushable"
+
+ if inner_from_where is None and inner_from_prewhere is None:
+ return "no_pushable_predicates"
+
+ inner_where = self._prepare_inner_predicate(inner_from_where, select_aliases)
+ inner_prewhere = self._prepare_inner_predicate(inner_from_prewhere, select_aliases)
+
+ # The optimization only pays off when a LIMIT can short-circuit the events read. Predicates + an inner
+ # LIMIT beat the flat query for every column type; predicates-only regresses for the raw blob, and
+ # ORDER BY blocks the inner LIMIT. So push the inner LIMIT when result-equivalent, else decline.
+ inner_limit = self._safe_inner_limit(node, new_where, new_prewhere)
+ if inner_limit is None:
+ return "no_short_circuitable_limit"
+
+ # Build the subquery from the outer query's resolved types. The inner events table keeps the outer
+ # alias so the pushed predicates resolve against it; the printer injects the per-table team_id guard.
+ events_subquery = self._build_typed_subquery(
+ collector.collected_fields,
+ collector.materialized_columns,
+ events_table_type,
+ inner_where,
+ inner_prewhere,
+ alias=node.select_from.alias,
+ limit=inner_limit,
+ )
+ if events_subquery is None:
+ return "subquery_build_failed"
+ subquery_type = events_subquery.type
+ assert subquery_type is not None
+
+ # Commit: drop the pushed predicates and swap the events table for the subquery, keeping the alias.
+ node.where = new_where
+ node.prewhere = new_prewhere
+ original_alias = node.select_from.alias
+ new_alias = original_alias or "events"
+ node.select_from.table = events_subquery
+ node.select_from.alias = new_alias
+
+ # Outer field refs keep their original types and resolve against the alias by name.
+ # TODO: re-point outer field refs so query metadata reflects the rewrite.
+ node.select_from.type = ast.SelectQueryAliasType(
+ alias=new_alias,
+ select_query_type=subquery_type,
+ )
+ return None
+
+ def _should_apply_pushdown(self, node: ast.SelectQuery) -> bool:
+ """Eligible when the query selects FROM events directly (no SAMPLE), has a WHERE/PREWHERE, has joins,
+ has an effective LIMIT, and does not aggregate / DISTINCT / window (those read the whole set regardless
+ of the LIMIT, so the pre-filter would be pure overhead)."""
+ return (
+ events_pushdown_enabled(self.context.modifiers)
+ and node.select_from is not None
+ and node.select_from.sample is None
+ and self._from_is_events_table(node.select_from)
+ and (node.where is not None or node.prewhere is not None)
+ and node.select_from.next_join is not None
+ and self._has_effective_limit(node)
+ and not self._forces_full_event_read(node)
+ )
+
+ def _has_effective_limit(self, node: ast.SelectQuery) -> bool:
+ """A top-level select counts (the printer injects a cap <= MAX_SELECT_RETURNED_ROWS); a nested select
+ counts only with an explicit LIMIT. Contexts that disable the cap (limit_top_select=False) decline."""
+ if not self.context.limit_top_select:
+ return False
+ return id(node) in self.top_level_select_ids or node.limit is not None
+
+ def _forces_full_event_read(self, node: ast.SelectQuery) -> bool:
+ """True if the query consumes the whole filtered event set before its LIMIT applies. GROUP BY, DISTINCT,
+ and aggregate / window functions (incl. in ORDER BY / HAVING / QUALIFY) block the short-circuit; a plain
+ `ORDER BY <column>` does not."""
+ if node.group_by or node.distinct:
+ return True
+ finder = _ShortCircuitBlockerFinder()
+ for expr in (*node.select, node.having, node.qualify, *(node.order_by or [])):
+ if expr is not None:
+ finder.visit(expr)
+ return finder.found
+
+ def _all_joins_preserve_every_row(self, node: ast.SelectQuery) -> bool:
+ """True if every events row yields >= 1 output row (all joins LEFT [OUTER]); an INNER / CROSS join could drop one."""
+ join = node.select_from.next_join if node.select_from is not None else None
+ while join is not None:
+ if join.join_type not in ("LEFT JOIN", "LEFT OUTER JOIN"):
+ return False
+ join = join.next_join
+ return True
+
+ def _safe_inner_limit(
+ self, node: ast.SelectQuery, residual_where: ast.Expr | None, residual_prewhere: ast.Expr | None
+ ) -> ast.Constant | None:
+ """The LIMIT to push into the events subquery, or None if pushing it would change results.
+
+ Safe only when nothing after the events scan can drop or reorder rows: no ORDER BY / LIMIT BY / ARRAY
+ JOIN / WITH TIES / percent, no residual outer predicate, all joins LEFT. Then the first `offset + limit`
+ events cover the outer slice. The pushed value is the explicit LIMIT capped at (or, when absent,
+ replaced by) the context cap the printer applies to a top-level select, so the inner scan never reads
+ rows the capped outer slice can't emit.
+ """
+ if (
+ node.order_by is not None
+ or node.limit_by is not None
+ or node.array_join_list is not None
+ or node.limit_with_ties
+ or node.limit_percent
+ ):
+ return None
+ if residual_where is not None or residual_prewhere is not None:
+ return None
+ if not self._all_joins_preserve_every_row(node):
+ return None
+ offset = 0
+ if node.offset is not None:
+ if not isinstance(node.offset, ast.Constant) or not isinstance(node.offset.value, int):
+ return None
+ offset = node.offset.value
+ # Derive the cap from limit_context (not a hardcoded MAX_SELECT_RETURNED_ROWS) so larger-cap contexts
+ # (EXPORT / HEATMAPS / RETENTION) aren't under-capped, which would drop rows.
+ cap = (
+ get_max_limit_for_context(self.context.limit_context or LimitContext.QUERY)
+ if self._is_top_level(node)
+ else None
+ )
+ if isinstance(node.limit, ast.Constant) and isinstance(node.limit.value, int):
+ limit_value = min(node.limit.value, cap) if cap is not None else node.limit.value
+ return ast.Constant(value=limit_value + offset)
+ # No explicit LIMIT: only a top-level select is safe (the printer injects its cap as the outer LIMIT).
+ if cap is not None:
+ return ast.Constant(value=cap + offset)
+ return None
+
+ def _is_top_level(self, node: ast.SelectQuery) -> bool:
+ return id(node) in self.top_level_select_ids
+
+ def _from_is_events_table(self, join_expr: ast.JoinExpr) -> bool:
+ """True when the FROM resolves directly to the physical events table (not a subquery). Checking the
+ resolved type also matches the qualified `FROM posthog.events`, which a chain comparison misses."""
+ table_type: ast.Type | None = join_expr.type
+ while isinstance(table_type, (ast.TableAliasType, ast.VirtualTableType)):
+ table_type = table_type.table_type
+ return isinstance(table_type, ast.TableType) and isinstance(table_type.table, EventsTable)
+
+ def _collect_joined_aliases(self, node: ast.SelectQuery) -> set[str]:
+ """Aliases from the JOIN chain, or an empty set if any join uses an unsafe type (causing the caller to bail)."""
+ aliases: set[str] = set()
+ join = node.select_from.next_join if node.select_from else None
+ while join is not None:
+ # A missing join_type is unreachable today but treated as unsafe rather than safe.
+ if join.join_type is None or join.join_type not in self._SAFE_JOIN_TYPES:
+ return set()
+ if join.alias:
+ aliases.add(join.alias)
+ join = join.next_join
+ return aliases
+
+ def _collect_needed_columns(
+ self, node: ast.SelectQuery, events_table_type: ast.TableType | ast.TableAliasType
+ ) -> EventsFieldCollector | None:
+ """Collect the events columns the outer query references; None if it can't be pushed (lazy or non-direct fields)."""
+ lazy_detector = LazyTypeDetector()
+ lazy_detector.visit(node)
+ if lazy_detector.found_lazy_type:
+ return None
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ if collector.has_non_direct_fields:
+ return None
+
+ return collector
+
+ def _prepare_inner_predicate(self, expr: ast.Expr | None, select_aliases: dict[str, ast.Expr]) -> ast.Expr | None:
+ """Ready a pushed predicate for the inner subquery (inline SELECT-alias refs, clone), or None if there is none."""
+ if expr is None:
+ return None
+ expr = SelectAliasInliner(select_aliases).visit(expr)
+ return clone_expr(expr)
+
+ def _build_typed_subquery(
+ self,
+ collected_fields: dict[str, ast.FieldType],
+ materialized_columns: set[str],
+ events_table_type: ast.TableType | ast.TableAliasType,
+ where_clause: ast.Expr | None,
+ prewhere_clause: ast.Expr | None = None,
+ alias: str | None = None,
+ limit: ast.Constant | None = None,
+ ) -> ast.SelectQuery | None:
+ """Build the subquery from the outer query's resolved FieldTypes (avoiding resolve_types, which might
+ re-resolve lazy joins). Keeps the outer events alias so pushed predicates and the SELECT list match."""
+ base_table_type: ast.Type = events_table_type
+ if isinstance(base_table_type, ast.TableAliasType):
+ base_table_type = base_table_type.table_type
+ if not isinstance(base_table_type, ast.TableType):
+ return None
+
+ inner_table_type = self._inner_table_type_with_materialized_columns(base_table_type, materialized_columns)
+ ref_table_type: ast.TableType | ast.TableAliasType = (
+ ast.TableAliasType(alias=alias, table_type=inner_table_type) if alias else inner_table_type
+ )
+
+ # One aliased Field per column, so names survive even if PropertySwapper rewrites the inner expr.
+ select_fields: list[ast.Expr] = []
+ columns_in_scope: dict[str, ast.Type] = {}
+
+ for col_name in sorted(collected_fields.keys()):
+ original_field_type = collected_fields[col_name]
+
+ if isinstance(original_field_type.table_type, ast.VirtualTableType):
+ virtual_table_type = ast.VirtualTableType(
+ table_type=ref_table_type,
+ field=original_field_type.table_type.field,
+ virtual_table=original_field_type.table_type.virtual_table,
+ )
+ field_type = ast.FieldType(name=original_field_type.name, table_type=virtual_table_type)
+ else:
+ field_type = ast.FieldType(name=col_name, table_type=ref_table_type)
+
+ field_node = ast.Field(chain=[col_name], type=field_type)
+ alias_node = ast.Alias(alias=col_name, expr=field_node, type=field_type)
+ select_fields.append(alias_node)
+ columns_in_scope[col_name] = field_type
+
+ # Expose the raw physical mat/dmat/group columns so the printer's outer references resolve against the
+ # subquery alias; the outer query re-applies the property semantics.
+ for col_name in sorted(materialized_columns):
+ if col_name in columns_in_scope:
+ continue
+ field_type = ast.FieldType(name=col_name, table_type=ref_table_type)
+ field_node = ast.Field(chain=[col_name], type=field_type)
+ select_fields.append(ast.Alias(alias=col_name, expr=field_node, type=field_type))
+ columns_in_scope[col_name] = field_type
+
+ events_field = ast.Field(chain=["events"], type=inner_table_type)
+ select_from = ast.JoinExpr(table=events_field, alias=alias, type=ref_table_type)
+ select_query_type = ast.SelectQueryType(columns=columns_in_scope, tables={alias or "events": ref_table_type})
+
+ return ast.SelectQuery(
+ select=select_fields,
+ select_from=select_from,
+ where=where_clause,
+ prewhere=prewhere_clause,
+ limit=limit,
+ type=select_query_type,
+ )
+
+ def _inner_table_type_with_materialized_columns(
+ self, base_table_type: ast.TableType, materialized_columns: set[str]
+ ) -> ast.TableType:
+ """Inner events table type augmented with synthetic DatabaseFields for the materialized columns (physical
+ ClickHouse columns, not HogQL schema fields). Uses a copy; the shared table object is never mutated."""
+ synthetic_fields = {
+ column: DatabaseField(name=column)
+ for column in materialized_columns
+ if not base_table_type.table.has_field(column)
+ }
+ if not synthetic_fields:
+ return base_table_type
+ augmented_table = base_table_type.table.model_copy(
+ update={"fields": {**base_table_type.table.fields, **synthetic_fields}}
+ )
+ return ast.TableType(table=augmented_table)
diff --git a/posthog/hogql/transforms/test/__snapshots__/test_events_predicate_pushdown.ambr b/posthog/hogql/transforms/test/__snapshots__/test_events_predicate_pushdown.ambr
new file mode 100644
index 000000000000..bd96ea4787a0
--- /dev/null
+++ b/posthog/hogql/transforms/test/__snapshots__/test_events_predicate_pushdown.ambr
@@ -0,0 +1,363 @@
+# serializer version: 1
+# name: TestEventsPredicatePushdownExecution.test_exec_aliased_events_timestamp_filter_with_session_join
+ '''
+
+ SELECT e.event AS event, e__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT e.`$session_id` AS `$session_id`, e.event AS event, toTimeZone(e.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events AS e
+ WHERE and(equals(e.team_id, 420), greaterOrEquals(e.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), less(e.timestamp, toDateTime64(%(hogql_val_3)s, 6, %(hogql_val_4)s)))
+ LIMIT 50) AS e LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_9)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_10)s)), e__session.session_id_v7)
+ LIMIT 50
+ '''
+# ---
+# name: TestEventsPredicatePushdownExecution.test_exec_timestamp_filter_with_session_join
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), 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)))
+ LIMIT 50) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_9)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_10)s)), events__session.session_id_v7)
+ LIMIT 50
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_bare_timestamp_with_select_alias_pushes_down
+ '''
+
+ SELECT events.event AS event, toTimeZone(toTimeZone(events.timestamp, %(hogql_val_10)s), %(hogql_val_11)s) AS timestamp, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_1)s), toDateTime64(%(hogql_val_2)s, 6, %(hogql_val_3)s)), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_4)s), today()))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(today(), toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_9)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_events_with_alias_and_session_join
+ '''
+
+ SELECT e.event AS event, e__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT e.`$session_id` AS `$session_id`, e.event AS event, toTimeZone(e.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events AS e
+ WHERE and(equals(e.team_id, 420), greaterOrEquals(e.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000) AS e LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_7)s)), e__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_events_with_session_join_and_timestamp_filter
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_events_without_join_no_pushdown
+ '''
+
+ SELECT events.event AS event
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_0)s, 6, %(hogql_val_1)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_events_without_where_no_pushdown
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_0)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE equals(raw_sessions.team_id, 420)
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_3)s)), events__session.session_id_v7)
+ WHERE equals(events.team_id, 420)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_multiple_poe_fields_with_session_join
+ '''
+
+ SELECT events.event AS event, events.person_id AS id, events.person_properties AS properties, toTimeZone(events.person_created_at, %(hogql_val_9)s) AS created_at, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.person_created_at, %(hogql_val_0)s) AS person_created_at, events.person_id AS person_id, events.person_properties AS person_properties, toTimeZone(events.timestamp, %(hogql_val_1)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_2)s, 6, %(hogql_val_3)s)))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_8)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_multiple_pushable_predicates
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), equals(events.event, %(hogql_val_3)s))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_8)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_non_row_preserving_join_skips_pushdown_0_explicit_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM events JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_0)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_non_row_preserving_join_skips_pushdown_1_inner_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM events INNER JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_0)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_non_row_preserving_join_skips_pushdown_2_cross_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM events CROSS JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_0)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_non_row_preserving_join_skips_pushdown_3_right_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM events RIGHT JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_0)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_non_row_preserving_join_skips_pushdown_4_right_outer_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM events RIGHT OUTER JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_0)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_non_row_preserving_join_skips_pushdown_5_full_outer_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM events FULL OUTER JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_0)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_non_row_preserving_join_skips_pushdown_6_full_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM events FULL JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_0)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_poe_created_at_with_session_join
+ '''
+
+ SELECT events.event AS event, toTimeZone(events.person_created_at, %(hogql_val_9)s) AS created_at, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.person_created_at, %(hogql_val_0)s) AS person_created_at, toTimeZone(events.timestamp, %(hogql_val_1)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_2)s, 6, %(hogql_val_3)s)))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_8)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_poe_id_with_session_join
+ '''
+
+ SELECT events.person_id AS id, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.person_id AS person_id, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_poe_properties_with_session_join
+ '''
+
+ SELECT events.event AS event, events.person_properties AS properties, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, events.person_properties AS person_properties, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_3)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_4)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_5)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_6)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_7)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_row_preserving_join_pushes_timestamp_down_0_left_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp, events.uuid AS uuid
+ FROM events
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_row_preserving_join_pushes_timestamp_down_1_left_outer_join
+ '''
+
+ SELECT sessions.session_id AS session_id, events.uuid AS uuid
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp, events.uuid AS uuid
+ FROM events
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000) AS events LEFT OUTER JOIN (
+ SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS sessions ON equals(events.`$session_id`, sessions.session_id)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_session_duration_filter_declines
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_0)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_4)s)), events__session.session_id_v7)
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), ifNull(greater(events__session.`$session_duration`, 0), 0))
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_simple_events_with_person_join
+ '''
+
+ SELECT events.event AS event, events__person.id AS id
+ FROM (
+ SELECT events.distinct_id AS distinct_id, events.event AS event, events.person_id AS person_id, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greater(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)))
+ LIMIT 50000) AS events LEFT OUTER JOIN (
+ SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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, 420)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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
+ FROM person
+ WHERE equals(person.team_id, 420)
+ GROUP BY person.id
+ HAVING and(ifNull(equals(tupleElement(argMax(tuple(person.is_deleted), person.version), 1), 0), 0), ifNull(less(tupleElement(argMax(tuple(toTimeZone(person.created_at, %(hogql_val_3)s)), person.version), 1), plus(now64(6, %(hogql_val_4)s), toIntervalDay(1))), 0))
+ 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)
+ LIMIT 50000
+ '''
+# ---
+# name: TestEventsPredicatePushdownTransform.test_subquery_with_pushdown
+ '''
+
+ SELECT event AS event, avg(`$session_duration`) AS `avg($session_duration)`
+ FROM (
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), or(equals(events.event, %(hogql_val_3)s), equals(events.event, %(hogql_val_4)s)))
+ LIMIT 100) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_9)s)), events__session.session_id_v7)
+ LIMIT 100)
+ GROUP BY event
+ LIMIT 50000
+ '''
+# ---
diff --git a/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambr b/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambr
index 23397d9d80ee..071fb5332be2 100644
--- a/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambr
+++ b/posthog/hogql/transforms/test/__snapshots__/test_lazy_tables.ambr
@@ -1,4 +1,65 @@
# serializer version: 1
+# name: TestLazyJoins.test_events_session_join_with_multiple_predicates
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), 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)), equals(events.event, %(hogql_val_5)s), isNotNull(events.`$session_id`))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_6)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_7)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_8)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_9)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_10)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_11)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestLazyJoins.test_events_session_join_with_session_duration_filter
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_0)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_1)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_2)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_3)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_4)s)), events__session.session_id_v7)
+ WHERE and(equals(events.team_id, 420), greaterOrEquals(events.timestamp, toDateTime64(%(hogql_val_5)s, 6, %(hogql_val_6)s)), ifNull(greater(events__session.`$session_duration`, 0), 0))
+ LIMIT 50000
+ '''
+# ---
+# name: TestLazyJoins.test_events_session_join_with_timestamp_filter
+ '''
+
+ SELECT events.event AS event, events__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT events.`$session_id` AS `$session_id`, events.event AS event, toTimeZone(events.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 420), 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)))
+ LIMIT 50000) AS events LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_5)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_6)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_7)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_8)s, toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(%(hogql_val_9)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(toUInt128(accurateCastOrNull(events.`$session_id`, %(hogql_val_10)s)), events__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
+# name: TestLazyJoins.test_events_sessions_join_with_alias
+ '''
+
+ SELECT e.event AS event, e__session.`$session_duration` AS `$session_duration`
+ FROM (
+ SELECT e.`$session_id` AS `$session_id`, e.event AS event, toTimeZone(e.timestamp, %(hogql_val_0)s) AS timestamp
+ FROM events AS e
+ WHERE and(equals(e.team_id, 420), greaterOrEquals(e.timestamp, toDateTime64(%(hogql_val_1)s, 6, %(hogql_val_2)s)), equals(e.event, %(hogql_val_3)s))
+ LIMIT 50000) AS e LEFT JOIN (
+ SELECT dateDiff(%(hogql_val_4)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_5)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_6)s))) AS `$session_duration`, raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 420), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(%(hogql_val_7)s, toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS e__session ON equals(toUInt128(accurateCastOrNull(e.`$session_id`, %(hogql_val_8)s)), e__session.session_id_v7)
+ LIMIT 50000
+ '''
+# ---
# name: TestLazyJoins.test_lazy_join_on_lazy_table
'''
diff --git a/posthog/hogql/transforms/test/test_events_predicate_pushdown.py b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py
new file mode 100644
index 000000000000..64bfe9e4f821
--- /dev/null
+++ b/posthog/hogql/transforms/test/test_events_predicate_pushdown.py
@@ -0,0 +1,2000 @@
+import json
+from typing import Any
+from uuid import uuid4
+
+import pytest
+from posthog.test.base import (
+ APIBaseTest,
+ BaseTest,
+ ClickhouseTestMixin,
+ _create_event,
+ _create_person,
+ flush_persons_and_events,
+ materialized,
+)
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.schema import InCohortVia, InlineCohortCalculation, PersonsOnEventsMode, PropertyGroupsMode
+
+from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.database.models import IntegerDatabaseField, SavedQuery, StringDatabaseField, TableNode
+from posthog.hogql.database.schema.events import EventsTable
+from posthog.hogql.database.schema.util.where_clause_extractor import EventsPredicatePushdownExtractor
+from posthog.hogql.modifiers import HogQLQueryModifiers
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer.utils import prepare_and_print_ast
+from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.resolver import resolve_types
+from posthog.hogql.test.utils import pretty_print_in_tests
+from posthog.hogql.transforms.events_predicate_pushdown import (
+ EventsFieldCollector,
+ EventsPredicatePushdownTransform,
+ LazyTypeDetector,
+ _printer_top_level_select_ids,
+)
+from posthog.hogql.transforms.lazy_tables import resolve_lazy_tables
+
+from posthog.clickhouse.client import sync_execute
+from posthog.models import Cohort, MaterializedColumnSlot, MaterializedColumnSlotState, PropertyDefinition
+from posthog.models.cohort.util import recalculate_cohortpeople
+from posthog.models.utils import uuid7
+
+from products.event_definitions.backend.models.property_definition import PropertyType
+
+
+class TestEventsPredicatePushdownTransform(BaseTest):
+ snapshot: Any
+ maxDiff = None
+
+ def _print_select(self, select: str, modifiers: HogQLQueryModifiers | None = None):
+ expr = parse_select(select)
+ query, _ = prepare_and_print_ast(
+ expr,
+ HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=modifiers if modifiers is not None else HogQLQueryModifiers(pushDownPredicates=True),
+ ),
+ "clickhouse",
+ )
+ return pretty_print_in_tests(query, self.team.pk)
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_with_session_join_and_timestamp_filter(self):
+ """Pushes timestamp filter into subquery when events table has lazy session join."""
+ printed = self._print_select(
+ "SELECT event, session.$session_duration FROM events WHERE timestamp >= '2024-01-01'"
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_with_alias_and_session_join(self):
+ """Preserves events table alias in the subquery wrapper."""
+ printed = self._print_select(
+ "SELECT e.event, session.$session_duration FROM events AS e WHERE e.timestamp >= '2024-01-01'"
+ )
+ assert printed == self.snapshot
+
+ def test_aliased_events_pushdown_subquery_defines_its_own_alias(self):
+ # When the events table is aliased (FROM events AS e), the pushed predicate keeps referencing `e`.
+ # Rather than rewrite every reference to the inner table (fragile: the printer renders a field from
+ # its resolved type, not its chain, so a materialized property still leaked `e.mat_*`), the inner
+ # subquery keeps the same alias on its own FROM (`FROM events AS e`), so `e.timestamp` resolves there.
+ printed = self._print_select(
+ "SELECT e.event, session.$session_duration FROM events AS e WHERE e.timestamp >= '2024-01-01'"
+ )
+
+ # Isolate the pushed-down events subquery: `FROM ( <subquery> ) AS e LEFT JOIN ...`
+ assert "FROM (" in printed and ") AS e LEFT JOIN" in printed, printed
+ events_subquery = printed.split("FROM (", 1)[1].split(") AS e LEFT JOIN", 1)[0]
+
+ # The subquery aliases its own events scan as `e`, so the pushed `e.timestamp` predicate resolves
+ # against it, not the out-of-scope outer alias.
+ assert "FROM events AS e" in events_subquery, (
+ "expected the inner subquery to alias events as `e` so pushed `e.*` predicates resolve:\n" + events_subquery
+ )
+ assert "e.timestamp" in events_subquery, (
+ "expected the pushed-down predicate to reference the inner `e`-aliased events table:\n" + events_subquery
+ )
+
+ def test_unexpected_internal_error_degrades_to_flat_query(self):
+ # Pushdown is a pure optimization: an unexpected raise inside the rewrite must leave the query intact
+ # (run flat), never break it. Force a raise in _build_typed_subquery (called before any mutation) and
+ # assert the printed SQL matches the un-pushed flat form.
+ select = "SELECT event, session.$session_duration FROM events WHERE timestamp >= '2024-01-01' LIMIT 10"
+ flat = self._print_select(select, modifiers=HogQLQueryModifiers(pushDownPredicates=False))
+ with patch.object(EventsPredicatePushdownTransform, "_build_typed_subquery", side_effect=RuntimeError("boom")):
+ guarded = self._print_select(select, modifiers=HogQLQueryModifiers(pushDownPredicates=True))
+ assert guarded == flat, f"expected flat fallback on internal error:\nflat={flat}\nguarded={guarded}"
+ assert ") AS events LEFT JOIN" not in guarded, f"the events scan must not be wrapped on fallback:\n{guarded}"
+
+ def test_restricted_property_still_stripped_after_pushdown(self):
+ # Property-level access control strips a restricted event property from the raw `properties` blob via
+ # JSONDropKeys. Pushdown exposes that blob inside the events subquery, so the stripping must apply there
+ # too (the subquery's events scan keeps its EventsTable type). Pin it on both the pushed and flat forms.
+ select = (
+ "SELECT properties, session.$session_duration AS d FROM events WHERE timestamp >= '2024-01-01' LIMIT 10"
+ )
+
+ def _print(push_down: bool) -> str:
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(pushDownPredicates=push_down),
+ )
+ context.restricted_properties = {("email", PropertyDefinition.Type.EVENT)}
+ query, _ = prepare_and_print_ast(parse_select(select), context, "clickhouse")
+ return pretty_print_in_tests(query, self.team.pk)
+
+ flat = _print(False)
+ assert "JSONDropKeys" in flat, f"expected the restricted key stripped in the flat query:\n{flat}"
+ pushed = _print(True)
+ assert ") AS events LEFT JOIN" in pushed, f"expected pushdown to fire:\n{pushed}"
+ events_subquery = pushed.split("FROM (", 1)[1].split(") AS events LEFT JOIN", 1)[0]
+ assert "JSONDropKeys" in events_subquery, (
+ "pushdown must preserve restricted-key stripping on the inner events scan:\n" + events_subquery
+ )
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_without_join_no_pushdown(self):
+ """No pushdown when there are no lazy joins."""
+ printed = self._print_select("SELECT event FROM events WHERE timestamp >= '2024-01-01'")
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_without_where_no_pushdown(self):
+ """No pushdown when there is no WHERE clause."""
+ printed = self._print_select("SELECT event, session.$session_duration FROM events")
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_session_duration_filter_declines(self):
+ """A session-duration predicate is residual (can't be pushed into the events subquery), so the whole
+ pushdown declines and the query runs flat with the predicate in the outer WHERE."""
+ printed = self._print_select(
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01' AND session.$session_duration > 0"
+ )
+ assert ") AS events LEFT JOIN" not in printed, printed
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_multiple_pushable_predicates(self):
+ """Multiple events-table predicates can be pushed down together."""
+ printed = self._print_select(
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01' AND event = '$pageview'"
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_subquery_with_pushdown(self):
+ """Subquery pushdown"""
+ # The inner subquery is nested (not outermost), so it needs its own explicit LIMIT to be pushed;
+ # the outer aggregate (avg + GROUP BY) is correctly left un-pushed.
+ printed = self._print_select(
+ "SELECT event, avg($session_duration) FROM ("
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01' AND (event = '$pageview' OR event = '$pageleave') "
+ "LIMIT 100"
+ ") GROUP BY event"
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_simple_events_with_person_join(self):
+ printed = self._print_select(
+ "SELECT event, person.id FROM events WHERE timestamp > '2024-01-01'",
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_poe_properties_with_session_join(self):
+ """VirtualTable field poe.properties is included in subquery as person_properties."""
+ printed = self._print_select(
+ "SELECT event, poe.properties, session.$session_duration FROM events WHERE timestamp >= '2024-01-01'"
+ )
+ assert ") AS events LEFT JOIN" in printed, printed
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_poe_id_with_session_join(self):
+ """VirtualTable field poe.id is included in subquery as person_id."""
+ printed = self._print_select(
+ "SELECT poe.id, session.$session_duration FROM events WHERE timestamp >= '2024-01-01'"
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_poe_created_at_with_session_join(self):
+ """VirtualTable field poe.created_at is included in subquery as person_created_at."""
+ printed = self._print_select(
+ "SELECT event, poe.created_at, session.$session_duration FROM events WHERE timestamp >= '2024-01-01'"
+ )
+ assert ") AS events LEFT JOIN" in printed, printed
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_multiple_poe_fields_with_session_join(self):
+ """Multiple VirtualTable fields are all included in the subquery."""
+ printed = self._print_select(
+ "SELECT event, poe.id, poe.properties, poe.created_at, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01'"
+ )
+ assert ") AS events LEFT JOIN" in printed, printed
+ assert printed == self.snapshot
+
+ # Only LEFT [OUTER] joins preserve every events row, so only they let the pushed inner LIMIT stay
+ # result-equivalent and push. INNER / CROSS can drop an events row, and RIGHT / FULL can synthesize null
+ # events rows, so both groups decline under the single-rule gate (no safe inner LIMIT). Join types within
+ # each group differ only in the keyword, so they share one parameterized snapshot test.
+ _ROW_PRESERVING_JOINS = [
+ ("left_join", "LEFT JOIN sessions ON events.$session_id = sessions.session_id"),
+ ("left_outer_join", "LEFT OUTER JOIN sessions ON events.$session_id = sessions.session_id"),
+ ]
+ _NON_ROW_PRESERVING_JOINS = [
+ ("explicit_join", "JOIN sessions ON events.$session_id = sessions.session_id"),
+ ("inner_join", "INNER JOIN sessions ON events.$session_id = sessions.session_id"),
+ ("cross_join", "CROSS JOIN sessions"),
+ ("right_join", "RIGHT JOIN sessions ON events.$session_id = sessions.session_id"),
+ ("right_outer_join", "RIGHT OUTER JOIN sessions ON events.$session_id = sessions.session_id"),
+ ("full_outer_join", "FULL OUTER JOIN sessions ON events.$session_id = sessions.session_id"),
+ ("full_join", "FULL JOIN sessions ON events.$session_id = sessions.session_id"),
+ ]
+
+ @parameterized.expand(_ROW_PRESERVING_JOINS)
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_row_preserving_join_pushes_timestamp_down(self, _name: str, join_clause: str):
+ """LEFT [OUTER] joins preserve every events row, so the inner LIMIT stays equivalent and the
+ events.timestamp predicate is pushed into the subquery."""
+ printed = self._print_select(
+ f"SELECT sessions.session_id, uuid FROM events {join_clause} WHERE events.timestamp > '2021-01-01'"
+ )
+ assert ") AS events LEFT" in printed, f"{_name} should push the predicate into a subquery:\n{printed}"
+ assert printed == self.snapshot
+
+ @parameterized.expand(_NON_ROW_PRESERVING_JOINS)
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_non_row_preserving_join_skips_pushdown(self, _name: str, join_clause: str):
+ """INNER / CROSS can drop an events row and RIGHT / FULL can synthesize null events rows, so the
+ pushed inner LIMIT would change results; the pushdown declines and the query runs flat."""
+ printed = self._print_select(
+ f"SELECT sessions.session_id, uuid FROM events {join_clause} WHERE events.timestamp > '2021-01-01'"
+ )
+ assert ") AS events LEFT JOIN" not in printed, f"{_name} should not push the predicate:\n{printed}"
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_bare_timestamp_with_select_alias_pushes_down(self):
+ printed = self._print_select(
+ "SELECT event, toTimeZone(timestamp, 'UTC') as timestamp, session.$session_duration "
+ "FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp <= today()"
+ )
+ assert printed == self.snapshot
+
+ def test_non_pushable_prewhere_bails(self):
+ # A PREWHERE with a non-events (joined) predicate can't be pushed, and can't stay on the outer query
+ # either: after pushdown the outer FROM is a subquery, where PREWHERE is invalid. So the transform
+ # bails rather than emit an invalid PREWHERE on a subquery. (Such a query is already invalid ClickHouse
+ # since PREWHERE can't reference a joined column, so this just guarantees we don't make it worse.)
+ printed = self._print_select(
+ "SELECT event, session.$session_duration FROM events "
+ "PREWHERE timestamp >= '2024-01-01' AND session.$session_duration > 0"
+ )
+ assert ") AS events LEFT JOIN" not in printed, (
+ "expected pushdown to bail on a non-pushable PREWHERE:\n" + printed
+ )
+
+ def test_pushable_prewhere_and_where_both_pushed(self):
+ # An events-only PREWHERE and an events-only WHERE are both pushable. The PREWHERE stays a PREWHERE on
+ # the inner events scan (honoring intent), the WHERE goes to the inner WHERE, and no PREWHERE remains
+ # on the outer subquery-based query (where it would be invalid).
+ printed = self._print_select(
+ "SELECT event, session.$session_duration FROM events PREWHERE event = '$pageview' WHERE timestamp >= '2024-01-01'"
+ )
+ # Compact all whitespace so the structural assertions don't depend on pretty-printer line breaks.
+ compact = "".join(printed.split())
+ assert ")ASeventsLEFTJOIN" in compact, "expected pushdown to fire:\n" + printed
+ subquery = compact.split("FROM(", 1)[1].split(")ASeventsLEFTJOIN", 1)[0]
+ assert "PREWHERE" in subquery, "pushed PREWHERE should stay a PREWHERE on the inner events scan:\n" + printed
+ assert "equals(events.event" in subquery, "PREWHERE predicate should be on the inner scan:\n" + printed
+ assert "greaterOrEquals(events.timestamp" in subquery, (
+ "WHERE predicate should be pushed into the subquery:\n" + printed
+ )
+ assert "PREWHERE" not in compact.split(")ASeventsLEFTJOIN", 1)[1], (
+ "no PREWHERE should remain on the subquery-based outer query:\n" + printed
+ )
+
+ # Gate: pushdown only helps when the LIMIT can short-circuit the events scan. Aggregate / GROUP BY /
+ # DISTINCT / window all consume the whole filtered set before the LIMIT applies, so the pre-filter
+ # subquery would be pure materialization overhead; decline (still correct, just not worth it).
+ _FORCES_FULL_READ_SHAPES = [
+ (
+ "aggregate_fn",
+ "SELECT count() AS c, max(session.$session_duration) AS d FROM events WHERE timestamp >= '2024-01-01'",
+ ),
+ (
+ "group_by",
+ "SELECT event, count() AS c FROM events WHERE timestamp >= '2024-01-01' AND session.$session_duration > 0 GROUP BY event",
+ ),
+ ("distinct", "SELECT DISTINCT event, session.$session_duration FROM events WHERE timestamp >= '2024-01-01'"),
+ (
+ "window_fn",
+ "SELECT event, row_number() OVER (ORDER BY timestamp) AS rn, session.$session_duration FROM events WHERE timestamp >= '2024-01-01'",
+ ),
+ ]
+
+ @parameterized.expand(_FORCES_FULL_READ_SHAPES)
+ def test_full_event_read_shapes_are_not_pushed(self, _name: str, select: str):
+ printed = self._print_select(select)
+ assert ") AS events LEFT JOIN" not in printed, f"{_name} should not be pushed (full-read shape):\n{printed}"
+
+ def test_nested_subquery_without_limit_is_not_pushed(self):
+ # A nested events subquery gets no auto-limit, and without an explicit one its LIMIT can't
+ # short-circuit the events scan, so we decline.
+ printed = self._print_select(
+ "SELECT event, d FROM ("
+ "SELECT event, session.$session_duration AS d FROM events WHERE timestamp >= '2024-01-01'"
+ ") LIMIT 100"
+ )
+ assert ") AS events LEFT JOIN" not in printed, (
+ "nested subquery without a LIMIT should not be pushed:\n" + printed
+ )
+
+ def test_nested_subquery_with_explicit_limit_is_pushed(self):
+ # The same nested subquery with its own LIMIT can short-circuit, so it is pushed.
+ printed = self._print_select(
+ "SELECT event, d FROM ("
+ "SELECT event, session.$session_duration AS d FROM events WHERE timestamp >= '2024-01-01' LIMIT 100"
+ ")"
+ )
+ assert ") AS events LEFT JOIN" in printed, (
+ "nested subquery with an explicit LIMIT should be pushed:\n" + printed
+ )
+
+
+class TestOuterWhereAssignment:
+ """Verify that _apply_pushdown assigns outer_where back to node.where."""
+
+ def test_extractor_correctly_splits_mixed_predicates(self):
+ timestamp_pred = ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value="2024-01-01"),
+ )
+ session_pred = ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Field(chain=["events__session", "duration"]),
+ right=ast.Constant(value=0),
+ )
+ where = ast.And(exprs=[timestamp_pred, session_pred])
+
+ extractor = EventsPredicatePushdownExtractor(joined_table_aliases={"events__session"})
+ inner_where, outer_where = extractor.get_pushdown_predicates(where)
+
+ assert inner_where is not None
+ assert outer_where is not None
+
+
+class TestEventsPredicatePushdownTransformUnit:
+ """Unit tests for helper methods that don't require database/context."""
+
+ def _make_events_select_with_join(
+ self, where_clause: ast.Expr | None = None, alias: str | None = None, sample: ast.SampleExpr | None = None
+ ) -> ast.SelectQuery:
+ """Create a minimal SELECT query from events with a join for testing."""
+ events_field = ast.Field(chain=["events"])
+
+ mock_join = ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=ast.SelectQuery(
+ select=[ast.Field(chain=["*"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["sessions"])),
+ ),
+ alias="events__session",
+ )
+
+ select_from = ast.JoinExpr(
+ table=events_field,
+ alias=alias,
+ next_join=mock_join,
+ sample=sample,
+ # _should_apply_pushdown now keys off the resolved table type (it runs post-resolution),
+ # so the FROM must carry the events TableType for these unit tests.
+ type=ast.TableType(table=EventsTable()),
+ )
+
+ return ast.SelectQuery(
+ select=[ast.Field(chain=["event"])],
+ select_from=select_from,
+ where=where_clause,
+ # The gate requires an effective LIMIT (so the LIMIT can short-circuit the events scan); give the
+ # node an explicit one. Tests asserting decline fail on their own check (no WHERE, SAMPLE, etc.).
+ limit=ast.Constant(value=100),
+ )
+
+ def test_printer_top_level_select_ids_excludes_nested_union_branches(self):
+ # The printer injects a top-level LIMIT only on the root select or the direct branches of the
+ # OUTERMOST union (depth 2). A nested-union inner branch sits deeper, so it must be excluded; else it
+ # would get an inner LIMIT with no matching printer-injected outer cap, diverging from the flat query.
+ a, b, c = (parse_select("SELECT event FROM events") for _ in range(3))
+ assert isinstance(a, ast.SelectQuery) and isinstance(b, ast.SelectQuery) and isinstance(c, ast.SelectQuery)
+
+ assert _printer_top_level_select_ids(a) == {id(a)}, "a root SelectQuery is itself top-level"
+
+ simple = ast.SelectSetQuery.create_from_queries([a, b], "UNION ALL")
+ assert _printer_top_level_select_ids(simple) == {id(a), id(b)}, "both direct branches of a union are top-level"
+
+ inner = ast.SelectSetQuery.create_from_queries([a, b], "UNION ALL")
+ nested = ast.SelectSetQuery.create_from_queries([inner, c], "UNION ALL")
+ assert _printer_top_level_select_ids(nested) == {id(c)}, (
+ "only the outermost direct SelectQuery branch is top-level"
+ )
+
+ def test_should_apply_pushdown_with_valid_query(self):
+ where_clause = ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value="2024-01-01"),
+ )
+ node = self._make_events_select_with_join(where_clause=where_clause)
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._should_apply_pushdown(node) is True
+
+ def test_should_not_apply_pushdown_without_where(self):
+ node = self._make_events_select_with_join(where_clause=None)
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_not_apply_pushdown_without_joins(self):
+ events_field = ast.Field(chain=["events"])
+ select_from = ast.JoinExpr(table=events_field, next_join=None)
+ node = ast.SelectQuery(
+ select=[ast.Field(chain=["event"])],
+ select_from=select_from,
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value="2024-01-01"),
+ ),
+ )
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_not_apply_pushdown_for_non_events_table(self):
+ persons_field = ast.Field(chain=["persons"])
+ mock_join = ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=ast.Field(chain=["other"]),
+ alias="other_alias",
+ )
+ select_from = ast.JoinExpr(table=persons_field, next_join=mock_join)
+ node = ast.SelectQuery(
+ select=[ast.Field(chain=["id"])],
+ select_from=select_from,
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["created_at"]),
+ right=ast.Constant(value="2024-01-01"),
+ ),
+ )
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_apply_pushdown_with_prewhere_instead_of_where(self):
+ """Bug: queries with PREWHERE but no WHERE skip pushdown entirely."""
+ prewhere = ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value="2024-01-01"),
+ )
+ node = self._make_events_select_with_join(where_clause=None)
+ node.prewhere = prewhere
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._should_apply_pushdown(node) is True
+
+ def test_should_not_apply_pushdown_with_sample_clause(self):
+ sample = ast.SampleExpr(sample_value=ast.RatioExpr(left=ast.Constant(value=1), right=ast.Constant(value=10)))
+ where_clause = ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value="2024-01-01"),
+ )
+ node = self._make_events_select_with_join(where_clause=where_clause, sample=sample)
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._should_apply_pushdown(node) is False
+
+ _TS_PRED = ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value="2024-01-01"),
+ )
+
+ def test_should_not_apply_pushdown_without_effective_limit(self):
+ # No explicit LIMIT and not an outermost select → nothing for the pushdown to short-circuit, decline.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.limit = None
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_apply_pushdown_for_top_level_without_explicit_limit(self):
+ # An outermost select gets a top-level LIMIT injected later, so it counts as limited even with no
+ # LIMIT on the AST yet (the auto-limit mechanism the gate relies on).
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.limit = None
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1), top_level_select_ids={id(node)})
+
+ assert transform._should_apply_pushdown(node) is True
+
+ def test_should_not_apply_pushdown_with_aggregate_nested_in_call(self):
+ # The aggregate is wrapped in a non-aggregate call, so the blocker finder must recurse into call args
+ # to detect it; otherwise the whole-set read would be missed and the subquery wasted.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.select = [
+ ast.Call(
+ name="round", args=[ast.Call(name="avg", args=[ast.Field(chain=["timestamp"])]), ast.Constant(value=2)]
+ )
+ ]
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_not_apply_pushdown_with_aggregate_only_in_having(self):
+ # An aggregate reachable only via HAVING still consumes the whole filtered set before the LIMIT.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.having = ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt, left=ast.Call(name="count", args=[]), right=ast.Constant(value=0)
+ )
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_apply_pushdown_ignoring_aggregate_in_scalar_subquery(self):
+ # An aggregate inside a scalar subquery in the SELECT list belongs to that subquery's scope, not this
+ # one, so it must NOT make this (non-aggregate) query decline, or we'd lose the optimization.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ scalar_subquery = ast.SelectQuery(
+ select=[ast.Call(name="count", args=[])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ )
+ node.select = [ast.Field(chain=["event"]), scalar_subquery]
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+
+ assert transform._should_apply_pushdown(node) is True
+
+ def test_should_not_apply_pushdown_when_top_level_limit_disabled(self):
+ # COHORT_CALCULATION / SAVED_QUERY / exports set limit_top_select=False and inject only a huge
+ # sentinel limit, nothing for the LIMIT to short-circuit, so decline even though node.limit is set.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ context = HogQLContext(team_id=1)
+ context.limit_top_select = False
+
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_not_apply_pushdown_with_aggregate_in_order_by(self):
+ # A bare aggregate in ORDER BY (no GROUP BY) is an implicit whole-set read, so the LIMIT can't
+ # short-circuit; decline.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.order_by = [ast.OrderExpr(expr=ast.Call(name="count", args=[]), order="DESC")]
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_not_apply_pushdown_with_aggregate_in_qualify(self):
+ # An aggregate/window reachable only via QUALIFY also forces a whole-set read.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.qualify = ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt, left=ast.Call(name="count", args=[]), right=ast.Constant(value=0)
+ )
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_should_not_apply_pushdown_with_aggregate_in_call_filter(self):
+ # An aggregate hidden in a non-arg call position (here filter_expr of a non-aggregate call) must still
+ # be detected: the finder recurses into every child position, not just args.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.select = [
+ ast.Call(name="toString", args=[ast.Field(chain=["event"])], filter_expr=ast.Call(name="count", args=[]))
+ ]
+
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+
+ assert transform._should_apply_pushdown(node) is False
+
+ def test_safe_inner_limit_for_safe_left_join_query(self):
+ # No ORDER BY, no residual predicate, LEFT join, concrete LIMIT -> push the limit (offset 0).
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+ result = transform._safe_inner_limit(node, residual_where=None, residual_prewhere=None)
+ assert isinstance(result, ast.Constant) and result.value == 100
+
+ def test_safe_inner_limit_adds_offset(self):
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.offset = ast.Constant(value=20)
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+ result = transform._safe_inner_limit(node, None, None)
+ assert isinstance(result, ast.Constant) and result.value == 120 # limit 100 + offset 20
+
+ def test_safe_inner_limit_declines_with_order_by(self):
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.order_by = [ast.OrderExpr(expr=ast.Field(chain=["timestamp"]), order="ASC")]
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+ assert transform._safe_inner_limit(node, None, None) is None
+
+ def test_safe_inner_limit_declines_with_residual_predicate(self):
+ # A predicate left on the outer query removes post-join rows, so an inner LIMIT would keep too few.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+ assert (
+ transform._safe_inner_limit(node, residual_where=ast.Constant(value=True), residual_prewhere=None) is None
+ )
+
+ def test_safe_inner_limit_declines_for_inner_join(self):
+ # An INNER join can drop an events row, so the inner LIMIT might leave fewer than `limit` rows.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ assert node.select_from is not None and node.select_from.next_join is not None
+ node.select_from.next_join.join_type = "INNER JOIN"
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+ assert transform._safe_inner_limit(node, None, None) is None
+
+ def test_safe_inner_limit_declines_without_concrete_limit(self):
+ # A top-level query before the executor injects a limit has no value to push.
+ node = self._make_events_select_with_join(where_clause=self._TS_PRED)
+ node.limit = None
+ transform = EventsPredicatePushdownTransform(HogQLContext(team_id=1))
+ assert transform._safe_inner_limit(node, None, None) is None
+
+ def test_collect_joined_aliases_single_join(self):
+ node = self._make_events_select_with_join(where_clause=ast.Constant(value=True))
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ aliases = transform._collect_joined_aliases(node)
+
+ assert aliases == {"events__session"}
+
+ def test_collect_joined_aliases_multiple_joins(self):
+ events_field = ast.Field(chain=["events"])
+ third_join = ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=ast.Field(chain=["cohorts"]),
+ alias="events__cohort",
+ )
+ second_join = ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=ast.Field(chain=["persons"]),
+ alias="events__person",
+ next_join=third_join,
+ )
+ first_join = ast.JoinExpr(
+ join_type="LEFT JOIN",
+ table=ast.Field(chain=["sessions"]),
+ alias="events__session",
+ next_join=second_join,
+ )
+ select_from = ast.JoinExpr(table=events_field, next_join=first_join)
+ node = ast.SelectQuery(
+ select=[ast.Field(chain=["event"])],
+ select_from=select_from,
+ where=ast.Constant(value=True),
+ )
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ aliases = transform._collect_joined_aliases(node)
+
+ assert aliases == {"events__session", "events__person", "events__cohort"}
+
+ @pytest.mark.parametrize(
+ "join_type",
+ ["RIGHT JOIN", "RIGHT OUTER JOIN", "FULL JOIN", "FULL OUTER JOIN"],
+ )
+ def test_collect_joined_aliases_empty_for_unsafe_join_type(self, join_type: str):
+ events_field = ast.Field(chain=["events"])
+ mock_join = ast.JoinExpr(
+ join_type=join_type,
+ table=ast.Field(chain=["sessions"]),
+ alias="events__session",
+ )
+ select_from = ast.JoinExpr(table=events_field, next_join=mock_join)
+ node = ast.SelectQuery(
+ select=[ast.Field(chain=["event"])],
+ select_from=select_from,
+ where=ast.Constant(value=True),
+ )
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ assert transform._collect_joined_aliases(node) == set()
+
+ def test_collect_joined_aliases_empty_when_no_joins(self):
+ events_field = ast.Field(chain=["events"])
+ select_from = ast.JoinExpr(table=events_field, next_join=None)
+ node = ast.SelectQuery(
+ select=[ast.Field(chain=["event"])],
+ select_from=select_from,
+ where=ast.Constant(value=True),
+ )
+
+ context = HogQLContext(team_id=1)
+ transform = EventsPredicatePushdownTransform(context)
+
+ aliases = transform._collect_joined_aliases(node)
+ assert aliases == set()
+
+
+class TestLazyTypeDetector(BaseTest):
+ """Tests for LazyTypeDetector using real HogQL queries.
+
+ A LazyJoinType / LazyTableType in the AST means lazy join resolution hasn't completed, so predicate
+ pushdown should be skipped.
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.database = Database.create_for(team=self.team)
+ self.context = HogQLContext(team_id=self.team.pk, database=self.database, enable_select_queries=True)
+
+ def _resolve_query(self, query: str) -> ast.SelectQuery:
+ """Parse and resolve types for a query (without lazy table resolution)."""
+ parsed = parse_select(query)
+ resolved = resolve_types(parsed, self.context, dialect="clickhouse")
+ assert isinstance(resolved, ast.SelectQuery)
+ return resolved
+
+ def test_detects_lazy_join_from_session_field(self):
+ """Query accessing session.$session_duration has LazyJoinType before lazy resolution."""
+ # session is a LazyJoin on events, so resolve_types produces a LazyJoinType
+ node = self._resolve_query("SELECT session.$session_duration FROM events")
+
+ detector = LazyTypeDetector()
+ detector.visit(node)
+
+ assert detector.found_lazy_type is True
+
+ def test_detects_lazy_join_from_person_field(self):
+ """Query accessing person.id has LazyJoinType before lazy resolution."""
+ node = self._resolve_query("SELECT person.id FROM events")
+
+ detector = LazyTypeDetector()
+ detector.visit(node)
+
+ assert detector.found_lazy_type is True
+
+ def test_no_lazy_type_for_direct_events_columns(self):
+ """Query with only direct events columns has no lazy types."""
+ node = self._resolve_query("SELECT event, timestamp, distinct_id FROM events")
+
+ detector = LazyTypeDetector()
+ detector.visit(node)
+
+ assert detector.found_lazy_type is False
+
+ def test_no_lazy_type_after_lazy_table_resolution(self):
+ """After resolve_lazy_tables, there should be no lazy types in the main query fields."""
+ resolved = self._resolve_query(
+ "SELECT event, session.$session_duration FROM events WHERE timestamp > '2024-01-01'"
+ )
+ resolve_lazy_tables(resolved, "clickhouse", [], self.context)
+
+ # Check only the SELECT fields (not the joined subqueries which may have their own structure)
+ detector = LazyTypeDetector()
+ for field in resolved.select:
+ detector.visit(field)
+
+ assert detector.found_lazy_type is False
+
+
+class TestEventsFieldCollector(BaseTest):
+ """Tests for EventsFieldCollector using real HogQL queries.
+
+ EventsFieldCollector collects the events database columns a query needs and detects non-direct fields
+ (PropertyType, LazyJoinType) that prevent safe pushdown.
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.database = Database.create_for(team=self.team)
+ self.context = HogQLContext(team_id=self.team.pk, database=self.database, enable_select_queries=True)
+
+ def _resolve_query(self, query: str) -> tuple[ast.SelectQuery, ast.TableType | ast.TableAliasType]:
+ """Parse, resolve types, and return query with events table type."""
+ parsed = parse_select(query)
+ resolved = resolve_types(parsed, self.context, dialect="clickhouse")
+ assert isinstance(resolved, ast.SelectQuery)
+ assert resolved.select_from is not None
+ events_table_type = resolved.select_from.type
+ assert isinstance(events_table_type, (ast.TableType, ast.TableAliasType))
+ return resolved, events_table_type
+
+ def test_collects_direct_database_columns(self):
+ """Direct events columns like event, timestamp are collected."""
+ node, events_table_type = self._resolve_query("SELECT event, timestamp FROM events WHERE distinct_id = 'user1'")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert "event" in collector.collected_fields
+ assert "timestamp" in collector.collected_fields
+ assert "distinct_id" in collector.collected_fields
+ assert collector.has_non_direct_fields is False
+
+ def test_property_access_collects_base_column(self):
+ # Accessing properties.$browser collects the base `properties` column so the property filter
+ # can be pushed and re-typed to the inner events table, rather than flagging it as non-direct.
+ node, events_table_type = self._resolve_query("SELECT properties.$browser FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert "properties" in collector.collected_fields
+ assert collector.has_non_direct_fields is False
+
+ def test_lazy_join_field_triggers_non_direct_flag(self):
+ """Accessing session.$session_duration (lazy join) triggers has_non_direct_fields."""
+ node, events_table_type = self._resolve_query("SELECT session.$session_duration FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert collector.has_non_direct_fields is True
+
+ def test_session_id_from_events_is_direct_column(self):
+ """$session_id on events is a direct column (not a property access)."""
+ node, events_table_type = self._resolve_query("SELECT `$session_id` FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ # $session_id is a direct column on events table
+ assert "$session_id" in collector.collected_fields
+ assert collector.has_non_direct_fields is False
+
+ def test_poe_properties_collected_as_person_properties(self):
+ """poe.properties (VirtualTable) resolves to database column person_properties."""
+ node, events_table_type = self._resolve_query("SELECT poe.properties FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert "person_properties" in collector.collected_fields
+ assert collector.has_non_direct_fields is False
+
+ def test_poe_id_collected_as_person_id(self):
+ """poe.id (VirtualTable) resolves to database column person_id."""
+ node, events_table_type = self._resolve_query("SELECT poe.id FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert "person_id" in collector.collected_fields
+ assert collector.has_non_direct_fields is False
+
+ def test_poe_created_at_collected_as_person_created_at(self):
+ """poe.created_at (VirtualTable) resolves to database column person_created_at."""
+ node, events_table_type = self._resolve_query("SELECT poe.created_at FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert "person_created_at" in collector.collected_fields
+ assert collector.has_non_direct_fields is False
+
+ def test_poe_field_type_has_virtual_table_type(self):
+ """Collected poe field has VirtualTableType as its table_type."""
+ node, events_table_type = self._resolve_query("SELECT poe.properties FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ field_type = collector.collected_fields["person_properties"]
+ assert isinstance(field_type.table_type, ast.VirtualTableType)
+
+ def test_poe_mixed_with_direct_columns(self):
+ """VirtualTable fields and direct columns are both collected."""
+ node, events_table_type = self._resolve_query("SELECT event, poe.id, timestamp FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert "event" in collector.collected_fields
+ assert "person_id" in collector.collected_fields
+ assert "timestamp" in collector.collected_fields
+ assert collector.has_non_direct_fields is False
+
+ def test_poe_revenue_analytics_lazy_join_triggers_non_direct(self):
+ """poe.revenue_analytics is a LazyJoin inside VirtualTable, so it triggers the non-direct flag."""
+ node, events_table_type = self._resolve_query("SELECT poe.revenue_analytics.revenue FROM events")
+
+ collector = EventsFieldCollector(events_table_type, self.context)
+ collector.visit(node)
+
+ assert collector.has_non_direct_fields is True
+
+
+class TestSavedQueryWithLazyJoins(BaseTest):
+ """Tests for predicate pushdown with SavedQuery views that contain lazy joins.
+
+ A SavedQuery view's lazy joins (like events.person.distinct_id) should be fully resolved when the view is
+ expanded during resolve_types, before predicate pushdown runs.
+ """
+
+ def setUp(self):
+ super().setUp()
+ self.database = Database.create_for(team=self.team)
+
+ # A SavedQuery containing lazy joins, simulating what revenue_analytics views do.
+ self.saved_query = SavedQuery(
+ id="test_view",
+ name="test_events_with_person",
+ query="SELECT event, person.id AS person_id, session.$session_duration AS session_duration FROM events WHERE timestamp > '2024-01-01'",
+ fields={
+ "event": StringDatabaseField(name="event"),
+ "person_id": StringDatabaseField(name="person_id"),
+ "session_duration": IntegerDatabaseField(name="session_duration"),
+ },
+ )
+
+ self.database.tables.add_child(TableNode(name="test_events_with_person", table=self.saved_query))
+
+ self.context = HogQLContext(
+ team_id=self.team.pk,
+ database=self.database,
+ enable_select_queries=True,
+ )
+
+ def test_saved_query_with_lazy_joins_and_session_join(self):
+ """Query from SavedQuery that internally uses lazy joins should resolve properly."""
+
+ # The persons table join needs the team on the context.
+ self.context.team = self.team
+
+ query_str = "SELECT event, person_id, session_duration FROM test_events_with_person"
+
+ query, prepared_ast = prepare_and_print_ast(
+ parse_select(query_str),
+ self.context,
+ "clickhouse",
+ )
+
+ # Completing without error verifies the lazy joins were fully resolved.
+ assert "SELECT" in query
+
+
+# Result-equivalence tests that run real ClickHouse queries. Unlike the printer tests above (which only
+# assert on the generated SQL string), these create events, execute the query with pushDownPredicates on
+# and off, and assert identical results: pushdown is a pure optimization, and executing the query surfaces
+# any SQL ClickHouse rejects (e.g. an outer-alias leak), which string snapshots cannot catch.
+class _PushdownExecutionTestBase(ClickhouseTestMixin, APIBaseTest):
+ snapshot: Any
+ _property_groups_mode: PropertyGroupsMode | None = None
+ _pass_team = False # Dmat slot resolution needs the team on the print context
+
+ def _modifiers(self, *, push_down: bool) -> HogQLQueryModifiers:
+ extra = {"propertyGroupsMode": self._property_groups_mode} if self._property_groups_mode is not None else {}
+ return HogQLQueryModifiers(pushDownPredicates=push_down, **extra)
+
+ def _print_pushdown_sql(self, select: str) -> str:
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team if self._pass_team else None,
+ enable_select_queries=True,
+ modifiers=self._modifiers(push_down=True),
+ )
+ query, _ = prepare_and_print_ast(parse_select(select), context, "clickhouse")
+ return pretty_print_in_tests(query, self.team.pk)
+
+ def _results(self, select: str, *, push_down: bool):
+ return execute_hogql_query(select, team=self.team, modifiers=self._modifiers(push_down=push_down)).results
+
+ @staticmethod
+ def _sorted(rows: list | None) -> list:
+ # Sort by repr so rows with NULL columns (e.g. an unmatched LEFT JOIN's NULL duration, or a missing
+ # property) don't raise on mixed None/str comparisons. Pushdown is order-agnostic with an inner LIMIT,
+ # so only the multiset of rows must match on vs off.
+ return sorted(rows or [], key=repr)
+
+ def _assert_results_equivalent(self, select: str) -> list:
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+ return with_pushdown or []
+
+ def _events_subquery(self, printed: str) -> str:
+ assert ") AS events LEFT JOIN" in printed, f"expected pushdown to wrap events in a subquery:\n{printed}"
+ return printed.split("FROM (", 1)[1].split(") AS events LEFT JOIN", 1)[0]
+
+
+class TestEventsPredicatePushdownExecution(_PushdownExecutionTestBase):
+ def _create_session(self, when_iso: str, distinct_id: str, tier: str, *event_timestamps: str) -> None:
+ # session_id is a uuid7 whose embedded time must line up with the events so the session join matches
+ session_id = str(uuid7(when_iso))
+ for ts in event_timestamps:
+ _create_event(
+ team=self.team,
+ event="watched movie",
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={"$session_id": session_id, "tier": tier},
+ )
+
+ def _create_data(self) -> None:
+ # Two in-range sessions (Jan 2024) plus one out-of-range session (2023) the timestamp filter must drop
+ self._create_session("2024-01-02T00:00:00", "u1", "pro", "2024-01-02T10:00:00", "2024-01-02T10:05:00")
+ self._create_session("2024-01-05T00:00:00", "u2", "free", "2024-01-05T09:00:00")
+ self._create_session("2023-06-01T00:00:00", "u3", "pro", "2023-06-01T09:00:00")
+ flush_persons_and_events()
+
+ def _assert_pushdown_equivalent(self, select: str, *, expected_rows: int) -> None:
+ # Sorted comparison: the pushed inner LIMIT means queries don't need an ORDER BY (which would decline
+ # the pushdown), so the row order isn't pinned; only the set of rows must match on vs off.
+ with_pushdown = self._assert_results_equivalent(select)
+ assert len(with_pushdown) == expected_rows, f"expected {expected_rows} rows, got {with_pushdown}"
+
+ def test_exec_self_join_with_inner_limit_stays_equivalent(self):
+ # Adversarial: a self-join shares the same `EventsTable` instance, so the column collector matches the
+ # right side's columns by identity, and the right side is one-to-many on distinct_id. With the pushed
+ # inner LIMIT bounding only the left scan, the full result set (LIMIT >= output) stays identical.
+ self._create_data()
+ select = (
+ "SELECT a.event AS ae, b.event AS be FROM events AS a "
+ "LEFT JOIN events AS b ON a.distinct_id = b.distinct_id "
+ "WHERE a.timestamp >= '2024-01-01' AND a.timestamp < '2024-01-08' LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert ") AS a LEFT JOIN" in printed, f"expected the self-join left scan to be pushed:\n{printed}"
+ self._assert_results_equivalent(select)
+
+ def test_exec_limit_below_match_count_returns_valid_rows_both_ways(self):
+ # A non-ORDER-BY LIMIT smaller than the matching set is non-deterministic (even two un-pushed runs can
+ # return different rows), so on==off isn't a valid assertion. The pushed inner LIMIT bounds the events
+ # scan rather than the joined output, so the chosen rows can differ; assert instead that BOTH forms
+ # return a valid result: exactly LIMIT rows, each drawn from the full matching set.
+ for i in range(1, 7):
+ self._create_session(f"2024-01-0{i}T00:00:00", f"u{i}", "pro", f"2024-01-0{i}T10:00:00")
+ self._create_session("2023-06-01T00:00:00", "u_old", "pro", "2023-06-01T09:00:00") # out of range
+ flush_persons_and_events()
+ base = (
+ "SELECT distinct_id, session.$session_duration AS d FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08'"
+ )
+ limited = base + " LIMIT 3"
+ assert ") AS events LEFT JOIN" in self._print_pushdown_sql(limited), "expected the LIMIT 3 query to push"
+ valid = {tuple(r) for r in (self._results(base + " LIMIT 1000", push_down=False) or [])}
+ assert len(valid) == 6, f"expected 6 matching rows in the full set, got {valid}"
+ for push in (True, False):
+ rows = self._results(limited, push_down=push) or []
+ assert len(rows) == 3, f"push={push}: expected exactly 3 rows, got {rows}"
+ assert all(tuple(r) in valid for r in rows), f"push={push}: returned a row outside the matching set: {rows}"
+
+ def test_exec_offset_with_fan_out_join_returns_valid_rows_both_ways(self):
+ # OFFSET + a one-to-many LEFT join. The pushed inner LIMIT is limit + offset, so the first
+ # offset+limit events still cover the outer [offset, offset+limit) slice. Below-match-count
+ # LIMIT/OFFSET is non-deterministic without ORDER BY (flat too), so assert both forms return exactly
+ # LIMIT rows drawn from the valid matching set, and that the inner LIMIT is limit+offset.
+ self._create_data() # u1 x2 + u2 x1 in range; self-join on distinct_id fans out (u1 -> 2 b-rows each)
+ base = (
+ "SELECT a.event AS ae, a.distinct_id AS aid FROM events AS a "
+ "LEFT JOIN events AS b ON a.distinct_id = b.distinct_id "
+ "WHERE a.timestamp >= '2024-01-01' AND a.timestamp < '2024-01-08'"
+ )
+ paged = base + " LIMIT 2 OFFSET 1"
+ printed = self._print_pushdown_sql(paged)
+ assert ") AS a LEFT JOIN" in printed, f"expected the OFFSET self-join left scan to push:\n{printed}"
+ subquery = printed.split("FROM (", 1)[1].split(") AS a LEFT JOIN", 1)[0]
+ assert "LIMIT 3" in subquery, f"inner LIMIT should be limit+offset (2+1=3):\n{subquery}"
+ valid = {tuple(r) for r in (self._results(base + " LIMIT 1000", push_down=False) or [])}
+ for push in (True, False):
+ rows = self._results(paged, push_down=push) or []
+ assert len(rows) == 2, f"push={push}: expected exactly 2 rows, got {rows}"
+ assert all(tuple(r) in valid for r in rows), f"push={push}: returned a row outside the matching set: {rows}"
+
+ def test_exec_binding_limit_grouped_join_returns_correct_count(self):
+ # The shape that motivated the gate: events LEFT JOIN a `GROUP BY session_id` subquery, with a LIMIT
+ # that actually BINDS (far more matching events than the limit, several events per session, so the
+ # grouped subquery fans in). The pushed inner LIMIT must cut EVENTS before the join (not the joined
+ # output), so both forms return exactly LIMIT rows from the valid set. 16 in-range events, LIMIT 5.
+ self._create_session("2024-01-02T00:00:00", "u1", "pro", *[f"2024-01-02T10:{m:02d}:00" for m in range(8)])
+ self._create_session("2024-01-05T00:00:00", "u2", "free", *[f"2024-01-05T11:{m:02d}:00" for m in range(8)])
+ flush_persons_and_events()
+ base = (
+ "SELECT timestamp, session.$session_duration AS d FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08'"
+ )
+ limited = base + " LIMIT 5"
+ subquery = self._events_subquery(self._print_pushdown_sql(limited))
+ assert "LIMIT 5" in subquery, f"expected the pushed inner LIMIT to bind:\n{subquery}"
+ valid = {tuple(r) for r in (self._results(base + " LIMIT 1000", push_down=False) or [])}
+ assert len(valid) == 16, f"expected 16 distinct matching rows (8 per session x 2), got {len(valid)}"
+ for push in (True, False):
+ rows = self._results(limited, push_down=push) or []
+ assert len(rows) == 5, f"push={push}: LIMIT 5 must bind to exactly 5 rows, got {len(rows)}: {rows}"
+ assert all(tuple(r) in valid for r in rows), f"push={push}: returned a row outside the matching set: {rows}"
+
+ def test_exec_binding_limit_true_fan_out_returns_valid_rows_both_ways(self):
+ # The highest-risk shape: a BINDING inner LIMIT (below the matching-event count) AND a true one-to-many
+ # fan-out (self-join on distinct_id, all events share one distinct_id, so each a-event joins to every
+ # b-event). The pushed inner LIMIT cuts EVENTS before the join, so the joined output still has >= LIMIT
+ # rows; both forms must return exactly LIMIT rows from the full valid set. 6 events on one distinct_id
+ # -> 36 joined pairs, LIMIT 3 binds.
+ self._create_session("2024-01-02T00:00:00", "u1", "pro", *[f"2024-01-02T10:0{m}:00" for m in range(6)])
+ self._create_session("2023-06-01T00:00:00", "u_old", "pro", "2023-06-01T09:00:00") # out of range, dropped
+ flush_persons_and_events()
+ base = (
+ "SELECT a.timestamp AS at, b.timestamp AS bt FROM events AS a "
+ "LEFT JOIN events AS b ON a.distinct_id = b.distinct_id "
+ "WHERE a.timestamp >= '2024-01-01' AND a.timestamp < '2024-01-08'"
+ )
+ limited = base + " LIMIT 3"
+ printed = self._print_pushdown_sql(limited)
+ assert ") AS a LEFT JOIN" in printed, f"expected the fan-out self-join left scan to push:\n{printed}"
+ subquery = printed.split("FROM (", 1)[1].split(") AS a LEFT JOIN", 1)[0]
+ assert "LIMIT 3" in subquery, f"expected the pushed inner LIMIT to bind:\n{subquery}"
+ valid = {tuple(r) for r in (self._results(base + " LIMIT 1000", push_down=False) or [])}
+ assert len(valid) == 36, f"expected 36 joined pairs (6 events x 6 self-join matches), got {len(valid)}"
+ for push in (True, False):
+ rows = self._results(limited, push_down=push) or []
+ assert len(rows) == 3, f"push={push}: LIMIT 3 must bind to exactly 3 rows, got {len(rows)}: {rows}"
+ assert all(tuple(r) in valid for r in rows), f"push={push}: returned a row outside the matching set: {rows}"
+
+ def _setup_cohort_data(self) -> "Cohort":
+ # c_in ($os=Chrome) is in the cohort with 2 in-range events; c_out ($os=Firefox) is out, with 1.
+ _create_person(team=self.team, distinct_ids=["c_in"], properties={"$os": "Chrome"}, is_identified=True)
+ _create_person(team=self.team, distinct_ids=["c_out"], properties={"$os": "Firefox"}, is_identified=True)
+ self._create_session("2024-01-02T00:00:00", "c_in", "pro", "2024-01-02T10:00:00", "2024-01-02T10:05:00")
+ self._create_session("2024-01-03T00:00:00", "c_out", "pro", "2024-01-03T09:00:00")
+ flush_persons_and_events()
+ cohort = Cohort.objects.create(
+ team=self.team, groups=[{"properties": [{"key": "$os", "value": "Chrome", "type": "person"}]}]
+ )
+ recalculate_cohortpeople(cohort, pending_version=0, initiating_user_id=None)
+ return cohort
+
+ # Cohort predicates must never push, regardless of how IN COHORT resolves: inCohortVia=LEFTJOIN leaves an
+ # unresolved InCohort op (kept outer), and SUBQUERY / CONJOINED / inline resolve to a nested subquery
+ # (kept outer), across every personsOnEventsMode, so the `person_id` resolution (direct vs lazy override)
+ # can't make it slip through. Each shape must decline (run flat) and stay result-equivalent on vs off.
+ _COHORT_SHAPES = [
+ (
+ "subquery_person_id_direct",
+ InCohortVia.SUBQUERY,
+ PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
+ InlineCohortCalculation.OFF,
+ "IN COHORT",
+ 2,
+ ),
+ (
+ "subquery_override_on_events",
+ InCohortVia.SUBQUERY,
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,
+ InlineCohortCalculation.OFF,
+ "IN COHORT",
+ 2,
+ ),
+ (
+ "subquery_poe_disabled",
+ InCohortVia.SUBQUERY,
+ PersonsOnEventsMode.DISABLED,
+ InlineCohortCalculation.OFF,
+ "IN COHORT",
+ 2,
+ ),
+ (
+ "leftjoin_person_id_direct",
+ InCohortVia.LEFTJOIN,
+ PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
+ InlineCohortCalculation.OFF,
+ "IN COHORT",
+ 2,
+ ),
+ (
+ "conjoined_person_id_direct",
+ InCohortVia.LEFTJOIN_CONJOINED,
+ PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
+ InlineCohortCalculation.OFF,
+ "IN COHORT",
+ 2,
+ ),
+ (
+ "subquery_inline_calc",
+ InCohortVia.SUBQUERY,
+ PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
+ InlineCohortCalculation.ALWAYS,
+ "IN COHORT",
+ 2,
+ ),
+ (
+ "not_in_cohort",
+ InCohortVia.SUBQUERY,
+ PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
+ InlineCohortCalculation.OFF,
+ "NOT IN COHORT",
+ 1,
+ ),
+ ]
+
+ @parameterized.expand(_COHORT_SHAPES)
+ @override_settings(PERSON_ON_EVENTS_OVERRIDE=True, PERSON_ON_EVENTS_V2_OVERRIDE=False)
+ def test_exec_cohort_predicate_declines_and_stays_equivalent(
+ self, _name, in_cohort_via, poe_mode, inline, predicate, expected_count
+ ):
+ cohort = self._setup_cohort_data()
+ select = (
+ f"SELECT event, session.$session_duration FROM events "
+ f"WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08' "
+ f"AND person_id {predicate} {cohort.pk} LIMIT 50"
+ )
+
+ def mods(push: bool) -> HogQLQueryModifiers:
+ return HogQLQueryModifiers(
+ pushDownPredicates=push,
+ inCohortVia=in_cohort_via,
+ personsOnEventsMode=poe_mode,
+ inlineCohortCalculation=inline,
+ )
+
+ printed, _ = prepare_and_print_ast(
+ parse_select(select),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True, modifiers=mods(True)),
+ "clickhouse",
+ )
+ assert ") AS events LEFT JOIN" not in printed, f"{_name}: cohort predicate must not push:\n{printed}"
+ on = execute_hogql_query(select, team=self.team, modifiers=mods(True)).results
+ off = execute_hogql_query(select, team=self.team, modifiers=mods(False)).results
+ assert sorted(on or []) == sorted(off or []), f"{_name}: pushdown changed results: on={on} off={off}"
+ assert len(on or []) == expected_count, f"{_name}: expected {expected_count} rows, got {on}"
+
+ # `events.person.properties.email` is a DIRECT events column (read from `person_properties`) under the
+ # "properties on events" POE modes (so it's pushable) but a lazy persons join under "properties joined" /
+ # disabled, where it declines. The pushdown runs before the person-property PropertySwapper, so the pushed
+ # PropertyType is rewritten inside the subquery; the collector pre-exposes `person_properties`. Either way
+ # results must stay equivalent on vs off.
+ _POE_PERSON_PROPERTY_SHAPES = [
+ ("properties_on_events_no_override", PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS, True),
+ ("properties_on_events_override", PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS, True),
+ ("properties_joined", PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED, False),
+ ("poe_disabled", PersonsOnEventsMode.DISABLED, False),
+ ]
+
+ @parameterized.expand(_POE_PERSON_PROPERTY_SHAPES)
+ @override_settings(PERSON_ON_EVENTS_OVERRIDE=True, PERSON_ON_EVENTS_V2_OVERRIDE=False)
+ def test_exec_poe_person_property_filter(self, _name, poe_mode, expect_push):
+ _create_person(team=self.team, distinct_ids=["pp_in"], properties={"email": "[email protected]"}, is_identified=True)
+ _create_person(team=self.team, distinct_ids=["pp_out"], properties={"email": "[email protected]"}, is_identified=True)
+ self._create_session("2024-01-02T00:00:00", "pp_in", "pro", "2024-01-02T10:00:00", "2024-01-02T10:05:00")
+ self._create_session("2024-01-03T00:00:00", "pp_out", "pro", "2024-01-03T09:00:00")
+ flush_persons_and_events()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08' AND person.properties.email = '[email protected]' LIMIT 50"
+ )
+
+ def mods(push: bool) -> HogQLQueryModifiers:
+ return HogQLQueryModifiers(pushDownPredicates=push, personsOnEventsMode=poe_mode)
+
+ printed, _ = prepare_and_print_ast(
+ parse_select(select),
+ HogQLContext(team_id=self.team.pk, enable_select_queries=True, modifiers=mods(True)),
+ "clickhouse",
+ )
+ pushed = ") AS events LEFT JOIN" in printed
+ assert pushed is expect_push, f"{_name}: expected pushed={expect_push}:\n{printed}"
+ if pushed:
+ subquery = printed.split("FROM (", 1)[1].split(") AS events LEFT JOIN", 1)[0]
+ assert "person_properties" in subquery, f"{_name}: subquery should read person_properties:\n{subquery}"
+ assert "LIMIT" in subquery, f"{_name}: pushed subquery should carry an inner LIMIT:\n{subquery}"
+ on = execute_hogql_query(select, team=self.team, modifiers=mods(True)).results
+ off = execute_hogql_query(select, team=self.team, modifiers=mods(False)).results
+ assert sorted(on or []) == sorted(off or []), f"{_name}: pushdown changed results: on={on} off={off}"
+ assert len(on or []) == 2, f"{_name}: expected 2 rows (pp_in's events), got {on}"
+
+ def test_exec_array_join_predicate_not_pushed_stays_equivalent(self):
+ # arrayJoin in a predicate is residual (it can't be pushed into the events subquery), so the whole
+ # pushdown declines: with a residual predicate left on the outer query an inner LIMIT would be unsafe,
+ # so the query runs flat. Results must stay equivalent regardless.
+ self._create_data()
+ select = (
+ f"SELECT arrayJoin([1, 2]) AS n, session.$session_duration AS d FROM events "
+ f"WHERE {self._RANGE} AND arrayJoin([1, 2]) > 0"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert ") AS events LEFT JOIN" not in printed and ") AS e LEFT JOIN" not in printed, (
+ f"expected pushdown to decline with a residual arrayJoin predicate:\n{printed}"
+ )
+ # 3 in-range events x arrayJoin([1, 2]) = 6 rows, identical on vs off.
+ self._assert_pushdown_equivalent(select, expected_rows=6)
+
+ def test_exec_array_join_via_aliased_events_column_not_pushed(self):
+ # The arrayJoin is hidden behind a SELECT alias that shadows the `event` column and is referenced in
+ # the WHERE. The bare-alias predicate is residual (an arrayJoin can't be pushed), so the whole
+ # pushdown declines and the query runs flat. Results stay equivalent on vs off.
+ self._create_data()
+ select = (
+ f"SELECT arrayJoin([event, 'extra']) AS event, session.$session_duration AS d FROM events "
+ f"WHERE {self._RANGE} AND event = 'watched movie'"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert ") AS events LEFT JOIN" not in printed and ") AS e LEFT JOIN" not in printed, (
+ f"expected pushdown to decline with a residual arrayJoin alias predicate:\n{printed}"
+ )
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_exec_timestamp_filter_with_session_join(self):
+ self._create_data()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08' LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert printed == self.snapshot
+ assert "LIMIT" in self._events_subquery(printed)
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_exec_aliased_events_timestamp_filter_with_session_join(self):
+ self._create_data()
+ select = (
+ "SELECT e.event, session.$session_duration FROM events AS e "
+ "WHERE e.timestamp >= '2024-01-01' AND e.timestamp < '2024-01-08' LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert printed == self.snapshot
+ assert ") AS e LEFT JOIN" in printed, f"expected pushdown to wrap events:\n{printed}"
+ subquery = printed.split("FROM (", 1)[1].split(") AS e LEFT JOIN", 1)[0]
+ assert "LIMIT" in subquery
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ def test_exec_property_filter_pushes_with_inner_limit(self):
+ # A non-materialized property filter forces a raw `properties` blob read in the subquery, which
+ # regresses without a short-circuit. With no ORDER BY / residual predicate and a LEFT join, the
+ # transform pushes a LIMIT into the subquery so the blob read stops early; results stay identical.
+ self._create_data()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08' AND properties.tier = 'pro' LIMIT 50"
+ )
+ subquery = self._events_subquery(self._print_pushdown_sql(select))
+ assert "LIMIT 50" in subquery, f"expected the pushed LIMIT in the events subquery:\n{subquery}"
+ assert "JSONExtract" in subquery, f"expected the raw-blob filter in the subquery:\n{subquery}"
+ on = self._assert_results_equivalent(select)
+ assert len(on) == 2
+
+ def test_exec_aliased_property_filter_pushes_with_inner_limit(self):
+ # Same blob-safe-push path with an aliased events table: the inner subquery keeps the `e` alias and
+ # carries the pushed LIMIT.
+ self._create_data()
+ select = (
+ "SELECT e.event, session.$session_duration FROM events AS e "
+ "WHERE e.timestamp >= '2024-01-01' AND e.timestamp < '2024-01-08' AND e.properties.tier = 'pro' LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert ") AS e LEFT JOIN" in printed, f"expected property filter pushed into an events subquery:\n{printed}"
+ subquery = printed.split("FROM (", 1)[1].split(") AS e LEFT JOIN", 1)[0]
+ assert "FROM events AS e" in subquery, f"expected the subquery to define alias `e`:\n{subquery}"
+ assert "LIMIT 50" in subquery, f"expected the pushed LIMIT in the subquery:\n{subquery}"
+ on = self._assert_results_equivalent(select)
+ assert len(on) == 2
+
+ def test_exec_blob_property_with_order_by_declines(self):
+ # The same raw-blob property filter WITH an ORDER BY can't push a LIMIT safely (the sort needs the
+ # whole set), so the transform declines rather than read the blob across a wide scan. Still equivalent.
+ self._create_data()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08' AND properties.tier = 'pro' ORDER BY timestamp"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert ") AS events LEFT JOIN" not in printed, (
+ f"expected pushdown to decline (raw blob, no safe limit to short-circuit):\n{printed}"
+ )
+ self._assert_pushdown_equivalent(select, expected_rows=2)
+
+ def test_exec_alias_shadowing_constant_predicate_stays_correct(self):
+ # A SELECT alias whose name collides with an events column but whose expression is a constant
+ # must not be pushed by name: `WHERE event = 'x'` means `'x' = 'x'` (true), not events.event = 'x'.
+ self._create_data()
+ select = (
+ "SELECT 'x' AS event, session.$session_duration FROM events "
+ "WHERE event = 'x' AND timestamp >= '2024-01-01' AND timestamp < '2024-01-08' LIMIT 50"
+ )
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ def test_exec_alias_shadowing_joined_predicate_stays_correct(self):
+ # A SELECT alias whose name collides with an events column but whose expression references the
+ # joined session table must not be pushed into the events subquery. The residual joined predicate
+ # makes the whole pushdown decline; results stay equivalent either way.
+ self._create_data()
+ select = (
+ "SELECT ifNull(session.$session_duration, 0) AS event FROM events "
+ "WHERE event >= 0 AND timestamp >= '2024-01-01' AND timestamp < '2024-01-08' LIMIT 50"
+ )
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ def test_exec_events_prewhere_with_session_join_stays_correct(self):
+ # A pushable events-column PREWHERE plus a session join must stay result-equivalent on/off, and the
+ # PREWHERE must stay a PREWHERE on the inner events scan (not be demoted to WHERE). With no ORDER BY
+ # and a LEFT join the pushdown also carries an inner LIMIT.
+ self._create_data()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "PREWHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08' "
+ "WHERE event = 'watched movie' LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ subquery = "".join(printed.split()).split("FROM(", 1)[1].split(")ASeventsLEFTJOIN", 1)[0]
+ assert "PREWHERE" in subquery, "pushed PREWHERE should stay a PREWHERE on the inner scan:\n" + printed
+ assert "LIMIT" in subquery, "pushed subquery should carry an inner LIMIT:\n" + printed
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ def test_exec_prewhere_only_with_session_join_stays_correct(self):
+ # A PREWHERE-only events query (no WHERE) still pushes: the subquery keeps the PREWHERE and the
+ # printer injects the team_id guard as the subquery's WHERE. Exercises the where=None subquery path.
+ self._create_data()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "PREWHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08' LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ subquery = "".join(printed.split()).split("FROM(", 1)[1].split(")ASeventsLEFTJOIN", 1)[0]
+ assert "PREWHERE" in subquery, "pushed PREWHERE should stay a PREWHERE on the inner scan:\n" + printed
+ assert "LIMIT" in subquery, "pushed subquery should carry an inner LIMIT:\n" + printed
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ def test_exec_non_pushable_prewhere_bails(self):
+ # A PREWHERE referencing a non-events (joined) column can't be pushed and can't stay on the outer
+ # query either: after pushdown the outer FROM is a subquery, where PREWHERE is invalid. Pushdown
+ # must bail so we never emit a PREWHERE on a subquery. (The query is already invalid CH regardless,
+ # so this is a print-level check that we don't make it worse, not an execution one.)
+ self._create_data()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "PREWHERE session.$session_duration > 0 AND timestamp >= '2024-01-01' "
+ "WHERE event = 'watched movie'"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert ") AS events LEFT JOIN" not in printed, (
+ f"pushdown must bail when a PREWHERE predicate isn't fully pushable (no PREWHERE on a subquery):\n{printed}"
+ )
+
+ def test_exec_aliased_function_shadowing_column_pushes_full_expression(self):
+ # A non-identity function aliased back to its own column name (upper(event) AS event) and filtered
+ # on must push the full expression, not re-bind the bare name to the raw column (which would drop
+ # upper() and filter case-sensitively). Events are lowercase, so re-binding would return 0 rows.
+ self._create_data()
+ select = (
+ "SELECT upper(event) AS event, session.$session_duration FROM events "
+ "WHERE event = 'WATCHED MOVIE' AND timestamp >= '2024-01-01' AND timestamp < '2024-01-08' "
+ "LIMIT 50"
+ )
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ def test_exec_events_only_or_predicate_stays_correct(self):
+ # An OR predicate referencing only events columns is pushed atomically and must stay equivalent.
+ self._create_data()
+ select = (
+ "SELECT event, session.$session_duration FROM events "
+ "WHERE (event = 'watched movie' OR event = 'nonexistent') "
+ "AND timestamp >= '2024-01-01' AND timestamp < '2024-01-08' LIMIT 50"
+ )
+ self._assert_pushdown_equivalent(select, expected_rows=3)
+
+ def _create_diverse_data(self) -> None:
+ # A second event name (so event filters actually discriminate) and a row whose `$session_id` is
+ # invalid (so its LEFT JOIN finds no session and the duration is NULL, an unmatched-join row).
+ s1, s2 = str(uuid7("2024-01-02T00:00:00")), str(uuid7("2024-01-03T00:00:00"))
+ rows = [
+ ("u1", "watched movie", s1, "2024-01-02T10:00:00"),
+ ("u1", "watched movie", s1, "2024-01-02T10:05:00"),
+ ("u2", "added to cart", s2, "2024-01-03T09:00:00"),
+ ("u3", "watched movie", "", "2024-01-04T09:00:00"), # invalid session_id → unmatched LEFT JOIN
+ ]
+ for distinct_id, event, session_id, ts in rows:
+ _create_event(
+ team=self.team,
+ event=event,
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={"$session_id": session_id, "tier": "pro"},
+ )
+ flush_persons_and_events()
+
+ def test_exec_event_filter_discriminates_and_stays_equivalent(self):
+ # With two event names, an event-name filter must return fewer rows than the unfiltered baseline
+ # (otherwise the shape doesn't actually test the predicate), and stay pushdown-equivalent.
+ self._create_diverse_data()
+ baseline = f"SELECT event, session.$session_duration FROM events WHERE {self._RANGE} LIMIT 50"
+ filtered = f"SELECT event, session.$session_duration FROM events WHERE {self._RANGE} AND event = 'watched movie' LIMIT 50"
+ self._assert_pushdown_equivalent(baseline, expected_rows=4)
+ self._assert_pushdown_equivalent(filtered, expected_rows=3)
+
+ def test_exec_unmatched_left_join_null_duration_stays_equivalent(self):
+ # The row with an invalid `$session_id` has a NULL session duration (LEFT JOIN miss). Pushdown must
+ # not change which rows survive or their NULL durations.
+ self._create_diverse_data()
+ select = f"SELECT event, session.$session_duration AS d FROM events WHERE {self._RANGE} LIMIT 50"
+ self._assert_pushdown_equivalent(select, expected_rows=4)
+ # the unmatched row must actually be present with a NULL/zero duration in both modes
+ results = self._results(select, push_down=True)
+ assert any(row[1] in (None, 0) for row in results), f"expected an unmatched-join NULL/0 duration row: {results}"
+
+ _RANGE = "timestamp >= '2024-01-01' AND timestamp < '2024-01-08'"
+ # The core "pure optimization" invariant across many query shapes. Each shape pushes: a session (LEFT)
+ # join, a fully-pushable events predicate, no ORDER BY / aggregate, and an effective LIMIT. The runner
+ # asserts the events subquery (with its inner LIMIT) was created, then compares sorted results on vs off
+ # (the inner LIMIT means there is no ORDER BY to pin row order).
+ EQUIVALENCE_SHAPES = [
+ ("baseline", f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} LIMIT 50"),
+ (
+ "event_equals",
+ f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} AND event = 'watched movie' LIMIT 50",
+ ),
+ (
+ "event_or",
+ f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} AND (event = 'watched movie' OR event = 'other') LIMIT 50",
+ ),
+ (
+ "event_not",
+ f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} AND NOT (event = 'nope') LIMIT 50",
+ ),
+ (
+ "event_in",
+ f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} AND event IN ('watched movie', 'other') LIMIT 50",
+ ),
+ (
+ "comparison_ops",
+ f"SELECT event, session.$session_duration FROM events WHERE timestamp > '2024-01-01' AND timestamp <= '2024-01-08' LIMIT 50",
+ ),
+ (
+ "limit",
+ f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} LIMIT 50",
+ ),
+ (
+ "aliased_table",
+ f"SELECT e.event, session.$session_duration FROM events AS e WHERE e.timestamp >= '2024-01-01' AND e.timestamp < '2024-01-08' AND e.event = 'watched movie' LIMIT 50",
+ ),
+ (
+ "aliased_function_shadowing",
+ f"SELECT upper(event) AS event, session.$session_duration FROM events WHERE {_RANGE} AND event = 'WATCHED MOVIE' LIMIT 50",
+ ),
+ (
+ # An aggregate inside a scalar subquery belongs to that subquery's scope; this outer query is
+ # non-aggregate and must still push (the gate must not be fooled into declining).
+ "scalar_subquery_aggregate",
+ f"SELECT event, (SELECT count() FROM events) AS total, session.$session_duration FROM events WHERE {_RANGE} LIMIT 50",
+ ),
+ ]
+
+ @parameterized.expand(EQUIVALENCE_SHAPES)
+ def test_exec_pushdown_result_equivalence(self, _name: str, select: str):
+ self._create_data()
+ printed = self._print_pushdown_sql(select)
+ assert ") AS events LEFT JOIN" in printed or ") AS e LEFT JOIN" in printed, (
+ f"{_name}: expected pushdown to wrap events in a subquery, but it bailed:\n{printed}"
+ )
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"{_name}: pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+
+ # Shapes the gate must decline: a full-read (GROUP BY / DISTINCT / window) or an aggregate makes the
+ # LIMIT unable to short-circuit the events scan; an ORDER BY blocks the inner LIMIT; and a residual
+ # joined-table predicate (or ordering by a joined column) leaves a predicate on the outer query so the
+ # inner LIMIT would be unsafe. In every case the query runs flat and results must be unchanged. ORDER BY
+ # is kept here so the on/off comparison can stay order-sensitive (no inner LIMIT reshuffles the set).
+ DECLINE_SHAPES = [
+ (
+ "group_by_aggregation",
+ f"SELECT event, count() AS c, max(session.$session_duration) AS d FROM events WHERE {_RANGE} GROUP BY event ORDER BY event",
+ ),
+ (
+ "group_by_having",
+ f"SELECT event, count() AS c, max(session.$session_duration) AS d FROM events WHERE {_RANGE} GROUP BY event HAVING count() > 0 ORDER BY event",
+ ),
+ (
+ "distinct",
+ f"SELECT DISTINCT properties.tier AS t, session.$session_duration AS d FROM events WHERE {_RANGE} ORDER BY t, d",
+ ),
+ (
+ "window_function",
+ f"SELECT event, row_number() OVER (ORDER BY timestamp) AS rn, session.$session_duration AS d FROM events WHERE {_RANGE} ORDER BY timestamp, event",
+ ),
+ (
+ # ORDER BY a joined column declines (any ORDER BY blocks the inner LIMIT, so the pushdown bails).
+ "order_by_joined_column",
+ f"SELECT event, session.$session_duration AS d FROM events WHERE {_RANGE} ORDER BY d, timestamp",
+ ),
+ (
+ # A residual joined-table predicate (session.$session_duration) can't be pushed into the events
+ # subquery, so the whole pushdown declines.
+ "mixed_events_and_joined_predicate",
+ f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} AND session.$session_duration >= 0 ORDER BY timestamp",
+ ),
+ (
+ # A clause-level ARRAY JOIN multiplies rows before the LIMIT applies, so pushing the LIMIT into the
+ # events subquery (which runs before the ARRAY JOIN) would change the row count. Must decline.
+ "array_join_clause",
+ f"SELECT n, session.$session_duration AS d FROM events ARRAY JOIN [1, 2] AS n WHERE {_RANGE}",
+ ),
+ (
+ # A total aggregation (no GROUP BY) consumes the whole filtered set before the LIMIT. Must decline.
+ "aggregate_no_group_by",
+ f"SELECT count() AS c, max(session.$session_duration) AS d FROM events WHERE {_RANGE}",
+ ),
+ ]
+
+ @parameterized.expand(DECLINE_SHAPES)
+ def test_exec_full_read_shapes_decline_but_stay_equivalent(self, _name: str, select: str):
+ self._create_data()
+ printed = self._print_pushdown_sql(select)
+ assert ") AS events LEFT JOIN" not in printed and ") AS e LEFT JOIN" not in printed, (
+ f"{_name}: expected pushdown to decline (no short-circuit possible), but it wrapped events:\n{printed}"
+ )
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"{_name}: pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+
+
+class TestEventsPredicatePushdownMaterializedExecution(_PushdownExecutionTestBase):
+ """Pushdown must stay a pure optimization on teams that have materialized columns.
+
+ The test ClickHouse has no materialized columns by default, so the rest of the suite never prints
+ `events.mat_*`. These tests materialize a property first, so the printer reads the physical column and
+ the pushdown subquery must expose it; without that exposure a property referenced outside the pushed
+ predicate (SELECT / GROUP BY / ORDER BY / HAVING) prints `events.mat_tier` against a subquery alias that
+ doesn't have it → `Unknown identifier`. Every assertion checks pushdown-on == pushdown-off.
+ """
+
+ def _create_data(self) -> None:
+ # Same shape as the non-materialized suite; called inside a materialized() block so the physical
+ # column is computed at insert time (ClickHouse MATERIALIZED columns are evaluated on INSERT).
+ for distinct_id, tier, timestamps in [
+ ("u1", "pro", ["2024-01-02T10:00:00", "2024-01-02T10:05:00"]),
+ ("u2", "free", ["2024-01-05T09:00:00"]),
+ ("u3", "pro", ["2023-06-01T09:00:00"]),
+ ]:
+ session_id = str(uuid7(timestamps[0]))
+ for ts in timestamps:
+ _create_event(
+ team=self.team,
+ event="watched movie",
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={"$session_id": session_id, "tier": tier},
+ )
+ flush_persons_and_events()
+
+ def _assert_equivalent(self, select: str, *, expected_rows: int) -> None:
+ with_pushdown = self._assert_results_equivalent(select)
+ assert len(with_pushdown) == expected_rows, f"expected {expected_rows} rows, got {with_pushdown}"
+
+ _RANGE = "timestamp >= '2024-01-01' AND timestamp < '2024-01-08'"
+
+ def test_exec_materialized_property_in_outer_select(self):
+ # The CRITICAL repro: a materialized property in the outer SELECT. The subquery must expose
+ # `mat_tier` or the outer `events.mat_tier` is an Unknown identifier.
+ with materialized("events", "tier") as mat_col:
+ self._create_data()
+ select = (
+ f"SELECT properties.tier AS t, session.$session_duration AS d FROM events WHERE {self._RANGE} LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ subquery = self._events_subquery(printed)
+ assert mat_col.name in subquery, f"expected the materialized column exposed in the subquery:\n{printed}"
+ assert "LIMIT" in subquery, f"expected the pushed subquery to carry an inner LIMIT:\n{printed}"
+ # The materialized property must NOT also drag the raw `properties` blob into the subquery
+ # projection (over-projection would force a ~100x-slower full-Map read). Guards drift on the
+ # plain-materialized PropertyType path, mirroring the JSONHas blob-projection guard.
+ assert "properties AS properties" not in subquery, (
+ f"materialized property over-projected the blob:\n{printed}"
+ )
+ self._assert_equivalent(select, expected_rows=3)
+
+ def test_exec_materialized_property_in_order_by_declines(self):
+ # A materialized property in ORDER BY: any ORDER BY blocks the inner LIMIT, so the pushdown declines
+ # and the query runs flat. Results must stay equivalent.
+ with materialized("events", "tier"):
+ self._create_data()
+ select = f"SELECT event, session.$session_duration FROM events WHERE {self._RANGE} ORDER BY properties.tier, timestamp"
+ printed = self._print_pushdown_sql(select)
+ assert ") AS events LEFT JOIN" not in printed and ") AS e LEFT JOIN" not in printed, (
+ f"expected pushdown to decline with an ORDER BY:\n{printed}"
+ )
+ self._assert_equivalent(select, expected_rows=3)
+
+ def test_exec_materialized_property_filter_pushed_uses_mat_column(self):
+ # Property in the pushed predicate: the subquery WHERE must use the materialized column, not the
+ # JSONExtract blob path, and results must match pushdown-off.
+ with materialized("events", "tier") as mat_col:
+ self._create_data()
+ select = f"SELECT event, session.$session_duration FROM events WHERE {self._RANGE} AND properties.tier = 'pro' LIMIT 50"
+ printed = self._print_pushdown_sql(select)
+ subquery = self._events_subquery(printed)
+ assert mat_col.name in subquery, (
+ f"expected the materialized column used in the pushed predicate:\n{printed}"
+ )
+ assert "JSONExtract" not in subquery, (
+ f"materialized column should avoid the JSONExtract blob path:\n{printed}"
+ )
+ assert "LIMIT" in subquery, f"expected the pushed subquery to carry an inner LIMIT:\n{printed}"
+ self._assert_equivalent(select, expected_rows=2)
+
+ def test_exec_aliased_materialized_property_filter_pushed_uses_inner_table(self):
+ # When the events table is aliased (FROM events AS e) and a *materialized* property is in the pushed
+ # predicate, the printer renders `e.mat_tier` from the property's type. The inner subquery keeps the
+ # `e` alias on its own events scan, so `e.mat_tier` resolves there instead of being an unknown
+ # identifier (a rewrite-to-inner-table approach would miss the materialized property path).
+ with materialized("events", "tier") as mat_col:
+ self._create_data()
+ select = (
+ "SELECT e.event, session.$session_duration FROM events AS e "
+ "WHERE e.timestamp >= '2024-01-01' AND e.timestamp < '2024-01-08' AND e.properties.tier = 'pro' "
+ "LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert ") AS e LEFT JOIN" in printed, (
+ f"expected the materialized property filter pushed into a subquery:\n{printed}"
+ )
+ subquery = printed.split("FROM (", 1)[1].split(") AS e LEFT JOIN", 1)[0]
+ assert mat_col.name in subquery, f"expected the materialized column in the pushed predicate:\n{printed}"
+ assert "FROM events AS e" in subquery, f"expected the subquery to define alias `e`:\n{subquery}"
+ assert "LIMIT" in subquery, f"expected the pushed subquery to carry an inner LIMIT:\n{printed}"
+ self._assert_equivalent(select, expected_rows=2)
+
+ def test_exec_materialized_property_not_referenced_outside_predicate(self):
+ # Property only in the pushed predicate (not the outer query): still equivalent, and the subquery
+ # reads the materialized column rather than the properties blob.
+ with materialized("events", "tier") as mat_col:
+ self._create_data()
+ select = f"SELECT event, session.$session_duration FROM events WHERE {self._RANGE} AND properties.tier IN ('pro', 'free') LIMIT 50"
+ printed = self._print_pushdown_sql(select)
+ assert mat_col.name in self._events_subquery(printed)
+ self._assert_equivalent(select, expected_rows=3)
+
+ MATERIALIZED_SHAPES = [
+ (
+ "property_equals",
+ f"SELECT event, session.$session_duration FROM events WHERE {_RANGE} AND properties.tier = 'pro' LIMIT 50",
+ ),
+ (
+ "property_in_select_and_filter",
+ f"SELECT properties.tier AS t, session.$session_duration FROM events WHERE {_RANGE} AND properties.tier = 'pro' LIMIT 50",
+ ),
+ ]
+
+ @parameterized.expand(MATERIALIZED_SHAPES)
+ def test_exec_materialized_pushdown_result_equivalence(self, _name: str, select: str):
+ with materialized("events", "tier") as mat_col:
+ self._create_data()
+ printed = self._print_pushdown_sql(select)
+ assert mat_col.name in self._events_subquery(printed), (
+ f"{_name}: materialized column not exposed:\n{printed}"
+ )
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"{_name}: pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+
+
+class TestEventsPredicatePushdownPropertyGroupsExecution(_PushdownExecutionTestBase):
+ """Pushdown must stay a pure optimization under propertyGroupsMode=OPTIMIZED (the PostHog Cloud default).
+
+ In OPTIMIZED mode the printer rewrites `JSONHas(properties, 'k')` into `has(events.properties_group_*,
+ 'k')`, referencing a property-group Map column. JSONHas's argument is the bare `properties` column (not
+ a `properties.k` PropertyType), so the subquery must still expose that Map column or an outer-scope
+ JSONHas resolves against a column the subquery alias doesn't carry → `Unknown identifier`.
+ """
+
+ _property_groups_mode = PropertyGroupsMode.OPTIMIZED
+
+ def _create_data(self) -> None:
+ # Two events that have the `tier` property and one that doesn't, so JSONHas(properties, 'tier')
+ # discriminates (2 true, 1 false). All in range with a valid session for the lazy join.
+ for distinct_id, props, timestamps in [
+ ("u1", {"tier": "pro"}, ["2024-01-02T10:00:00", "2024-01-02T10:05:00"]),
+ ("u2", {}, ["2024-01-05T09:00:00"]),
+ ]:
+ session_id = str(uuid7(timestamps[0]))
+ for ts in timestamps:
+ _create_event(
+ team=self.team,
+ event="watched movie",
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={"$session_id": session_id, **props},
+ )
+ flush_persons_and_events()
+
+ _RANGE = "timestamp >= '2024-01-01' AND timestamp < '2024-01-08'"
+
+ def test_exec_outer_json_has_exposes_property_group_column(self):
+ # The reproduced break: an outer JSONHas → printer emits has(events.properties_group_*), which the
+ # subquery must expose. JSONHas is in the SELECT (referenced outside the pushed predicate) so the
+ # pushdown still fires with an inner LIMIT.
+ self._create_data()
+ select = (
+ f"SELECT event, JSONHas(properties, 'tier') AS h, session.$session_duration FROM events "
+ f"WHERE {self._RANGE} LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert "properties_group" in self._events_subquery(printed), (
+ f"expected the property-group Map column exposed in the subquery:\n{printed}"
+ )
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+ assert len(with_pushdown or []) == 3
+
+ def test_exec_json_has_does_not_project_properties_blob(self):
+ # Under OPTIMIZED the printer reads only the property-group Map column for JSONHas, never the
+ # `properties` blob. When JSONHas is the sole `properties` reference, the subquery must expose the
+ # Map column and NOT project the full blob (which would force a ~100x Map read for nothing).
+ self._create_data()
+ select = (
+ f"SELECT event, JSONHas(properties, 'tier') AS h, session.$session_duration FROM events "
+ f"WHERE {self._RANGE} LIMIT 50"
+ )
+ subquery = self._events_subquery(self._print_pushdown_sql(select))
+ assert "properties_group" in subquery, f"expected the group Map column exposed:\n{subquery}"
+ assert "properties AS properties" not in subquery, (
+ f"the raw properties blob must NOT be projected when only JSONHas reads it:\n{subquery}"
+ )
+
+ def test_exec_json_has_in_select_stays_equivalent(self):
+ self._create_data()
+ select = (
+ f"SELECT JSONHas(properties, 'tier') AS h, session.$session_duration FROM events "
+ f"WHERE {self._RANGE} LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert "properties_group" in self._events_subquery(printed), printed
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+
+ def test_exec_json_has_property_filter_pushed_stays_equivalent(self):
+ # JSONHas in the pushed predicate (WHERE): goes into the subquery, which can reference the group
+ # column directly. Must stay equivalent.
+ self._create_data()
+ select = (
+ f"SELECT event, session.$session_duration FROM events "
+ f"WHERE {self._RANGE} AND JSONHas(properties, 'tier') LIMIT 50"
+ )
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+ assert len(with_pushdown or []) == 2 # only u1's two events have the tier property
+
+ def test_exec_property_type_uses_property_group_column(self):
+ # `properties.tier` (a PropertyType, not JSONHas) under OPTIMIZED is read from the property-group
+ # Map column by the printer; the collector's PropertyType path must expose it too. Distinct code
+ # path from the JSONHas tests above (visit_field/_collect_materialized_column, not visit_call).
+ self._create_data()
+ select = f"SELECT properties.tier AS t, session.$session_duration AS d FROM events WHERE {self._RANGE} LIMIT 50"
+ printed = self._print_pushdown_sql(select)
+ assert "properties_group" in self._events_subquery(printed), printed
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+ assert len(with_pushdown or []) == 3 # u1's two tier='pro' events and u2's no-tier event
+
+ def test_exec_is_not_null_uses_property_group_column(self):
+ # Under OPTIMIZED the printer rewrites isNull/isNotNull(properties.k) to the property-group has()
+ # expression, so the Map column must be exposed. The arg is a PropertyType (visit_field path), so
+ # the group column is exposed by _collect_materialized_column; pin that equivalence here.
+ self._create_data()
+ select = (
+ f"SELECT isNotNull(properties.tier) AS has_tier, session.$session_duration AS d "
+ f"FROM events WHERE {self._RANGE} LIMIT 50"
+ )
+ printed = self._print_pushdown_sql(select)
+ assert "properties_group" in self._events_subquery(printed), printed
+ with_pushdown = self._results(select, push_down=True)
+ without_pushdown = self._results(select, push_down=False)
+ assert self._sorted(with_pushdown) == self._sorted(without_pushdown), (
+ f"pushdown changed results: on={with_pushdown} off={without_pushdown}"
+ )
+ assert len(with_pushdown or []) == 3 # u1's two events (has tier) and u2's event (no tier)
+
+
+class TestEventsPredicatePushdownDmatExecution(_PushdownExecutionTestBase):
+ """Pushdown must expose dmat (dynamic materialized) columns in the subquery too.
+
+ A property with a READY MaterializedColumnSlot is read from `dmat_string_<n>` by the printer, so an
+ outer reference to that property after pushdown must resolve against the subquery alias. The test DB
+ has the physical dmat columns but `_create_event` doesn't populate them, so events are inserted with
+ the column pre-filled (same approach as test_property_types_dmat.py).
+ """
+
+ _SLOT_INDEX = 0
+ _pass_team = True # the print context needs the team to resolve the dmat slot
+
+ def _setup_dmat_events(self) -> None:
+ prop_def = PropertyDefinition.objects.create(
+ team=self.team,
+ name="tier",
+ property_type=PropertyType.String,
+ type=PropertyDefinition.Type.EVENT,
+ )
+ MaterializedColumnSlot.objects.create(
+ team=self.team,
+ property_definition=prop_def,
+ slot_index=self._SLOT_INDEX,
+ state=MaterializedColumnSlotState.READY,
+ )
+ for distinct_id, tier in [("u1", "pro"), ("u2", "free")]:
+ sync_execute(
+ f"""
+ INSERT INTO sharded_events (uuid, team_id, event, distinct_id, timestamp, properties, dmat_string_{self._SLOT_INDEX})
+ SELECT %(uuid)s, %(team_id)s, 'watched movie', %(distinct_id)s, now(), %(properties)s, %(dmat)s
+ """,
+ {
+ "uuid": str(uuid4()),
+ "team_id": self.team.pk,
+ "distinct_id": distinct_id,
+ "properties": json.dumps({"tier": tier}),
+ "dmat": tier,
+ },
+ flush=False,
+ )
+
+ def test_exec_dmat_property_in_select_stays_equivalent(self):
+ self._setup_dmat_events()
+ select = "SELECT properties.tier AS t, session.$session_duration AS d FROM events WHERE timestamp >= '2020-01-01' LIMIT 50"
+ printed = self._print_pushdown_sql(select)
+ assert f"dmat_string_{self._SLOT_INDEX}" in self._events_subquery(printed), printed
+ on = self._assert_results_equivalent(select)
+ assert len(on) == 2
diff --git a/posthog/hogql/transforms/test/test_lazy_tables.py b/posthog/hogql/transforms/test/test_lazy_tables.py
index 2b1f8838d89b..4bc502acc889 100644
--- a/posthog/hogql/transforms/test/test_lazy_tables.py
+++ b/posthog/hogql/transforms/test/test_lazy_tables.py
@@ -158,3 +158,47 @@ class TestLazyJoins(BaseTest):
HogQLQueryModifiers(personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED),
)
assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_session_join_with_timestamp_filter(self):
+ # Documents SQL generation for events with session access and a timestamp filter.
+ printed = self._print_select(
+ "SELECT event, session.$session_duration "
+ "FROM events "
+ "WHERE timestamp >= '2024-01-01' AND timestamp < '2024-01-08'"
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_sessions_join_with_alias(self):
+ # Documents that events table alias is propagated.
+ printed = self._print_select(
+ "SELECT event, session.$session_duration "
+ "FROM events AS e "
+ "WHERE e.timestamp >= '2024-01-01' AND event = 'my-event'"
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_session_join_with_multiple_predicates(self):
+ # Documents events query with session access and multiple event-level predicates.
+ printed = self._print_select(
+ "SELECT event, session.$session_duration "
+ "FROM events "
+ "WHERE timestamp >= '2024-01-01' "
+ "AND timestamp < '2024-01-08' "
+ "AND event = '$pageview' "
+ "AND $session_id IS NOT NULL"
+ )
+ assert printed == self.snapshot
+
+ @pytest.mark.usefixtures("unittest_snapshot")
+ def test_events_session_join_with_session_duration_filter(self):
+ # Documents that session duration filters remain in outer WHERE (can't be pushed down).
+ printed = self._print_select(
+ "SELECT event, session.$session_duration "
+ "FROM events "
+ "WHERE timestamp >= '2024-01-01' "
+ "AND session.$session_duration > 0"
+ )
+ assert printed == self.snapshot
diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.py
index 14b37b196cce..fa9c5507b631 100644
--- a/posthog/hogql/transforms/test/test_property_types.py
+++ b/posthog/hogql/transforms/test/test_property_types.py
@@ -17,6 +17,7 @@ from django.test import override_settings
from parameterized import parameterized
from posthog.hogql.context import HogQLContext
+from posthog.hogql.modifiers import HogQLQueryModifiers
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.query import execute_hogql_query
@@ -408,7 +409,15 @@ class TestTimezoneIndexPruning(ClickhouseTestMixin, BaseTest):
def _compile_hogql(self, hogql: str, timezone: str = "UTC") -> tuple[str, dict]:
self.team.timezone = timezone
self.team.save()
- context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
+ # This class asserts the structural shape of toTimeZone stripping (a PropertySwapper concern).
+ # Predicate pushdown is orthogonal: it relocates the (already-stripped) WHERE into an events subquery,
+ # changing where these comparisons appear without changing the tz behavior. Disable it here so the
+ # assertions stay about tz stripping; pushdown has its own test suite.
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(pushDownPredicates=False),
+ )
node = parse_select(hogql)
clickhouse_sql, _ = prepare_and_print_ast(node, context=context, dialect="clickhouse")
return clickhouse_sql, context.values
diff --git a/posthog/schema.py b/posthog/schema.py
index 2e9b73377c81..d3a041bffaed 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -7644,6 +7644,7 @@ class HogQLQueryModifiers(BaseModel):
personsJoinMode: PersonsJoinMode | None = None
personsOnEventsMode: PersonsOnEventsMode | None = None
propertyGroupsMode: PropertyGroupsMode | None = None
+ pushDownPredicates: bool | None = None
s3TableUseInvalidColumns: bool | None = None
sessionIdPushdown: bool | None = Field(
default=None,
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index a9aab31785e6..eefd67ca7d4e 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -745,6 +745,7 @@ export interface HogQLQueryModifiersApi {
personsJoinMode?: PersonsJoinModeApi | null
personsOnEventsMode?: PersonsOnEventsModeApi | null
propertyGroupsMode?: PropertyGroupsModeApi | null
+ pushDownPredicates?: boolean | null
s3TableUseInvalidColumns?: boolean | null
/** Push a `session_id_v7 IN (SELECT … FROM events WHERE …)` predicate into the raw_sessions subquery to limit aggregation to sessions that participate in the outer events filter. */
sessionIdPushdown?: boolean | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 545ddcb4b89e..0c08bcdbd36e 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -438,6 +438,7 @@ export interface HogQLQueryModifiersApi {
personsJoinMode?: PersonsJoinModeApi | null
personsOnEventsMode?: PersonsOnEventsModeApi | null
propertyGroupsMode?: PropertyGroupsModeApi | null
+ pushDownPredicates?: boolean | null
s3TableUseInvalidColumns?: boolean | null
/** Push a `session_id_v7 IN (SELECT … FROM events WHERE …)` predicate into the raw_sessions subquery to limit aggregation to sessions that participate in the outer events filter. */
sessionIdPushdown?: boolean | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 046f6816f928..51d3f04e48bf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -395,6 +395,7 @@ export namespace Schemas {
personsJoinMode?: PersonsJoinMode | null;
personsOnEventsMode?: PersonsOnEventsMode | null;
propertyGroupsMode?: PropertyGroupsMode | null;
+ pushDownPredicates?: boolean | null;
s3TableUseInvalidColumns?: boolean | null;
/** Push a `session_id_v7 IN (SELECT … FROM events WHERE …)` predicate into the raw_sessions subquery to limit aggregation to sessions that participate in the outer events filter. */
sessionIdPushdown?: boolean | null;