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(replay): push session-id filters into the sessions join subquery (#72420)

Andy Zhao6d49ef88db2f
diff --git a/posthog/hogql/database/schema/sessions_v2.py b/posthog/hogql/database/schema/sessions_v2.py
index 75d5699aaf4a..0999cd92b1b2 100644
--- a/posthog/hogql/database/schema/sessions_v2.py
+++ b/posthog/hogql/database/schema/sessions_v2.py
@@ -21,6 +21,7 @@ from posthog.hogql.database.schema.channel_type import DEFAULT_CHANNEL_TYPES, Ch
from posthog.hogql.database.schema.sessions_v1 import DEFAULT_BOUNCE_RATE_DURATION_SECONDS, null_if_empty
from posthog.hogql.database.schema.util.where_clause_extractor import (
SessionMinTimestampWhereClauseExtractorV2,
+ build_session_id_literal_pushdown_predicate,
build_session_id_v7_pushdown_predicate,
build_session_property_pre_aggregation_predicate,
)
@@ -656,14 +657,21 @@ def join_events_table_to_sessions_table_v2(
extra_where: Optional[ast.Expr] = None
# Only push down in UUID join mode — the `$session_id` string mode would require wrapping
# the IN-subquery output in `_toUInt128(toUUID(...))` and isn't needed for the common path.
- if context.modifiers.sessionIdPushdown and context.modifiers.sessionsV2JoinMode == SessionsV2JoinMode.UUID:
- extra_where = build_session_id_v7_pushdown_predicate(
+ if context.modifiers.sessionsV2JoinMode == SessionsV2JoinMode.UUID:
+ # literal id sets push down ungated: no extra events scan, prune-only
+ extra_where = build_session_id_literal_pushdown_predicate(
node,
join_to_add,
- context,
session_id_v7_field=ast.Field(chain=["raw_sessions", "session_id_v7"]),
- events_session_id_field=["$session_id_uuid"],
)
+ if extra_where is None and context.modifiers.sessionIdPushdown:
+ extra_where = build_session_id_v7_pushdown_predicate(
+ node,
+ join_to_add,
+ context,
+ session_id_v7_field=ast.Field(chain=["raw_sessions", "session_id_v7"]),
+ events_session_id_field=["$session_id_uuid"],
+ )
if context.modifiers.sessionPropertyPreAggregation:
pre_agg_where = build_session_property_pre_aggregation_predicate(
diff --git a/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py b/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py
index 9a697005d317..46e92b0dce61 100644
--- a/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py
+++ b/posthog/hogql/database/schema/util/test/test_session_v2_where_clause_extractor.py
@@ -14,7 +14,10 @@ from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.sessions_v2 import SessionsTableV2, build_direct_session_id_in_pushdown
-from posthog.hogql.database.schema.util.where_clause_extractor import SessionMinTimestampWhereClauseExtractorV2
+from posthog.hogql.database.schema.util.where_clause_extractor import (
+ SESSION_ID_LITERAL_PUSHDOWN_MAX_IDS,
+ SessionMinTimestampWhereClauseExtractorV2,
+)
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast
@@ -24,6 +27,7 @@ from posthog.hogql.visitor import clone_expr
from posthog.models import EventDefinition
from posthog.models.utils import uuid7
+from posthog.schema_enums import SessionsV2JoinMode
def f(s: Union[str, ast.Expr, None], placeholders: Optional[dict[str, ast.Expr]] = None) -> Union[ast.Expr, None]:
@@ -920,6 +924,144 @@ class TestDirectSessionIdInPushdownV2(ClickhouseTestMixin, APIBaseTest):
assert results[True] == [(matching_session,)]
+class TestSessionIdLiteralPushdownV2(ClickhouseTestMixin, APIBaseTest):
+ # Locks build_session_id_literal_pushdown_predicate: literal $session_id filters on the
+ # events side must reach the raw_sessions join subquery, and only for the exact shapes below.
+
+ SESSION_A = "0195331e-a9f4-7d10-b04a-c9a24e0f1b17"
+ SESSION_B = "01953321-3966-73b3-9de3-b1a1c9b78de5"
+
+ # filters on the SELECT alias, exactly like the frontend's buildPropertiesQuery output
+ REPLAY_LIST_SHAPE = (
+ "SELECT $session_id AS session_id, any(events.session.$entry_current_url) AS entry_url "
+ "FROM events "
+ f"WHERE session_id IN ('{SESSION_A}', '{SESSION_B}') "
+ "AND timestamp >= '2026-03-27 00:00:00' AND timestamp <= '2026-03-31 23:59:59' "
+ "GROUP BY session_id"
+ )
+
+ def print_query(self, query: str, join_mode: SessionsV2JoinMode = SessionsV2JoinMode.UUID) -> str:
+ modifiers = create_default_modifiers_for_team(self.team)
+ modifiers.sessionTableVersion = SessionTableVersion.V2
+ modifiers.sessionsV2JoinMode = join_mode
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ enable_select_queries=True,
+ modifiers=modifiers,
+ )
+ prepared_ast = prepare_ast_for_printing(node=parse(query), context=context, dialect="clickhouse")
+ assert prepared_ast is not None
+ return " ".join(print_prepared_ast(prepared_ast, context=context, dialect="clickhouse", pretty=True).split())
+
+ @parameterized.expand(
+ [
+ ("in_list", REPLAY_LIST_SHAPE),
+ (
+ "eq_single_value",
+ "SELECT $session_id AS session_id, any(events.session.$entry_pathname) AS entry "
+ f"FROM events WHERE $session_id = '{SESSION_A}' GROUP BY session_id",
+ ),
+ ]
+ )
+ def test_literal_filter_is_pushed_into_join_subquery(self, _name: str, query: str):
+ sql = self.print_query(query)
+ assert "in(raw_sessions.session_id_v7, tuple(toUInt128(accurateCastOrNull(" in sql, sql
+ # the literal push must not add a second events scan
+ assert sql.count("FROM events") == 1, sql
+
+ @parameterized.expand(
+ [
+ # not a hard constraint; pushing would drop the other branch's sessions
+ (
+ "or_nested",
+ "SELECT $session_id AS sid, any(events.session.$entry_pathname) AS entry FROM events "
+ f"WHERE $session_id IN ('{SESSION_A}') OR event = '$pageview' GROUP BY sid",
+ SessionsV2JoinMode.UUID,
+ ),
+ (
+ "not_in",
+ "SELECT $session_id AS sid, any(events.session.$entry_pathname) AS entry FROM events "
+ f"WHERE $session_id NOT IN ('{SESSION_A}') GROUP BY sid",
+ SessionsV2JoinMode.UUID,
+ ),
+ # same all-valid-UUIDs gate as the printer's $session_id_uuid rewrite
+ (
+ "mixed_non_uuid_values",
+ "SELECT $session_id AS sid, any(events.session.$entry_pathname) AS entry FROM events "
+ f"WHERE $session_id IN ('{SESSION_A}', 'not-a-uuid') GROUP BY sid",
+ SessionsV2JoinMode.UUID,
+ ),
+ # subquery id sets stay behind the sessionIdPushdown modifier (off here)
+ (
+ "subquery_rhs",
+ "SELECT $session_id AS sid, any(events.session.$entry_pathname) AS entry FROM events "
+ "WHERE $session_id IN (SELECT $session_id FROM events WHERE event = '$pageview') GROUP BY sid",
+ SessionsV2JoinMode.UUID,
+ ),
+ # a self-join's other occurrence must not be hijacked
+ (
+ "other_events_occurrence",
+ "SELECT e1.$session_id AS sid, any(e1.session.$entry_pathname) AS entry "
+ "FROM events e1 JOIN events e2 ON e1.uuid = e2.uuid "
+ f"WHERE e2.$session_id IN ('{SESSION_A}') GROUP BY sid",
+ SessionsV2JoinMode.UUID,
+ ),
+ # the uint128 push only applies to UUID join mode
+ ("string_join_mode", REPLAY_LIST_SHAPE, SessionsV2JoinMode.STRING),
+ ]
+ )
+ def test_unsupported_shapes_are_not_pushed(self, _name: str, query: str, join_mode: SessionsV2JoinMode):
+ sql = self.print_query(query, join_mode=join_mode)
+ assert "in(raw_sessions.session_id_v7, tuple(" not in sql, sql
+ assert "globalIn(raw_sessions.session_id_v7" not in sql, sql
+
+ def test_oversized_id_list_is_not_pushed(self):
+ ids = ", ".join(f"'{uuid7()}'" for _ in range(SESSION_ID_LITERAL_PUSHDOWN_MAX_IDS + 1))
+ query = (
+ "SELECT $session_id AS sid, any(events.session.$entry_pathname) AS entry "
+ f"FROM events WHERE $session_id IN ({ids}) GROUP BY sid"
+ )
+ sql = self.print_query(query)
+ assert "in(raw_sessions.session_id_v7, tuple(" not in sql
+
+ def test_pushdown_preserves_join_results(self):
+ session_a = str(uuid7("2026-03-27"))
+ session_b = str(uuid7("2026-03-28"))
+ session_c = str(uuid7("2026-03-28"))
+ for session_id, distinct_id, timestamp, url in [
+ (session_a, "d1", "2026-03-27T10:00:00Z", "https://example.com/a"),
+ (session_b, "d2", "2026-03-28T10:00:00Z", "https://example.com/b"),
+ (session_c, "d3", "2026-03-28T11:00:00Z", "https://example.com/c"),
+ ]:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=timestamp,
+ properties={"$session_id": session_id, "$current_url": url},
+ )
+
+ query = (
+ "SELECT $session_id AS session_id, any(events.session.$entry_current_url) AS entry_url "
+ "FROM events "
+ f"WHERE $session_id IN ('{session_a}', '{session_b}') "
+ "GROUP BY session_id ORDER BY session_id"
+ )
+ modifiers = create_default_modifiers_for_team(self.team)
+ modifiers.sessionTableVersion = SessionTableVersion.V2
+ modifiers.sessionsV2JoinMode = SessionsV2JoinMode.UUID
+ response = execute_hogql_query(query=query, team=self.team, modifiers=modifiers)
+
+ # guard against passing vacuously: the pushed shape must actually execute
+ assert response.clickhouse is not None
+ assert "in(raw_sessions.session_id_v7, tuple(" in response.clickhouse
+
+ # a conversion bug in the pushed id set would surface as NULL entry urls
+ expected = sorted([(session_a, "https://example.com/a"), (session_b, "https://example.com/b")])
+ assert response.results == expected
+
+
class TestSessionPropertyPreAggregationV2(ClickhouseTestMixin, APIBaseTest):
# Tests for the sessionPropertyPreAggregation modifier — narrows the raw_sessions GROUP BY
# hash table by IN-filtering on a cheap pre-aggregation that only materializes the columns
diff --git a/posthog/hogql/database/schema/util/where_clause_extractor.py b/posthog/hogql/database/schema/util/where_clause_extractor.py
index 99b58ef4dabf..418c5f607537 100644
--- a/posthog/hogql/database/schema/util/where_clause_extractor.py
+++ b/posthog/hogql/database/schema/util/where_clause_extractor.py
@@ -19,9 +19,14 @@ from posthog.hogql.functions.mapping import HOGQL_COMPARISON_MAPPING
from posthog.hogql.helpers.timestamp_visitor import is_simple_timestamp_field_expression, is_time_or_interval_constant
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
+from posthog.uuidt import UUIDT
+
SESSION_BUFFER_DAYS = 3
DEFAULT_SESSION_LOOKBACK_DAYS = 30
DEFAULT_SESSION_LOOKBACK_CACHE_TTL_SECONDS = 60
+# beyond this, duplicating the id list into the join subquery risks query-size limits;
+# covers the largest observed production batch (~1.2k ids) at ~13% of max_query_size
+SESSION_ID_LITERAL_PUSHDOWN_MAX_IDS = 2000
class WhereClauseExtractor(CloningVisitor):
@@ -590,6 +595,127 @@ def is_events_only_field(node: ast.Field) -> bool:
return False
+def _unwrap_field_alias_type(expr_type: Optional[ast.Type]) -> Optional[ast.Type]:
+ while isinstance(expr_type, ast.FieldAliasType):
+ expr_type = expr_type.type
+ return expr_type
+
+
+def _unwrap_table_alias_type(table_type: Optional[ast.Type]) -> Optional[ast.Type]:
+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):
+ table_type = table_type.table_type
+ return table_type
+
+
+def get_events_session_id_table_type(node: ast.Expr) -> Optional[ast.BaseTableType]:
+ """If the expression resolves to $session_id on the events table, return its (possibly aliased) table type."""
+ from posthog.hogql.database.schema.events import EventsTable # noqa: PLC0415 - breaks the schema import cycle
+
+ expr_type = _unwrap_field_alias_type(node.type)
+
+ if isinstance(expr_type, ast.FieldType) and expr_type.name == "$session_id":
+ table_type = expr_type.table_type
+ elif (
+ isinstance(expr_type, ast.PropertyType)
+ and expr_type.chain == ["$session_id"]
+ and expr_type.field_type.name == "properties"
+ ):
+ table_type = expr_type.field_type.table_type
+ elif (
+ isinstance(node, ast.JsonSubcolumnAccess)
+ and node.keys == ["$session_id"]
+ and isinstance(_unwrap_field_alias_type(node.expr.type), ast.FieldType)
+ ):
+ field_type = cast(ast.FieldType, _unwrap_field_alias_type(node.expr.type))
+ if field_type.name != "properties":
+ return None
+ table_type = field_type.table_type
+ else:
+ return None
+
+ unwrapped = _unwrap_table_alias_type(table_type)
+ if isinstance(unwrapped, ast.TableType) and isinstance(unwrapped.table, EventsTable):
+ return cast(ast.BaseTableType, table_type)
+ return None
+
+
+def extract_uuid_constants(node: ast.Expr) -> list[ast.Constant]:
+ """Extract UUID string constants from an expression. Returns empty list if any value is not a valid UUID."""
+ if isinstance(node, ast.Constant):
+ return [node] if UUIDT.is_valid_uuid(node.value) else []
+ if isinstance(node, (ast.Tuple, ast.Array)):
+ result: list[ast.Constant] = []
+ for expr in node.exprs:
+ if not isinstance(expr, ast.Constant) or not UUIDT.is_valid_uuid(expr.value):
+ return []
+ result.append(expr)
+ return result
+ return []
+
+
+def build_session_id_literal_pushdown_predicate(
+ outer_node: ast.SelectQuery,
+ join_to_add: LazyJoinToAdd,
+ session_id_v7_field: ast.Expr,
+) -> Optional[ast.Expr]:
+ """Push a literal ``$session_id IN (...)`` events filter into the sessions join subquery.
+
+ Safe ungated: the pushed column is the join key, so pruning the right side of the LEFT
+ JOIN cannot change any row the outer WHERE keeps. Fails open on any other shape.
+ """
+ if outer_node.where is None:
+ return None
+ events_join = _find_join_for_alias(outer_node.select_from, join_to_add.from_table)
+ if events_join is None or not isinstance(events_join.table, ast.Field):
+ return None
+
+ events_table_type = _unwrap_table_alias_type(events_join.table.type)
+ if events_table_type is None:
+ return None
+
+ def flatten_and(expr: ast.Expr) -> list[ast.Expr]:
+ if isinstance(expr, ast.And):
+ return [t for sub in expr.exprs for t in flatten_and(sub)]
+ if isinstance(expr, ast.Call) and expr.name == "and":
+ return [t for sub in expr.args for t in flatten_and(sub)]
+ return [expr]
+
+ for term in flatten_and(outer_node.where):
+ if not isinstance(term, ast.CompareOperation) or term.op not in (
+ CompareOperationOp.In,
+ CompareOperationOp.Eq,
+ ):
+ continue
+ if term.op == CompareOperationOp.Eq and not isinstance(term.right, ast.Constant):
+ continue
+ # only push filters owned by the events occurrence this lazy join hangs off
+ owner = get_events_session_id_table_type(term.left)
+ if owner is None or _unwrap_table_alias_type(owner) is not events_table_type:
+ continue
+ constants = extract_uuid_constants(term.right)
+ if not constants or len(constants) > SESSION_ID_LITERAL_PUSHDOWN_MAX_IDS:
+ continue
+ return ast.CompareOperation(
+ op=CompareOperationOp.In,
+ left=session_id_v7_field,
+ right=ast.Tuple(
+ exprs=[
+ ast.Call(
+ name="_toUInt128",
+ args=[
+ ast.Call(
+ name="accurateCastOrNull",
+ args=[ast.Constant(value=constant.value), ast.Constant(value="UUID")],
+ )
+ ],
+ )
+ for constant in constants
+ ]
+ ),
+ )
+ return None
+
+
def build_session_id_v7_pushdown_predicate(
outer_node: ast.SelectQuery,
join_to_add: LazyJoinToAdd,
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index d1672c286c13..0ce7c0cfbe55 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -17,6 +17,10 @@ from posthog.hogql.database.models import (
)
from posthog.hogql.database.s3_table import DataWarehouseTable, S3Table
from posthog.hogql.database.schema.events import EVENTS_TABLE_TYPES
+from posthog.hogql.database.schema.util.where_clause_extractor import (
+ extract_uuid_constants,
+ get_events_session_id_table_type,
+)
from posthog.hogql.errors import ImpossibleASTError, InternalHogQLError, QueryError
from posthog.hogql.escape_sql import (
escape_clickhouse_identifier,
@@ -588,39 +592,6 @@ class ClickHousePrinter(BasePrinter):
keys_placeholder = self.context.add_sensitive_value(sorted(keys_to_drop))
return f"{JSON_DROP_KEYS_CLICKHOUSE_NAME}({keys_placeholder})({field_sql})"
- def _get_events_session_id_table_type(self, node: ast.Expr) -> ast.BaseTableType | None:
- """If the expression resolves to $session_id on the events table, return the table type."""
- from posthog.hogql.database.schema.events import EventsTable
-
- expr_type = resolve_field_type(node)
-
- if isinstance(expr_type, ast.FieldType) and expr_type.name == "$session_id":
- table_type = expr_type.table_type
- elif (
- isinstance(expr_type, ast.PropertyType)
- and expr_type.chain == ["$session_id"]
- and expr_type.field_type.name == "properties"
- ):
- table_type = expr_type.field_type.table_type
- elif (
- isinstance(node, ast.JsonSubcolumnAccess)
- and node.keys == ["$session_id"]
- and isinstance(resolve_field_type(node.expr), ast.FieldType)
- ):
- field_type = cast(ast.FieldType, resolve_field_type(node.expr))
- if field_type.name != "properties":
- return None
- table_type = field_type.table_type
- else:
- return None
-
- original_table_type = table_type
- while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):
- table_type = table_type.table_type
- if isinstance(table_type, ast.TableType) and isinstance(table_type.table, EventsTable):
- return cast(ast.BaseTableType, original_table_type)
- return None
-
def _get_optimized_session_id_compare_operation(self, node: ast.CompareOperation) -> str | None:
"""Rewrite $session_id comparisons against UUID constants to use the $session_id_uuid column."""
op_name = {
@@ -635,13 +606,13 @@ class ClickHousePrinter(BasePrinter):
session_id_table: ast.BaseTableType | None = None
constants: list[ast.Constant] = []
- if table := self._get_events_session_id_table_type(node.left):
+ if table := get_events_session_id_table_type(node.left):
session_id_table = table
- constants = self._extract_uuid_constants(node.right)
+ constants = extract_uuid_constants(node.right)
elif node.op in (ast.CompareOperationOp.Eq, ast.CompareOperationOp.NotEq):
- if table := self._get_events_session_id_table_type(node.right):
+ if table := get_events_session_id_table_type(node.right):
session_id_table = table
- constants = self._extract_uuid_constants(node.left)
+ constants = extract_uuid_constants(node.left)
if session_id_table is None or not constants:
return None
@@ -653,20 +624,6 @@ class ClickHousePrinter(BasePrinter):
return f"{op_name}({field_sql}, {wrapped[0]})"
return f"{op_name}({field_sql}, tuple({', '.join(wrapped)}))"
- @staticmethod
- def _extract_uuid_constants(node: ast.Expr) -> list[ast.Constant]:
- """Extract UUID string constants from an expression. Returns empty list if any value is not a valid UUID."""
- if isinstance(node, ast.Constant):
- return [node] if UUIDT.is_valid_uuid(node.value) else []
- if isinstance(node, (ast.Tuple, ast.Array)):
- result: list[ast.Constant] = []
- for expr in node.exprs:
- if not isinstance(expr, ast.Constant) or not UUIDT.is_valid_uuid(expr.value):
- return []
- result.append(expr)
- return result
- return []
-
@staticmethod
def _parse_zoned_datetime_constant(node: ast.Expr) -> datetime | None:
return parse_zoned_datetime_string(node.value) if isinstance(node, ast.Constant) else None