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(web-analytics): session id set fast path for filtered web overview and paths tile (#70847)

Lucas Ricoy96b408e624af
diff --git a/posthog/hogql/database/schema/sessions_v2.py b/posthog/hogql/database/schema/sessions_v2.py
index 4f9df3bdac3b..75d5699aaf4a 100644
--- a/posthog/hogql/database/schema/sessions_v2.py
+++ b/posthog/hogql/database/schema/sessions_v2.py
@@ -26,6 +26,7 @@ from posthog.hogql.database.schema.util.where_clause_extractor import (
)
from posthog.hogql.errors import ResolutionError
from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.visitor import clone_expr
from posthog.queries.insight import insight_sync_execute
from posthog.schema_enums import BounceRatePageViewMode, SessionsV2JoinMode
@@ -448,6 +449,162 @@ def select_from_sessions_table_v2(
)
+def _single_sessions_occurrence_type(node: ast.SelectQuery, lazy_table: "SessionsTableV2") -> Optional[ast.Type]:
+ """The resolved type of the query's only ``sessions`` occurrence, or None.
+
+ Returns None when the sessions table appears more than once in the FROM/JOIN
+ chain (a self-join — ownership of a ``session_id`` filter is then ambiguous
+ because lazy expansion processes occurrences one at a time against the same
+ node), or when it cannot be identified. Used to prove a WHERE term belongs to
+ the occurrence currently being expanded before pushing it down.
+ """
+ found: Optional[ast.Type] = None
+ join: Optional[ast.JoinExpr] = node.select_from
+ while join is not None:
+ if isinstance(join.table, ast.Field):
+ table_type = join.table.type
+ unwrapped = table_type.table_type if isinstance(table_type, ast.TableAliasType) else table_type
+ if isinstance(unwrapped, ast.LazyTableType) and unwrapped.table is lazy_table:
+ if found is not None:
+ return None
+ found = table_type
+ join = join.next_join
+ return found
+
+
+def build_direct_session_id_in_pushdown(
+ node: ast.SelectQuery, context: HogQLContext, lazy_table: "SessionsTableV2"
+) -> Optional[ast.Expr]:
+ """Push a top-level ``session_id IN (SELECT …)`` filter below the per-session GROUP BY.
+
+ A direct select over ``sessions`` aggregates every session in the date range
+ before outer WHERE filters apply, so an id-set filter (the session-id-set
+ pattern: events side first, sessions restricted to matching ids) pays the full
+ aggregation anyway. Rewriting it onto ``raw_sessions.session_id_v7`` inside the
+ subquery prunes before aggregation — memory and CPU then scale with matching
+ sessions, not all sessions. ``GlobalIn`` keeps the id subquery executing once
+ on the initiator instead of once per shard. When the rewrite fires, the
+ original outer term is neutralized in place (rewritten to ``1 = 1``) so the id
+ subquery is not executed a second time above the GROUP BY.
+
+ Exposure: this is keyed on the ``sessionIdPushdown`` modifier, which teams can
+ persist in ``team.modifiers`` — so any HogQL query with a matching shape
+ (including SQL editor queries) can hit this rewrite, not just the web overview
+ runner. That is safe because the rewrite is semantics-preserving: the filter is
+ on the GROUP BY key itself, so pruning before aggregation returns the same rows
+ as filtering after, string ids are matched only in their canonical (lowercase)
+ UUID form exactly like the un-rewritten string comparison, and the rewrite only
+ fires when the filtered column provably belongs to this sessions occurrence —
+ the query's single one; joined tables' own ``session_id`` columns and sessions
+ self-joins are left untouched (locked by the parity and hijack tests in
+ test_session_v2_where_clause_extractor.py). Fails open (returns None, outer
+ term untouched) on any shape it doesn't recognize — NOT IN, literal lists,
+ OR-nested terms, multi-column subqueries — preserving exact original semantics
+ there.
+ """
+ if not context.modifiers or not context.modifiers.sessionIdPushdown:
+ return None
+ if node.where is None:
+ return None
+ occurrence_type = _single_sessions_occurrence_type(node, lazy_table)
+ if occurrence_type is None:
+ return None
+
+ def flatten_and(expr: ast.Expr) -> list[ast.Expr]:
+ if isinstance(expr, ast.And):
+ return [t for sub in expr.exprs for t in flatten_and(sub)]
+ if isinstance(expr, ast.Call) and expr.name == "and":
+ return [t for sub in expr.args for t in flatten_and(sub)]
+ return [expr]
+
+ for term in flatten_and(node.where):
+ if not isinstance(term, ast.CompareOperation) or term.op not in (
+ ast.CompareOperationOp.In,
+ ast.CompareOperationOp.GlobalIn,
+ ):
+ continue
+ left = term.left.expr if isinstance(term.left, ast.Alias) else term.left
+ if (
+ not isinstance(left, ast.Field)
+ or left.chain[-1] not in ("session_id", "session_id_v7")
+ or not isinstance(term.right, ast.SelectQuery)
+ ):
+ continue
+ # Ownership: the field must resolve to THIS sessions occurrence. Chain
+ # names alone would also match e.g. `events.properties.session_id`, a
+ # replay/warehouse table's own session_id column, or the other side of a
+ # sessions self-join — rewriting those would silently drop the user's
+ # filter and apply a different one to a different table.
+ if not isinstance(left.type, ast.FieldType) or left.type.table_type is not occurrence_type:
+ continue
+
+ subquery = cast(ast.SelectQuery, clone_expr(term.right, clear_types=True, clear_locations=True))
+ if len(subquery.select) != 1:
+ return None
+ inner = subquery.select[0]
+ if isinstance(inner, ast.Alias):
+ alias = inner.alias
+ else:
+ alias = "session_id_value"
+ subquery.select[0] = ast.Alias(alias=alias, expr=inner)
+
+ if left.chain[-1] == "session_id_v7":
+ # Already UInt128 — no conversion needed.
+ id_expr: ast.Expr = ast.Field(chain=[alias])
+ else:
+ # String session ids: accurateCastOrNull keeps malformed values from
+ # aborting the query (they become NULL and drop out of the set, which
+ # matches the join path leaving them unmatched). The toString
+ # round-trip keeps only canonical (lowercase) UUID strings: the
+ # un-rewritten predicate is a byte-exact string comparison against
+ # sessions.session_id (always canonical), so a non-canonical form
+ # like an uppercased UUID must not match here either.
+ # Two separate cast nodes on purpose — sharing one AST node between
+ # parents breaks cloning/resolution assumptions.
+ cast_for_check = ast.Call(
+ name="accurateCastOrNull", args=[ast.Field(chain=[alias]), ast.Constant(value="UUID")]
+ )
+ cast_for_value = ast.Call(
+ name="accurateCastOrNull", args=[ast.Field(chain=[alias]), ast.Constant(value="UUID")]
+ )
+ id_expr = ast.Call(
+ name="_toUInt128",
+ args=[
+ ast.Call(
+ name="if",
+ args=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Call(name="toString", args=[cast_for_check]),
+ right=ast.Field(chain=[alias]),
+ ),
+ cast_for_value,
+ ast.Constant(value=None),
+ ],
+ )
+ ],
+ )
+
+ wrapped = ast.SelectQuery(
+ select=[id_expr],
+ select_from=ast.JoinExpr(table=subquery),
+ )
+ # Neutralize the original outer predicate in place: keeping it would make
+ # ClickHouse execute the identical GLOBAL IN id-subquery twice (once pushed
+ # down, once post-aggregation) — measured as an extra full filtered-events
+ # scan per query. The pushed copy below subsumes it exactly.
+ term.op = ast.CompareOperationOp.Eq
+ term.left = ast.Constant(value=1)
+ term.right = ast.Constant(value=1)
+
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.GlobalIn,
+ left=ast.Field(chain=["raw_sessions", "session_id_v7"]),
+ right=wrapped,
+ )
+ return None
+
+
class SessionsTableV2(LazyTable):
description: str = (
"Aggregated user sessions (one row per session), with entry/exit URLs, attribution, and duration. "
@@ -461,7 +618,8 @@ class SessionsTableV2(LazyTable):
context,
node: ast.SelectQuery,
):
- return select_from_sessions_table_v2(table_to_add.fields_accessed, node, context)
+ extra_where = build_direct_session_id_in_pushdown(node, context, self)
+ return select_from_sessions_table_v2(table_to_add.fields_accessed, node, context, extra_where=extra_where)
def to_printed_clickhouse(self, context):
return "sessions"
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 e023623ad1ad..9a697005d317 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
@@ -2,7 +2,7 @@ from datetime import UTC, datetime
from typing import Any, Optional, Union
import pytest
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
from django.conf import settings
@@ -12,13 +12,18 @@ from posthog.schema import SessionTableVersion
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.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
+from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.resolver import resolve_types
from posthog.hogql.visitor import clone_expr
from posthog.models import EventDefinition
+from posthog.models.utils import uuid7
def f(s: Union[str, ast.Expr, None], placeholders: Optional[dict[str, ast.Expr]] = None) -> Union[ast.Expr, None]:
@@ -738,6 +743,183 @@ WHERE events.timestamp >= '2026-03-27 00:00:00'
assert "or(" not in in_subquery, f"Expected no OR in narrowed IN; got:\n{in_subquery}"
+class TestDirectSessionIdInPushdownV2(ClickhouseTestMixin, APIBaseTest):
+ # Locks build_direct_session_id_in_pushdown, the rewrite behind the web
+ # analytics session-id-set fast path. It is keyed on the sessionIdPushdown
+ # modifier, which teams can persist in team.modifiers — so ANY HogQL query
+ # with a matching shape (SQL editor included) can hit it. These tests pin:
+ # (a) it fires only for the exact supported shape, (b) it moves the id filter
+ # instead of copying it, and (c) it never changes query results.
+
+ ID_SUBQUERY_SHAPE = (
+ "SELECT $start_timestamp FROM sessions "
+ "WHERE session_id IN (SELECT $session_id FROM events WHERE event = '$pageview')"
+ )
+
+ def print_query(self, query: str, pushdown: bool, version: SessionTableVersion = SessionTableVersion.V2) -> str:
+ modifiers = create_default_modifiers_for_team(self.team)
+ modifiers.sessionTableVersion = version
+ modifiers.sessionIdPushdown = pushdown
+ 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())
+
+ def test_rewrites_id_subquery_below_group_by_exactly_once(self):
+ sql = self.print_query(self.ID_SUBQUERY_SHAPE, pushdown=True)
+ assert sql.count("globalIn(raw_sessions.session_id_v7") == 1, sql
+ # Moved, not copied: a retained outer copy of the id subquery makes
+ # ClickHouse run the identical filtered-events scan a second time.
+ assert sql.count("FROM events") == 1, sql
+
+ def test_session_id_v7_subquery_skips_uuid_cast(self):
+ sql = self.print_query("SELECT $start_timestamp FROM sessions WHERE session_id_v7 IN (SELECT 1)", pushdown=True)
+ assert "globalIn(raw_sessions.session_id_v7" in sql, sql
+ # session_id_v7 is already UInt128 — wrapping it in the string→UUID cast
+ # would NULL out every id and silently return zero sessions.
+ assert "accurateCastOrNull" not in sql, sql
+
+ @parameterized.expand(
+ [
+ ("literal_list", "SELECT $start_timestamp FROM sessions WHERE session_id IN ('a', 'b')", True),
+ (
+ "not_in_subquery",
+ "SELECT $start_timestamp FROM sessions "
+ "WHERE session_id NOT IN (SELECT $session_id FROM events WHERE event = '$pageview')",
+ True,
+ ),
+ (
+ "or_nested",
+ "SELECT $start_timestamp FROM sessions "
+ "WHERE session_id IN (SELECT $session_id FROM events WHERE event = '$pageview') "
+ "OR $start_timestamp > '2026-01-01'",
+ True,
+ ),
+ ("modifier_off", ID_SUBQUERY_SHAPE, False),
+ ]
+ )
+ def test_unsupported_shapes_are_not_rewritten(self, _name: str, query: str, pushdown: bool):
+ sql = self.print_query(query, pushdown=pushdown)
+ assert "globalIn(raw_sessions.session_id_v7" not in sql, sql
+
+ def test_multi_column_subquery_fails_open_without_neutralizing(self):
+ modifiers = create_default_modifiers_for_team(self.team)
+ modifiers.sessionTableVersion = SessionTableVersion.V2
+ modifiers.sessionIdPushdown = True
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ enable_select_queries=True,
+ modifiers=modifiers,
+ database=Database.create_for(team=self.team, modifiers=modifiers),
+ )
+ node = resolve_types(
+ parse("SELECT session_id FROM sessions WHERE session_id IN (SELECT $session_id, event FROM events)"),
+ context,
+ dialect="clickhouse",
+ )
+ assert isinstance(node, ast.SelectQuery)
+ assert node.where is not None
+ where_before = clone_expr(node.where, clear_types=True, clear_locations=True)
+ assert context.database is not None
+ sessions_table = context.database.get_table("sessions")
+ assert isinstance(sessions_table, SessionsTableV2)
+
+ assert build_direct_session_id_in_pushdown(node, context, sessions_table) is None
+ # Fail-open must leave the original predicate intact — neutralizing it
+ # without returning a replacement would drop the filter entirely.
+ where_after = node.where
+ assert where_after is not None
+ assert clone_expr(where_after, clear_types=True, clear_locations=True) == where_before
+
+ @parameterized.expand(
+ [
+ # Another table's session_id-named column must never be hijacked:
+ # rewriting it would silently drop the user's filter and apply a
+ # different one to the sessions subquery instead.
+ (
+ "events_property_named_session_id",
+ "SELECT s.$start_timestamp FROM sessions s JOIN events e ON e.$session_id = s.session_id "
+ "WHERE e.properties.session_id IN (SELECT $session_id FROM events WHERE event = '$pageview')",
+ ),
+ (
+ "replay_table_session_id",
+ "SELECT r.session_id FROM session_replay_events r LEFT JOIN sessions s ON s.session_id = r.session_id "
+ "WHERE r.session_id IN (SELECT $session_id FROM events WHERE event = '$pageview')",
+ ),
+ # A sessions self-join makes ownership ambiguous (lazy expansion
+ # processes occurrences one at a time against the same node), so the
+ # rewrite must skip entirely rather than push a's filter into b.
+ (
+ "sessions_self_join",
+ "SELECT a.session_id FROM sessions a CROSS JOIN sessions b "
+ "WHERE a.session_id IN (SELECT $session_id FROM events WHERE event = '$pageview')",
+ ),
+ ]
+ )
+ def test_other_tables_and_self_joins_are_not_hijacked(self, _name: str, query: str):
+ with_pushdown = self.print_query(query, pushdown=True)
+ without_pushdown = self.print_query(query, pushdown=False)
+ assert with_pushdown == without_pushdown
+
+ def test_v3_sessions_are_not_rewritten(self):
+ with_pushdown = self.print_query(self.ID_SUBQUERY_SHAPE, pushdown=True, version=SessionTableVersion.V3)
+ without_pushdown = self.print_query(self.ID_SUBQUERY_SHAPE, pushdown=False, version=SessionTableVersion.V3)
+ assert with_pushdown == without_pushdown
+
+ def test_pushdown_preserves_results_for_direct_sessions_query(self):
+ # The SQL-editor safety proof: a team that persists sessionIdPushdown in
+ # team.modifiers gets this rewrite on every matching query, so the modifier
+ # must never change which rows come back — including for malformed
+ # (non-UUID) session ids, which the cast drops from the pushed set exactly
+ # like the un-pushed filter leaves them unmatched.
+ matching_session = str(uuid7("2026-03-27"))
+ other_session = str(uuid7("2026-03-28"))
+ for session_id, distinct_id, timestamp, url in [
+ (matching_session, "d1", "2026-03-27T10:00:00Z", "/a"),
+ (other_session, "d2", "2026-03-28T10:00:00Z", "/b"),
+ ("not-a-uuid", "d3", "2026-03-27T11:00:00Z", "/a"),
+ # Uppercase UUID: casts to the same UUID value as other_session, but
+ # the un-rewritten predicate is a byte-exact string comparison against
+ # the canonical lowercase sessions.session_id — so it must not match
+ # under the pushdown either.
+ (other_session.upper(), "d4", "2026-03-28T11:00:00Z", "/a"),
+ ]:
+ _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 FROM sessions "
+ "WHERE session_id IN (SELECT $session_id FROM events WHERE properties.$current_url = '/a') "
+ "ORDER BY session_id"
+ )
+ results = {}
+ for pushdown in (True, False):
+ modifiers = create_default_modifiers_for_team(self.team)
+ modifiers.sessionTableVersion = SessionTableVersion.V2
+ modifiers.sessionIdPushdown = pushdown
+ response = execute_hogql_query(query=query, team=self.team, modifiers=modifiers)
+ results[pushdown] = response.results
+ # Guard against this test passing vacuously: the rewrite fails open,
+ # so also pin that the pushed shape actually executed (and only when
+ # the modifier is on).
+ assert response.clickhouse is not None
+ assert ("globalIn(raw_sessions.session_id_v7" in response.clickhouse) == pushdown
+
+ assert results[True] == results[False]
+ assert results[True] == [(matching_session,)]
+
+
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/settings/web.py b/posthog/settings/web.py
index 6784e9be8bb3..5b02bf579e5b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1196,6 +1196,20 @@ WEB_ANALYTICS_NO_JOIN_ROLLOUT_PERCENT: int = get_from_env(
"WEB_ANALYTICS_NO_JOIN_ROLLOUT_PERCENT", _NO_JOIN_DEFAULT_ROLLOUT_PERCENT, type_cast=int
)
+
+# Teams whose *filtered* web overview queries (event-property filters only) run as two
+# independent scans linked by a session-id set: the events side evaluates the filters and
+# collects the matching session ids, then the sessions side aggregates only over that id
+# set (pushed below the per-session GROUP BY, executed once via GLOBAL IN instead of per
+# shard). Allowlist only — no percent rollout yet. Defaults to the Cloud dogfooding team
+# (project 2) on US Cloud, where the pattern was validated against prod; empty on EU
+# (pending its ClickHouse upgrade + verification) and on self-hosted, where project id 2
+# is an arbitrary customer.
+_SESSION_ID_SET_DEFAULT_TEAM_IDS = "2" if (CLOUD_DEPLOYMENT or "").upper() == "US" and not TEST else ""
+WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS: list[int] = [
+ int(team_id)
+ for team_id in get_list(get_from_env("WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS", _SESSION_ID_SET_DEFAULT_TEAM_IDS))
+]
# Admission control for long-lived SSE streams: the maximum number of streams
# one worker process serves concurrently. Above the cap, sse_streaming_response()
# returns 503 with a jittered Retry-After instead of opening the stream, keeping
diff --git a/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py b/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
index a8d555d92d3e..ec64b0af5a5e 100644
--- a/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
+++ b/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
@@ -187,6 +187,10 @@ GROUP BY session_id, breakdown_value
# (bucketed by session start), instead of routing both through the events↔sessions
# lazy join. The join shape re-executes the sessions subquery on every shard of the
# events cluster, so for unfiltered queries these variants read ~10× fewer rows.
+# The filter placeholders ({event_filters}, {bounce_sessions_filter},
+# {time_on_page_filters}) are constant-true for the unfiltered no-join strategies;
+# the session-id-set strategies fill them with events-side filters and a
+# session-id IN filter so filtered queries share the same two-scan shape.
NO_JOIN_PATH_BOUNCE_QUERY = """
SELECT
counts.breakdown_value AS "context.columns.breakdown_value",
@@ -205,6 +209,7 @@ FROM (
{events_session_id_present},
or(events.event == '$pageview', events.event == '$screen'),
{inside_timestamp_periods},
+ {event_filters},
)
GROUP BY breakdown_value
) AS counts
@@ -217,6 +222,7 @@ LEFT JOIN (
WHERE and(
{inside_session_periods},
or(sessions.$pageview_count > 0, sessions.$screen_count > 0),
+ {bounce_sessions_filter},
)
GROUP BY breakdown_value
) AS bounce
@@ -253,6 +259,7 @@ FROM (
{events_session_id_present},
or(events.event == '$pageview', events.event == '$screen'),
{inside_timestamp_periods},
+ {event_filters},
)
GROUP BY breakdown_value
) AS counts
@@ -274,6 +281,7 @@ LEFT JOIN (
{time_on_page_breakdown_value} IS NOT NULL,
events.properties.`$prev_pageview_duration` IS NOT NULL,
{inside_timestamp_periods},
+ {time_on_page_filters},
)
GROUP BY breakdown_value
) AS time_on_page
@@ -288,6 +296,7 @@ LEFT JOIN (
WHERE and(
{inside_session_periods},
or(sessions.$pageview_count > 0, sessions.$screen_count > 0),
+ {bounce_sessions_filter},
)
GROUP BY breakdown_value
) AS bounce
diff --git a/products/web_analytics/backend/hogql_queries/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
index eb0a5cb8eacd..0f6b4d9ee4fe 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -18,7 +18,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.constants import LimitContext
-from posthog.hogql.parser import parse_expr
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.property import (
get_property_key,
get_property_operator,
@@ -29,6 +29,7 @@ from posthog.hogql.property import (
from posthog.clickhouse.query_tagging import clear_tag, get_query_tag_value
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
+from posthog.models.filters.mixins.utils import cached_property
from products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilder
from products.web_analytics.backend.hogql_queries.stats_table_strategies import (
@@ -38,6 +39,8 @@ from products.web_analytics.backend.hogql_queries.stats_table_strategies import
NoJoinPathBounceStrategy,
PathBounceAvgTimeStrategy,
PathBounceStrategy,
+ SessionIdSetPathBounceAvgTimeStrategy,
+ SessionIdSetPathBounceStrategy,
SimpleBreakdownStrategy,
StatsTableQueryStrategy,
)
@@ -88,6 +91,8 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
team_version = getattr(self.team, "web_analytics_pre_aggregated_tables_version", None)
self.use_v2_tables = team_version == "v2" if team_version is not None else use_v2_tables
self.used_preaggregated_tables = False
+ # None = not yet checked (e.g. EXPLAIN paths); set by `_calculate` before execution.
+ self._session_id_set_selectivity_ok: Optional[bool] = None
limit = self.query.limit if self.query.limit else None
offset = self.query.offset if self.query.offset else None
@@ -99,14 +104,17 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
self.preaggregated_query_builder = StatsTablePreAggregatedQueryBuilder(self)
- def _resolve_strategy(self) -> ResolvedStatsTableStrategy:
- if (
+ def _can_serve_preaggregated(self) -> bool:
+ return bool(
self.modifiers
and self.modifiers.useWebAnalyticsPreAggregatedTables
and self.preaggregated_query_builder.can_use_preaggregated_tables()
and not self.query.includeAvgTimeOnPage
and not self.query.conversionGoal
- ):
+ )
+
+ def _resolve_strategy(self) -> ResolvedStatsTableStrategy:
+ if self._can_serve_preaggregated():
if self.query.breakdownBy == WebStatsBreakdown.PAGE:
return ResolvedStatsTableStrategy(
strategy="stats_table_preaggregated_path_breakdown",
@@ -145,7 +153,12 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
def _strategy_name(self, strategy: StatsTableQueryStrategy) -> str:
if isinstance(strategy, FrustrationMetricsStrategy):
return "stats_table_frustration_metrics"
- # No-join variants first: they don't subclass the join strategies.
+ # Session-id-set variants first: they subclass the no-join strategies.
+ if isinstance(strategy, SessionIdSetPathBounceAvgTimeStrategy):
+ return "stats_table_session_id_set_path_bounce_and_avg_time"
+ if isinstance(strategy, SessionIdSetPathBounceStrategy):
+ return "stats_table_session_id_set_path_bounce"
+ # No-join variants next: they don't subclass the join strategies.
if isinstance(strategy, NoJoinPathBounceAvgTimeStrategy):
return "stats_table_no_join_path_bounce_and_avg_time"
if isinstance(strategy, NoJoinPathBounceStrategy):
@@ -177,10 +190,14 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
if self.query.includeAvgTimeOnPage:
if self.should_skip_session_join:
return NoJoinPathBounceAvgTimeStrategy(self)
+ if self.should_use_session_id_set and self._session_id_set_selectivity_ok is not False:
+ return SessionIdSetPathBounceAvgTimeStrategy(self)
return PathBounceAvgTimeStrategy(self)
if self.query.includeBounceRate:
if self.should_skip_session_join:
return NoJoinPathBounceStrategy(self)
+ if self.should_use_session_id_set and self._session_id_set_selectivity_ok is not False:
+ return SessionIdSetPathBounceStrategy(self)
return PathBounceStrategy(self)
if self.query.breakdownBy == WebStatsBreakdown.INITIAL_PAGE and self.query.includeBounceRate:
@@ -370,6 +387,70 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
]
return property_to_expr(properties, team=self.team, scope="event")
+ @cached_property
+ def should_use_session_id_set(self) -> bool:
+ """Whether a filtered paths query can run as the two-scan no-join shape
+ linked by a session-id set (see `_session_id_set_common_eligibility`).
+ Only the PAGE bounce strategies support the shape; anything else keeps
+ the join path.
+ """
+ if self.query.breakdownBy != WebStatsBreakdown.PAGE:
+ return False
+ if not (self.query.includeBounceRate or self.query.includeAvgTimeOnPage):
+ return False
+ if self.should_skip_session_join:
+ return False
+ return self._session_id_set_common_eligibility()
+
+ @cached_property
+ def _session_id_set_bounce_properties(self) -> list[Union[EventPropertyFilter, PersonPropertyFilter, dict]]:
+ # The bounce side mirrors the join path's `_event_properties_for_bounce_rate`
+ # semantics: pathname filters are excluded, because bounce is attributed to
+ # the session's ENTRY path — restricting the id collection by the viewed
+ # pathname would compute each entry path's bounce rate over the wrong
+ # session population.
+ return [
+ p
+ for p in self.query.properties + self._test_account_filters
+ if not (get_property_type(p) == "event" and get_property_key(p) == "$pathname")
+ ]
+
+ def _session_id_set_bounce_filter(self) -> ast.Expr:
+ if not self._session_id_set_bounce_properties:
+ # Only-`$pathname` filters: nothing constrains session membership on
+ # the bounce side, so it stays a plain unfiltered sessions scan.
+ return ast.Constant(value=True)
+ matching_session_ids = parse_select(
+ """
+SELECT DISTINCT events.$session_id_uuid AS session_id_uuid
+FROM events
+WHERE and(
+ events.$session_id_uuid IS NOT NULL,
+ or(events.event = '$pageview', events.event = '$screen'),
+ {inside_timestamp_periods},
+ {filters},
+)
+ """,
+ placeholders={
+ "inside_timestamp_periods": self._periods_expression("timestamp"),
+ "filters": property_to_expr(self._session_id_set_bounce_properties, team=self.team, scope="event"),
+ },
+ )
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["sessions", "session_id_v7"]),
+ right=matching_session_ids,
+ )
+
+ def _check_session_id_set_selectivity(self) -> bool:
+ if not self._session_id_set_bounce_properties:
+ # No id set will be built (only-`$pathname` filters) — nothing to bound.
+ return True
+ return self._run_session_id_set_preflight(
+ filters=property_to_expr(self._session_id_set_bounce_properties, team=self.team, scope="event"),
+ query_type="stats_table_session_id_set_preflight",
+ )
+
def _all_properties(self) -> ast.Expr:
properties = self.query.properties + self._test_account_filters
return property_to_expr(properties, team=self.team)
@@ -607,6 +688,11 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
if lazy_result is not None:
return self._build_response_from_lazy(lazy_result)
+ # Preflight only when the live query will actually run as the id-set
+ # shape — pre-aggregated serving must not pay a discarded events scan.
+ if self.should_use_session_id_set and not self._can_serve_preaggregated():
+ self._session_id_set_selectivity_ok = self._check_session_id_set_selectivity()
+
query = self.to_query()
# Pre-aggregated tables store data in UTC **buckets**, so we need to disable timezone conversion
@@ -615,6 +701,12 @@ class WebStatsTableQueryRunner(WebAnalyticsQueryRunner[WebStatsTableQueryRespons
if self.used_preaggregated_tables:
modifiers = self.modifiers.model_copy() if self.modifiers else HogQLQueryModifiers()
modifiers.convertToProjectTimezone = False
+ elif self.query_strategy().startswith("stats_table_session_id_set"):
+ # The id-set shape relies on `build_direct_session_id_in_pushdown`
+ # rewriting the bounce side's id filter below the sessions GROUP BY;
+ # that rewrite is gated on the sessionIdPushdown modifier.
+ modifiers = self.modifiers.model_copy() if self.modifiers else HogQLQueryModifiers()
+ modifiers.sessionIdPushdown = True
response = self.paginator.execute_hogql_query(
query_type=self.clickhouse_query_type(),
diff --git a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
index 4bd39380c403..4b5ca7ffd27b 100644
--- a/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
@@ -226,9 +226,10 @@ class NoJoinPathBounceStrategy(StatsTableQueryStrategy):
QUERY = NO_JOIN_PATH_BOUNCE_QUERY
TIMING_KEY = "stats_table_no_join_path_bounce"
+ COUNTER_FAMILY = "stats_table_paths"
def build_query(self) -> ast.SelectQuery:
- WEB_ANALYTICS_NO_JOIN_SERVED.labels(family="stats_table_paths").inc()
+ WEB_ANALYTICS_NO_JOIN_SERVED.labels(family=self.COUNTER_FAMILY).inc()
with self.runner.timings.measure(self.TIMING_KEY):
query = parse_select(
self.QUERY,
@@ -249,6 +250,8 @@ class NoJoinPathBounceStrategy(StatsTableQueryStrategy):
"current_session_period": self.runner._current_period_expression("$start_timestamp"),
"previous_session_period": self.runner._previous_period_expression("$start_timestamp"),
"inside_session_periods": self.runner._periods_expression("$start_timestamp"),
+ "event_filters": ast.Constant(value=True),
+ "bounce_sessions_filter": ast.Constant(value=True),
}
@@ -266,6 +269,48 @@ class NoJoinPathBounceAvgTimeStrategy(NoJoinPathBounceStrategy):
return {
**super()._placeholders(),
"time_on_page_breakdown_value": self.runner._scroll_prev_pathname_breakdown(),
+ "time_on_page_filters": ast.Constant(value=True),
+ }
+
+
+class SessionIdSetPathBounceStrategy(NoJoinPathBounceStrategy):
+ """PAGE breakdown with bounce rate for filtered queries, join-free.
+
+ Same two-scan shape as the no-join strategy, linked by a session-id set:
+ counts apply the events-side filters directly; the bounce side aggregates
+ only sessions whose ids appear in a `SELECT DISTINCT $session_id_uuid`
+ subquery over events matching the pathname-excluded filters (mirroring the
+ join path's `_event_properties_for_bounce_rate` semantics — a session's
+ entry-path bounce rate must not be restricted by which pathname is being
+ viewed). The id filter is rewritten below the per-session GROUP BY by
+ `build_direct_session_id_in_pushdown` (GLOBAL IN, executed once) when the
+ runner flips the `sessionIdPushdown` modifier at execution. When the only
+ filter is `$pathname`, the bounce side has nothing to filter by and stays
+ unfiltered — no id set, no preflight.
+ """
+
+ TIMING_KEY = "stats_table_session_id_set_path_bounce"
+ COUNTER_FAMILY = "stats_table_paths_session_id_set"
+
+ def _placeholders(self) -> dict[str, ast.Expr]:
+ return {
+ **super()._placeholders(),
+ "event_filters": self.runner._event_properties(),
+ "bounce_sessions_filter": self.runner._session_id_set_bounce_filter(),
+ }
+
+
+class SessionIdSetPathBounceAvgTimeStrategy(SessionIdSetPathBounceStrategy):
+ """PAGE breakdown with average time on page and bounce rate, filtered, join-free."""
+
+ QUERY = NO_JOIN_PATH_BOUNCE_AND_AVG_TIME_QUERY
+ TIMING_KEY = "stats_table_session_id_set_path_bounce_and_avg_time"
+
+ def _placeholders(self) -> dict[str, ast.Expr]:
+ return {
+ **super()._placeholders(),
+ "time_on_page_breakdown_value": self.runner._scroll_prev_pathname_breakdown(),
+ "time_on_page_filters": self.runner._event_properties_for_scroll(),
}
diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
index 4aac36d9fbf4..f040164df0d7 100644
--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
@@ -1228,3 +1228,6 @@
use_hive_partitioning=0
'''
# ---
+# name: TestWebOverviewSessionIdSetFastPath.test_session_id_set_pushes_id_filter_below_session_aggregation
+ 'SELECT events_agg.unique_users AS unique_users, events_agg.previous_unique_users AS previous_unique_users, events_agg.total_filtered_pageview_count AS total_filtered_pageview_count, events_agg.previous_total_filtered_pageview_count AS previous_total_filtered_pageview_count, sessions_agg.unique_sessions AS unique_sessions, sessions_agg.previous_unique_sessions AS previous_unique_sessions, sessions_agg.avg_duration_s AS avg_duration_s, sessions_agg.previous_avg_duration_s AS previous_avg_duration_s, sessions_agg.bounce_rate AS bounce_rate, sessions_agg.previous_bounce_rate AS previous_bounce_rate FROM (SELECT uniqIf(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), and(greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_0)s), assumeNotNull(toDateTime(%(hogql_val_1)s, %(hogql_val_2)s))), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_3)s), assumeNotNull(toDateTime(%(hogql_val_4)s, %(hogql_val_5)s))))) AS unique_users, NULL AS previous_unique_users, countIf(and(greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_6)s), assumeNotNull(toDateTime(%(hogql_val_7)s, %(hogql_val_8)s))), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_9)s), assumeNotNull(toDateTime(%(hogql_val_10)s, %(hogql_val_11)s))))) AS total_filtered_pageview_count, NULL AS previous_total_filtered_pageview_count FROM events LEFT OUTER JOIN (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id FROM person_distinct_id_overrides WHERE equals(person_distinct_id_overrides.team_id, <TEAM_ID>) GROUP BY person_distinct_id_overrides.distinct_id HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) WHERE and(equals(events.team_id, <TEAM_ID>), and(isNotNull(events.`$session_id_uuid`), or(equals(events.event, %(hogql_val_12)s), equals(events.event, %(hogql_val_13)s)), or(and(greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_14)s), assumeNotNull(toDateTime(%(hogql_val_15)s, %(hogql_val_16)s))), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_17)s), assumeNotNull(toDateTime(%(hogql_val_18)s, %(hogql_val_19)s)))), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_20)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_21)s), 0)))) AS events_agg CROSS JOIN (SELECT uniqIf(sessions.session_id, and(greaterOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_43)s, %(hogql_val_44)s))), lessOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_45)s, %(hogql_val_46)s))))) AS unique_sessions, NULL AS previous_unique_sessions, avgIf(sessions.`$session_duration`, and(greaterOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_47)s, %(hogql_val_48)s))), lessOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_49)s, %(hogql_val_50)s))))) AS avg_duration_s, NULL AS previous_avg_duration_s, avgIf(sessions.`$is_bounce`, and(greaterOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_51)s, %(hogql_val_52)s))), lessOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_53)s, %(hogql_val_54)s))))) AS bounce_rate, NULL AS previous_bounce_rate FROM (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_22)s)) AS `$start_timestamp`, dateDiff(%(hogql_val_23)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_24)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_25)s))) AS `$session_duration`, if(equals(uniqMerge(raw_sessions.pageview_uniq), 0), NULL, not(or(greater(uniqMerge(raw_sessions.pageview_uniq), 1), greater(uniqMerge(raw_sessions.autocapture_uniq), 0), greaterOrEquals(dateDiff(%(hogql_val_26)s, min(toTimeZone(raw_sessions.min_timestamp, %(hogql_val_27)s)), max(toTimeZone(raw_sessions.max_timestamp, %(hogql_val_28)s))), 10)))) AS `$is_bounce`, uniqMerge(raw_sessions.pageview_uniq) AS `$pageview_count`, uniqMerge(raw_sessions.screen_uniq) AS `$screen_count`, raw_sessions.session_id_v7 AS session_id_v7 FROM raw_sessions WHERE and(equals(raw_sessions.team_id, <TEAM_ID>), and(greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime(%(hogql_val_29)s, %(hogql_val_30)s)), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime(%(hogql_val_31)s, %(hogql_val_32)s)), toIntervalDay(3)))), globalIn(raw_sessions.session_id_v7, (SELECT session_id_uuid AS session_id_uuid FROM (SELECT DISTINCT events.`$session_id_uuid` AS session_id_uuid FROM events WHERE and(equals(events.team_id, <TEAM_ID>), and(isNotNull(events.`$session_id_uuid`), or(equals(events.event, %(hogql_val_33)s), equals(events.event, %(hogql_val_34)s)), or(and(greaterOrEquals(toTimeZone(events.timestamp, %(hogql_val_35)s), assumeNotNull(toDateTime(%(hogql_val_36)s, %(hogql_val_37)s))), lessOrEquals(toTimeZone(events.timestamp, %(hogql_val_38)s), assumeNotNull(toDateTime(%(hogql_val_39)s, %(hogql_val_40)s)))), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_41)s), \'\'), \'null\'), \'^"|"$\', \'\'), %(hogql_val_42)s), 0))))))) GROUP BY raw_sessions.session_id_v7) AS sessions WHERE and(or(and(greaterOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_55)s, %(hogql_val_56)s))), lessOrEquals(sessions.`$start_timestamp`, assumeNotNull(toDateTime(%(hogql_val_57)s, %(hogql_val_58)s)))), 0), or(greater(sessions.`$pageview_count`, 0), greater(sessions.`$screen_count`, 0)), 1)) AS sessions_agg LIMIT 50000'
+# ---
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
index 169407d4dcc6..625c563f3e1a 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
@@ -1,7 +1,8 @@
from datetime import UTC, datetime, timedelta
-from typing import Optional
+from typing import Any, Optional
from zoneinfo import ZoneInfo
+import pytest
from freezegun import freeze_time
from posthog.test.base import (
APIBaseTest,
@@ -37,6 +38,7 @@ from posthog.schema import (
from posthog.hogql.constants import LimitContext
from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.execute import sync_execute
from posthog.models import Element
@@ -1146,6 +1148,278 @@ class TestWebOverviewNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
assert not runner.should_skip_session_join
[email protected]("unittest_snapshot")
+class TestWebOverviewSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
+ QUERY_TIMESTAMP = "2025-01-29"
+ snapshot: Any
+
+ def _create_pageviews(self):
+ s1, s2, s3 = str(uuid7("2025-01-10")), str(uuid7("2025-01-11")), str(uuid7("2025-01-12"))
+ for distinct_id, session_id, path_timestamps in [
+ ("user_a", s1, [("/pricing", "2025-01-10T10:00:00Z"), ("/docs", "2025-01-10T10:05:00Z")]),
+ ("user_a", s2, [("/docs", "2025-01-11T09:00:00Z")]),
+ ("user_b", s3, [("/pricing", "2025-01-12T12:00:00Z"), ("/pricing", "2025-01-12T12:00:30Z")]),
+ ]:
+ with freeze_time(path_timestamps[0][1]):
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
+ for pathname, ts in path_timestamps:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={
+ "$session_id": session_id,
+ "$pathname": pathname,
+ "$current_url": f"https://example.com{pathname}",
+ },
+ )
+ # A matching pageview with a malformed (non-UUID) session id: the join path
+ # leaves it unmatched; the session-id-set id set must drop it instead of feeding
+ # a toUUID() conversion that aborts the whole query.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="user_b",
+ timestamp="2025-01-12T13:00:00Z",
+ properties={"$session_id": "legacy-session", "$pathname": "/pricing"},
+ )
+
+ def _make_runner(self, **query_kwargs) -> WebOverviewQueryRunner:
+ query = WebOverviewQuery(
+ dateRange=DateRange(date_from="2025-01-08", date_to="2025-01-15"),
+ properties=query_kwargs.pop(
+ "properties",
+ [EventPropertyFilter(key="$pathname", operator=PropertyOperator.EXACT, value="/pricing")],
+ ),
+ **query_kwargs,
+ )
+ return WebOverviewQueryRunner(team=self.team, query=query)
+
+ @parameterized.expand([(True,), (False,)])
+ def test_session_id_set_results_match_join_path(self, compare: bool):
+ self._create_pageviews()
+
+ kwargs = {"compareFilter": CompareFilter(compare=True)} if compare else {}
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ fast_runner = self._make_runner(**kwargs)
+ assert fast_runner.should_use_session_id_set
+ assert not fast_runner.should_skip_session_join
+ fast_results = fast_runner.calculate().results
+
+ join_runner = self._make_runner(**kwargs)
+ assert not join_runner.should_use_session_id_set
+ join_results = join_runner.calculate().results
+
+ assert [item.key for item in fast_results] == [item.key for item in join_results]
+ for fast, join in zip(fast_results, join_results):
+ assert fast.value == join.value, f"{fast.key}: {fast.value} != {join.value}"
+ assert fast.previous == join.previous, f"{fast.key} previous: {fast.previous} != {join.previous}"
+
+ @parameterized.expand(
+ [
+ ("event_property_filter", {}, True),
+ ("no_filters", {"properties": []}, False),
+ (
+ "session_property_filter",
+ {
+ "properties": [
+ SessionPropertyFilter(key="$channel_type", operator=PropertyOperator.EXACT, value="Direct")
+ ]
+ },
+ False,
+ ),
+ (
+ "mixed_filters",
+ {
+ "properties": [
+ EventPropertyFilter(key="$pathname", operator=PropertyOperator.EXACT, value="/pricing"),
+ SessionPropertyFilter(key="$channel_type", operator=PropertyOperator.EXACT, value="Direct"),
+ ]
+ },
+ False,
+ ),
+ ("conversion_goal", {"conversionGoal": CustomEventConversionGoal(customEventName="purchase")}, False),
+ # Sampling fields are accepted-but-ignored no-ops across web analytics,
+ # so they must not kick eligible queries off the session-id-set path.
+ ("sampling_enabled_ignored", {"sampling": WebAnalyticsSampling(enabled=True)}, True),
+ ("sampling_factor_ignored", {"samplingFactor": 0.1}, True),
+ ]
+ )
+ def test_session_id_set_eligibility(self, _name: str, query_kwargs: dict, expected: bool):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner(**query_kwargs)
+ assert runner.should_use_session_id_set == expected
+
+ @parameterized.expand(
+ [
+ (
+ "event_test_filter",
+ [{"key": "$host", "type": "event", "operator": "exact", "value": "example.com"}],
+ True,
+ ),
+ (
+ "person_test_filter",
+ [{"key": "email", "type": "person", "operator": "not_icontains", "value": "@posthog.com"}],
+ True,
+ ),
+ ("cohort_test_filter", [{"key": "id", "type": "cohort", "value": 1}], False),
+ ]
+ )
+ def test_session_id_set_supports_event_and_person_test_account_filters(self, _name, filters, expected):
+ self.team.test_account_filters = filters
+ self.team.save()
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner(filterTestAccounts=True)
+ assert runner.should_use_session_id_set == expected
+
+ def test_session_id_set_with_test_filters_matches_join_path(self):
+ self._create_pageviews()
+ self.team.test_account_filters = [
+ {"key": "$pathname", "type": "event", "operator": "not_icontains", "value": "/docs"}
+ ]
+ self.team.save()
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ fast_runner = self._make_runner(filterTestAccounts=True)
+ assert fast_runner.should_use_session_id_set
+ fast_results = fast_runner.calculate().results
+ join_results = self._make_runner(filterTestAccounts=True).calculate().results
+
+ for fast, join in zip(fast_results, join_results):
+ assert fast.value == join.value, f"{fast.key}: {fast.value} != {join.value}"
+
+ def test_session_id_set_requires_team_allowlist(self):
+ runner = self._make_runner()
+ assert not runner.should_use_session_id_set
+
+ def test_session_id_set_pushes_id_filter_below_session_aggregation(self):
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner()
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(sessionIdPushdown=True),
+ )
+ sql, _ = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
+
+ # The rewrite is fail-open, so without this assertion a silent break would
+ # keep results correct while regressing the sessions scan back to
+ # aggregating every session in range.
+ assert "globalIn(raw_sessions.session_id_v7" in sql
+ # The pushdown must MOVE the id filter, not copy it: a retained outer
+ # predicate makes ClickHouse execute the identical GLOBAL IN id-subquery
+ # twice — one extra full filtered-events scan per query.
+ assert sql.count("globalIn(") == 1
+ # Full-shape lock on the generated SQL, complementing the targeted
+ # assertions above — any change to the rendered fast-path query shows up
+ # in review as a snapshot diff.
+ assert self.generalize_sql(sql) == self.snapshot
+
+ def test_session_id_set_executes_with_pushdown_modifier_and_tag(self):
+ # The fast path only pays off if _calculate actually flips the
+ # sessionIdPushdown modifier on the executed query — the rewrite fails
+ # open, so dropping the modifier wiring would keep every parity test
+ # green while silently regressing the sessions scan.
+ self._create_pageviews()
+ calls: list[tuple[Optional[str], Optional[HogQLQueryModifiers]]] = []
+
+ def record_calls(*args, **kwargs):
+ calls.append((kwargs.get("query_type"), kwargs.get("modifiers")))
+ return execute_hogql_query(*args, **kwargs)
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_overview.execute_hogql_query",
+ side_effect=record_calls,
+ ):
+ self._make_runner().calculate()
+
+ main_calls = [c for c in calls if c[0] == "web_overview_session_id_set_query"]
+ assert len(main_calls) == 1, calls
+ modifiers = main_calls[0][1]
+ assert modifiers is not None and modifiers.sessionIdPushdown is True
+
+ def test_session_id_set_falls_back_to_join_when_preflight_query_fails(self):
+ self._create_pageviews()
+ calls: list[Optional[str]] = []
+
+ def fail_preflight(*args, **kwargs):
+ if kwargs.get("query_type") == "web_overview_session_id_set_preflight":
+ raise Exception("clickhouse unavailable")
+ calls.append(kwargs.get("query_type"))
+ return execute_hogql_query(*args, **kwargs)
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ # The preflight executes from the shared base module; the main
+ # query from the runner module — both must be intercepted.
+ with (
+ patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.execute_hogql_query",
+ side_effect=fail_preflight,
+ ),
+ patch(
+ "products.web_analytics.backend.hogql_queries.web_overview.execute_hogql_query",
+ side_effect=fail_preflight,
+ ),
+ ):
+ runner = self._make_runner()
+ fallback_results = runner.calculate().results
+ assert runner._session_id_set_selectivity_ok is False
+
+ join_results = self._make_runner().calculate().results
+
+ # The fallback must be observable, not just an internal flag: the main
+ # query has to run as the plain join (results alone can't distinguish the
+ # branches — the two paths are result-equivalent by design).
+ assert calls == ["web_overview_query"]
+ for fallback, join in zip(fallback_results, join_results):
+ assert fallback.value == join.value, f"{fallback.key}: {fallback.value} != {join.value}"
+
+ def test_session_id_set_falls_back_to_join_when_filter_is_unselective(self):
+ self._create_pageviews()
+ calls: list[Optional[str]] = []
+
+ def record_calls(*args, **kwargs):
+ calls.append(kwargs.get("query_type"))
+ return execute_hogql_query(*args, **kwargs)
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.SESSION_ID_SET_MAX_MATCHING_SESSIONS",
+ 0,
+ ):
+ # The preflight executes from the shared base module; the main
+ # query from the runner module — record both.
+ with (
+ patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.execute_hogql_query",
+ side_effect=record_calls,
+ ),
+ patch(
+ "products.web_analytics.backend.hogql_queries.web_overview.execute_hogql_query",
+ side_effect=record_calls,
+ ),
+ ):
+ runner = self._make_runner()
+ gated_results = runner.calculate().results
+ assert runner._session_id_set_selectivity_ok is False
+
+ join_results = self._make_runner().calculate().results
+
+ # Over-cap must observably serve the join — this is the memory guard
+ # against shipping unbounded GLOBAL IN sets to shards.
+ assert calls == ["web_overview_session_id_set_preflight", "web_overview_query"]
+ for gated, join in zip(gated_results, join_results):
+ assert gated.value == join.value, f"{gated.key}: {gated.value} != {join.value}"
+
+
class TestWebOverviewNoJoinRolloutPercent(ClickhouseTestMixin, APIBaseTest):
def _runner(self) -> WebOverviewQueryRunner:
query = WebOverviewQuery(dateRange=DateRange(date_from="-7d"), properties=[])
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index 39ef8ae58742..98a1ab41d4e7 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -12,6 +12,7 @@ from posthog.test.base import (
flush_persons_and_events,
snapshot_clickhouse_queries,
)
+from unittest.mock import patch
from django.test import override_settings
@@ -32,10 +33,14 @@ from posthog.schema import (
SessionTableVersion,
WebAnalyticsOrderByDirection,
WebAnalyticsOrderByFields,
+ WebAnalyticsSampling,
WebStatsBreakdown,
WebStatsTableQuery,
)
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.printer import prepare_and_print_ast
+
from posthog.models import Element
from posthog.models.utils import uuid7
@@ -2589,3 +2594,210 @@ class TestWebStatsTableNoJoinFastPath(ClickhouseTestMixin, APIBaseTest):
def test_no_join_paths_requires_team_allowlist(self):
runner = self._make_runner()
assert not runner.query_strategy().startswith("stats_table_no_join")
+
+
+class TestWebStatsTableSessionIdSetFastPath(ClickhouseTestMixin, APIBaseTest):
+ QUERY_TIMESTAMP = "2025-01-29"
+
+ def _create_pageviews(self):
+ s1, s2, s3 = str(uuid7("2025-01-10")), str(uuid7("2025-01-11")), str(uuid7("2025-01-12"))
+ # One person per distinct_id, created once — a second `_create_person` for
+ # the same distinct_id mints a second person, and events then carry
+ # whichever person id existed at creation time, manufacturing the known
+ # per-event vs per-session visitor-count drift inside a single session.
+ with freeze_time("2025-01-10T09:00:00Z"):
+ _create_person(team_id=self.team.pk, distinct_ids=["user_a"])
+ with freeze_time("2025-01-12T09:00:00Z"):
+ _create_person(team_id=self.team.pk, distinct_ids=["user_b"])
+ for distinct_id, session_id, browser, path_timestamps in [
+ ("user_a", s1, "Chrome", [("/", "2025-01-10T10:00:00Z"), ("/pricing", "2025-01-10T10:05:00Z")]),
+ ("user_a", s2, "Chrome", [("/pricing", "2025-01-11T09:00:00Z")]),
+ ("user_b", s3, "Firefox", [("/", "2025-01-12T12:00:00Z"), ("/", "2025-01-12T12:00:30Z")]),
+ ]:
+ for pathname, ts in path_timestamps:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={
+ "$session_id": session_id,
+ "$pathname": pathname,
+ "$browser": browser,
+ "$current_url": f"https://example.com{pathname}",
+ },
+ )
+ # Time-on-page signal so the avg-time parity assertion is non-vacuous.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="user_a",
+ timestamp="2025-01-10T10:05:00Z",
+ properties={
+ "$session_id": s1,
+ "$pathname": "/pricing",
+ "$browser": "Chrome",
+ "$prev_pageview_pathname": "/",
+ "$prev_pageview_duration": 300,
+ },
+ )
+ # Matching event with a malformed (non-UUID) session id: the id set must
+ # drop it instead of aborting the whole query on a UUID conversion.
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="user_b",
+ timestamp="2025-01-12T13:00:00Z",
+ properties={"$session_id": "legacy-session", "$pathname": "/", "$browser": "Chrome"},
+ )
+ flush_persons_and_events()
+
+ def _make_runner(self, **query_kwargs) -> WebStatsTableQueryRunner:
+ query = WebStatsTableQuery(
+ dateRange=DateRange(date_from="2025-01-08", date_to="2025-01-15"),
+ breakdownBy=query_kwargs.pop("breakdownBy", WebStatsBreakdown.PAGE),
+ includeBounceRate=query_kwargs.pop("includeBounceRate", True),
+ properties=query_kwargs.pop(
+ "properties",
+ [EventPropertyFilter(key="$browser", operator=PropertyOperator.EXACT, value="Chrome")],
+ ),
+ **query_kwargs,
+ )
+ return WebStatsTableQueryRunner(team=self.team, query=query)
+
+ @parameterized.expand(
+ [
+ ("bounce_browser_filter", False, "$browser", "Chrome"),
+ ("avg_time_browser_filter", True, "$browser", "Chrome"),
+ # Only-$pathname filters leave the bounce side unfiltered (no id set);
+ # counts still filter events-side.
+ ("bounce_pathname_filter", False, "$pathname", "/pricing"),
+ ]
+ )
+ def test_session_id_set_paths_results_match_join_path(
+ self, _name: str, include_avg_time: bool, key: str, value: str
+ ):
+ self._create_pageviews()
+ properties = [EventPropertyFilter(key=key, operator=PropertyOperator.EXACT, value=value)]
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ fast_runner = self._make_runner(includeAvgTimeOnPage=include_avg_time, properties=properties)
+ assert fast_runner.query_strategy().startswith("stats_table_session_id_set")
+ fast_results = fast_runner.calculate().results
+
+ join_runner = self._make_runner(includeAvgTimeOnPage=include_avg_time, properties=properties)
+ assert join_runner.query_strategy().startswith("stats_table_path_bounce")
+ join_results = join_runner.calculate().results
+
+ assert sorted(r[0] for r in fast_results) == sorted(r[0] for r in join_results)
+ fast_by_path = {r[0]: r[1:] for r in fast_results}
+ join_by_path = {r[0]: r[1:] for r in join_results}
+ for path, join_row in join_by_path.items():
+ assert fast_by_path[path] == join_row, f"{path}: {fast_by_path[path]} != {join_row}"
+
+ @parameterized.expand(
+ [
+ ("event_property_filter", {}, True),
+ ("pathname_only_filter", {"properties": [EventPropertyFilter(key="$pathname", value="/")]}, True),
+ ("no_filters", {"properties": []}, False),
+ (
+ "session_property_filter",
+ {"properties": [SessionPropertyFilter(key="$channel_type", value="Direct", operator="exact")]},
+ False,
+ ),
+ ("conversion_goal", {"conversionGoal": CustomEventConversionGoal(customEventName="purchase")}, False),
+ ("non_page_breakdown", {"breakdownBy": WebStatsBreakdown.INITIAL_CHANNEL_TYPE}, False),
+ ("no_bounce_rate", {"includeBounceRate": False}, False),
+ # Sampling fields are accepted-but-ignored no-ops across web analytics,
+ # so they must not kick eligible queries off the session-id-set path.
+ ("sampling_enabled_ignored", {"sampling": WebAnalyticsSampling(enabled=True)}, True),
+ ("sampling_factor_ignored", {"samplingFactor": 0.1}, True),
+ ]
+ )
+ def test_session_id_set_paths_strategy_selection(self, _name: str, query_kwargs: dict, expected: bool):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner(**query_kwargs)
+ assert runner.query_strategy().startswith("stats_table_session_id_set") == expected
+
+ def test_session_id_set_paths_requires_team_allowlist(self):
+ runner = self._make_runner()
+ assert not runner.query_strategy().startswith("stats_table_session_id_set")
+
+ def test_session_id_set_paths_no_join_precedence(self):
+ # An unfiltered query on a no-join-enrolled team keeps the plain no-join
+ # strategy — the id-set variant is strictly for filtered queries.
+ with override_settings(
+ WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk],
+ WEB_ANALYTICS_NO_JOIN_TEAM_IDS=[self.team.pk],
+ ):
+ runner = self._make_runner(properties=[])
+ assert runner.query_strategy().startswith("stats_table_no_join")
+
+ @parameterized.expand(
+ [
+ # Non-pathname filter: bounce side gets the id set, pushed below the
+ # sessions GROUP BY exactly once (moved, not copied).
+ ("browser_filter", "$browser", "Chrome", 1),
+ # Only-$pathname filter: no id set at all — the bounce side must stay
+ # a plain unfiltered sessions scan, not pay an events scan for a
+ # filter that can't constrain it.
+ ("pathname_filter", "$pathname", "/pricing", 0),
+ ]
+ )
+ def test_session_id_set_paths_pushes_id_filter_below_session_aggregation(
+ self, _name: str, key: str, value: str, expected_global_in: int
+ ):
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner(
+ properties=[EventPropertyFilter(key=key, operator=PropertyOperator.EXACT, value=value)]
+ )
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(sessionIdPushdown=True),
+ )
+ sql, _ = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
+
+ assert sql.count("globalIn(raw_sessions.session_id_v7") == expected_global_in, sql
+ assert sql.count("globalIn(") == expected_global_in, sql
+
+ def test_session_id_set_paths_executes_with_pushdown_modifier_and_tag(self):
+ self._create_pageviews()
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ runner = self._make_runner()
+ original_execute = runner.paginator.execute_hogql_query
+ calls: list[tuple[Optional[str], Optional[HogQLQueryModifiers]]] = []
+
+ def record_calls(*args, **kwargs):
+ calls.append((kwargs.get("query_type"), kwargs.get("modifiers")))
+ return original_execute(*args, **kwargs)
+
+ with patch.object(runner.paginator, "execute_hogql_query", side_effect=record_calls):
+ runner.calculate()
+
+ assert [c[0] for c in calls] == ["stats_table_session_id_set_path_bounce_query"], calls
+ modifiers = calls[0][1]
+ assert modifiers is not None and modifiers.sessionIdPushdown is True
+
+ def test_session_id_set_paths_falls_back_to_join_when_filter_is_unselective(self):
+ self._create_pageviews()
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ with override_settings(WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk]):
+ with patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.SESSION_ID_SET_MAX_MATCHING_SESSIONS",
+ 0,
+ ):
+ runner = self._make_runner()
+ gated_results = runner.calculate().results
+ assert runner._session_id_set_selectivity_ok is False
+ # Over-cap must observably serve the join strategy.
+ assert runner.query_strategy() == "stats_table_path_bounce"
+
+ join_results = self._make_runner().calculate().results
+
+ assert gated_results == join_results
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 98561553245c..cc49238b47e9 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -30,8 +30,9 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.errors import QueryError
-from posthog.hogql.parser import parse_expr
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.property import action_to_expr, apply_path_cleaning, property_to_expr
+from posthog.hogql.query import execute_hogql_query
from posthog.caching.insights_api import BASE_MINIMUM_INSIGHT_REFRESH_INTERVAL, REDUCED_MINIMUM_INSIGHT_REFRESH_INTERVAL
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tag_value, tag_queries
@@ -62,6 +63,14 @@ WEB_ANALYTICS_NO_JOIN_SERVED = Counter(
["family"],
)
+# Ceiling on the number of matching session ids a session-id-set fast path may ship
+# to shards via GLOBAL IN. Cross-team prod validation: memory scales ~linearly at
+# ~190 MiB per million ids on the sessions side; the id-set shape beats the join at
+# 4-5M ids (3.8s/727MiB vs 6.8s/4.5GiB at 3.8M); the extrapolated crossover where
+# the shipped set stops paying is ~20M. 10M caps session-id-set memory at ~2 GiB —
+# under half the join's typical footprint — with margin before the crossover.
+SESSION_ID_SET_MAX_MATCHING_SESSIONS = 10_000_000
+
WebQueryNode = Union[
WebOverviewQuery,
WebStatsTableQuery,
@@ -241,6 +250,70 @@ class WebAnalyticsQueryRunner(AnalyticsQueryRunner[WAR], ABC):
# path for everyone on a team, so the rollout unit is the team, not the user.
return percent > 0 and self.team.pk % 100 < percent
+ def _session_id_set_common_eligibility(self) -> bool:
+ """Shared gates for the session-id-set fast paths (filtered two-scan shape).
+
+ A filter is only evaluable events-side when it's an event property filter
+ (user filters) or an event/person test-account filter (person props via
+ person-on-events). Session/cohort filters can't feed the id collection
+ and keep the join path. Runners add their own shape-specific gates on top.
+ """
+ if self.team.pk not in settings.WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS:
+ return False
+ if getattr(self.query, "conversionGoal", None):
+ return False
+ properties = getattr(self.query, "properties", None) or []
+ if not properties and not self._test_account_filters:
+ return False
+ if not all(isinstance(p, EventPropertyFilter) for p in properties):
+ return False
+ if not all(f.get("type") in ("event", "person") for f in self._test_account_filters):
+ return False
+ return True
+
+ def _run_session_id_set_preflight(self, filters: ast.Expr, query_type: str) -> bool:
+ """Preflight: is the filtered session-id set small enough to ship to shards?
+
+ A cheap count over the filtered events (materialized columns only) — the
+ events scan is work the id collection does anyway, so this bounds the
+ worst case at one extra sub-second query for eligible teams. Fails closed
+ to the join path on error.
+ """
+ count_query = parse_select(
+ """
+SELECT uniq(events.$session_id_uuid) AS matching_sessions
+FROM events
+WHERE and(
+ events.$session_id_uuid IS NOT NULL,
+ {event_type_expr},
+ {inside_timestamp_period},
+ {filters},
+)
+ """,
+ placeholders={
+ "event_type_expr": self.event_type_expr,
+ "inside_timestamp_period": self._periods_expression("timestamp"),
+ "filters": filters,
+ },
+ )
+ try:
+ response = execute_hogql_query(
+ query_type=query_type,
+ query=count_query,
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ )
+ matching = response.results[0][0] if response.results else None
+ if matching is None:
+ return False
+ return matching <= SESSION_ID_SET_MAX_MATCHING_SESSIONS
+ except Exception as e:
+ logger.exception("web_analytics_session_id_set_preflight_failed", error=e, query_type=query_type)
+ return False
+
@cached_property
def filters_eligibility_hash(self) -> Optional[str]:
"""Stable hash of the user-facing query inputs that would fragment a
@@ -609,14 +682,14 @@ class WebAnalyticsQueryRunner(AnalyticsQueryRunner[WAR], ABC):
def events_session_id_present(self) -> ast.Expr:
"""True when the event carries a usable session id.
- A missing `$session_id` materializes as an empty string, not NULL, so an
- `IS NOT NULL` check alone lets sessionless (server-side) events through.
- The join path excludes them implicitly (NULL session start fails the
- period HAVING); the no-join query shapes need this explicit guard.
+ Uses the nullable-UUID materialized column in both join modes: a missing
+ `$session_id` materializes as an empty string (not NULL) and a malformed
+ one isn't a UUID — both become NULL here and are excluded, which is
+ exactly what the join path does implicitly (their NULL session start
+ fails the period HAVING). The no-join query shapes need the explicit
+ guard to match.
"""
- if self.query.modifiers and self.query.modifiers.sessionsV2JoinMode == "uuid":
- return parse_expr("events.$session_id_uuid IS NOT NULL")
- return parse_expr("events.$session_id IS NOT NULL AND events.$session_id != ''")
+ return parse_expr("events.$session_id_uuid IS NOT NULL")
def map_columns(results, mapper: dict[int, typing.Callable]):
diff --git a/products/web_analytics/backend/hogql_queries/web_overview.py b/products/web_analytics/backend/hogql_queries/web_overview.py
index 7401d07c378a..4d5cf4bff048 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview.py
@@ -44,15 +44,93 @@ class WebOverviewQueryRunner(WebAnalyticsQueryRunner[WebOverviewQueryResponse]):
team_version = getattr(self.team, "web_analytics_pre_aggregated_tables_version", "v2")
self.use_v2_tables = team_version == "v2" if team_version else use_v2_tables
self.preaggregated_query_builder = WebOverviewPreAggregatedQueryBuilder(self)
+ # None = not yet checked (e.g. EXPLAIN paths); set by `_calculate` before execution.
+ self._session_id_set_selectivity_ok: Optional[bool] = None
def to_query(self) -> ast.SelectQuery:
if self.should_skip_session_join:
WEB_ANALYTICS_NO_JOIN_SERVED.labels(family="overview").inc()
return self.no_join_select
+ if self.should_use_session_id_set and self._session_id_set_selectivity_ok is not False:
+ # Count only executions whose preflight passed — `to_query` also runs for
+ # EXPLAIN/debug paths where selectivity was never checked (None).
+ if self._session_id_set_selectivity_ok:
+ WEB_ANALYTICS_NO_JOIN_SERVED.labels(family="overview_session_id_set").inc()
+ return self.session_id_set_select
return self.outer_select
+ def _check_session_id_set_selectivity(self) -> bool:
+ return self._run_session_id_set_preflight(
+ filters=property_to_expr(list(self.query.properties) + self._test_account_filters, team=self.team),
+ query_type="web_overview_session_id_set_preflight",
+ )
+
+ @cached_property
+ def should_use_session_id_set(self) -> bool:
+ """Whether a filtered query can run as two independent scans linked by an id set.
+
+ Applies when every filter is evaluable events-side (see
+ `_session_id_set_common_eligibility`): the events side evaluates the
+ filters directly, and the sessions side aggregates only the sessions
+ whose ids appear in a `SELECT DISTINCT $session_id` subquery over the
+ filtered events (rewritten below the per-session GROUP BY by
+ `build_direct_session_id_in_pushdown`, executing once via GLOBAL IN).
+ """
+ return self._session_id_set_common_eligibility()
+
+ @cached_property
+ def session_id_set_select(self) -> ast.SelectQuery:
+ """Filtered overview as two scans linked by the set of matching session ids.
+
+ Instead of joining events to sessions (which re-executes the sessions
+ subquery on every shard), run the filtered events scan first and collect
+ the distinct session ids it matches, then aggregate the sessions side
+ only over that id set. `build_direct_session_id_in_pushdown` rewrites the
+ `IN` into a GLOBAL IN on `raw_sessions.session_id_v7` below the
+ per-session GROUP BY, so the id collection executes once on the initiator
+ and the set is broadcast to shards. `_check_session_id_set_selectivity`
+ bounds the set size beforehand so we never ship a set too large to hold
+ in memory.
+ """
+ filters = property_to_expr(list(self.query.properties) + self._test_account_filters, team=self.team)
+ # The id set flows as the nullable-UUID materialized column: malformed
+ # `$session_id` strings become NULL and drop out of the set (the join path
+ # left such events unmatched; a string set would hit toUUID() and abort the
+ # whole query). Matching on `session_id_v7` keeps the flow UInt128 end to
+ # end — no string↔UUID conversion anywhere, in either join mode.
+ matching_session_ids = parse_select(
+ """
+SELECT DISTINCT events.$session_id_uuid AS session_id_uuid
+FROM events
+WHERE and(
+ events.$session_id_uuid IS NOT NULL,
+ {event_type_expr},
+ {inside_timestamp_period},
+ {filters},
+)
+ """,
+ placeholders={
+ "event_type_expr": self.event_type_expr,
+ "inside_timestamp_period": self._periods_expression("timestamp"),
+ "filters": filters,
+ },
+ )
+ sessions_id_filter = ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["sessions", "session_id_v7"]),
+ right=matching_session_ids,
+ )
+ return self._two_scan_select(events_extra_where=filters, sessions_extra_where=sessions_id_filter)
+
@cached_property
def no_join_select(self) -> ast.SelectQuery:
+ return self._two_scan_select()
+
+ def _two_scan_select(
+ self,
+ events_extra_where: Optional[ast.Expr] = None,
+ sessions_extra_where: Optional[ast.Expr] = None,
+ ) -> ast.SelectQuery:
"""Overview metrics from two independent scans, no events↔sessions join.
Column order must match ``outer_select`` — ``_calculate`` indexes rows
@@ -76,9 +154,11 @@ WHERE and(
{events_session_id_present},
{event_type_expr},
{inside_timestamp_period},
+ {events_extra_where},
)
""",
placeholders={
+ "events_extra_where": events_extra_where or ast.Constant(value=True),
"events_session_id_present": self.events_session_id_present,
"event_type_expr": self.event_type_expr,
"inside_timestamp_period": self._periods_expression("timestamp"),
@@ -116,9 +196,11 @@ FROM sessions
WHERE and(
{inside_start_timestamp_period},
or(sessions.$pageview_count > 0, sessions.$screen_count > 0),
+ {sessions_extra_where},
)
""",
placeholders={
+ "sessions_extra_where": sessions_extra_where or ast.Constant(value=True),
"inside_start_timestamp_period": self._periods_expression("$start_timestamp"),
"current_period": self._current_period_expression("$start_timestamp"),
"previous_sessions": (
@@ -247,16 +329,42 @@ CROSS JOIN {sessions_agg} AS sessions_agg
pre_aggregated_response = self.get_pre_aggregated_response()
+ # Preflight only when the main query will actually run — if the
+ # pre-aggregated builder already served the response, spending a
+ # filtered-events scan on selectivity would be pure waste (and would emit
+ # orphan preflight tags into query_log).
+ if self.should_use_session_id_set and not self.should_skip_session_join and not pre_aggregated_response:
+ self._session_id_set_selectivity_ok = self._check_session_id_set_selectivity()
+
+ execution_modifiers = self.modifiers
+ if (
+ self.should_use_session_id_set
+ and self._session_id_set_selectivity_ok is not False
+ and not self.should_skip_session_join
+ ):
+ # The session-id-set shape relies on `build_direct_session_id_in_pushdown`
+ # rewriting the id-set filter below the sessions GROUP BY; that rewrite
+ # is gated on the sessionIdPushdown modifier.
+ execution_modifiers = self.modifiers.model_copy() if self.modifiers else HogQLQueryModifiers()
+ execution_modifiers.sessionIdPushdown = True
+
response = (
execute_hogql_query(
- # Distinct tag for the fast path so query_log analysis doesn't need
- # to text-match the SQL shape (see /evaluating-web-analytics-performance).
- query_type="web_overview_no_join_query" if self.should_skip_session_join else "web_overview_query",
+ # Distinct tags per strategy so query_log analysis doesn't need to
+ # text-match the SQL shape (see /evaluating-web-analytics-performance).
+ # Cache warming prefix-matches web_overview_, so new tags stay warmed.
+ query_type=(
+ "web_overview_no_join_query"
+ if self.should_skip_session_join
+ else "web_overview_session_id_set_query"
+ if self.should_use_session_id_set and self._session_id_set_selectivity_ok is not False
+ else "web_overview_query"
+ ),
query=self.to_query(),
team=self.team,
user=self.user,
timings=self.timings,
- modifiers=self.modifiers,
+ modifiers=execution_modifiers,
limit_context=self.limit_context,
)
if not pre_aggregated_response
diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.py
index 90bfec6861a5..7be5f6c6a773 100644
--- a/products/web_analytics/dags/cache_warming.py
+++ b/products/web_analytics/dags/cache_warming.py
@@ -113,7 +113,7 @@ def queries_to_keep_fresh(
AND (
startsWith(query_type, 'stats_table_')
-- Overview strategy variants get their own tags (no_join today,
- -- two_phase next); prefix-match like stats_table_ so new variants
+ -- session_id_set next); prefix-match like stats_table_ so new variants
-- can't silently fall out of warming.
OR startsWith(query_type, 'web_overview_')
OR query_type IN (