: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(replay-vision): correlate sweep event lookups to their candidate sessions (#87022)
Tue Haulundc4705e38f023
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pyindex f25a0a379f48..1850d480aaf1 100644--- a/products/replay_vision/backend/queries/scanner_candidate_query.py+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -1,6 +1,7 @@"""Find session recordings a scanner should observe: ended past the watermark and quiet for 35+ minutes."""import datetime as dt+from collections.abc import Callablefrom dataclasses import dataclassfrom typing import Literal, cast@@ -12,6 +13,7 @@ from posthog.schema import RecordingsQueryfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.query import execute_hogql_query+from posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -46,13 +48,29 @@ BACKFILL_CANDIDATE_QUERY_TYPE = "ReplayVisionBackfillCandidateQuery"BACKFILL_COUNT_QUERY_TYPE = "ReplayVisionBackfillCountQuery"DEEP_SWEEP_CANDIDATE_QUERY_TYPE = "ReplayVisionDeepSweepCandidateQuery"SWEEP_CANDIDATE_QUERY_TYPE = "ReplayVisionScannerCandidateQuery"+SWEEP_CANDIDATE_SCAN_QUERY_TYPE = "ReplayVisionScannerCandidateScanQuery"EXCLUDED_SESSIONS_QUERY_TYPE = "ReplayVisionExcludedSessionsQuery"BACKFILL_EXCLUDED_SESSIONS_QUERY_TYPE = "ReplayVisionBackfillExcludedSessionsQuery"+# The candidate-selection tags the read meter charges the frequent sweep's throttle on. A new+# selection query that is not listed here spends unmetered and never stretches the cadence. The+# one-shot priming query is deliberately outside it.+FAST_SWEEP_QUERY_TYPES = [+ SWEEP_CANDIDATE_QUERY_TYPE,+ SWEEP_CANDIDATE_SCAN_QUERY_TYPE,+ EXCLUDED_SESSIONS_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_PRECISIONDEFAULT_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_000DEFAULT_MAX_EXECUTION_SECONDS = 180# Emitted by `emit_observation_event_activity` once an observation succeeds.@@ -137,6 +155,21 @@ class CandidateSession:session_end: dt.datetime+@dataclass(frozen=True)+class CandidateBatch:+ """What one sweep tick considered and what it will dispatch.++ `keyset_end`/`keyset_session_id` mark the last session the tick *considered*, matched or not, so+ the watermark moves over ground actually covered rather than over the dispatch list. Advancing it+ past sessions that were fetched but never evaluated would drop them for good.+ """++ matched: list[CandidateSession]+ keyset_end: dt.datetime | None = None+ keyset_session_id: str = ""+ saturated: bool = False++class ScannerCandidateQuery:def __init__(self,@@ -218,10 +251,23 @@ class ScannerCandidateQuery:@tracer.start_as_current_span("ScannerCandidateQuery.run")def run(self) -> list[CandidateSession]:+ return self._execute(self.get_query(), SWEEP_CANDIDATE_QUERY_TYPE)++ @tracer.start_as_current_span("ScannerCandidateQuery.run_batch")+ def run_batch(self, dispatch_limit: int) -> CandidateBatch:+ return run_correlated_batch(+ build=self.get_query,+ execute=self._execute,+ scan_query_type=SWEEP_CANDIDATE_SCAN_QUERY_TYPE,+ match_query_type=SWEEP_CANDIDATE_QUERY_TYPE,+ dispatch_limit=dispatch_limit,+ )++ def _execute(self, query: ast.SelectQuery, query_type: str) -> list[CandidateSession]:rows = execute_candidate_query(- self.get_query(),+ query,team=self._team,- query_type=SWEEP_CANDIDATE_QUERY_TYPE,+ query_type=query_type,max_execution_time_seconds=self._max_execution_time_seconds,scanner_id=self._scanner_id,)@@ -265,6 +311,136 @@ class ScannerCandidateQuery:return sampling_predicate(self._sampling_rate, self._sampling_salt)+def run_correlated_batch(+ *,+ build: Callable[[], ast.SelectQuery],+ execute: Callable[[ast.SelectQuery, str], list[CandidateSession]],+ scan_query_type: str,+ match_query_type: str,+ dispatch_limit: int,+) -> CandidateBatch:+ """Name the candidate sessions first, then ask the events table only about those.++ Asking instead which sessions matched anywhere in the lookback makes ClickHouse read the team's+ whole event volume for that window and then throw nearly all of it away against the few hundred+ 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.+ """+ 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)++ for predicate in predicates:+ _drop_event_filter(predicate)+ query.limit = ast.Constant(value=CANDIDATE_SCAN_LIMIT)+ considered = execute(query, scan_query_type)+ if not considered:+ return CandidateBatch(matched=[])++ matching = build()+ session_ids = [c.session_id for c in considered]+ for predicate in session_in_predicates(matching):+ _restrict_to_sessions(predicate, session_ids)+ # Also bound the outer query to the page. A filter whose operand is OR can match a session+ # 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)+ matched = execute(matching, match_query_type)+ return build_candidate_batch(considered, matched, dispatch_limit, CANDIDATE_SCAN_LIMIT)+++def session_in_predicates(query: ast.SelectQuery) -> list[ast.CompareOperation]:+ """Every `session_id in (events subquery)` predicate the compiled query carries.++ A scanner with test-account filters or event entities compiles to more than one. Restricting only+ the first leaves the others scanning the whole events window, which costs the entire saving while+ still returning the right sessions - a silent performance regression, not a visible failure.+ """+ inner = query.select_from.table if query.select_from else None+ if not isinstance(inner, ast.SelectQuery):+ return []+ collector = _SessionInCollector()+ collector.visit(inner.where)+ return collector.found+++class _SessionInCollector(TraversingVisitor):+ """Collects the session-in predicates without descending into the subqueries they carry."""++ def __init__(self) -> None:+ self.found: list[ast.CompareOperation] = []++ def visit_compare_operation(self, node: ast.CompareOperation) -> None:+ if _is_session_in(node):+ self.found.append(node)+ return+ super().visit_compare_operation(node)+++def _is_session_in(expr: ast.Expr) -> bool:+ return (+ isinstance(expr, ast.CompareOperation)+ and expr.op in (ast.CompareOperationOp.GlobalIn, ast.CompareOperationOp.In)+ and isinstance(expr.left, ast.Field)+ and expr.left.chain[-1] == "session_id"+ and isinstance(expr.right, ast.SelectQuery)+ )+++def _drop_event_filter(predicate: ast.CompareOperation) -> None:+ """Turn the predicate into a tautology; this pass wants every session in the window."""+ predicate.op = ast.CompareOperationOp.Eq+ predicate.left = ast.Constant(value=1)+ predicate.right = ast.Constant(value=1)+++def _restrict_to_sessions(predicate: ast.CompareOperation, session_ids: list[str]) -> None:+ subquery = predicate.right+ assert isinstance(subquery, ast.SelectQuery)+ selected = subquery.select[0]+ session_expr = selected.expr if isinstance(selected, ast.Alias) else selected+ restriction = ast.CompareOperation(+ op=ast.CompareOperationOp.In, left=session_expr, right=ast.Constant(value=session_ids)+ )+ subquery.where = ast.And(exprs=[subquery.where, restriction]) if subquery.where else restriction+++def _restrict_outer_to_sessions(query: ast.SelectQuery, session_ids: list[str]) -> None:+ restriction = ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["sessions", "session_id"]),+ right=ast.Constant(value=session_ids),+ )+ query.where = ast.And(exprs=[query.where, restriction]) if query.where else restriction+++def build_candidate_batch(+ considered: list[CandidateSession], matched: list[CandidateSession], dispatch_limit: int, scan_limit: int+) -> CandidateBatch:+ if len(matched) > dispatch_limit:+ # More matches than there is room to dispatch, so the walk stops at the last one that fits:+ # everything past it is re-considered next tick rather than skipped.+ matched = matched[:dispatch_limit]+ last = matched[-1]+ return CandidateBatch(+ matched=matched, keyset_end=last.session_end, keyset_session_id=last.session_id, saturated=True+ )+ if not considered:+ return CandidateBatch(matched=matched)+ last = considered[-1]+ return CandidateBatch(+ matched=matched,+ keyset_end=last.session_end,+ keyset_session_id=last.session_id,+ saturated=len(considered) >= scan_limit,+ )++def keyset_order_by(ascending: bool) -> list[ast.OrderExpr]:"""Ordering the keyset predicate below assumes; the two have to move together."""direction: Literal["ASC", "DESC"] = "ASC" if ascending else "DESC"@@ -416,10 +592,13 @@ class WindowedCandidateQuery:@tracer.start_as_current_span("WindowedCandidateQuery.run")def run(self) -> list[CandidateSession]:+ return self._execute(self.get_query(), self._query_type)++ def _execute(self, query: ast.SelectQuery, query_type: str) -> list[CandidateSession]:rows = execute_candidate_query(- self.get_query(),+ query,team=self._team,- query_type=self._query_type,+ query_type=query_type,max_execution_time_seconds=self._max_execution_time_seconds,scanner_id=self._scanner_id,)diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.pyindex ec0f96033369..112626785a8d 100644--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py@@ -36,7 +36,12 @@ from products.replay_vision.backend.temporal.constants import (SCANNER_SCHEDULE_INTERVAL,)from products.replay_vision.backend.temporal.decorators import track_activity-from products.replay_vision.backend.temporal.metrics import record_deep_sweep_failure, record_sweep_outcome+from products.replay_vision.backend.temporal.metrics import (+ record_candidate_page_full,+ record_deep_candidates,+ record_deep_sweep_failure,+ record_sweep_outcome,+)from products.replay_vision.backend.temporal.read_meter_types import (deep_spend_bytes_per_day,deep_sweep_throttle_factor,@@ -109,10 +114,10 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Finskip_negative_blocklists=True,scanner_id=str(scanner.id),)- fetched = candidate_query.run()- # A full batch means there may be more past the keyset; the next sweep resumes from the last row.- # Measured before exclusion, since the keyset walks what was fetched, not what survived.- saturated = len(fetched) == limit+ batch = candidate_query.run_batch(limit)+ fetched = batch.matched+ if batch.saturated:+ record_candidate_page_full()# Deliberately not wrapped: the in-query blocklists are off, so a swallowed failure here would# dispatch the batch unfiltered. Returns empty when the scanner excludes nothing.@@ -178,16 +183,18 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Findeep_candidates = [c for c in deep_candidates if c.session_id not in stuck]priming_candidates = [c for c in priming_candidates if c.session_id not in stuck]+ if deep_candidates:+ record_deep_candidates(len(deep_candidates))record_sweep_outcome("candidates_found" if candidates or deep_candidates or priming_candidates else "no_candidates",candidates=len(candidates) + len(deep_candidates) + len(priming_candidates),)return FindScannerCandidatesOutput(candidates=[CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in candidates],- saturated=saturated,+ saturated=batch.saturated,swept_through=candidate_query.settle_cutoff,- keyset_end=fetched[-1].session_end if fetched else None,- keyset_session_id=fetched[-1].session_id if fetched else "",+ keyset_end=batch.keyset_end,+ keyset_session_id=batch.keyset_session_id,deep_candidates=[CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in deep_candidates],diff --git a/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py b/products/replay_vision/backend/temporal/activities/meter_scanner_reads.pyindex d132ed62d9ad..26137ddf6817 100644--- a/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py+++ b/products/replay_vision/backend/temporal/activities/meter_scanner_reads.py@@ -9,8 +9,7 @@ from posthog.clickhouse.workload import Workloadfrom products.replay_vision.backend.models.replay_scanner import ReplayScannerfrom products.replay_vision.backend.queries.scanner_candidate_query import (DEEP_SWEEP_CANDIDATE_QUERY_TYPE,- EXCLUDED_SESSIONS_QUERY_TYPE,- SWEEP_CANDIDATE_QUERY_TYPE,+ FAST_SWEEP_QUERY_TYPES,)from products.replay_vision.backend.temporal.constants import DEEP_SPEND_WINDOW_DAYSfrom products.replay_vision.backend.temporal.decorators import track_activity@@ -21,10 +20,6 @@ from products.replay_vision.backend.temporal.read_meter_types import MeterScanne# lands in its (re-scanned, complete) hour bucket._FULL_HOURS_RESCANNED = 2-# Metered positively rather than by subtraction: a backfill runs under the same scanner id, so-# anything not named here is not charged to the frequent sweep's cadence.-_FAST_QUERY_TYPES = [SWEEP_CANDIDATE_QUERY_TYPE, EXCLUDED_SESSIONS_QUERY_TYPE]-_READ_BYTES_BY_SCANNER_HOUR_SQL = """SELECTJSONExtractString(log_comment, 'scanner_id') AS scanner_id,@@ -61,7 +56,7 @@ def meter_scanner_read_bytes_activity() -> MeterScannerReadsResult:"cluster": settings.CLICKHOUSE_CLUSTER,"since": since,"deep_query_type": DEEP_SWEEP_CANDIDATE_QUERY_TYPE,- "fast_query_types": _FAST_QUERY_TYPES,+ "fast_query_types": FAST_SWEEP_QUERY_TYPES,},workload=Workload.OFFLINE,settings={"max_execution_time": 120, "skip_unavailable_shards": 1},diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex 9585ff0e8475..d41a765d638d 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -109,6 +109,18 @@ REPLAY_VISION_AUTO_MATERIALIZE_OUTCOMES = Counter(["outcome"],)+REPLAY_VISION_DEEP_CANDIDATES = Counter(+ "replay_vision_deep_candidates_total",+ "Sessions the catch-up pass found that the frequent sweep had missed. This is the pass's whole "+ "justification, so it is the number to weigh against what its wide-lookback query costs",+)++REPLAY_VISION_SWEEP_CANDIDATE_PAGE_FULL = Counter(+ "replay_vision_sweep_candidate_page_full_total",+ "Sweep ticks whose candidate page filled, meaning the window held more sessions than one tick "+ "could correlate; a scanner stuck at this is no longer keeping up with its own window",+)+REPLAY_VISION_SWEEP_CANDIDATES = Counter("replay_vision_sweep_candidates_total","Candidate sessions returned to sweeps for dispatch",@@ -228,6 +240,16 @@ def record_auto_materialize_outcome(outcome: str, count: int) -> None:_otel.record_counter_twin(REPLAY_VISION_AUTO_MATERIALIZE_OUTCOMES, count, {"outcome": outcome})+def record_deep_candidates(count: int) -> None:+ REPLAY_VISION_DEEP_CANDIDATES.inc(count)+ _otel.record_counter_twin(REPLAY_VISION_DEEP_CANDIDATES, count, {})+++def record_candidate_page_full() -> None:+ REPLAY_VISION_SWEEP_CANDIDATE_PAGE_FULL.inc()+ _otel.record_counter_twin(REPLAY_VISION_SWEEP_CANDIDATE_PAGE_FULL, 1, {})++def record_deep_sweep_failure() -> None:REPLAY_VISION_DEEP_SWEEP_FAILURES.inc()_otel.record_counter_twin(REPLAY_VISION_DEEP_SWEEP_FAILURES, 1, {})diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.pyindex fe81bf962a90..2a69b49dd0ca 100644--- a/products/replay_vision/backend/temporal/sweep_workflow.py+++ b/products/replay_vision/backend/temporal/sweep_workflow.py@@ -189,7 +189,9 @@ class SweepScannerWorkflow(PostHogWorkflow):# The fetched batch's last row, which sits ahead of the dispatched candidates whenever# exclusion dropped some, so dropping rows cannot stall the walk.swept_at = find_result.keyset_end- last_seen_session_id = find_result.keyset_session_id if find_result.saturated else ""+ # Always carried: the keyset compares the whole tuple, so keeping the tiebreaker cannot+ # skip anything, while dropping it hides any session tied at that exact end_time.+ last_seen_session_id = find_result.keyset_session_idelif find_result.candidates:# Activity results recorded before this deploy carry no keyset.last = find_result.candidates[-1]diff --git a/products/replay_vision/backend/tests/test_candidate_batch.py b/products/replay_vision/backend/tests/test_candidate_batch.pynew file mode 100644index 000000000000..21e805d829c6--- /dev/null+++ b/products/replay_vision/backend/tests/test_candidate_batch.py@@ -0,0 +1,144 @@+import datetime as dt++import pytest++from parameterized import parameterized++from posthog.schema import RecordingsQuery++from posthog.hogql import ast++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 (+ CandidateSession,+ ScannerCandidateQuery,+ build_candidate_batch,+ run_correlated_batch,+ session_in_predicates,+)++_T0 = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)+++def _sessions(count: int, prefix: str = "s") -> list[CandidateSession]:+ return [+ CandidateSession(session_id=f"{prefix}-{i}", session_end=_T0 + dt.timedelta(seconds=i)) for i in range(count)+ ]+++def _bounds_sessions(node: ast.Expr | None) -> bool:+ """Whether the outer query restricts `sessions.session_id` to a fixed list."""+ if node is None:+ return False+ if (+ isinstance(node, ast.CompareOperation)+ and node.op == ast.CompareOperationOp.In+ and isinstance(node.left, ast.Field)+ and node.left.chain[-1] == "session_id"+ and isinstance(node.right, ast.Constant)+ ):+ return True+ return any(_bounds_sessions(e) for e in (getattr(node, "exprs", None) or []))+++class TestBuildCandidateBatch:+ @parameterized.expand(+ [+ # Fewer matches than room to dispatch: the walk covered every candidate, so it may move+ # past the ones that did not match. Stopping at the last match would re-walk them forever.+ ("all_matches_fit", 10, 3, 20, 100, 3, "s-9", False),+ # More matches than room: everything past the last dispatched one is unexamined ground.+ # Advancing to the last candidate here would drop matched sessions permanently.+ ("more_matches_than_room", 50, 40, 10, 100, 10, "m-9", True),+ # Candidate scan hit its own cap, so more sessions wait past the keyset.+ ("candidate_scan_saturated", 100, 2, 20, 100, 2, "s-99", True),+ ("nothing_matched", 10, 0, 20, 100, 0, "s-9", False),+ ]+ )+ def test_keyset_stops_where_the_tick_stopped(+ self,+ _name: str,+ considered_count: int,+ matched_count: int,+ dispatch_limit: int,+ scan_limit: int,+ expected_dispatched: int,+ expected_keyset_id: str,+ expected_saturated: bool,+ ) -> None:+ considered = _sessions(considered_count, "s")+ matched = _sessions(matched_count, "m")++ batch = build_candidate_batch(considered, matched, dispatch_limit, scan_limit)++ assert len(batch.matched) == expected_dispatched+ assert batch.keyset_session_id == expected_keyset_id+ assert batch.saturated is expected_saturated++ def test_no_candidates_leaves_the_watermark_alone(self) -> None:+ batch = build_candidate_batch([], [], 20, 100)++ assert batch.keyset_end is None+ assert batch.keyset_session_id == ""+++class TestSessionInPredicates:+ def _query(+ self, *, filter_test_accounts: bool, with_event_filter: bool, operand: str = "AND"+ ) -> ScannerCandidateQuery:+ org = Organization.objects.create(name="predicate-test-org")+ team = Team.objects.create(+ organization=org,+ name="predicate-test-team",+ test_account_filters=[+ {"key": "$host", "type": "event", "value": "app.example.com", "operator": "icontains"}+ ],+ )+ query: dict = {"kind": "RecordingsQuery", "filter_test_accounts": filter_test_accounts, "operand": operand}+ if with_event_filter:+ query["properties"] = [{"key": "plan", "type": "event", "value": "pro", "operator": "exact"}]+ return ScannerCandidateQuery(+ team=team,+ query=RecordingsQuery.model_validate(query),+ last_swept_at=dt.datetime.now(dt.UTC) - SETTLE_INTERVAL - dt.timedelta(minutes=10),+ sampling_rate=1.0,+ sampling_salt="salt",+ events_lookback=dt.timedelta(hours=4),+ skip_negative_blocklists=True,+ )++ def test_finds_the_test_account_subquery_as_well_as_the_scanners_own(self) -> None:+ # Test-account filters compile to a second events subquery. Restricting only the first leaves+ # the other scanning the whole events window, which silently costs the entire saving.+ predicates = session_in_predicates(self._query(filter_test_accounts=True, with_event_filter=True).get_query())++ assert len(predicates) == 2++ 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+ # keyset is computed from, so the walk advances over sessions it never correlated.+ candidate_query = self._query(filter_test_accounts=False, with_event_filter=True, operand="OR")+ executed: list[ast.SelectQuery] = []++ def execute(query: ast.SelectQuery, query_type: str) -> list[CandidateSession]:+ executed.append(query)+ return [CandidateSession(session_id="sess-a", session_end=_T0)] if len(executed) == 1 else []++ run_correlated_batch(+ build=candidate_query.get_query,+ execute=execute,+ scan_query_type="scan",+ match_query_type="match",+ dispatch_limit=10,+ )++ assert _bounds_sessions(executed[1].where)++ 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())++ assert predicates == []diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.pyindex 8e6649188210..ea449397a3db 100644--- a/products/replay_vision/backend/tests/test_sweep.py+++ b/products/replay_vision/backend/tests/test_sweep.py@@ -32,7 +32,9 @@ from products.replay_vision.backend.queries import excluded_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import (DEFAULT_CANDIDATE_LIMIT,SWEEP_EVENTS_LOOKBACK,+ CandidateBatch,CandidateSession,+ build_candidate_batch,)from products.replay_vision.backend.temporal import SweepScannerWorkflowfrom products.replay_vision.backend.temporal.activities.advance_scanner_watermark import (@@ -83,6 +85,20 @@ _OBSERVATION_CREDITS = observation_credits_for_model(ScannerModel.GEMINI_3_7_FLA_ACTIVITY = "products.replay_vision.backend.temporal.activities.find_scanner_candidates"+def _wire_batch(mock_query: MagicMock) -> None:+ """Let tests keep expressing the fetched batch as `run.return_value`.++ The activity asks for a `CandidateBatch` now; building it from the same list keeps the old+ meaning (keyset at the last fetched row, saturated when the batch filled).+ """++ def run_batch(dispatch_limit: int, **_: object) -> CandidateBatch:+ fetched = mock_query.return_value.run() or []+ return build_candidate_batch(fetched, fetched, dispatch_limit, dispatch_limit)++ mock_query.return_value.run_batch.side_effect = run_batch++@contextmanagerdef _patched_queries() -> Iterator[tuple[MagicMock, MagicMock]]:"""Patch both candidate queries at the activity's import site, with an empty fast batch by default."""@@ -93,6 +109,7 @@ def _patched_queries() -> Iterator[tuple[MagicMock, MagicMock]]:MockQuery.return_value.run.return_value = []MockQuery.return_value.matches_on_events.return_value = TrueMockDeep.return_value.run.return_value = []+ _wire_batch(MockQuery)yield MockQuery, MockDeep@@ -191,6 +208,7 @@ class TestFindScannerCandidatesActivity:with patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery:+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = []result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -211,6 +229,7 @@ class TestFindScannerCandidatesActivity:with patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery:+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = [candidate_a, candidate_b]result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -245,6 +264,7 @@ class TestFindScannerCandidatesActivity:with patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery:+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = [candidate_ok, candidate_stuck]result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -258,6 +278,7 @@ class TestFindScannerCandidatesActivity:with patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery:+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = []find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -279,6 +300,7 @@ class TestFindScannerCandidatesActivity:with patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery:+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = candidatesresult = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -439,6 +461,7 @@ class TestFindScannerCandidatesActivity:with patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery:+ _wire_batch(MockQuery)find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id))@@ -706,6 +729,7 @@ class TestFindScannerCandidatesActivity:with patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery:+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = []result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -732,6 +756,7 @@ class TestFindScannerCandidatesActivity:patch(f"{_ACTIVITY}.ScannerCandidateQuery") as MockQuery,patch.object(excluded_sessions, "excluded_session_ids", return_value={"blocked"}),):+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = fetchedresult = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -750,6 +775,7 @@ class TestFindScannerCandidatesActivity:patch(f"{_ACTIVITY}.ScannerCandidateQuery") as MockQuery,patch.object(excluded_sessions, "excluded_session_ids", side_effect=RuntimeError("clickhouse down")),):+ _wire_batch(MockQuery)MockQuery.return_value.run.return_value = [CandidateSession(session_id="sess-a", session_end=dt.datetime(2026, 5, 1, 10, 0, tzinfo=dt.UTC))]@@ -783,6 +809,7 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockWindowed,):+ _wire_batch(MockFast)MockFast.return_value.run.return_value = []MockWindowed.return_value.run.return_value = primedresult = find_scanner_candidates_activity(@@ -807,6 +834,7 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockWindowed,):+ _wire_batch(MockFast)MockFast.return_value.run.return_value = []result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -830,6 +858,7 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockWindowed,):+ _wire_batch(MockFast)MockFast.return_value.run.return_value = fastresult = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=2)@@ -851,6 +880,7 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockWindowed,):+ _wire_batch(MockFast)MockFast.return_value.run.return_value = []result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)