: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
feat(replay-vision): scope negative-filter exclusion to the sweep's candidates (#82551)
Tue Haulund97321d2e9b0f
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex deaa25886c87..7f37d099b492 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -6,7 +6,6 @@ from dateutil.relativedelta import relativedeltafrom opentelemetry import tracefrom posthog.schema import (- FilterLogicalOperator,HogQLQueryModifiers,PropertyOperator,RecordingOrder,@@ -34,6 +33,7 @@ from posthog.session_recordings.queries.utils import (_strip_person_and_event_and_cohort_properties,expand_test_account_filters,is_session_property,+ test_account_scoped_query,)from posthog.types import AnyPropertyFilter@@ -132,6 +132,8 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):max_execution_time: int | None = None,extra_having_predicates: list[ast.Expr] | None = None,session_ids_to_exclude: list[str] | None = None,+ # For callers that evaluate negative filters themselves against the fetched rows.+ skip_negative_blocklists: bool = False,bypass_date_window_for_session_ids: bool = False,user: User | None = None,events_sample_factor: float | None = None,@@ -209,6 +211,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):self._max_execution_time = max_execution_timeself._extra_having_predicates = extra_having_predicates or []self._session_ids_to_exclude = session_ids_to_exclude+ self._skip_negative_blocklists = skip_negative_blocklists@tracer.start_as_current_span("SessionRecordingListFromQuery.run")def run(self) -> SessionRecordingQueryResult:@@ -230,13 +233,16 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):)# After the results are in, check whether the exclusion blocklist hit its row cap,- # because past the cap the query silently under-excludes. No-op without negated entities.- ReplayFiltersEventsSubQuery(- self._team,- self._query,- self._allow_event_property_expansion,- hogql_query_modifiers=self._hogql_query_modifiers,- ).check_negative_blocklist_truncation()+ # because past the cap the query silently under-excludes. No-op without negated entities, and+ # nothing to probe when the caller excluded against its own rows instead, where the scoped+ # query is bounded by the ids it was given rather than by the cap.+ if not self._skip_negative_blocklists:+ ReplayFiltersEventsSubQuery(+ self._team,+ self._query,+ self._allow_event_property_expansion,+ hogql_query_modifiers=self._hogql_query_modifiers,+ ).check_negative_blocklist_truncation()with tracer.start_as_current_span("SessionRecordingListFromQuery._data_to_return"):next_cursor = None@@ -296,6 +302,30 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):return ast.OrderExpr(expr=ast.Field(chain=[order_by]), order=direction)@tracer.start_as_current_span("SessionRecordingListFromQuery._where_predicates")+ def excluded_sessions_queries(self, session_ids: list[str]) -> list[ast.SelectQuery]:+ """The scoped counterpart to `skip_negative_blocklists`: which of `session_ids` are excluded.++ A caller that turns the in-query blocklists off must run these and drop what they return.+ They are built from the same preprocessed query this class filters with, so the two forms+ cannot answer for different windows or different property sets.++ Empty when nothing is excluded, which is also how a caller can tell it has nothing to run.+ """+ return [q for b in self._negative_filter_builders() if (q := b.get_excluded_sessions_query(session_ids))]++ def _negative_filter_builders(self) -> list[ReplayFiltersEventsSubQuery]:+ """Every builder that can contribute a negative blocklist: the query's own, plus test accounts."""+ builders = [ReplayFiltersEventsSubQuery(self._team, self._query, self._allow_event_property_expansion)]+ if self._test_account_filters:+ builders.append(+ ReplayFiltersEventsSubQuery(+ self._team,+ test_account_scoped_query(self._query, self._test_account_filters),+ self._allow_event_property_expansion,+ )+ )+ return builders+def _where_predicates(self) -> Union[ast.And, ast.Or]:exprs: list[ast.Expr] = []@@ -411,7 +441,9 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# Negative property filters (NOT_ICONTAINS, IS_NOT, etc.) are handled via a blocklist:# find the small set of sessions that MATCH the positive form, then exclude them.# This avoids scanning all event-sessions which can exceed the LIMIT on high-traffic teams.- negative_blocklist = events_sub_query_builder.get_negative_blocklist_query()+ negative_blocklist = (+ None if self._skip_negative_blocklists else events_sub_query_builder.get_negative_blocklist_query()+ )self.events_subqueries_sampled |= events_sub_query_builder.emitted_sampled_subqueryif negative_blocklist:exprs.append(@@ -510,12 +542,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# a person sub-query, event props need an events sub-query, etc.), so we# build a minimal query with just the test account filters and AND operand.if self._test_account_filters:- test_account_query = self._query.model_copy(deep=True)- test_account_query.properties = list(self._test_account_filters)- test_account_query.operand = FilterLogicalOperator.AND_- test_account_query.events = None- test_account_query.actions = None- test_account_query.console_log_filters = None+ test_account_query = test_account_scoped_query(self._query, self._test_account_filters)test_account_events_builder = ReplayFiltersEventsSubQuery(self._team,@@ -530,7 +557,9 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):op=ast.CompareOperationOp.GlobalIn, left=ast.Field(chain=["s", "session_id"]), right=sub_q))- test_account_negative_blocklist = test_account_events_builder.get_negative_blocklist_query()+ test_account_negative_blocklist = (+ None if self._skip_negative_blocklists else test_account_events_builder.get_negative_blocklist_query()+ )self.events_subqueries_sampled |= test_account_events_builder.emitted_sampled_subqueryif test_account_negative_blocklist:exprs.append(diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.pyindex 93b4305f8110..995e1a1ca011 100644--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py@@ -544,6 +544,62 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):def get_negative_blocklist_query(self) -> ast.SelectQuery | None:return self._negative_blocklist_query()+ def get_excluded_sessions_query(self, session_ids: list[str]) -> ast.SelectQuery | None:+ """Which of `session_ids` carry an event that a negative filter excludes.++ Same predicates as the in-query blocklist, asked the other way round. That form builds every+ blocked session in the lookback so it can be anti-joined during selection; this one starts+ from candidates the caller already holds, so naming them lets the scan prune on session id+ instead of sweeping the window. It returns nothing when the query has no negative filters.++ The `timestamp <= now()` bound is dropped here. Senders choose the timestamp, and a+ future-dated event would otherwise let its session through.+ """+ if not session_ids:+ return None+ where_expr = self._inverted_negative_expr()+ if where_expr is None:+ return None++ where = ast.And(+ exprs=[+ self._where_predicates(where_expr, apply_timestamp_floor=False, apply_future_bound=False),+ ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=_event_session_id_field(),+ right=ast.Constant(value=session_ids),+ ),+ ]+ )+ return ast.SelectQuery(+ select=[ast.Alias(alias="session_id", expr=_event_session_id_field())],+ select_from=self._events_join(sample=False),+ where=where,+ group_by=[_event_session_id_field()],+ # A session id can only be returned once, so the input bounds the output.+ limit=ast.Constant(value=len(session_ids)),+ )++ def _inverted_negative_expr(self) -> ast.Expr | None:+ """Everything that disqualifies a session, as a positive predicate over its events.++ Shared by the in-query blocklist and the scoped exclusion so the two cannot cover different+ filters. None when this query excludes nothing.+ """+ # a negated entity's predicate is already the positive form: sessions performing it get blocked+ blocklist_exprs: list[ast.Expr] = self._event_predicates(self.negated_entities, self._team)++ if self._query.operand != "OR":+ for prop in self._collect_negative_properties():+ operator = cast(PropertyOperator, prop.operator) # type: ignore[union-attr]+ inverted = prop.model_copy(update={"operator": INVERSE_OPERATOR_FOR[operator]})+ blocklist_exprs.append(property_to_expr(inverted, team=self._team, scope="event"))++ if not blocklist_exprs:+ return None+ # Any event matching any positive condition → session goes in blocklist+ return ast.Or(exprs=blocklist_exprs) if len(blocklist_exprs) > 1 else blocklist_exprs[0]+def get_query_for_event_id_matching(self) -> ast.SelectQuery | ast.SelectSetQuery:"""The ids of a session's events that matched ANY ONE of the query's event/action filters,@@ -618,19 +674,25 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):return max(bounds) if bounds else Nonedef _where_predicates(- self, where_expr: ast.Expr | list[ast.Expr] | None, apply_timestamp_floor: bool = True+ self,+ where_expr: ast.Expr | list[ast.Expr] | None,+ apply_timestamp_floor: bool = True,+ apply_future_bound: bool = True,) -> ast.Expr:exprs: list[ast.Expr] = [ast.Call(name="notEmpty",args=[_event_session_id_field()],),- ast.CompareOperation(- op=ast.CompareOperationOp.LtEq,- left=ast.Field(chain=["timestamp"]),- right=ast.Call(name="now", args=[]),- ),]+ if apply_future_bound:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Call(name="now", args=[]),+ )+ )if isinstance(where_expr, ast.Expr):exprs.append(where_expr)@@ -782,21 +844,10 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):operands. Negative property filters stay AND-only because inverting them under ORwould change existing semantics."""- # a negated entity's predicate is already the positive form: sessions performing it get blocked- blocklist_exprs: list[ast.Expr] = self._event_predicates(self.negated_entities, self._team)-- if self._query.operand != "OR":- for prop in self._collect_negative_properties():- operator = cast(PropertyOperator, prop.operator) # type: ignore[union-attr]- inverted = prop.model_copy(update={"operator": INVERSE_OPERATOR_FOR[operator]})- blocklist_exprs.append(property_to_expr(inverted, team=self._team, scope="event"))-- if not blocklist_exprs:+ where_expr = self._inverted_negative_expr()+ if where_expr is None:return None- # Any event matching any positive condition → session goes in blocklist- where_expr = ast.Or(exprs=blocklist_exprs) if len(blocklist_exprs) > 1 else blocklist_exprs[0]-return ast.SelectQuery(select=[ast.Alias(alias="session_id", expr=_event_session_id_field())],select_from=self._events_join(sample=False),diff --git a/posthog/session_recordings/queries/utils.py b/posthog/session_recordings/queries/utils.pyindex ba944c73ca38..ac3c7d196957 100644--- a/posthog/session_recordings/queries/utils.py+++ b/posthog/session_recordings/queries/utils.py@@ -9,12 +9,14 @@ from posthog.schema import (CohortPropertyFilter,EventPropertyFilter,EventsNode,+ FilterLogicalOperator,GroupPropertyFilter,HogQLPropertyFilter,PersonPropertyFilter,PersonsOnEventsMode,PropertyOperator,QueryTiming,+ RecordingsQuery,)from posthog.hogql import ast@@ -179,3 +181,19 @@ def _entity_to_expr(entity: EventsNode | ActionsNode) -> ast.Expr:left=ast.Field(chain=["events", "event"]),right=ast.Constant(value=entity.name),)+++def test_account_scoped_query(query: RecordingsQuery, test_account_filters: list) -> RecordingsQuery:+ """The test-account filters as a query in their own right.++ They are always AND'd regardless of the user's operand, and they need the same sub-query routing+ as user filters, so they get a minimal query of their own rather than joining the property list.+ Shared so a caller evaluating these filters separately cannot drift from the recordings list.+ """+ scoped = query.model_copy(deep=True)+ scoped.properties = list(test_account_filters)+ scoped.operand = FilterLogicalOperator.AND_+ scoped.events = None+ scoped.actions = None+ scoped.console_log_filters = None+ return scopeddiff --git a/products/replay_vision/backend/queries/excluded_sessions.py b/products/replay_vision/backend/queries/excluded_sessions.pynew file mode 100644index 000000000000..2c4bc3e93bba--- /dev/null+++ b/products/replay_vision/backend/queries/excluded_sessions.py@@ -0,0 +1,87 @@+"""Negative-filter exclusion, asked about the candidates a sweep already holds.++A scanner with a negative filter ("host is not X") must never observe a session containing a+disqualifying event, and an observation cannot be retracted. The recordings list enforces that with a+`globalNotIn` subquery that builds every blocked session across the whole lookback, then anti-joins+during selection. Correct, but it costs the same whether the tick has one candidate or none, and most+ticks have none.++The sweep already knows which sessions it is about to dispatch, and that set is small: bounded by the+scanner's in-flight headroom. So it turns the in-query blocklists off, fetches candidates, and asks+the narrow question instead. A tick with no candidates asks nothing at all.++The queries come from the candidate query itself rather than being rebuilt here, so they inherit the+same window and the same preprocessed filters the fetch used. Rebuilding them from the scanner's+stored query is how the two drift: that query carries no dates, so it would scan a window anchored to+now while the fetch is anchored to the watermark.++Nothing is cached. The check is a live query evaluated after the candidates are chosen, so it reads a+strictly more recent snapshot than the in-query form would have, and mutable inputs (cohort+membership, group and person properties) resolve at query time exactly as they do today.+"""++import time++from opentelemetry import trace++from posthog.models import Team++from products.replay_vision.backend.queries.scanner_candidate_query import (+ CandidateSession,+ ScannerCandidateQuery,+ execute_candidate_query,+)++tracer = trace.get_tracer(__name__)++# Bounded by the caller's candidate batch, so it only has to outlast a scan over named session ids.+_MAX_EXECUTION_SECONDS = 60+# Overrunning the activity is worse than a slow scan: the attempt is killed after the candidates were+# found, so the tick retries from the same watermark and never dispatches. Leave room for the caller+# to finish up.+_ACTIVITY_RESERVE_SECONDS = 15+# Session ids are inlined as constants and ClickHouse caps a statement at 1 MiB, so a saturated batch+# could build a query the server rejects. That would fail the tick forever rather than once, since the+# next tick refetches the same rows.+_MAX_IDS_PER_QUERY = 1_000++[email protected]_as_current_span("excluded_session_ids")+def excluded_session_ids(+ *,+ team: Team,+ candidate_query: ScannerCandidateQuery,+ candidates: list[CandidateSession],+ scanner_id: str | None = None,+ seconds_remaining: float | None = None,+) -> set[str]:+ """Which of `candidates` carry an event that a negative filter excludes.++ Empty when the query excludes nothing, so the caller can run this unconditionally.++ Raises rather than returning a partial answer. The in-query blocklists are off by this point, so+ a swallowed failure would dispatch the whole batch unfiltered.+ """+ session_ids = [c.session_id for c in candidates]+ if not session_ids:+ return set()++ budget = _MAX_EXECUTION_SECONDS+ if seconds_remaining is not None:+ budget = min(budget, max(1, int(seconds_remaining - _ACTIVITY_RESERVE_SECONDS)))++ excluded: set[str] = set()+ deadline = time.monotonic() + budget+ for start in range(0, len(session_ids), _MAX_IDS_PER_QUERY):+ chunk = session_ids[start : start + _MAX_IDS_PER_QUERY]+ for exclusion in candidate_query.excluded_sessions_queries(chunk):+ rows = execute_candidate_query(+ exclusion,+ team=team,+ query_type="ReplayVisionExcludedSessionsQuery",+ max_execution_time_seconds=max(1, int(deadline - time.monotonic())),+ # Metered against the scanner's read budget like its candidate query.+ scanner_id=scanner_id,+ )+ excluded.update(row[0] for row in rows)+ return excludeddiff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pyindex 77e48a5f4a73..8a10152e8917 100644--- a/products/replay_vision/backend/queries/scanner_candidate_query.py+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -104,7 +104,7 @@ def eligibility_predicates() -> list[ast.Expr]:]-def _execute_candidate_query(+def execute_candidate_query(query: ast.SelectQuery, *, team: Team, query_type: str, max_execution_time_seconds: int, scanner_id: str | None) -> list[list]:"""One home for the candidate queries' ClickHouse execution policy.@@ -143,6 +143,9 @@ class ScannerCandidateQuery:candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,events_lookback: dt.timedelta | None = None,+ # The sweep drops negative-filter matches after fetching, so it turns the in-query blocklists+ # off and asks about its own candidates instead.+ skip_negative_blocklists: bool = False,# Tags the ClickHouse query for per-scanner read metering; sweep callers should always pass it.scanner_id: str | None = None,) -> None:@@ -193,11 +196,20 @@ class ScannerCandidateQuery:query=inner_query,extra_having_predicates=extra_having,events_timestamp_floor=events_timestamp_floor,+ skip_negative_blocklists=skip_negative_blocklists,)@tracer.start_as_current_span("ScannerCandidateQuery.run")+ def excluded_sessions_queries(self, session_ids: list[str]) -> list[ast.SelectQuery]:+ """Which of `session_ids` this scanner's negative filters exclude, as queries to run.++ Delegates so the exclusion inherits the window and preprocessed filters this query fetched+ with. Empty when nothing is excluded.+ """+ return self._inner.excluded_sessions_queries(session_ids)+def run(self) -> list[CandidateSession]:- rows = _execute_candidate_query(+ rows = execute_candidate_query(self.get_query(),team=self._team,query_type="ReplayVisionScannerCandidateQuery",@@ -363,7 +375,7 @@ class BackfillCandidateQuery:@tracer.start_as_current_span("BackfillCandidateQuery.run")def run(self) -> list[CandidateSession]:- rows = _execute_candidate_query(+ rows = execute_candidate_query(self.get_query(),team=self._team,query_type="ReplayVisionBackfillCandidateQuery",@@ -378,7 +390,7 @@ class BackfillCandidateQuery:select=[ast.Call(name="count", args=[])],select_from=ast.JoinExpr(table=self._windowed_candidates(), alias="candidates"),)- rows = _execute_candidate_query(+ rows = execute_candidate_query(counted,team=self._team,query_type="ReplayVisionBackfillCountQuery",diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.pyindex f219fd7eae1a..52f2a39639bd 100644--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py@@ -1,3 +1,4 @@+import timeimport datetime as dtfrom django.utils import timezone@@ -12,6 +13,7 @@ from posthog.rbac.user_access_control import UserAccessControlfrom products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner+from products.replay_vision.backend.queries import excluded_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import (DEFAULT_CANDIDATE_LIMIT,SWEEP_EVENTS_LOOKBACK,@@ -22,6 +24,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (from products.replay_vision.backend.temporal.constants import (DEEP_SWEEP_INTERVAL,DEEP_SWEEP_MAX_EXECUTION_SECONDS,+ FIND_SCANNER_CANDIDATES_TIMEOUT,SCANNER_SCHEDULE_INTERVAL,)from products.replay_vision.backend.temporal.decorators import track_activity@@ -64,6 +67,7 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin# No watermark advance, so the next executed sweep covers the skipped range in one query.return FindScannerCandidatesOutput(candidates=[], saturated=False)+ started_at = time.monotonic()limit = inputs.candidate_limit if inputs.candidate_limit is not None else DEFAULT_CANDIDATE_LIMITcandidate_query = ScannerCandidateQuery(team=scanner.team,@@ -75,11 +79,25 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Finlast_seen_session_id=scanner.last_seen_session_id or None,candidate_limit=limit,events_lookback=SWEEP_EVENTS_LOOKBACK,+ # Exclusion is applied below against the fetched batch instead.+ skip_negative_blocklists=True,scanner_id=str(scanner.id),)- candidates = candidate_query.run()- # A full batch means there may be more past the keyset; the next sweep resumes from the last candidate.- saturated = len(candidates) == limit+ 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++ # 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.+ excluded = excluded_sessions.excluded_session_ids(+ team=scanner.team,+ candidate_query=candidate_query,+ candidates=fetched,+ scanner_id=str(scanner.id),+ seconds_remaining=FIND_SCANNER_CANDIDATES_TIMEOUT.total_seconds() - (time.monotonic() - started_at),+ )+ candidates = [c for c in fetched if c.session_id not in excluded]# Deep candidates dispatch alongside fast ones, so the two share one in-flight budget: the deep# pass gets whatever headroom the fast pass left. At zero there is nothing left to dispatch, which@@ -103,6 +121,8 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fincandidates=[CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in candidates],saturated=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 "",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/constants.py b/products/replay_vision/backend/temporal/constants.pyindex 7fbb0f79cb77..5b810d463ebf 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -82,6 +82,11 @@ SWEEP_WORKFLOW_EXECUTION_TIMEOUT = dt.timedelta(minutes=15)# attempt, swallowed by the sweep) rather than a retry, and the next tick picks it up.REFRESH_PROMPT_SUGGESTION_TIMEOUT = dt.timedelta(minutes=5)+# What one sweep tick's activity gets end to end. Its ClickHouse queries share this, so the exclusion+# scan is capped by what the candidate query left rather than by a fixed budget of its own: overrunning+# kills the attempt after the candidates were found, so the tick retries without ever dispatching.+FIND_SCANNER_CANDIDATES_TIMEOUT = dt.timedelta(seconds=200)+SCANNER_SCHEDULE_ID_PREFIX = "replay-vision-scanner"# Search-attribute value stamped on every per-scanner schedule so the reconciler can list them.SCANNER_SCHEDULE_TYPE = "replay-vision-scanner-sweep"diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.pyindex 93a27b018a06..1f23eb8e41d2 100644--- a/products/replay_vision/backend/temporal/sweep_types.py+++ b/products/replay_vision/backend/temporal/sweep_types.py@@ -46,6 +46,11 @@ class FindScannerCandidatesOutput(BaseModel, frozen=True):deep_candidates: list[CandidateSessionPayload] = Field(default_factory=list)# Horizon the deep pass covered; None when it didn't run or its batch saturated.deep_swept_through: dt.datetime | None = None+ # Last row of the fetched batch, before negative-filter exclusion dropped any of it. Dropping rows+ # must not regress or stall the keyset. None on pre-deploy histories and on empty batches, where+ # the workflow falls back to deriving the position from `candidates`/`swept_through`.+ keyset_end: dt.datetime | None = None+ keyset_session_id: str = ""class RefreshPromptSuggestionInputs(BaseModel, frozen=True):diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.pyindex 62835e4ce305..4ce9f25749d9 100644--- a/products/replay_vision/backend/temporal/sweep_workflow.py+++ b/products/replay_vision/backend/temporal/sweep_workflow.py@@ -38,6 +38,7 @@ from products.replay_vision.backend.temporal.constants import (APPLY_SCANNER_WORKFLOW_NAME,CHECK_SCANNER_BUDGET_TIMEOUT,COUNT_IN_FLIGHT_APPLIES_TIMEOUT,+ FIND_SCANNER_CANDIDATES_TIMEOUT,PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,PROCESS_VISION_ACTION_WORKFLOW_NAME,REFRESH_PROMPT_SUGGESTION_TIMEOUT,@@ -156,7 +157,7 @@ class SweepScannerWorkflow(PostHogWorkflow):find_result = await wf.execute_activity(find_scanner_candidates_activity,FindScannerCandidatesInputs(scanner_id=inputs.scanner_id, team_id=inputs.team_id, candidate_limit=headroom),- start_to_close_timeout=dt.timedelta(seconds=200),+ start_to_close_timeout=FIND_SCANNER_CANDIDATES_TIMEOUT,schedule_to_close_timeout=dt.timedelta(seconds=450),retry_policy=common.RetryPolicy(initial_interval=dt.timedelta(seconds=5),@@ -171,7 +172,13 @@ class SweepScannerWorkflow(PostHogWorkflow):*(self._start_child(inputs, c) for c in (*find_result.candidates, *find_result.deep_candidates)))- if find_result.candidates:+ if find_result.keyset_end is not None:+ # 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 ""+ elif find_result.candidates:+ # Activity results recorded before this deploy carry no keyset.last = find_result.candidates[-1]swept_at, last_seen_session_id = last.session_end, (last.session_id if find_result.saturated else "")elif find_result.swept_through is not None:diff --git a/products/replay_vision/backend/tests/test_excluded_sessions.py b/products/replay_vision/backend/tests/test_excluded_sessions.pynew file mode 100644index 000000000000..2d47fcf17371--- /dev/null+++ b/products/replay_vision/backend/tests/test_excluded_sessions.py@@ -0,0 +1,146 @@+import datetime as dt++import pytest+from freezegun import freeze_time+from posthog.test.base import ClickhouseTestMixin, _create_event++from posthog.schema import EventPropertyFilter, FilterLogicalOperator, PropertyOperator, RecordingsQuery++from products.replay_vision.backend.models.replay_scanner import SamplingMode+from products.replay_vision.backend.queries.excluded_sessions import excluded_session_ids+from products.replay_vision.backend.queries.scanner_candidate_query import CandidateSession, ScannerCandidateQuery++_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)+_FROZEN_TIME = _NOW.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _not_host(value: str = "internal.example.com") -> RecordingsQuery:+ return RecordingsQuery(+ properties=[EventPropertyFilter(key="$host", value=[value], operator=PropertyOperator.IS_NOT, type="event")]+ )+++def _query_for(team, query: RecordingsQuery, *, last_swept_at: dt.datetime | None = None) -> ScannerCandidateQuery:+ return ScannerCandidateQuery(+ team=team,+ query=query,+ last_swept_at=last_swept_at or (_NOW - dt.timedelta(minutes=5)),+ sampling_rate=1.0,+ sampling_salt="salt",+ sampling_mode=SamplingMode.BALANCED,+ )+++def _candidates(*session_ids: str) -> list[CandidateSession]:+ return [CandidateSession(session_id=s, session_end=_NOW - dt.timedelta(hours=1)) for s in session_ids]+++def _event(team, session_id: str, at: dt.datetime, **props) -> None:+ _create_event(+ team=team,+ event="$pageview",+ distinct_id="d1",+ timestamp=at,+ properties={"$session_id": session_id, **props},+ )+++@freeze_time(_FROZEN_TIME)+class TestExcludedSessions(ClickhouseTestMixin):+ @pytest.mark.django_db+ def test_excludes_only_the_sessions_carrying_a_disqualifying_event(self, team) -> None:+ _event(team, "dirty", _NOW - dt.timedelta(hours=2), **{"$host": "internal.example.com"})+ _event(team, "clean", _NOW - dt.timedelta(hours=2), **{"$host": "app.example.com"})+ # Blocked, but not in this batch: the answer must be scoped to what was asked about.+ _event(team, "elsewhere", _NOW - dt.timedelta(hours=2), **{"$host": "internal.example.com"})++ excluded = excluded_session_ids(+ team=team, candidate_query=_query_for(team, _not_host()), candidates=_candidates("dirty", "clean")+ )++ assert excluded == {"dirty"}++ @pytest.mark.django_db+ def test_excludes_when_the_watermark_lags_behind_the_default_window(self, team) -> None:+ # The scanner's stored query carries no dates, so an exclusion rebuilt from it would scan a+ # window anchored to now and miss a backlog entirely, dispatching it unfiltered.+ lagged = _NOW - dt.timedelta(days=10)+ _event(team, "old-dirty", lagged - dt.timedelta(hours=1), **{"$host": "internal.example.com"})++ excluded = excluded_session_ids(+ team=team,+ candidate_query=_query_for(team, _not_host(), last_swept_at=lagged),+ candidates=_candidates("old-dirty"),+ )++ assert excluded == {"old-dirty"}++ @pytest.mark.django_db+ def test_library_filters_do_not_exclude(self, team) -> None:+ # $lib is routed to a snapshot_library predicate before the events builder sees it, so+ # treating it as an event filter here would drop sessions the recordings list keeps.+ query = RecordingsQuery(+ properties=[EventPropertyFilter(key="$lib", value=["web"], operator=PropertyOperator.IS_NOT, type="event")]+ )+ _event(team, "web-session", _NOW - dt.timedelta(hours=2), **{"$lib": "web"})++ excluded = excluded_session_ids(+ team=team, candidate_query=_query_for(team, query), candidates=_candidates("web-session")+ )++ assert excluded == set()++ @pytest.mark.django_db+ def test_future_dated_disqualifying_event_still_excludes(self, team) -> None:+ # The sender picks the timestamp, so capping the scan at now() would let this session through.+ _event(team, "future", _NOW + dt.timedelta(hours=2), **{"$host": "internal.example.com"})++ assert excluded_session_ids(+ team=team, candidate_query=_query_for(team, _not_host()), candidates=_candidates("future")+ ) == {"future"}++ @pytest.mark.django_db+ def test_team_test_account_filters_exclude(self, team) -> None:+ # Team config AND'd on top of the scanner's own filters, from a separate builder that would+ # silently stop applying if it were dropped.+ team.test_account_filters = [+ {"key": "$host", "value": ["staging.example.com"], "operator": "is_not", "type": "event"}+ ]+ team.save()+ query = _not_host()+ query.filter_test_accounts = True+ _event(team, "staging", _NOW - dt.timedelta(hours=2), **{"$host": "staging.example.com"})+ _event(team, "clean", _NOW - dt.timedelta(hours=2), **{"$host": "app.example.com"})++ excluded = excluded_session_ids(+ team=team, candidate_query=_query_for(team, query), candidates=_candidates("staging", "clean")+ )++ assert excluded == {"staging"}++ # pytest's own parametrize, not parameterized.expand, which does not compose with fixtures.+ @pytest.mark.parametrize(+ "operator,operand,expected",+ [+ (PropertyOperator.EXACT, FilterLogicalOperator.AND_, False),+ (PropertyOperator.IS_NOT, FilterLogicalOperator.AND_, True),+ # Under OR the in-query blocklist does not apply either, so neither must this.+ (PropertyOperator.IS_NOT, FilterLogicalOperator.OR_, False),+ ],+ )+ @pytest.mark.django_db+ def test_only_negative_and_operand_queries_produce_an_exclusion(+ self, operator: PropertyOperator, operand: FilterLogicalOperator, expected: bool, team+ ) -> None:+ # Turning the in-query blocklist off is unconditional, so this decides what replaces it.+ query = RecordingsQuery(+ properties=[EventPropertyFilter(key="$host", value=["x.example.com"], operator=operator, type="event")],+ operand=operand,+ )++ assert bool(_query_for(team, query).excluded_sessions_queries(["s1"])) is expected++ @pytest.mark.django_db+ def test_no_candidates_asks_nothing(self, team) -> None:+ # Where the saving comes from: most ticks have no candidates and must issue no query.+ assert excluded_session_ids(team=team, candidate_query=_query_for(team, _not_host()), candidates=[]) == set()diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.pyindex 6def9d0ecf84..5905792d950d 100644--- a/products/replay_vision/backend/tests/test_sweep.py+++ b/products/replay_vision/backend/tests/test_sweep.py@@ -17,6 +17,7 @@ from products.replay_vision.backend.models.replay_observation import (ReplayObservation,)from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.queries import excluded_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import (DEFAULT_CANDIDATE_LIMIT,SWEEP_EVENTS_LOOKBACK,@@ -438,6 +439,51 @@ class TestFindScannerCandidatesActivity:assert result.swept_through is Noneassert result.candidates == []+ _NEGATIVE_QUERY = {+ "kind": "RecordingsQuery",+ "properties": [{"key": "$host", "value": ["internal.example.com"], "operator": "is_not", "type": "event"}],+ }++ def test_fully_excluded_batch_still_advances_the_keyset(self) -> None:+ # Falling back to the last surviving candidate would leave the keyset where it was and refetch+ # the same excluded rows forever.+ scanner = _make_scanner(query=self._NEGATIVE_QUERY)+ fetched = [CandidateSession(session_id="blocked", session_end=dt.datetime(2026, 5, 1, 10, 0, tzinfo=dt.UTC))]++ with (+ patch(+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"+ ) as MockQuery,+ patch.object(excluded_sessions, "excluded_session_ids", return_value={"blocked"}),+ ):+ MockQuery.return_value.run.return_value = fetched+ result = find_scanner_candidates_activity(+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ assert MockQuery.call_args.kwargs["skip_negative_blocklists"] is True+ assert result.candidates == []+ assert result.keyset_session_id == "blocked"+ assert result.keyset_end == fetched[0].session_end++ def test_exclusion_failure_fails_the_tick_rather_than_dispatching(self) -> None:+ # The in-query blocklists are off by this point, so swallowing this would dispatch unfiltered.+ scanner = _make_scanner(query=self._NEGATIVE_QUERY)++ with (+ patch(+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"+ ) as MockQuery,+ patch.object(excluded_sessions, "excluded_session_ids", side_effect=RuntimeError("clickhouse down")),+ ):+ MockQuery.return_value.run.return_value = [+ CandidateSession(session_id="sess-a", session_end=dt.datetime(2026, 5, 1, 10, 0, tzinfo=dt.UTC))+ ]+ with pytest.raises(RuntimeError):+ find_scanner_candidates_activity(+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )+def test_raises_non_retryable_on_malformed_query(self) -> None:scanner = _make_scanner()scanner.query = {"kind": "TrendsQuery"}