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 for filtered lazy precompute inserts (#72094)

Lucas Ricoydcb9628aadd6
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index 8ebab7725e61..0edc884aea0b 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -18,6 +18,8 @@ import structlog
from clickhouse_driver.errors import ServerException
from prometheus_client import Counter
+from posthog.schema import HogQLQueryModifiers
+
from posthog.hogql import ast
from posthog.hogql.constants import (
MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY,
@@ -1193,6 +1195,7 @@ def ensure_precomputed(
spill_to_disk: bool = False,
wait_timeout_seconds: float | None = None,
stale_while_revalidate_seconds: float | None = None,
+ modifiers: HogQLQueryModifiers | None = None,
) -> LazyComputationResult:
"""
Ensure lazy-computed data exists for the given query and time range.
@@ -1246,6 +1249,11 @@ def ensure_precomputed(
background. Only for user-facing callers with a refresh
mechanism; background refreshers must leave this unset or they
would serve stale to themselves and never recompute.
+ modifiers: HogQL modifiers used when printing the INSERT's SELECT (defaults to
+ the team's default modifiers). NOT part of job identity — the job
+ hash covers only the substituted AST — so modifiers must never
+ change what the query computes, only how it executes (e.g.
+ `sessionIdPushdown`, which is semantics-preserving by design).
Returns:
ComputationResult with job_ids that can be used to query the data
@@ -1313,6 +1321,7 @@ def ensure_precomputed(
insert_query=insert_query,
table=table,
base_placeholders=base_placeholders,
+ modifiers=modifiers,
)
set_ch_query_started(job.id)
tag_kwargs: dict = {
@@ -1364,6 +1373,7 @@ def _build_manual_insert_sql(
insert_query: str | ast.SelectQuery,
table: LazyComputationTable,
base_placeholders: dict[str, ast.Expr] | None = None,
+ modifiers: HogQLQueryModifiers | None = None,
) -> tuple[str, dict]:
"""
Build INSERT SQL for manual lazy computation.
@@ -1413,7 +1423,7 @@ def _build_manual_insert_sql(
team=team,
enable_select_queries=True,
limit_top_select=False,
- modifiers=create_default_modifiers_for_team(team),
+ modifiers=modifiers if modifiers is not None else create_default_modifiers_for_team(team),
bypass_warehouse_access_control=True,
)
select_sql, _ = prepare_and_print_ast(
diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
index 0c0a6ad19ee8..9f25a54f3cb7 100644
--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
@@ -863,6 +863,50 @@ class TestBuildManualInsertSQL(BaseTest):
assert "2024-01-01" in sql
assert "2024-01-02" in sql
+ def test_uses_provided_modifiers_when_printing(self):
+ # Callers (web analytics session-id-set inserts) pass modifiers that change the
+ # execution plan the printer emits; dropping the pass-through would silently
+ # revert those inserts to the unoptimized shape while all results stay equal.
+ from posthog.schema import HogQLQueryModifiers, SessionTableVersion
+
+ job = PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash="test_hash",
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 2, tzinfo=UTC),
+ status=PreaggregationJob.Status.PENDING,
+ expires_at=django_timezone.now() + timedelta(days=7),
+ )
+ sessions_query = """
+ SELECT toStartOfHour(sessions.$start_timestamp) AS time_window_start,
+ uniqState(sessions.session_id) AS uniq_sessions_state
+ FROM sessions
+ WHERE and(
+ sessions.$start_timestamp >= {time_window_min},
+ sessions.$start_timestamp < {time_window_max},
+ sessions.session_id_v7 IN (SELECT DISTINCT events.$session_id_uuid FROM events)
+ )
+ GROUP BY time_window_start
+ """
+ modifiers = HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2, sessionIdPushdown=True)
+
+ with_modifiers, _ = _build_manual_insert_sql(
+ team=self.team,
+ job=job,
+ insert_query=sessions_query,
+ table=LazyComputationTable.PREAGGREGATION_RESULTS,
+ modifiers=modifiers,
+ )
+ without_modifiers, _ = _build_manual_insert_sql(
+ team=self.team,
+ job=job,
+ insert_query=sessions_query,
+ table=LazyComputationTable.PREAGGREGATION_RESULTS,
+ )
+
+ assert "globalIn(raw_sessions.session_id_v7" in with_modifiers
+ assert "globalIn(raw_sessions.session_id_v7" not in without_modifiers
+
def test_accepts_custom_placeholders(self):
job = PreaggregationJob.objects.create(
team=self.team,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
index f6ea3357dcf6..45d93550299e 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
@@ -1,4 +1,5 @@
import uuid
+from datetime import UTC, datetime
import unittest
from freezegun import freeze_time
@@ -21,6 +22,8 @@ from posthog.schema import (
WebOverviewQuery,
)
+from posthog.hogql import ast
+
from posthog.clickhouse.client import sync_execute
from posthog.models.utils import uuid7
@@ -694,3 +697,167 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert delay.call_count == 1
assert delay.call_args.kwargs["team_id"] == self.team.pk
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestWebOverviewSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):
+ """The filtered-insert chooser and the id-set insert's parity with the join insert."""
+
+ def _make_runner(self, properties: list | None = None, filter_test_accounts: bool = False):
+ query = WebOverviewQuery(
+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-07"),
+ properties=properties or [],
+ filterTestAccounts=filter_test_accounts,
+ useWebAnalyticsPrecompute=True,
+ )
+ return WebOverviewQueryRunner(team=self.team, query=query)
+
+ @parameterized.expand(
+ [
+ ("unfiltered", [], False, None, "no_join"),
+ (
+ "event_filter_allowlisted",
+ [EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)],
+ False,
+ True,
+ "session_id_set",
+ ),
+ (
+ "cohort_test_filter",
+ [EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)],
+ True, # team test filters include a cohort filter (set below)
+ True,
+ "join",
+ ),
+ (
+ "event_filter_not_allowlisted",
+ [EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)],
+ False,
+ False,
+ "join",
+ ),
+ ]
+ )
+ def test_insert_template_chooser(self, _name, properties, cohort_test_filter, allowlisted, expected):
+ from products.web_analytics.backend.hogql_queries import web_overview_lazy_precompute as mod
+
+ if cohort_test_filter:
+ from products.cohorts.backend.models.cohort import Cohort
+
+ cohort = Cohort.objects.create(team=self.team, name="test-accounts", groups=[], is_static=True)
+ self.team.test_account_filters = [{"key": "id", "type": "cohort", "value": cohort.pk}]
+ self.team.save()
+
+ allowlist = [self.team.pk] if allowlisted else []
+ captured: dict = {}
+
+ def capture(**kwargs):
+ captured.update(kwargs)
+ return LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)
+
+ with override_settings(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],
+ WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=allowlist,
+ ):
+ runner = self._make_runner(properties=properties, filter_test_accounts=cohort_test_filter)
+ with patch.object(mod, "web_ensure_precomputed", side_effect=capture):
+ mod.ensure_web_overview_precomputed(
+ runner, datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 7, tzinfo=UTC)
+ )
+
+ template = captured["insert_query"]
+ modifiers = captured["modifiers"]
+ if expected == "no_join":
+ assert template is mod.NO_JOIN_INSERT_QUERY_TEMPLATE
+ assert modifiers is None
+ elif expected == "session_id_set":
+ assert template is mod.SESSION_ID_SET_INSERT_QUERY_TEMPLATE
+ assert template.count("session_id_v7 IN") == 1
+ assert modifiers is not None and modifiers.sessionIdPushdown is True
+ else:
+ assert template is mod.JOIN_INSERT_QUERY_TEMPLATE
+ assert modifiers is None
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_filtered_insert_matches_join_insert(self):
+ """The id-set insert must store the same finalized metrics as the join insert
+ for the same filtered key — the whole point of the shape swap. Compares the
+ two templates' SELECT output directly (finalized with -Merge) instead of the
+ distributed INSERT round trip, which is flaky (see the skip above)."""
+ from posthog.hogql.context import HogQLContext
+ from posthog.hogql.modifiers import create_default_modifiers_for_team
+ from posthog.hogql.parser import parse_select
+ from posthog.hogql.printer import prepare_and_print_ast
+
+ from products.web_analytics.backend.hogql_queries import web_overview_lazy_precompute as mod
+ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ SESSION_FORWARD_PAD_MINUTES,
+ events_session_id_expr,
+ test_account_filter_expr,
+ user_filter_expr,
+ )
+
+ # Sessions on both sides of the filter plus a malformed session id. The v7
+ # ids embed the first-event timestamp — the no-join shape buckets by the
+ # embedded time, so a midnight-embedded id would bucket differently from
+ # the join shape by construction.
+ s1, s2 = str(uuid7("2024-01-02T10:00:00")), str(uuid7("2024-01-03T11:00:00"))
+ _create_person(team_id=self.team.pk, distinct_ids=["p1"])
+ _create_person(team_id=self.team.pk, distinct_ids=["p2"])
+ for sid, did, ts, host, n_views in [
+ (s1, "p1", "2024-01-02T10:00:00Z", "example.com", 2),
+ (s2, "p2", "2024-01-03T11:00:00Z", "other.com", 1),
+ ]:
+ for i in range(n_views):
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=did,
+ timestamp=ts[:-1] + f"" if i == 0 else ts,
+ properties={"$session_id": sid, "$host": host},
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="p1",
+ timestamp="2024-01-02T12:00:00Z",
+ properties={"$session_id": "legacy-session", "$host": "example.com"},
+ )
+
+ with override_settings(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],
+ WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk],
+ ):
+ runner = self._make_runner(
+ properties=[EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)]
+ )
+ placeholders = {
+ "events_session_id": events_session_id_expr(runner),
+ "event_type_filter": runner.event_type_expr,
+ "user_filter": user_filter_expr(runner),
+ "test_account_filter": test_account_filter_expr(runner),
+ "pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
+ "time_window_min": ast.Constant(value=datetime(2024, 1, 1, tzinfo=UTC)),
+ "time_window_max": ast.Constant(value=datetime(2024, 1, 7, tzinfo=UTC)),
+ }
+
+ def run_template(template: str, pushdown: bool):
+ modifiers = create_default_modifiers_for_team(self.team)
+ modifiers.sessionIdPushdown = pushdown
+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, modifiers=modifiers)
+ inner = parse_select(template, placeholders=dict(placeholders))
+ sql, _ = prepare_and_print_ast(inner, context=context, dialect="clickhouse")
+ merged = f"""
+ SELECT formatDateTime(time_window_start, '%%Y-%%m-%%d %%H:%%i:%%S') AS window_key,
+ uniqMerge(uniq_users_state), uniqMerge(uniq_sessions_state),
+ sumMerge(sum_pageviews_state),
+ round(avgMerge(avg_duration_state), 4), round(avgMerge(avg_bounce_state), 4)
+ FROM ({sql}) GROUP BY time_window_start ORDER BY time_window_start
+ """
+ return sync_execute(merged, context.values, team_id=self.team.pk)
+
+ join_rows = run_template(mod.JOIN_INSERT_QUERY_TEMPLATE, pushdown=False)
+ id_set_rows = run_template(mod.SESSION_ID_SET_INSERT_QUERY_TEMPLATE, pushdown=True)
+
+ assert join_rows, "join insert produced no rows — fixture broken"
+ assert id_set_rows == join_rows
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
index 24cf6ad87067..6e69344fe754 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py
@@ -945,3 +945,216 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# no-compare sentinel, which would defeat the pruning entirely).
expected_min = prev_start if compare else cur_start
assert bounds == {"min": expected_min, "max": cur_end}
+
+
+class _SessionIdInCounter:
+ """Counts (GLOBAL pair-tuple INs, plain single-column session-id INs) in a tree."""
+
+ def __init__(self) -> None:
+ self.pair = 0
+ self.single = 0
+
+ def count(self, node: ast.AST) -> tuple[int, int]:
+ from posthog.hogql.visitor import TraversingVisitor
+
+ counter = self
+
+ class Visitor(TraversingVisitor):
+ def visit_compare_operation(self, cmp: ast.CompareOperation) -> None:
+ if cmp.op == ast.CompareOperationOp.GlobalIn and isinstance(cmp.left, ast.Tuple):
+ counter.pair += 1
+ elif (
+ cmp.op == ast.CompareOperationOp.In
+ and isinstance(cmp.left, ast.Field)
+ and cmp.left.chain[-1] == "session_id_v7"
+ ):
+ counter.single += 1
+ super().visit_compare_operation(cmp)
+
+ Visitor().visit(node)
+ return self.pair, self.single
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestWebStatsPathsSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):
+ """The filtered-insert chooser and the pruned-join insert's parity with the plain
+ join insert. Paths cannot use a plain session-id set: the join attributes bounce
+ per (session, path) from filtered events, so the filtered variant keeps the join's
+ exact per-path attribution — but with the sessions side pruned to the id-set. The
+ parity fixture encodes the divergence a plain id-set would introduce (a session whose
+ only matching event is NOT on its entry path) and asserts the pruned-join avoids it."""
+
+ HOST_FILTER = [EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)]
+
+ def _make_runner(self, **kwargs) -> WebStatsTableQueryRunner:
+ query = WebStatsTableQuery(
+ dateRange=DateRange(date_from="2024-01-01", date_to="2024-01-07"),
+ properties=kwargs.pop("properties", []),
+ breakdownBy=kwargs.pop("breakdown_by", WebStatsBreakdown.PAGE),
+ includeBounceRate=True,
+ useWebAnalyticsPrecompute=True,
+ **kwargs,
+ )
+ return WebStatsTableQueryRunner(team=self.team, query=query)
+
+ @parameterized.expand(
+ [
+ ("unfiltered_page", [], WebStatsBreakdown.PAGE, True, "no_join"),
+ ("filtered_page_allowlisted", HOST_FILTER, WebStatsBreakdown.PAGE, True, "pruned_join"),
+ ("filtered_page_not_allowlisted", HOST_FILTER, WebStatsBreakdown.PAGE, False, "join"),
+ ("filtered_initial_page", HOST_FILTER, WebStatsBreakdown.INITIAL_PAGE, True, "join"),
+ ]
+ )
+ def test_insert_template_chooser(self, _name, properties, breakdown_by, allowlisted, expected):
+ from datetime import UTC, datetime
+
+ from posthog.hogql.placeholders import find_placeholders
+
+ from products.web_analytics.backend.hogql_queries import web_stats_paths_lazy_precompute as mod
+
+ captured: dict = {}
+
+ def capture(**kwargs):
+ captured.update(kwargs)
+ return LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)
+
+ with override_settings(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],
+ WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk] if allowlisted else [],
+ ):
+ runner = self._make_runner(properties=properties, breakdown_by=breakdown_by)
+ with patch.object(mod, "web_ensure_precomputed", side_effect=capture):
+ mod.ensure_web_stats_paths_precomputed(
+ runner, datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 7, tzinfo=UTC)
+ )
+
+ insert_query = captured["insert_query"]
+ modifiers = captured["modifiers"]
+ # Default sort is DESC visitors -> the capped variants are selected.
+ if expected == "no_join":
+ assert insert_query is mod.NO_JOIN_INSERT_QUERY_TEMPLATE_CAPPED
+ assert modifiers is None
+ elif expected == "pruned_join":
+ assert isinstance(insert_query, ast.SelectQuery)
+ assert modifiers is not None and modifiers.sessionIdPushdown is True
+ # Only the framework-managed windows are left for per-job substitution.
+ assert captured["placeholders"] == {}
+ leftover = {str(c[0]) for c in find_placeholders(insert_query).placeholder_fields}
+ assert leftover == {"time_window_min", "time_window_max"}
+ # Exactly one single-column session-id IN (rewritten onto the pruned
+ # raw_sessions build side at print time) and no tuple pair IN.
+ assert _SessionIdInCounter().count(insert_query) == (0, 1)
+ else:
+ assert insert_query is mod.INSERT_QUERY_TEMPLATE_CAPPED
+ assert "session_id_v7 IN" not in insert_query
+ assert modifiers is None
+
+ @freeze_time("2024-01-15T12:00:00Z")
+ def test_filtered_insert_matches_join_insert(self):
+ """The pruned-join insert must store the same finalized per-path metrics as the
+ plain join insert for the same filtered key. The fixture carries the divergence
+ case: s1 enters /landing but its only filter-matching event is on /pricing —
+ a plain session-id set admits s1's bounce to /landing (asserted below, so
+ the fixture can't silently go vacuous); the pruned-join must not."""
+ from datetime import UTC, datetime
+
+ from posthog.hogql.context import HogQLContext
+ from posthog.hogql.modifiers import create_default_modifiers_for_team
+ from posthog.hogql.placeholders import replace_placeholders
+ from posthog.hogql.printer import prepare_and_print_ast
+
+ from posthog.clickhouse.client import sync_execute
+
+ from products.web_analytics.backend.hogql_queries import web_stats_paths_lazy_precompute as mod
+ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ build_insert_select_ast,
+ with_insert_session_id_set_filter,
+ )
+
+ s1 = str(uuid7("2024-01-02T10:00:00"))
+ s2 = str(uuid7("2024-01-02T11:00:00"))
+ s3 = str(uuid7("2024-01-02T10:10:00"))
+ _create_person(team_id=self.team.pk, distinct_ids=["p1"])
+ _create_person(team_id=self.team.pk, distinct_ids=["p2"])
+ _create_person(team_id=self.team.pk, distinct_ids=["p3"])
+ # s1: enters /landing (no plan), matches the filter only on /pricing; bounce=0.
+ # s3: same hour, single-pageview /landing with plan=pro — its filtered event
+ # creates the (10:00, /landing) cell, so join bounce there is avg(s3)=1.0 while
+ # a plain session-id set admits s1's entry-path bounce too -> avg(0, 1)=0.5.
+ # s2: control session in another hour, matched on its entry path.
+ for did, ts, sid, path, props in [
+ ("p1", "2024-01-02T10:00:00Z", s1, "/landing", {}),
+ ("p1", "2024-01-02T10:05:00Z", s1, "/pricing", {"plan": "pro"}),
+ ("p3", "2024-01-02T10:10:00Z", s3, "/landing", {"plan": "pro"}),
+ ("p2", "2024-01-02T11:00:00Z", s2, "/landing", {"plan": "pro"}),
+ ("p1", "2024-01-02T12:00:00Z", "legacy-session", "/landing", {"plan": "pro"}),
+ ]:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=did,
+ timestamp=ts,
+ properties={
+ "$session_id": sid,
+ "$host": "example.com",
+ "$pathname": path,
+ "$current_url": f"https://example.com{path}",
+ **props,
+ },
+ )
+
+ with override_settings(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],
+ WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk],
+ ):
+ runner = self._make_runner(
+ properties=[EventPropertyFilter(key="plan", value="pro", operator=PropertyOperator.EXACT)]
+ )
+ placeholders = {
+ "events_session_id": mod._events_session_id_expr(runner),
+ "breakdown_value_expr": mod._breakdown_value_expr(runner),
+ "entry_breakdown_value_expr": mod._entry_breakdown_value_expr(runner),
+ "entry_breakdown_value_sessions_expr": mod._entry_breakdown_value_sessions_expr(runner),
+ "event_type_filter": runner.event_type_expr,
+ "user_filter": host_filter_expr(runner.query.properties or [], team=self.team),
+ "test_account_filter": _test_account_filter_expr(
+ test_account_filters=runner._test_account_filters, team=self.team
+ ),
+ "pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
+ }
+ windows = {
+ "time_window_min": ast.Constant(value=datetime(2024, 1, 1, tzinfo=UTC)),
+ "time_window_max": ast.Constant(value=datetime(2024, 1, 7, tzinfo=UTC)),
+ }
+
+ def run_template(template, pushdown: bool):
+ modifiers = create_default_modifiers_for_team(self.team)
+ modifiers.sessionIdPushdown = pushdown
+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True, modifiers=modifiers)
+ inner: ast.Expr
+ if isinstance(template, str):
+ inner = parse_select(template, placeholders={**placeholders, **windows})
+ else:
+ inner = replace_placeholders(template, dict(windows))
+ assert isinstance(inner, ast.SelectQuery)
+ sql, _ = prepare_and_print_ast(inner, context=context, dialect="clickhouse")
+ merged = f"""
+ SELECT formatDateTime(time_window_start, '%%Y-%%m-%%d %%H:%%i:%%S') AS window_key,
+ breakdown_value,
+ uniqMerge(uniq_users_state), sumMerge(sum_pageviews_state),
+ round(avgMerge(avg_bounce_state), 4)
+ FROM ({sql}) GROUP BY time_window_start, breakdown_value
+ ORDER BY time_window_start, breakdown_value
+ """
+ return sync_execute(merged, context.values, team_id=self.team.pk)
+
+ pruned_ast = build_insert_select_ast(mod.PRUNED_JOIN_INSERT_QUERY_TEMPLATE, placeholders)
+ join_rows = run_template(mod.INSERT_QUERY_TEMPLATE, pushdown=False)
+ plain_set_rows = run_template(
+ with_insert_session_id_set_filter(mod.NO_JOIN_INSERT_QUERY_TEMPLATE), pushdown=True
+ )
+ pruned_rows = run_template(pruned_ast, pushdown=True)
+
+ assert join_rows, "join insert produced no rows — fixture broken"
+ assert plain_set_rows != join_rows, "fixture no longer exercises the cross-path divergence"
+ assert pruned_rows == join_rows
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
index 5f6c8168b368..b58aae8ebca0 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
@@ -24,8 +24,11 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.placeholders import find_placeholders
from posthog.hogql.property import property_to_expr
from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
from posthog.models.team import Team
@@ -310,6 +313,107 @@ def is_constant_true(expr: ast.Expr) -> bool:
return isinstance(expr, ast.Constant) and expr.value is True
+# The line every no-join insert template's sessions-side WHERE ends with; the
+# session-id-set variants splice their id filter right after it.
+_SESSIONS_SIDE_ANCHOR = "or(sessions.$pageview_count > 0, sessions.$screen_count > 0),"
+
+# Sessions-side id-set filter for FILTERED insert keys: restrict the sessions scan
+# to sessions with at least one event matching the key's filters — the same session
+# membership the join insert template produces (full filters; a session qualifies
+# via ANY matching event in the padded window). `build_direct_session_id_in_pushdown`
+# rewrites the IN below the per-session GROUP BY when the caller passes modifiers
+# with `sessionIdPushdown=True` to `ensure_precomputed`.
+#
+# No selectivity preflight, deliberately. The concern a preflight would guard —
+# a broad filter putting a whole day of a huge team's sessions into the GLOBAL IN
+# set — is bounded and strictly cheaper than the alternative it replaces: the id
+# set costs ~190 MiB per million ids, a single day of the largest teams runs
+# low-single-digit millions of sessions, and the SAME key on the JOIN template
+# builds per-shard hash tables of those sessions PLUS their events (prod-measured
+# 4-8x the memory and read of the id-set shape). Falling back to the join on
+# "set too big" would therefore increase resource use, not cap it. Distinct-key
+# amplification (minting cache keys via filter values) is a property of filtered
+# precompute as such, not of this shape, and is bounded by the same controls as
+# today: the `WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS` allowlist, per-insert memory
+# limits (`_get_insert_settings`), and the OOM-pin machinery capping repeat
+# offenders to 1-day windows.
+_INSERT_SESSION_ID_SET_FILTER_SQL = """sessions.session_id_v7 IN (
+ SELECT DISTINCT events.$session_id_uuid
+ FROM events
+ WHERE and(
+ events.$session_id_uuid IS NOT NULL,
+ equals(bitAnd(bitShiftRight(events.$session_id_uuid, 76), 15), 7),
+ {event_type_filter},
+ timestamp >= {time_window_min},
+ timestamp < ({time_window_max} + toIntervalMinute({pad_minutes})),
+ {user_filter},
+ {test_account_filter}
+ )
+ ),"""
+
+
+def with_insert_session_id_set_filter(no_join_template: str) -> str:
+ """Derive the filtered (session-id-set) variant of a no-join insert template.
+
+ Splices the id-set filter into the sessions-side WHERE, leaving the source
+ template untouched — the unfiltered variant must stay byte-identical so
+ existing unfiltered jobs keep their AST hash and are not re-keyed."""
+ assert no_join_template.count(_SESSIONS_SIDE_ANCHOR) == 1, "no-join template sessions-side anchor drifted"
+ return no_join_template.replace(
+ _SESSIONS_SIDE_ANCHOR,
+ _SESSIONS_SIDE_ANCHOR + "\n " + _INSERT_SESSION_ID_SET_FILTER_SQL,
+ )
+
+
+class _PartialPlaceholderReplacer(CloningVisitor):
+ """Substitute only the given placeholders, leaving unknown ones (the
+ framework-managed `{time_window_min}`/`{time_window_max}`) as `ast.Placeholder`
+ nodes for `ensure_precomputed` to fill per job."""
+
+ def __init__(self, placeholders: dict[str, ast.Expr]) -> None:
+ super().__init__()
+ self.placeholders = placeholders
+
+ def visit_placeholder(self, node: ast.Placeholder) -> ast.Expr:
+ chain = node.chain
+ if chain is not None and len(chain) == 1 and str(chain[0]) in self.placeholders:
+ return clone_expr(self.placeholders[str(chain[0])])
+ return super().visit_placeholder(node)
+
+
+class _GlobalizeSessionTupleIn(TraversingVisitor):
+ """Upgrade `(sessions.session_id_v7, ...) IN (subquery)` to GLOBAL IN.
+
+ HogQL has no grammar for `GLOBAL IN`, and the sessions_v2 pushdown rewrite
+ only handles the single-column `session_id_v7 IN` form — without the upgrade
+ a distributed read would execute the tuple's right-side subquery once per
+ shard, which is exactly the amplification the id-set shape exists to avoid."""
+
+ def visit_compare_operation(self, node: ast.CompareOperation) -> None:
+ if (
+ node.op == ast.CompareOperationOp.In
+ and isinstance(node.left, ast.Tuple)
+ and len(node.left.exprs) > 0
+ and isinstance(node.left.exprs[0], ast.Field)
+ and node.left.exprs[0].chain[-1] == "session_id_v7"
+ ):
+ node.op = ast.CompareOperationOp.GlobalIn
+ super().visit_compare_operation(node)
+
+
+def build_insert_select_ast(template: str, placeholders: dict[str, ast.Expr]) -> ast.SelectQuery:
+ """Parse an insert template into the `ast.SelectQuery` form of `ensure_precomputed`'s
+ `insert_query`, with every placeholder except the framework-managed time windows
+ substituted, and session-id tuple INs upgraded to GLOBAL IN (no HogQL grammar for it)."""
+ parsed = parse_select(template)
+ node = _PartialPlaceholderReplacer(placeholders).visit(parsed)
+ assert isinstance(node, ast.SelectQuery)
+ _GlobalizeSessionTupleIn().visit(node)
+ leftover = {str(chain[0]) for chain in find_placeholders(node).placeholder_fields}
+ assert leftover <= {"time_window_min", "time_window_max"}, f"unsubstituted placeholders: {leftover}"
+ return node
+
+
def user_filter_expr(runner: LazyPrecomputeRunner) -> ast.Expr:
"""Build the AST expression that gets substituted into the INSERT's WHERE clause.
diff --git a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
index 03fbb1950958..0dc1bd8a6d01 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
@@ -5,7 +5,10 @@ from typing import TYPE_CHECKING, Optional
import structlog
from prometheus_client import Counter
+from posthog.schema import HogQLQueryModifiers
+
from posthog.hogql import ast
+from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (
@@ -30,6 +33,7 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute
is_constant_true,
test_account_filter_expr,
user_filter_expr,
+ with_insert_session_id_set_filter,
)
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
handle_stale_served,
@@ -76,11 +80,13 @@ _check_lazy_precompute_eligible = check_common_eligible
# sides): the events side derives the hour bucket from the v7-embedded timestamp,
# which is garbage for v4/custom UUIDs — the join shape bucketed those via real
# session timestamps, so excluding them symmetrically keeps both sides consistent.
-# Filtered cache keys (a `$host` user filter or applied test-account filters) keep the
-# join shape below: those filters constrain which sessions qualify and can only be
-# evaluated on the events side, so the two-scan template would cache wrong session
-# metrics for them. Unfiltered keys — the overwhelming majority — use the no-join
-# template: events self-attribute to the session-start hour via the UUIDv7 timestamp
+# Filtered cache keys take the two-scan shape too when their filters are
+# events-evaluable (allowlisted teams; see the chooser in
+# `ensure_web_overview_precomputed`): the sessions side is restricted to the
+# session-id set collected from the filtered events scan, pushed below the
+# per-session GROUP BY via the `sessionIdPushdown` modifier. Cohort/session
+# filters keep the join shape — they can't feed the id collection. Unfiltered
+# keys — the overwhelming majority — use the plain no-join template: events self-attribute to the session-start hour via the UUIDv7 timestamp
# embedded in the session id, and duration/bounce come straight from the sessions
# table (which also makes the forward-pad hack unnecessary on that side, since
# raw_sessions already holds complete-session state).
@@ -164,6 +170,9 @@ LEFT JOIN (
"""
+SESSION_ID_SET_INSERT_QUERY_TEMPLATE = with_insert_session_id_set_filter(NO_JOIN_INSERT_QUERY_TEMPLATE)
+
+
def ensure_web_overview_precomputed(
runner: "WebOverviewQueryRunner",
time_range_start: datetime,
@@ -179,15 +188,29 @@ def ensure_web_overview_precomputed(
is_unfiltered = all(is_constant_true(placeholders[key]) for key in ("user_filter", "test_account_filter"))
+ # Filtered keys whose filters are events-evaluable (allowlisted teams, event
+ # property user filters, event/person test filters) take the two-scan shape
+ # with a session-id-set link; anything else keeps the join template.
+ modifiers: Optional[HogQLQueryModifiers] = None
+ if is_unfiltered:
+ insert_query = NO_JOIN_INSERT_QUERY_TEMPLATE
+ elif runner._session_id_set_common_eligibility():
+ insert_query = SESSION_ID_SET_INSERT_QUERY_TEMPLATE
+ modifiers = create_default_modifiers_for_team(runner.team)
+ modifiers.sessionIdPushdown = True
+ else:
+ insert_query = JOIN_INSERT_QUERY_TEMPLATE
+
return web_ensure_precomputed(
team=runner.team,
- insert_query=NO_JOIN_INSERT_QUERY_TEMPLATE if is_unfiltered else JOIN_INSERT_QUERY_TEMPLATE,
+ insert_query=insert_query,
time_range_start=time_range_start,
time_range_end=time_range_end,
ttl_seconds=LAZY_TTL_SECONDS,
table=LazyComputationTable.WEB_OVERVIEW_PREAGGREGATED,
placeholders=placeholders,
query_type="web_overview_lazy_insert",
+ modifiers=modifiers,
)
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
index 5695f68b5912..9dfbdd3595bb 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
@@ -25,6 +25,7 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
@@ -34,7 +35,10 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
LazyComputationResult,
LazyComputationTable,
)
-from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import is_constant_true
+from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ build_insert_select_ast,
+ is_constant_true,
+)
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
LAZY_TTL_SECONDS,
SESSION_FORWARD_PAD_MINUTES,
@@ -424,6 +428,98 @@ WHERE breakdown_rank <= """ + str(PATHS_TOP_K)
INSERT_QUERY_TEMPLATE_CAPPED = "WITH per_window AS (" + _PER_WINDOW_AGG_SQL + _CAPPED_WRAPPER
NO_JOIN_INSERT_QUERY_TEMPLATE_CAPPED = "WITH per_window AS (" + _NO_JOIN_PER_WINDOW_AGG_SQL + _CAPPED_WRAPPER
+# Pruned-join variant for FILTERED PAGE keys. Paths bounce must attribute per
+# (session, path) — a session's bounce lands on its entry path only when it had a
+# matching event ON that path — so the events↔sessions association must be kept at
+# row level (a two-scan session-id set can't reproduce it; a global id set admits
+# the bounce whenever the session matched anywhere, ~2% relative bounce drift on
+# prod). This template keeps the join's EXACT semantics: the outer
+# `if(equals(breakdown_value, entry_breakdown_value), is_bounce, NULL)` is the same
+# per-path attribution the JOIN template uses.
+#
+# The win over the plain JOIN template: instead of HogQL's implicit events→sessions
+# join reading ALL sessions in range per shard (the read amplification #70847
+# removed for live queries), the sessions side is an explicit `FROM sessions`
+# subquery pruned to the id-set. `sessionIdPushdown` rewrites the single-column
+# `session_id_v7 IN (…)` onto `raw_sessions.session_id_v7` below the per-session
+# GROUP BY, and HogQL globalizes the events↔sessions join automatically, so the
+# small per-session summary (entry path, bounce, start) is broadcast once and
+# probed by events. Prod (team 2, 1 day): ~1.9s / 1.1 GiB / 22 GiB read vs the
+# JOIN template's ~3.7s / 1.7 GiB / 45 GiB — faster and lighter on every axis.
+#
+# The IN is single-column, so unlike the earlier pair-set shape this needs no tuple
+# GLOBAL-IN upgrade; it still goes through the AST-input path (`build_insert_select_ast`)
+# because the explicit join + person access does not resolve through `parse_select`
+# with inline placeholders. INNER (not LEFT) join drops non-uuidv7 sessions, matching
+# the no-join / session-id-set shapes already shipped for this feature.
+_PRUNED_JOIN_PER_WINDOW_AGG_SQL = """
+SELECT
+ toStartOfHour(start_timestamp) AS time_window_start,
+ breakdown_value AS breakdown_value,
+ uniqState(session_person_id) AS uniq_users_state,
+ sumState(assumeNotNull(toInt(filtered_pageview_count))) AS sum_pageviews_state,
+ avgState(
+ if(
+ equals(breakdown_value, entry_breakdown_value),
+ toFloat(is_bounce),
+ NULL
+ )
+ ) AS avg_bounce_state
+FROM (
+ SELECT
+ any(events.person_id) AS session_person_id,
+ {events_session_id} AS session_id,
+ {breakdown_value_expr} AS breakdown_value,
+ any(s.entry_breakdown_value) AS entry_breakdown_value,
+ countIf({event_type_filter}) AS filtered_pageview_count,
+ any(s.is_bounce) AS is_bounce,
+ min(s.start_timestamp) AS start_timestamp
+ FROM events
+ INNER JOIN (
+ SELECT
+ sessions.session_id_v7 AS session_id_v7,
+ {entry_breakdown_value_sessions_expr} AS entry_breakdown_value,
+ sessions.$is_bounce AS is_bounce,
+ sessions.$start_timestamp AS start_timestamp
+ FROM sessions
+ WHERE and(
+ sessions.session_id_v7 IN (
+ SELECT DISTINCT events.$session_id_uuid
+ FROM events
+ WHERE and(
+ events.$session_id_uuid IS NOT NULL,
+ equals(bitAnd(bitShiftRight(events.$session_id_uuid, 76), 15), 7),
+ {event_type_filter},
+ timestamp >= {time_window_min},
+ timestamp < ({time_window_max} + toIntervalMinute({pad_minutes})),
+ {user_filter},
+ {test_account_filter}
+ )
+ ),
+ or(sessions.$pageview_count > 0, sessions.$screen_count > 0)
+ )
+ ) AS s ON events.$session_id_uuid = s.session_id_v7
+ WHERE and(
+ {events_session_id} IS NOT NULL,
+ {event_type_filter},
+ timestamp >= {time_window_min},
+ timestamp < ({time_window_max} + toIntervalMinute({pad_minutes})),
+ {user_filter},
+ {test_account_filter}
+ )
+ GROUP BY session_id, breakdown_value
+ HAVING and(
+ breakdown_value IS NOT NULL,
+ toStartOfHour(min(s.start_timestamp)) >= {time_window_min},
+ toStartOfHour(min(s.start_timestamp)) < {time_window_max}
+ )
+)
+GROUP BY time_window_start, breakdown_value
+"""
+
+PRUNED_JOIN_INSERT_QUERY_TEMPLATE = _PRUNED_JOIN_PER_WINDOW_AGG_SQL
+PRUNED_JOIN_INSERT_QUERY_TEMPLATE_CAPPED = "WITH per_window AS (" + _PRUNED_JOIN_PER_WINDOW_AGG_SQL + _CAPPED_WRAPPER
+
def _top_k_ranking_expr(runner: "WebStatsTableQueryRunner") -> ast.Expr | None:
"""Ranking expression for the insert top-K cap, mirroring the read's sort.
@@ -498,22 +594,41 @@ def ensure_web_stats_paths_precomputed(
# Unfiltered PAGE keys use the no-join shape (events self-attribute to the
# session-start hour via the UUIDv7 session id; bounce comes from the sessions
- # table). INITIAL_PAGE needs the join for persons-per-entry-path, and filtered
- # keys need it because the sessions side can't evaluate event/person filters.
- use_no_join = runner.query.breakdownBy == WebStatsBreakdown.PAGE and all(
- is_constant_true(placeholders[key]) for key in ("user_filter", "test_account_filter")
- )
- if use_no_join:
+ # table). Filtered PAGE keys with events-evaluable filters use the pruned-join
+ # shape (see `_PRUNED_JOIN_PER_WINDOW_AGG_SQL`): the join's exact per-path bounce
+ # attribution, but with the sessions side pruned to the id-set instead of read
+ # in full per shard. INITIAL_PAGE and everything else (cohort/session filters,
+ # non-allowlisted teams) keep the plain join: persons-per-entry-path and
+ # non-events-evaluable filters both need the events↔sessions association.
+ is_page = runner.query.breakdownBy == WebStatsBreakdown.PAGE
+ use_no_join = is_page and all(is_constant_true(placeholders[key]) for key in ("user_filter", "test_account_filter"))
+ use_pruned_join = is_page and not use_no_join and runner._session_id_set_common_eligibility()
+ if use_no_join or use_pruned_join:
placeholders["entry_breakdown_value_sessions_expr"] = _entry_breakdown_value_sessions_expr(runner)
# Cap to the displayable top-K for descending sorts; store the full set otherwise.
# The metric goes into the INSERT AST, so the sort dimension joins the job hash.
ranking_expr = _top_k_ranking_expr(runner)
+ capped = ranking_expr is not None
if ranking_expr is not None:
- insert_query = NO_JOIN_INSERT_QUERY_TEMPLATE_CAPPED if use_no_join else INSERT_QUERY_TEMPLATE_CAPPED
placeholders["top_k_metric"] = ranking_expr
+
+ insert_query: str | ast.SelectQuery
+ modifiers: Optional[HogQLQueryModifiers] = None
+ if use_no_join:
+ insert_query = NO_JOIN_INSERT_QUERY_TEMPLATE_CAPPED if capped else NO_JOIN_INSERT_QUERY_TEMPLATE
+ elif use_pruned_join:
+ # AST input: the explicit sessions join + person access does not resolve
+ # through `parse_select` with inline placeholders, so substitute here and
+ # leave the window placeholders for the framework. sessionIdPushdown then
+ # prunes the sessions build side to the id-set at print time.
+ template = PRUNED_JOIN_INSERT_QUERY_TEMPLATE_CAPPED if capped else PRUNED_JOIN_INSERT_QUERY_TEMPLATE
+ insert_query = build_insert_select_ast(template, placeholders)
+ placeholders = {}
+ modifiers = create_default_modifiers_for_team(runner.team)
+ modifiers.sessionIdPushdown = True
else:
- insert_query = NO_JOIN_INSERT_QUERY_TEMPLATE if use_no_join else INSERT_QUERY_TEMPLATE
+ insert_query = INSERT_QUERY_TEMPLATE_CAPPED if capped else INSERT_QUERY_TEMPLATE
# Warmers keep the framework default; user-facing calls get the 10s budget, or the
# caller-provided remainder of it when this is the second (compare-period) ensure.
@@ -534,6 +649,7 @@ def ensure_web_stats_paths_precomputed(
query_type="web_stats_paths_lazy_insert",
spill_to_disk=True, # high-cardinality path breakdown GROUP BY; can build a large hash table
wait_timeout_seconds=wait_timeout,
+ modifiers=modifiers,
)