: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): separate the deep sweep from backfill reads (#83600)
Tue Haulund80f1ddd0a3c3
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex b1cd71d86dee..f804773e99ed 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -400,7 +400,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):return ast.OrderExpr(expr=ast.Field(chain=[order_by]), order=direction)- @tracer.start_as_current_span("SessionRecordingListFromQuery._where_predicates")+ @tracer.start_as_current_span("SessionRecordingListFromQuery.excluded_sessions_queries")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.@@ -410,10 +410,14 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):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))]+ return [q for b in self._events_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."""+ def matches_on_events(self) -> bool:+ """Whether any filter narrows sessions by their events, so `events_timestamp_floor` can cost results."""+ return any(b.get_queries_for_session_id_matching() for b in self._events_filter_builders())++ def _events_filter_builders(self) -> list[ReplayFiltersEventsSubQuery]:+ """Every builder that can contribute an events subquery: 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(diff --git a/products/replay_vision/backend/api/backfills.py b/products/replay_vision/backend/api/backfills.pyindex 692b304523df..7a335449442a 100644--- a/products/replay_vision/backend/api/backfills.py+++ b/products/replay_vision/backend/api/backfills.py@@ -30,7 +30,7 @@ from products.replay_vision.backend.models.replay_scanner_backfill import (BackfillStatus,ReplayScannerBackfill,)-from products.replay_vision.backend.queries.scanner_candidate_query import BackfillCandidateQuery+from products.replay_vision.backend.queries.scanner_candidate_query import WindowedCandidateQueryfrom products.replay_vision.backend.quota import quota_statefrom products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot@@ -215,18 +215,19 @@ class ReplayScannerBackfillViewSet(exclude_observed: bool = False,) -> int:snapshot = BackfillScannerSnapshot.from_scanner(scanner)- return BackfillCandidateQuery(+ return WindowedCandidateQuery(team=self.team,query=scanner.recordings_query(),window_start=window_start,window_end=window_end,+ query_type="ReplayVisionBackfillCandidateQuery",sampling_rate=snapshot.sampling_rate,sampling_salt=str(scanner.id),scanner_id=str(scanner.id),sampling_mode=snapshot.sampling_mode,exclude_observed_by_scanner=str(scanner.id) if exclude_observed else None,max_execution_time_seconds=ENUMERATION_MAX_EXECUTION_SECONDS,- ).count()+ ).count(query_type="ReplayVisionBackfillCountQuery")def _unobserved_count(self, scanner: ReplayScanner, window_start: datetime, window_end: datetime) -> int:"""Upper bound on what a backfill over this window would scan, rejecting when it is zero.diff --git a/products/replay_vision/backend/queries/excluded_sessions.py b/products/replay_vision/backend/queries/excluded_sessions.pyindex 44323c899686..6e473294ffc9 100644--- a/products/replay_vision/backend/queries/excluded_sessions.py+++ b/products/replay_vision/backend/queries/excluded_sessions.py@@ -27,14 +27,14 @@ from opentelemetry import tracefrom posthog.models import Teamfrom products.replay_vision.backend.queries.scanner_candidate_query import (- BackfillCandidateQuery,CandidateSession,ScannerCandidateQuery,+ WindowedCandidateQuery,execute_candidate_query,)# Both fetch candidates with the in-query blocklists off, so both owe the caller this question.-CandidateQuery = ScannerCandidateQuery | BackfillCandidateQuery+CandidateQuery = ScannerCandidateQuery | WindowedCandidateQuerytracer = trace.get_tracer(__name__)diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pyindex 300013769faa..1e73b2a21dee 100644--- a/products/replay_vision/backend/queries/scanner_candidate_query.py+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -199,11 +199,15 @@ class ScannerCandidateQuery: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]:"""Delegates, so the exclusion inherits the window and filters this query fetched with."""return self._inner.excluded_sessions_queries(session_ids)+ def matches_on_events(self) -> bool:+ """Whether `events_lookback` can cost this query candidates, so a deep pass has work to do."""+ return self._inner.matches_on_events()++ @tracer.start_as_current_span("ScannerCandidateQuery.run")def run(self) -> list[CandidateSession]:rows = execute_candidate_query(self.get_query(),@@ -295,14 +299,18 @@ def sampling_predicate(sampling_rate: float, sampling_salt: str) -> ast.Expr | N)-class BackfillCandidateQuery:- """Enumerate a backfill's candidate sessions inside a closed historical window.+class WindowedCandidateQuery:+ """Enumerate a scanner's candidate sessions inside a closed historical window.Same eligibility, sampling, and surfacing predicates as `ScannerCandidateQuery`, but bounded on bothsides and walked newest-first: batches descend from `window_end` via a `(end_time, session_id)` keysetcursor. `count()` runs the identical predicate set without cursor or limit, so the creation-timeenumeration is exactly the set the ticks will walk (the window is closed, so it can only shrink asrecordings expire from retention — never grow).++ Two callers walk windows this way: backfills over a user-chosen range, and the sweep's deep pass+ over the range behind its own watermark. Each names its own reads, so a shared class cannot make+ one path's ClickHouse cost look like the other's."""def __init__(@@ -312,6 +320,8 @@ class BackfillCandidateQuery:query: RecordingsQuery,window_start: dt.datetime,window_end: dt.datetime,+ # Tags this caller's reads in `system.query_log`; required so a new caller names itself.+ query_type: str,sampling_rate: float,sampling_salt: str,sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,@@ -342,6 +352,7 @@ class BackfillCandidateQuery:self._team = teamself._window_start = window_startself._window_end = window_end+ self._query_type = query_typeself._cursor_end_time = cursor_end_timeself._cursor_session_id = cursor_session_idself._exclude_observed_by_scanner = exclude_observed_by_scanner@@ -377,19 +388,19 @@ class BackfillCandidateQuery:"""Delegates, so the exclusion inherits the window and filters this query fetched with."""return self._inner.excluded_sessions_queries(session_ids)- @tracer.start_as_current_span("BackfillCandidateQuery.run")+ @tracer.start_as_current_span("WindowedCandidateQuery.run")def run(self) -> list[CandidateSession]:rows = execute_candidate_query(self.get_query(),team=self._team,- query_type="ReplayVisionBackfillCandidateQuery",+ query_type=self._query_type,max_execution_time_seconds=self._max_execution_time_seconds,scanner_id=self._scanner_id,)return [CandidateSession(session_id=row[0], session_end=row[1]) for row in rows]- @tracer.start_as_current_span("BackfillCandidateQuery.count")- def count(self) -> int:+ @tracer.start_as_current_span("WindowedCandidateQuery.count")+ def count(self, *, query_type: str) -> int:counted = ast.SelectQuery(select=[ast.Call(name="count", args=[])],select_from=ast.JoinExpr(table=self._windowed_candidates(), alias="candidates"),@@ -397,7 +408,7 @@ class BackfillCandidateQuery:rows = execute_candidate_query(counted,team=self._team,- query_type="ReplayVisionBackfillCountQuery",+ 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/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.pyindex c68cfb84bdf4..db7cbf0d87d6 100644--- a/products/replay_vision/backend/temporal/activities/backfill.py+++ b/products/replay_vision/backend/temporal/activities/backfill.py@@ -26,7 +26,7 @@ from products.replay_vision.backend.models.replay_scanner_backfill import (ReplayScannerBackfill,)from products.replay_vision.backend.queries import excluded_sessions-from products.replay_vision.backend.queries.scanner_candidate_query import BackfillCandidateQuery+from products.replay_vision.backend.queries.scanner_candidate_query import WindowedCandidateQueryfrom products.replay_vision.backend.quota import compute_scanner_budget, quota_statefrom products.replay_vision.backend.temporal.activities.count_in_flight_applies import (count_in_flight,@@ -157,11 +157,12 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> Ff"ReplayScannerBackfill {inputs.backfill_id} has malformed frozen query: {exc}", non_retryable=True) from exc- candidate_query = BackfillCandidateQuery(+ candidate_query = WindowedCandidateQuery(team=backfill.team,query=query,window_start=backfill.window_start,window_end=backfill.window_end,+ query_type="ReplayVisionBackfillCandidateQuery",sampling_rate=snapshot.sampling_rate,# Same salt as the live sweep, so a sampled scanner backfills the same deterministic bucket it scans live.sampling_salt=str(backfill.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 8a20eb9a6747..29b7e9602bea 100644--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py@@ -17,9 +17,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,- BackfillCandidateQuery,CandidateSession,ScannerCandidateQuery,+ WindowedCandidateQuery,)from products.replay_vision.backend.temporal.constants import (DEEP_SWEEP_INTERVAL,@@ -111,7 +111,7 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin# tick: seeding only once headroom frees up would leave the range in between with no deep pass.deep_swept_through = scanner.last_swept_atelif deep_limit > 0:- deep_candidates, deep_swept_through = _deep_sweep(scanner, query, deep_limit)+ deep_candidates, deep_swept_through = _deep_sweep(scanner, query, candidate_query, deep_limit)record_sweep_outcome("candidates_found" if candidates or deep_candidates else "no_candidates",@@ -152,7 +152,7 @@ def _throttled(scanner: ReplayScanner) -> bool:def _deep_sweep(- scanner: ReplayScanner, query: RecordingsQuery, limit: int+ scanner: ReplayScanner, query: RecordingsQuery, fast_query: ScannerCandidateQuery, limit: int) -> tuple[list[CandidateSession], dt.datetime | None]:"""Catch-up pass behind the fast watermark with the full events lookback.@@ -166,6 +166,17 @@ def _deep_sweep(if now - scanner.last_deep_swept_at < DEEP_SWEEP_INTERVAL or scanner.last_deep_swept_at >= scanner.last_swept_at:return [], None+ # Only the fast pass's events window can cost it candidates, so with nothing matching on events+ # this pass would re-find what the fast pass already dispatched. Advancing rather than parking the+ # watermark keeps the window this pass would open bounded if the query later gains an event filter.+ # The range behind the watermark has to have been swept under the current query though: an edit+ # that drops the last event filter leaves stragglers back there that only this pass ever revisits.+ # `updated_at` is safe to read as "query may have changed" because watermarks advance through+ # queryset updates, which do not touch it.+ settled_since_last_edit = scanner.updated_at <= scanner.last_deep_swept_at+ if settled_since_last_edit and not fast_query.matches_on_events():+ return [], scanner.last_swept_at+# Exclude on observation rows rather than on the `$recording_observed` event. That event only# lands on the success path, so failed and ineligible sessions would keep matching and the walk# would never move past them. It is also an ingested event, so it is not ours to trust.@@ -177,11 +188,12 @@ def _deep_sweep().values_list("session_id", flat=True)[:_DEEP_SWEEP_MAX_EXCLUSIONS])- deep_query = BackfillCandidateQuery(+ deep_query = WindowedCandidateQuery(team=scanner.team,query=query,window_start=scanner.last_deep_swept_at,window_end=scanner.last_swept_at,+ query_type="ReplayVisionDeepSweepCandidateQuery",sampling_rate=scanner.sampling_rate,sampling_salt=str(scanner.id),sampling_mode=scanner.sampling_mode,diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.pyindex 2c1744fcd18f..a3e4fb9cad6f 100644--- a/products/replay_vision/backend/tests/test_backfills.py+++ b/products/replay_vision/backend/tests/test_backfills.py@@ -485,7 +485,7 @@ class TestBackfillTickActivities:# tick died, the minute schedule refired forever, and the backfill sat RUNNING until cancelled.scanner = _make_scanner()backfill = _make_backfill(scanner)- with patch("products.replay_vision.backend.temporal.activities.backfill.BackfillCandidateQuery") as query_cls:+ with patch("products.replay_vision.backend.temporal.activities.backfill.WindowedCandidateQuery") as query_cls:query_cls.return_value.run.return_value = []result = find_backfill_candidates_activity(FindBackfillCandidatesInputs(backfill_id=backfill.id, team_id=backfill.team_id, candidate_limit=50)@@ -506,7 +506,7 @@ class TestBackfillTickActivities:CandidateSession(session_id="blocked", session_end=timezone.now() - dt.timedelta(hours=1)),]with (- patch("products.replay_vision.backend.temporal.activities.backfill.BackfillCandidateQuery") as query_cls,+ patch("products.replay_vision.backend.temporal.activities.backfill.WindowedCandidateQuery") as query_cls,patch.object(excluded_sessions, "excluded_session_ids", return_value={"blocked"}),):query_cls.return_value.run.return_value = fetched@@ -524,7 +524,7 @@ class TestBackfillTickActivities:scanner = _make_scanner()backfill = _make_backfill(scanner)with (- patch("products.replay_vision.backend.temporal.activities.backfill.BackfillCandidateQuery") as query_cls,+ patch("products.replay_vision.backend.temporal.activities.backfill.WindowedCandidateQuery") as query_cls,patch.object(excluded_sessions, "excluded_session_ids", side_effect=RuntimeError("clickhouse down")),):query_cls.return_value.run.return_value = [@@ -569,7 +569,7 @@ class TestBackfillsApi(APIBaseTest):}@patch("products.replay_vision.backend.temporal.schedule.a_upsert_backfill_schedule", new_callable=AsyncMock)- @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ @patch("products.replay_vision.backend.api.backfills.WindowedCandidateQuery")def test_create_freezes_config_clamps_window_to_settle_horizon_and_rejects_second_active(self, mock_query: MagicMock, mock_upsert: AsyncMock) -> None:@@ -597,7 +597,7 @@ class TestBackfillsApi(APIBaseTest):assert response.status_code == 400assert "active backfill" in response.json()["detail"]- @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ @patch("products.replay_vision.backend.api.backfills.WindowedCandidateQuery")def test_estimate_returns_exact_ceiling_without_creating_rows(self, mock_query: MagicMock) -> None:mock_query.return_value.count.return_value = 40response = self.client.post(f"{self.base_url}/estimate/", self._window_body(), format="json")@@ -607,7 +607,7 @@ class TestBackfillsApi(APIBaseTest):assert body["total_credits"] == 40 * body["credits_per_observation"]assert not ReplayScannerBackfill.objects.for_team(self.team.id).filter(scanner=self.scanner).exists()- @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ @patch("products.replay_vision.backend.api.backfills.WindowedCandidateQuery")def test_window_stops_at_the_settle_horizon_the_sweep_waits_for(self, mock_query: MagicMock) -> None:# A session inside the settle window is still recording or still merging. Scanning it yields a# truncated observation, and the unique (scanner, session) constraint means that is the only@@ -644,7 +644,7 @@ class TestBackfillsApi(APIBaseTest):assert response.status_code == 400assert "365 days" in str(response.json())- @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ @patch("products.replay_vision.backend.api.backfills.WindowedCandidateQuery")def test_estimate_rejects_when_every_candidate_is_already_observed(self, mock_query: MagicMock) -> None:# Excluded run returns 0 while the unfiltered run finds rows: nothing left for a backfill to do.mock_query.return_value.count.side_effect = [0, 5]@@ -660,7 +660,7 @@ class TestBackfillsApi(APIBaseTest):assert response.status_code == 400assert "already been scanned" in str(response.json())- @patch("products.replay_vision.backend.api.backfills.BackfillCandidateQuery")+ @patch("products.replay_vision.backend.api.backfills.WindowedCandidateQuery")def test_estimate_rejects_when_nothing_matches_the_scanner(self, mock_query: MagicMock) -> None:mock_query.return_value.count.return_value = 0response = self.client.post(f"{self.base_url}/estimate/", self._window_body(), format="json")diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.pyindex 960cea9b0cdb..466981a0b86c 100644--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py@@ -25,8 +25,8 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (FOCUSED_SURFACING_THRESHOLD,SETTLE_INTERVAL,SWEEP_EVENTS_LOOKBACK,- BackfillCandidateQuery,ScannerCandidateQuery,+ WindowedCandidateQuery,surfacing_score_predicate,)from products.replay_vision.backend.queries.scanner_volume_estimate import (@@ -187,6 +187,48 @@ def test_surfacing_score_predicate_emits_threshold(mode, expected_threshold):assert isinstance(expr.right, ast.Constant) and expr.right.value == expected_threshold+# Whether the narrow events window can cost this query candidates (needs a team, no ClickHouse).+++def _positive_event_filter() -> EventPropertyFilter:+ return EventPropertyFilter(key="$host", value=["app.example.com"], operator=PropertyOperator.EXACT, type="event")+++ "make_query, expected",+ [+ (lambda: RecordingsQuery(properties=[_positive_event_filter()]), True),+ # Negative filters are enforced unbounded, so the events window never costs them anything.+ (+ lambda: RecordingsQuery(+ properties=[+ EventPropertyFilter(+ key="$host", value=["internal.example.com"], operator=PropertyOperator.IS_NOT, type="event"+ )+ ]+ ),+ False,+ ),+ (lambda: RecordingsQuery(), False),+ ],+)+def test_matches_on_events_tracks_positive_event_filters(make_query, expected: bool, team) -> None:+ # A false negative here silently retires the deep pass for that scanner, and the stragglers it+ # exists to catch are then never observed at all.+ assert _make_query(team=team, query=make_query()).matches_on_events() is expected+++def test_matches_on_events_covers_test_account_filters(team) -> None:+ # Team config routes through a second builder that a naive implementation would never consult.+ team.test_account_filters = [{"key": "$host", "value": ["app.example.com"], "operator": "exact", "type": "event"}]+ team.save()+ query = RecordingsQuery(filter_test_accounts=True)++ assert _make_query(team=team, query=query).matches_on_events() is True++# Integration: actual ClickHouse query.@@ -741,7 +783,7 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):@freeze_time(_FROZEN_TIME)-class TestBackfillCandidateQueryAgainstClickHouse(ClickhouseTestMixin):+class TestWindowedCandidateQueryAgainstClickHouse(ClickhouseTestMixin):def setup_method(self, _method) -> None:sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())@@ -757,12 +799,13 @@ class TestBackfillCandidateQueryAgainstClickHouse(ClickhouseTestMixin):)@staticmethod- def _query(*, team, window_start: dt.datetime, window_end: dt.datetime, **kwargs) -> BackfillCandidateQuery:- return BackfillCandidateQuery(+ def _query(*, team, window_start: dt.datetime, window_end: dt.datetime, **kwargs) -> WindowedCandidateQuery:+ return WindowedCandidateQuery(team=team,query=kwargs.pop("query", RecordingsQuery()),window_start=window_start,window_end=window_end,+ query_type=kwargs.pop("query_type", "ReplayVisionBackfillCandidateQuery"),sampling_rate=kwargs.pop("sampling_rate", 1.0),sampling_salt=kwargs.pop("sampling_salt", "scanner-1"),**kwargs,@@ -792,7 +835,8 @@ class TestBackfillCandidateQueryAgainstClickHouse(ClickhouseTestMixin):team.id, "after-window", window_end + dt.timedelta(minutes=1), window_end + dt.timedelta(minutes=30))- assert self._query(team=team, window_start=window_start, window_end=window_end).count() == 6+ counted = self._query(team=team, window_start=window_start, window_end=window_end)+ assert counted.count(query_type="ReplayVisionBackfillCountQuery") == 6walked: list[str] = []cursor_end, cursor_sid = None, Nonediff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.pyindex b87cbd439669..2868d52702a4 100644--- a/products/replay_vision/backend/tests/test_sweep.py+++ b/products/replay_vision/backend/tests/test_sweep.py@@ -77,6 +77,16 @@ def _make_scanner(**overrides) -> ReplayScanner:return ReplayScanner.objects.create(**defaults)+def _settle_edit_clock(scanner: ReplayScanner) -> None:+ # Backdates `updated_at` past the deep watermark so the scanner reads as unedited since its last+ # deep pass. Queryset update, because `auto_now` would stamp it back to now on save().+ if scanner.last_deep_swept_at is None:+ return+ settled = scanner.last_deep_swept_at - dt.timedelta(minutes=1)+ ReplayScanner.objects.filter(pk=scanner.pk).update(updated_at=settled)+ scanner.updated_at = settled++def _seed_in_flight_observations(scanner: ReplayScanner, *, count: int) -> None:# Pending rows reserve credits live from their snapshot model. They settle no receipt until success.snapshot = snapshot_for(scanner)@@ -206,27 +216,65 @@ class TestFindScannerCandidatesActivity:assert result.saturated is Trueassert len(result.candidates) == DEFAULT_CANDIDATE_LIMIT- def test_first_sweep_initializes_deep_watermark_without_catchup_query(self) -> None:- scanner = _make_scanner()- assert scanner.last_deep_swept_at is None+ @parameterized.expand(+ [+ # Nothing swept yet, so there is no range behind the watermark to catch up on.+ ("first_sweep", None, True),+ # Nothing the narrow events window could have cost this scanner, so nothing to catch up on.+ ("no_events_filters", dt.timedelta(hours=7), False),+ ]+ )+ def test_deep_pass_skipped_but_watermark_still_advances(+ self, _name: str, deep_watermark_age: dt.timedelta | None, matches_on_events: bool+ ) -> None:+ scanner = _make_scanner(+ last_deep_swept_at=None if deep_watermark_age is None else dt.datetime.now(dt.UTC) - deep_watermark_age+ )+ _settle_edit_clock(scanner)with (patch("products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery,patch(- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.BackfillCandidateQuery"+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockDeep,):MockQuery.return_value.run.return_value = []+ MockQuery.return_value.matches_on_events.return_value = matches_on_eventsresult = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id))MockDeep.assert_not_called()assert result.deep_candidates == []+ # Parking the watermark instead would hand a later tick an arbitrarily wide catch-up window.assert result.deep_swept_through == scanner.last_swept_at+ def test_deep_pass_runs_once_more_after_the_query_loses_its_event_filters(self) -> None:+ # The range behind the watermark was swept under the old filters, with the fast pass's narrow+ # events window costing it candidates. Skipping on the new filters would strand them there:+ # the fast pass never looks back, so this is the only pass that revisits that range.+ scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))+ assert scanner.last_deep_swept_at is not None and scanner.updated_at > scanner.last_deep_swept_at++ with (+ patch(+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"+ ) as MockQuery,+ patch(+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery"+ ) as MockDeep,+ ):+ MockQuery.return_value.run.return_value = []+ MockQuery.return_value.matches_on_events.return_value = False+ MockDeep.return_value.run.return_value = []+ find_scanner_candidates_activity(+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)+ )++ MockDeep.assert_called_once()+def test_stale_deep_watermark_runs_full_width_catchup(self) -> None:deep_watermark = dt.datetime.now(dt.UTC) - dt.timedelta(hours=7)scanner = _make_scanner(last_deep_swept_at=deep_watermark)@@ -239,10 +287,11 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery,patch(- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.BackfillCandidateQuery"+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockDeep,):MockQuery.return_value.run.return_value = []+ MockQuery.return_value.matches_on_events.return_value = TrueMockDeep.return_value.run.return_value = [straggler]result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)@@ -270,10 +319,11 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery,patch(- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.BackfillCandidateQuery"+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockDeep,):MockQuery.return_value.run.return_value = []+ MockQuery.return_value.matches_on_events.return_value = TrueMockDeep.return_value.run.return_value = [straggler]result = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=5)@@ -300,7 +350,7 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery,patch(- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.BackfillCandidateQuery"+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockDeep,):MockQuery.return_value.run.return_value = fast@@ -333,7 +383,7 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery,patch(- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.BackfillCandidateQuery"+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockDeep,):MockQuery.return_value.run.return_value = fast@@ -368,10 +418,11 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery,patch(- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.BackfillCandidateQuery"+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockDeep,):MockQuery.return_value.run.return_value = []+ MockQuery.return_value.matches_on_events.return_value = TrueMockDeep.return_value.run.return_value = []find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=5)@@ -394,10 +445,11 @@ class TestFindScannerCandidatesActivity:"products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery") as MockQuery,patch(- "products.replay_vision.backend.temporal.activities.find_scanner_candidates.BackfillCandidateQuery"+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.WindowedCandidateQuery") as MockDeep,):MockQuery.return_value.run.return_value = []+ MockQuery.return_value.matches_on_events.return_value = TrueMockDeep.return_value.run.return_value = stragglersresult = find_scanner_candidates_activity(FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=3)