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.

perf(replay_vision): resolve group filters to keys instead of joining (#87207)

Tue Haulund9e885d009614
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index f804773e99ed..44ee79ffbe30 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -19,6 +19,7 @@ from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
+from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.insights.paginators import HogQLCursorPaginator, HogQLHasMorePaginator
from posthog.models import Team, User
@@ -143,6 +144,9 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
user: User | None = None,
events_sample_factor: float | None = None,
events_timestamp_floor: datetime | None = None,
+ # Opt-in: resolve group property filters to group keys instead of joining the groups table.
+ # Naming the ClickHouse user is the opt-in, since the resolution is itself a heavy query.
+ resolve_group_properties: ClickHouseUser | None = None,
**_,
):
self._user = user
@@ -151,6 +155,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
# Extra lower bound on positive events subqueries, for callers that re-run often over a wide
# session window and do not need each run to re-scan the whole range.
self._events_timestamp_floor = events_timestamp_floor
+ self._resolve_group_properties = resolve_group_properties
self.events_subqueries_sampled = False
self._bypass_date_window_for_session_ids = bypass_date_window_for_session_ids
# TRICKY: we need to make sure we init test account filters only once,
@@ -527,6 +532,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
self._allow_event_property_expansion,
sample_factor=self._events_sample_factor,
events_timestamp_floor=self._events_timestamp_floor,
+ resolve_group_properties=self._resolve_group_properties,
)
events_sub_queries = events_sub_query_builder.get_queries_for_session_id_matching()
for events_sub_query in events_sub_queries:
@@ -653,6 +659,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
self._allow_event_property_expansion,
sample_factor=self._events_sample_factor,
events_timestamp_floor=self._events_timestamp_floor,
+ resolve_group_properties=self._resolve_group_properties,
)
for sub_q in test_account_events_builder.get_queries_for_session_id_matching():
exprs.append(
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index 995e1a1ca011..fd34e23119d1 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -19,11 +19,13 @@ from posthog.hogql import ast
from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query, tracer
+from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.hogql_queries.legacy_compatibility.filter_to_query import MathAvailability, legacy_entity_to_node
from posthog.models import Entity, EventProperty, Team
from posthog.ph_client import feature_enabled_or_false
from posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsListingBaseQuery
+from posthog.session_recordings.queries.sub_queries.group_key_resolver import resolved_group_key_expr
from posthog.session_recordings.queries.utils import (
INVERSE_OPERATOR_FOR,
NEGATIVE_OPERATORS,
@@ -96,6 +98,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
hogql_query_modifiers: Optional[HogQLQueryModifiers] = None,
sample_factor: Optional[float] = None,
events_timestamp_floor: Optional[datetime] = None,
+ resolve_group_properties: ClickHouseUser | None = None,
):
super().__init__(team, query)
self._hogql_query_modifiers = hogql_query_modifiers
@@ -105,6 +108,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
# callers that re-run often over a wide session window. Exclusion blocklists never apply it,
# since a truncated blocklist would under-exclude.
self._events_timestamp_floor = events_timestamp_floor
+ self._resolve_group_properties = resolve_group_properties
self.emitted_sampled_subquery = False
def _events_join(self, sample: bool = True) -> ast.JoinExpr:
@@ -491,7 +495,12 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
for p in self.group_properties:
if skip_negative_properties and is_negative_prop(p):
continue
- gathered_exprs.append(property_to_expr(p, team=self._team))
+ resolved = (
+ resolved_group_key_expr(self._team, p, self._resolve_group_properties)
+ if self._resolve_group_properties is not None
+ else None
+ )
+ gathered_exprs.append(resolved if resolved is not None else property_to_expr(p, team=self._team))
# Handle person properties with hybrid query mode if enabled and appropriate
hybrid_query: Optional[ast.SelectQuery] = None
diff --git a/posthog/session_recordings/queries/sub_queries/group_key_resolver.py b/posthog/session_recordings/queries/sub_queries/group_key_resolver.py
new file mode 100644
index 000000000000..2bef9ab02470
--- /dev/null
+++ b/posthog/session_recordings/queries/sub_queries/group_key_resolver.py
@@ -0,0 +1,165 @@
+"""Turn a group property filter into the set of group keys it matches, so events queries can filter
+on the `$group_N` column instead of joining the groups table.
+
+The join reads every group row's `group_properties` JSON, and ClickHouse pushes it into the per-shard
+events subquery, so each shard pays that scan independently. Resolving the keys once and filtering on
+a column instead is measurably cheaper and returns the same sessions.
+"""
+
+import json
+import hashlib
+from collections.abc import Callable
+from typing import Any, cast
+
+from django.core.cache import cache
+
+import structlog
+
+from posthog.schema import EventPropertyFilter, GroupPropertyFilter, PropertyOperator
+
+from posthog.hogql import ast
+from posthog.hogql.property import property_to_expr
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.models import Team
+
+logger = structlog.get_logger(__name__)
+
+GROUP_KEY_RESOLUTION_QUERY_TYPE = "GroupKeyResolutionQuery"
+
+# Group membership changes on a human timescale, while a scanner sweeps every few minutes.
+GROUP_KEY_CACHE_TTL_SECONDS = 3600
+
+# Past this the key list stops being cheaper than the join, and it starts crowding `max_query_size`.
+MAX_RESOLVED_GROUP_KEYS = 10_000
+
+# A negated filter has to distinguish "this group does not match" from "this event has no group at
+# all", which an IN list over matching keys cannot express. Those keep the join.
+_RESOLVABLE_OPERATORS = {
+ PropertyOperator.EXACT,
+ PropertyOperator.IN_,
+ PropertyOperator.ICONTAINS,
+ PropertyOperator.REGEX,
+ PropertyOperator.GT,
+ PropertyOperator.GTE,
+ PropertyOperator.LT,
+ PropertyOperator.LTE,
+ PropertyOperator.IS_SET,
+}
+
+# Numeric comparisons need the cast the group-join path gets from its typed field.
+_NUMERIC_OPERATORS = {
+ PropertyOperator.GT: ast.CompareOperationOp.Gt,
+ PropertyOperator.GTE: ast.CompareOperationOp.GtEq,
+ PropertyOperator.LT: ast.CompareOperationOp.Lt,
+ PropertyOperator.LTE: ast.CompareOperationOp.LtEq,
+}
+
+_FALLBACK = "fallback"
+
+
+def resolved_group_key_expr(team: Team, prop: GroupPropertyFilter, ch_user: ClickHouseUser) -> ast.Expr | None:
+ """`$group_N IN (keys)` for this filter, or None when the caller should keep the join."""
+ if prop.operator not in _RESOLVABLE_OPERATORS or prop.group_type_index is None:
+ return None
+
+ keys = _group_keys(team, prop, ch_user)
+ if keys is None:
+ return None
+
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["events", f"$group_{prop.group_type_index}"]),
+ right=ast.Constant(value=keys),
+ )
+
+
+def _group_keys(team: Team, prop: GroupPropertyFilter, ch_user: ClickHouseUser) -> list[str] | None:
+ cache_key = _cache_key(team, prop)
+ cached = _swallowing_failure("group_key_cache_read_failed", team, prop, lambda: cache.get(cache_key))
+ if cached == _FALLBACK:
+ return None
+ if cached is not None:
+ return _cast_keys(cached)
+
+ keys = _swallowing_failure(
+ "group_key_resolution_failed", team, prop, lambda: _query_group_keys(team, prop, ch_user)
+ )
+ if keys is None:
+ return None
+
+ resolved: list[str] | None = None if len(keys) > MAX_RESOLVED_GROUP_KEYS else keys
+ _swallowing_failure(
+ "group_key_cache_write_failed",
+ team,
+ prop,
+ lambda: cache.set(cache_key, _FALLBACK if resolved is None else resolved, GROUP_KEY_CACHE_TTL_SECONDS),
+ )
+ return resolved
+
+
+def _swallowing_failure(event: str, team: Team, prop: GroupPropertyFilter, work: Callable[[], Any]) -> Any:
+ # Everything here is an optimisation over a join that already returns the right answer, so a
+ # broken cache or an unavailable ClickHouse costs reads rather than failing the caller's query.
+ try:
+ return work()
+ except Exception:
+ logger.exception(event, team_id=team.pk, property_key=prop.key)
+ return None
+
+
+def _resolution_predicate(team: Team, prop: GroupPropertyFilter) -> ast.Expr:
+ """The filter's predicate, expressed against the `properties` of a select over `groups`."""
+ numeric_op = _NUMERIC_OPERATORS.get(prop.operator)
+ if numeric_op is not None:
+ # A group property is stored as a JSON string, and the group-join path reaches it through a
+ # typed field that carries the cast. Comparing the raw string to a number instead fails on
+ # "no supertype for types String, Float64", so the cast has to be explicit here.
+ return ast.CompareOperation(
+ op=numeric_op,
+ left=ast.Call(name="toFloat", args=[ast.Field(chain=["properties", prop.key])]),
+ right=ast.Constant(value=float(cast(float | str, prop.value))),
+ )
+ # String operators need no cast, so reuse the event-property expression and keep their handling
+ # in one place. Inside a select over `groups`, `properties` resolves to that table's latest values.
+ return property_to_expr(
+ EventPropertyFilter(key=prop.key, value=prop.value, operator=prop.operator),
+ team=team,
+ scope="event",
+ )
+
+
+def _query_group_keys(team: Team, prop: GroupPropertyFilter, ch_user: ClickHouseUser) -> list[str]:
+ predicate = _resolution_predicate(team, prop)
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=["key"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["groups"])),
+ where=ast.And(
+ exprs=[
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["index"]),
+ right=ast.Constant(value=prop.group_type_index),
+ ),
+ predicate,
+ ]
+ ),
+ # One over the ceiling, so an over-broad filter is recognised without materialising the rest.
+ limit=ast.Constant(value=MAX_RESOLVED_GROUP_KEYS + 1),
+ )
+ response = execute_hogql_query(query=query, team=team, query_type=GROUP_KEY_RESOLUTION_QUERY_TYPE, ch_user=ch_user)
+ return [row[0] for row in (response.results or []) if row[0]]
+
+
+def _cast_keys(cached: Any) -> list[str]:
+ return [str(key) for key in cached]
+
+
+def _cache_key(team: Team, prop: GroupPropertyFilter) -> str:
+ payload = json.dumps(
+ [prop.group_type_index, prop.key, prop.operator, prop.value],
+ sort_keys=True,
+ default=str,
+ )
+ return f"group-keys:{team.pk}:{hashlib.sha256(payload.encode()).hexdigest()}"
diff --git a/posthog/session_recordings/queries/test/test_group_key_resolver.py b/posthog/session_recordings/queries/test/test_group_key_resolver.py
new file mode 100644
index 000000000000..feeca3094e2e
--- /dev/null
+++ b/posthog/session_recordings/queries/test/test_group_key_resolver.py
@@ -0,0 +1,112 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+
+from posthog.schema import GroupPropertyFilter, PropertyOperator
+
+from posthog.hogql import ast
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.session_recordings.queries.sub_queries.group_key_resolver import (
+ MAX_RESOLVED_GROUP_KEYS,
+ _resolution_predicate,
+ resolved_group_key_expr,
+)
+
+_RESOLVER = "posthog.session_recordings.queries.sub_queries.group_key_resolver._query_group_keys"
+_CH_USER = ClickHouseUser.DEFAULT
+
+
+def _filter(operator: PropertyOperator = PropertyOperator.EXACT) -> GroupPropertyFilter:
+ return GroupPropertyFilter(key="owner", value=["[email protected]"], operator=operator, group_type_index=0)
+
+
+class TestGroupKeyResolver(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def test_a_resolvable_filter_becomes_an_in_over_the_group_column(self) -> None:
+ with patch(_RESOLVER, return_value=["org-1", "org-2"]):
+ expr = resolved_group_key_expr(self.team, _filter(), _CH_USER)
+
+ assert isinstance(expr, ast.CompareOperation)
+ assert expr.op == ast.CompareOperationOp.In
+ assert isinstance(expr.left, ast.Field)
+ assert expr.left.chain == ["events", "$group_0"]
+ assert isinstance(expr.right, ast.Constant)
+ assert expr.right.value == ["org-1", "org-2"]
+
+ def test_the_second_build_reuses_the_first_resolution(self) -> None:
+ # Without the cache every sweep tick re-scans the whole groups table, which is the cost this
+ # resolution exists to remove.
+ with patch(_RESOLVER, return_value=["org-1"]) as resolve:
+ resolved_group_key_expr(self.team, _filter(), _CH_USER)
+ resolved_group_key_expr(self.team, _filter(), _CH_USER)
+
+ assert resolve.call_count == 1
+
+ def test_a_different_team_does_not_read_another_teams_keys(self) -> None:
+ other = self.organization.teams.create(name="other")
+ with patch(_RESOLVER, return_value=["org-1"]) as resolve:
+ resolved_group_key_expr(self.team, _filter(), _CH_USER)
+ resolved_group_key_expr(other, _filter(), _CH_USER)
+
+ assert resolve.call_count == 2
+
+ @parameterized.expand(
+ [
+ # An IN list over matching keys cannot say "has a group, and it does not match", so a
+ # negated filter resolved this way would silently change which sessions match.
+ ("negated", PropertyOperator.IS_NOT),
+ ("not_contains", PropertyOperator.NOT_ICONTAINS),
+ ]
+ )
+ def test_an_operator_the_key_list_cannot_express_keeps_the_join(
+ self, _name: str, operator: PropertyOperator
+ ) -> None:
+ with patch(_RESOLVER, return_value=["org-1"]):
+ assert resolved_group_key_expr(self.team, _filter(operator), _CH_USER) is None
+
+ def test_an_over_broad_filter_keeps_the_join(self) -> None:
+ keys = [f"org-{i}" for i in range(MAX_RESOLVED_GROUP_KEYS + 1)]
+ with patch(_RESOLVER, return_value=keys) as resolve:
+ assert resolved_group_key_expr(self.team, _filter(), _CH_USER) is None
+ assert resolved_group_key_expr(self.team, _filter(), _CH_USER) is None
+
+ assert resolve.call_count == 1
+
+ def test_a_numeric_comparison_casts_the_property(self) -> None:
+ # Without the cast ClickHouse rejects the resolution with "no supertype for types String,
+ # Float64", the resolver falls back, and the scanner silently keeps paying for the join.
+ prop = GroupPropertyFilter(key="score", value=8, operator=PropertyOperator.GT, group_type_index=0)
+
+ predicate = _resolution_predicate(self.team, prop)
+
+ assert isinstance(predicate, ast.CompareOperation)
+ assert predicate.op == ast.CompareOperationOp.Gt
+ assert isinstance(predicate.left, ast.Call)
+ assert predicate.left.name == "toFloat"
+ assert isinstance(predicate.right, ast.Constant)
+ assert predicate.right.value == 8.0
+
+ @parameterized.expand([("read", "get"), ("write", "set")])
+ def test_a_broken_cache_does_not_fail_the_query(self, _name: str, method: str) -> None:
+ # Everything here is an optimisation over a join that already works, so an unavailable Redis
+ # has to cost reads rather than break the sweep tick that was building the query.
+ with patch(
+ f"posthog.session_recordings.queries.sub_queries.group_key_resolver.cache.{method}",
+ side_effect=Exception("redis is down"),
+ ):
+ with patch(_RESOLVER, return_value=["org-1"]):
+ expr = resolved_group_key_expr(self.team, _filter(), _CH_USER)
+
+ # A broken cache degrades to resolving every time, not to failing and not to the join.
+ assert isinstance(expr, ast.CompareOperation)
+
+ def test_a_failed_resolution_keeps_the_join(self) -> None:
+ with patch(_RESOLVER, side_effect=Exception("clickhouse said no")):
+ assert resolved_group_key_expr(self.team, _filter(), _CH_USER) is None
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index 1850d480aaf1..472f8a237e98 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -22,6 +22,7 @@ from posthog.session_recordings.queries.session_recording_list_from_query import
UNSCORED_SURFACING_SCORE,
SessionRecordingListFromQuery,
)
+from posthog.session_recordings.queries.sub_queries.group_key_resolver import GROUP_KEY_RESOLUTION_QUERY_TYPE
from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, SamplingMode
from products.replay_vision.backend.session_limits import (
@@ -59,18 +60,19 @@ FAST_SWEEP_QUERY_TYPES = [
SWEEP_CANDIDATE_QUERY_TYPE,
SWEEP_CANDIDATE_SCAN_QUERY_TYPE,
EXCLUDED_SESSIONS_QUERY_TYPE,
+ GROUP_KEY_RESOLUTION_QUERY_TYPE,
]
SAMPLE_RATE_PRECISION = 10_000
# Smallest non-zero rate the modulo bucketing can express (one bucket); the API rejects non-zero rates below it.
MIN_SAMPLING_RATE = 1 / SAMPLE_RATE_PRECISION
DEFAULT_CANDIDATE_LIMIT = 5_000
-# How many sessions one tick pulls from the replay table before asking the events table about them.
-# The `$session_id` bloom filter stops discriminating once the list gets long: measured against
-# production scanners, a few hundred to a couple of thousand ids prune 4-15x, while ~8k ids prune
-# under 2x. Sized at the top of that band, since a page that is too small pays the events scan's
-# fixed cost again for no extra reach.
-CANDIDATE_SCAN_LIMIT = 2_000
+# Correlating only pays while the id list stays short. A bloom filter answers "might this granule
+# hold any of these values", so with N probes a granule survives with probability ~1-(1-p)^N and
+# pruning decays exponentially. Measured against a production 4h window: 1 id prunes 98.5% of
+# granules, 20 prunes 49%, 50 prunes 24%, and 300 prunes 0.2%. Past this many candidates the second
+# query reads what the single query would have read, on top of it, so the tick takes the plain path.
+CORRELATION_MAX_SESSIONS = 100
DEFAULT_MAX_EXECUTION_SECONDS = 180
# Emitted by `emit_observation_event_activity` once an observation succeeds.
@@ -239,6 +241,7 @@ class ScannerCandidateQuery:
extra_having_predicates=extra_having,
events_timestamp_floor=events_timestamp_floor,
skip_negative_blocklists=skip_negative_blocklists,
+ resolve_group_properties=ClickHouseUser.REPLAY_VISION,
)
def excluded_sessions_queries(self, session_ids: list[str]) -> list[ast.SelectQuery]:
@@ -274,6 +277,12 @@ class ScannerCandidateQuery:
return [CandidateSession(session_id=row[0], session_end=row[1]) for row in rows]
def get_query(self) -> ast.SelectQuery:
+ # Building resolves group filters, which runs its own ClickHouse query. Tagging the build too
+ # keeps that read attributable, so the throttle charges the sweep for it.
+ with tags_context(product=Product.REPLAY_VISION, feature=Feature.ENRICHMENT, scanner_id=self._scanner_id):
+ return self._build_query()
+
+ def _build_query(self) -> ast.SelectQuery:
# `_inner.get_query()` re-parses every call, so in-place mutation is safe.
inner = self._inner.get_query()
inner.order_by = None
@@ -326,20 +335,31 @@ def run_correlated_batch(
sessions the tick can dispatch. Listing the sessions up front lets the `$session_id` bloom filter
prune the scan, which is where the saving comes from.
"""
+
+ def single_query() -> CandidateBatch:
+ plain = build()
+ plain.limit = ast.Constant(value=dispatch_limit)
+ rows = execute(plain, match_query_type)
+ return build_candidate_batch(rows, rows, dispatch_limit, dispatch_limit)
+
query = build()
predicates = session_in_predicates(query)
if not predicates:
# No events subquery to correlate against, so splitting would only cost a second round trip.
- query.limit = ast.Constant(value=dispatch_limit)
- considered = execute(query, match_query_type)
- return build_candidate_batch(considered, considered, dispatch_limit, dispatch_limit)
+ return single_query()
for predicate in predicates:
_drop_event_filter(predicate)
- query.limit = ast.Constant(value=CANDIDATE_SCAN_LIMIT)
+ # One over the ceiling, so a window that holds too many to correlate is recognised without
+ # reading the rest of them.
+ query.limit = ast.Constant(value=CORRELATION_MAX_SESSIONS + 1)
considered = execute(query, scan_query_type)
if not considered:
return CandidateBatch(matched=[])
+ if len(considered) > CORRELATION_MAX_SESSIONS:
+ # Too many ids for the bloom filter to prune on, so correlating would read the whole window
+ # again. The scan above is the only cost of finding that out.
+ return single_query()
matching = build()
session_ids = [c.session_id for c in considered]
@@ -349,9 +369,9 @@ def run_correlated_batch(
# through a non-event branch, which the subquery restriction never sees; without this the match
# set could run past the page the keyset is computed from.
_restrict_outer_to_sessions(matching, session_ids)
- matching.limit = ast.Constant(value=CANDIDATE_SCAN_LIMIT)
+ matching.limit = ast.Constant(value=CORRELATION_MAX_SESSIONS)
matched = execute(matching, match_query_type)
- return build_candidate_batch(considered, matched, dispatch_limit, CANDIDATE_SCAN_LIMIT)
+ return build_candidate_batch(considered, matched, dispatch_limit, CORRELATION_MAX_SESSIONS + 1)
def session_in_predicates(query: ast.SelectQuery) -> list[ast.CompareOperation]:
@@ -584,6 +604,7 @@ class WindowedCandidateQuery:
extra_having_predicates=extra_having,
session_ids_to_exclude=exclude_session_ids,
skip_negative_blocklists=skip_negative_blocklists,
+ resolve_group_properties=ClickHouseUser.REPLAY_VISION,
)
def excluded_sessions_queries(self, session_ids: list[str]) -> list[ast.SelectQuery]:
@@ -630,6 +651,12 @@ class WindowedCandidateQuery:
def _windowed_candidates(self) -> ast.SelectQuery:
"""Window and eligibility predicates shared by the batch walk and the exact count."""
+ # Tagged for the same reason as `ScannerCandidateQuery.get_query`: building resolves group
+ # filters, and that read has to stay attributable to this scanner.
+ with tags_context(product=Product.REPLAY_VISION, feature=Feature.ENRICHMENT, scanner_id=self._scanner_id):
+ return self._build_windowed_candidates()
+
+ def _build_windowed_candidates(self) -> ast.SelectQuery:
# `_inner.get_query()` re-parses every call, so in-place mutation is safe.
inner = self._inner.get_query()
inner.order_by = None
diff --git a/products/replay_vision/backend/tests/test_candidate_batch.py b/products/replay_vision/backend/tests/test_candidate_batch.py
index 21e805d829c6..6d06304c977e 100644
--- a/products/replay_vision/backend/tests/test_candidate_batch.py
+++ b/products/replay_vision/backend/tests/test_candidate_batch.py
@@ -1,6 +1,7 @@
import datetime as dt
import pytest
+from unittest.mock import patch
from parameterized import parameterized
@@ -8,10 +9,12 @@ from posthog.schema import RecordingsQuery
from posthog.hogql import ast
+from posthog.clickhouse.query_tagging import Product, get_query_tags
from posthog.models import Organization, Team
from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL
from products.replay_vision.backend.queries.scanner_candidate_query import (
+ CORRELATION_MAX_SESSIONS,
CandidateSession,
ScannerCandidateQuery,
build_candidate_batch,
@@ -20,6 +23,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
)
_T0 = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
+_SCANNER_ID = "0199aaaa-bbbb-7ccc-8ddd-eeeeffff0000"
def _sessions(count: int, prefix: str = "s") -> list[CandidateSession]:
@@ -28,6 +32,38 @@ def _sessions(count: int, prefix: str = "s") -> list[CandidateSession]:
]
+def _group_column_bounds(node: ast.Expr | ast.SelectQuery | None) -> list[str] | None:
+ if node is None:
+ return None
+ if (
+ isinstance(node, ast.CompareOperation)
+ and node.op == ast.CompareOperationOp.In
+ and isinstance(node.left, ast.Field)
+ and str(node.left.chain[-1]).startswith("$group_")
+ and isinstance(node.right, ast.Constant)
+ ):
+ return list(node.right.value)
+ for child in _children(node):
+ found = _group_column_bounds(child)
+ if found is not None:
+ return found
+ return None
+
+
+def _children(node: ast.Expr | ast.SelectQuery) -> list:
+ if isinstance(node, ast.SelectQuery):
+ return [node.where, node.having, node.select_from, *(node.select or [])]
+ if isinstance(node, ast.JoinExpr):
+ return [node.table, node.constraint, node.next_join]
+ if isinstance(node, ast.JoinConstraint):
+ return [node.expr]
+ if isinstance(node, ast.CompareOperation):
+ return [node.left, node.right]
+ if isinstance(node, ast.Call):
+ return list(node.args or [])
+ return list(getattr(node, "exprs", None) or [])
+
+
def _bounds_sessions(node: ast.Expr | None) -> bool:
"""Whether the outer query restricts `sessions.session_id` to a fixed list."""
if node is None:
@@ -87,7 +123,12 @@ class TestBuildCandidateBatch:
@pytest.mark.django_db
class TestSessionInPredicates:
def _query(
- self, *, filter_test_accounts: bool, with_event_filter: bool, operand: str = "AND"
+ self,
+ *,
+ filter_test_accounts: bool,
+ with_event_filter: bool,
+ operand: str = "AND",
+ group_filter: bool = False,
) -> ScannerCandidateQuery:
org = Organization.objects.create(name="predicate-test-org")
team = Team.objects.create(
@@ -98,8 +139,21 @@ class TestSessionInPredicates:
],
)
query: dict = {"kind": "RecordingsQuery", "filter_test_accounts": filter_test_accounts, "operand": operand}
+ properties: list[dict] = []
if with_event_filter:
- query["properties"] = [{"key": "plan", "type": "event", "value": "pro", "operator": "exact"}]
+ properties.append({"key": "plan", "type": "event", "value": "pro", "operator": "exact"})
+ if group_filter:
+ properties.append(
+ {
+ "key": "owner",
+ "type": "group",
+ "value": ["[email protected]"],
+ "operator": "exact",
+ "group_type_index": 0,
+ }
+ )
+ if properties:
+ query["properties"] = properties
return ScannerCandidateQuery(
team=team,
query=RecordingsQuery.model_validate(query),
@@ -108,6 +162,7 @@ class TestSessionInPredicates:
sampling_salt="salt",
events_lookback=dt.timedelta(hours=4),
skip_negative_blocklists=True,
+ scanner_id=_SCANNER_ID,
)
def test_finds_the_test_account_subquery_as_well_as_the_scanners_own(self) -> None:
@@ -117,6 +172,30 @@ class TestSessionInPredicates:
assert len(predicates) == 2
+ def test_a_window_with_too_many_sessions_falls_back_to_one_query(self) -> None:
+ # A bloom filter cannot prune on a long id list, so past the ceiling the second query would
+ # read the whole window again on top of the first. One plain query is cheaper.
+ candidate_query = self._query(filter_test_accounts=False, with_event_filter=True)
+ executed: list[str] = []
+
+ def execute(query: ast.SelectQuery, query_type: str) -> list[CandidateSession]:
+ executed.append(query_type)
+ if len(executed) == 1:
+ return [
+ CandidateSession(session_id=f"s-{i}", session_end=_T0) for i in range(CORRELATION_MAX_SESSIONS + 1)
+ ]
+ return []
+
+ run_correlated_batch(
+ build=candidate_query.get_query,
+ execute=execute,
+ scan_query_type="scan",
+ match_query_type="match",
+ dispatch_limit=10,
+ )
+
+ assert executed == ["scan", "match"]
+
def test_an_or_filter_still_bounds_the_match_query_to_the_scanned_page(self) -> None:
# With operand OR a session can match through a non-event branch, which the subquery
# restriction never sees. Without the outer bound the match set runs past the page the
@@ -138,6 +217,38 @@ class TestSessionInPredicates:
assert _bounds_sessions(executed[1].where)
+ def test_a_group_filter_is_resolved_to_the_group_column(self) -> None:
+ # Joining the groups table makes every ClickHouse shard scan it independently, so a sweep
+ # tick pays that scan once per shard. Filtering on the resolved keys instead is the whole
+ # point of the opt-in, and losing it anywhere in the plumbing is invisible without this.
+ query = self._query(filter_test_accounts=False, with_event_filter=False, group_filter=True)
+ with patch(
+ "posthog.session_recordings.queries.sub_queries.group_key_resolver._query_group_keys",
+ return_value=["org-1"],
+ ):
+ built = query.get_query()
+
+ assert _group_column_bounds(built) == ["org-1"]
+
+ def test_the_group_resolution_read_is_attributable_to_the_scanner(self) -> None:
+ # The read meter only counts query-log rows carrying this product and a scanner id. Untag the
+ # build and the resolution spends silently, so the sweep throttle never charges it.
+ query = self._query(filter_test_accounts=False, with_event_filter=False, group_filter=True)
+ seen: list[tuple] = []
+
+ def capture(*_args, **_kwargs) -> list[str]:
+ tags = get_query_tags()
+ seen.append((tags.product, tags.scanner_id))
+ return ["org-1"]
+
+ with patch(
+ "posthog.session_recordings.queries.sub_queries.group_key_resolver._query_group_keys",
+ side_effect=capture,
+ ):
+ query.get_query()
+
+ assert seen == [(Product.REPLAY_VISION, _SCANNER_ID)]
+
def test_a_scanner_without_event_filters_has_nothing_to_correlate(self) -> None:
predicates = session_in_predicates(self._query(filter_test_accounts=False, with_event_filter=False).get_query())