Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): two-tier sweep with narrow events windows (#81725)

Tue Haulund72c695c4face
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index 413e5677fb52..6911b478cb58 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -135,11 +135,15 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
bypass_date_window_for_session_ids: bool = False,
user: User | None = None,
events_sample_factor: float | None = None,
+ events_timestamp_floor: datetime | None = None,
**_,
):
self._user = user
# Storage-level SAMPLE on any events subqueries; opt-in for estimates.
self._events_sample_factor = events_sample_factor
+ # Extra lower bound on positive events subqueries, for callers that re-run often over a wide
+ # session window and do not need each run to re-scan the whole range.
+ self._events_timestamp_floor = events_timestamp_floor
self.events_subqueries_sampled = False
self._bypass_date_window_for_session_ids = bypass_date_window_for_session_ids
# TRICKY: we need to make sure we init test account filters only once,
@@ -376,7 +380,11 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
# if in PoE mode then we should be pushing person property queries into here
events_sub_query_builder = ReplayFiltersEventsSubQuery(
- self._team, self._query, self._allow_event_property_expansion, sample_factor=self._events_sample_factor
+ self._team,
+ self._query,
+ self._allow_event_property_expansion,
+ sample_factor=self._events_sample_factor,
+ events_timestamp_floor=self._events_timestamp_floor,
)
events_sub_queries = events_sub_query_builder.get_queries_for_session_id_matching()
for events_sub_query in events_sub_queries:
@@ -505,6 +513,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
test_account_query,
self._allow_event_property_expansion,
sample_factor=self._events_sample_factor,
+ events_timestamp_floor=self._events_timestamp_floor,
)
for sub_q in test_account_events_builder.get_queries_for_session_id_matching():
exprs.append(
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index feeaf567529f..d0177582981c 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -1,5 +1,5 @@
from collections.abc import Iterable
-from datetime import timedelta
+from datetime import datetime, timedelta
from typing import Optional, cast
import posthoganalytics
@@ -85,11 +85,16 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
allow_event_property_expansion: bool = False,
hogql_query_modifiers: Optional[HogQLQueryModifiers] = None,
sample_factor: Optional[float] = None,
+ events_timestamp_floor: Optional[datetime] = None,
):
super().__init__(team, query)
self._hogql_query_modifiers = hogql_query_modifiers
self._allow_event_property_expansion = allow_event_property_expansion
self._sample_factor = sample_factor
+ # Extra lower bound on positive events scans; only ever narrows the date-range bound. For
+ # callers that re-run often over a wide session window. Exclusion blocklists never apply it,
+ # since a truncated blocklist would under-exclude.
+ self._events_timestamp_floor = events_timestamp_floor
self.emitted_sampled_subquery = False
def _events_join(self, sample: bool = True) -> ast.JoinExpr:
@@ -274,7 +279,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
"""
# Calculate date range with ±1 day buffer to match events_subquery behavior
# Events can arrive before session starts or after it ends
- date_from_buffered = self.query_date_range.date_from() - timedelta(days=1)
+ date_from_buffered = self._events_date_from() or self.query_date_range.date_from() - timedelta(days=1)
date_to_buffered = self.query_date_range.date_to() + timedelta(days=1)
return ast.SelectQuery(
@@ -583,7 +588,22 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
timings=hogql_query_response.timings,
)
- def _where_predicates(self, where_expr: ast.Expr | list[ast.Expr] | None) -> ast.Expr:
+ def _events_date_from(self, apply_floor: bool = True) -> Optional[datetime]:
+ """Lower bound for an events scan, or None when nothing bounds it.
+
+ The recording date range is pushed a day earlier because events can arrive before the
+ recording starts. A floor tightens that bound, and can only ever narrow it.
+ """
+ bounds: list[datetime] = []
+ if self._query.date_from:
+ bounds.append(self.query_date_range.date_from() - timedelta(days=1))
+ if apply_floor and self._events_timestamp_floor is not None:
+ bounds.append(self._events_timestamp_floor)
+ return max(bounds) if bounds else None
+
+ def _where_predicates(
+ self, where_expr: ast.Expr | list[ast.Expr] | None, apply_timestamp_floor: bool = True
+ ) -> ast.Expr:
exprs: list[ast.Expr] = [
ast.Call(
name="notEmpty",
@@ -603,7 +623,8 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
# TRICKY: we're adding a buffer to the date range to ensure we get all the events
# you can start sending us events before the session starts
- if self._query.date_from:
+ events_date_from = self._events_date_from(apply_floor=apply_timestamp_floor)
+ if events_date_from is not None:
exprs.append(
ast.CompareOperation(
op=ast.CompareOperationOp.GtEq,
@@ -611,7 +632,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
# TRICKY: technically you could start sending us events
# almost 24 hours before the session recording starts
# so we push the events date range a day earlier
- right=ast.Constant(value=self.query_date_range.date_from() - timedelta(days=1)),
+ right=ast.Constant(value=events_date_from),
)
)
@@ -740,7 +761,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
return ast.SelectQuery(
select=[ast.Alias(alias="session_id", expr=_event_session_id_field())],
select_from=self._events_join(sample=False),
- where=self._where_predicates(where_expr),
+ where=self._where_predicates(where_expr, apply_timestamp_floor=False),
group_by=[_event_session_id_field()],
limit=ast.Constant(value=1000000),
)
diff --git a/products/replay_vision/backend/migrations/0066_replayscanner_last_deep_swept_at.py b/products/replay_vision/backend/migrations/0066_replayscanner_last_deep_swept_at.py
new file mode 100644
index 000000000000..dc3d4fbdab8d
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0066_replayscanner_last_deep_swept_at.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.17 on 2026-08-12 07:52
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0065_replayscannerbackfill_skipped_count_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="last_deep_swept_at",
+ field=models.DateTimeField(
+ blank=True,
+ help_text="Watermark for the periodic full-events-lookback catch-up sweep; null until the first regular sweep initializes it.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 6454fd658495..b8a062b24a6b 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0065_replayscannerbackfill_skipped_count_and_more
+0066_replayscanner_last_deep_swept_at
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index c9e345251d45..fafb3df0692b 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -151,6 +151,11 @@ class ReplayScanner(UUIDModel):
db_default="",
help_text="Keyset tiebreaker; set when the last batch saturated so the next sweep resumes past session_end ties.",
)
+ last_deep_swept_at = models.DateTimeField(
+ null=True,
+ blank=True,
+ help_text="Watermark for the periodic full-events-lookback catch-up sweep; null until the first regular sweep initializes it.",
+ )
# Shape: ScannerExperimentTargetingSerializer. Stored because the compiled `query` speaks flag
# keys, so the experiment association isn't recoverable from it. Not version-tracked; scanning
@@ -272,7 +277,10 @@ class ReplayScanner(UUIDModel):
# Re-enabling restarts the sweep from now — don't backfill (and bill) the disabled gap.
self.last_swept_at = initial_watermark()
self.last_seen_session_id = ""
- extra_fields.extend(["last_swept_at", "last_seen_session_id"])
+ # The deep pass sweeps from this watermark up to the fast one, so leaving it
+ # behind would make its first window span the whole disabled gap.
+ self.last_deep_swept_at = self.last_swept_at
+ extra_fields.extend(["last_swept_at", "last_seen_session_id", "last_deep_swept_at"])
if update_fields is not None and extra_fields:
kwargs["update_fields"] = [*update_fields, *extra_fields]
super().save(*args, **kwargs)
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index 1e2a42f8f91d..350c86b54987 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -35,6 +35,11 @@ tracer = trace.get_tracer(__name__)
# Partition prune anchored to the SDK's 24h session_id rotation + 2h headroom for skew and lag.
_PARTITION_LOOKBACK = dt.timedelta(hours=26)
+# How far behind the watermark the frequent sweep's events subqueries scan. Covers the events of any
+# session up to ~3h long plus skew; sessions whose matching events are older surface via the periodic
+# deep sweep instead (see `find_scanner_candidates_activity`), which scans the full lookback.
+SWEEP_EVENTS_LOOKBACK = dt.timedelta(hours=4)
+
SAMPLE_RATE_PRECISION = 10_000
# Smallest non-zero rate the modulo bucketing can express (one bucket); the API rejects non-zero rates below it.
MIN_SAMPLING_RATE = 1 / SAMPLE_RATE_PRECISION
@@ -137,6 +142,7 @@ class ScannerCandidateQuery:
last_seen_session_id: str | None = None,
candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,
max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,
+ events_lookback: dt.timedelta | None = None,
) -> None:
if not isinstance(last_swept_at, dt.datetime):
raise TypeError(f"last_swept_at must be a datetime, got {type(last_swept_at).__name__}")
@@ -173,7 +179,18 @@ class ScannerCandidateQuery:
if (surfacing := surfacing_score_predicate(sampling_mode)) is not None:
extra_having.append(surfacing)
- self._inner = SessionRecordingListFromQuery(team=team, query=inner_query, extra_having_predicates=extra_having)
+ # Bounding positive events subqueries to a few hours keeps the every-few-minutes sweep from
+ # re-scanning the full events lookback each tick. Exclusion blocklists ignore the floor (see
+ # ReplayFiltersEventsSubQuery), so negative filters stay exact; a session whose only matching
+ # event is older than the floor is missed here and caught by the deep sweep.
+ events_timestamp_floor = (last_swept_at - events_lookback) if events_lookback is not None else None
+
+ self._inner = SessionRecordingListFromQuery(
+ team=team,
+ query=inner_query,
+ extra_having_predicates=extra_having,
+ events_timestamp_floor=events_timestamp_floor,
+ )
@tracer.start_as_current_span("ScannerCandidateQuery.run")
def run(self) -> list[CandidateSession]:
@@ -289,6 +306,10 @@ class BackfillCandidateQuery:
cursor_end_time: dt.datetime | None = None,
cursor_session_id: str | None = None,
exclude_observed_by_scanner: str | None = None,
+ # Session ids to drop inside the query. Unlike `exclude_observed_by_scanner` this comes from
+ # the caller rather than from the `$recording_observed` event, so it can carry observations in
+ # any state and cannot be influenced by ingested events.
+ exclude_session_ids: list[str] | None = None,
candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,
max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,
) -> None:
@@ -308,6 +329,7 @@ class BackfillCandidateQuery:
self._cursor_end_time = cursor_end_time
self._cursor_session_id = cursor_session_id
self._exclude_observed_by_scanner = exclude_observed_by_scanner
+ self._exclude_session_ids = exclude_session_ids
self._candidate_limit = candidate_limit
self._max_execution_time_seconds = max_execution_time_seconds
@@ -326,7 +348,12 @@ class BackfillCandidateQuery:
if (surfacing := surfacing_score_predicate(sampling_mode)) is not None:
extra_having.append(surfacing)
- self._inner = SessionRecordingListFromQuery(team=team, query=inner_query, extra_having_predicates=extra_having)
+ self._inner = SessionRecordingListFromQuery(
+ team=team,
+ query=inner_query,
+ extra_having_predicates=extra_having,
+ session_ids_to_exclude=exclude_session_ids,
+ )
@tracer.start_as_current_span("BackfillCandidateQuery.run")
def run(self) -> list[CandidateSession]:
diff --git a/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py b/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py
index 4ff5be5a4a04..a13bd99ee545 100644
--- a/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py
+++ b/products/replay_vision/backend/temporal/activities/advance_scanner_watermark.py
@@ -8,10 +8,13 @@ from products.replay_vision.backend.temporal.sweep_types import AdvanceScannerWa
@activity.defn
@track_activity()
def advance_scanner_watermark_activity(inputs: AdvanceScannerWatermarkInputs) -> None:
- updated = ReplayScanner.objects.filter(pk=inputs.scanner_id).update(
- last_swept_at=inputs.new_last_swept_at,
- last_seen_session_id=inputs.new_last_seen_session_id,
- )
+ updates: dict[str, object] = {
+ "last_swept_at": inputs.new_last_swept_at,
+ "last_seen_session_id": inputs.new_last_seen_session_id,
+ }
+ if inputs.new_last_deep_swept_at is not None:
+ updates["last_deep_swept_at"] = inputs.new_last_deep_swept_at
+ updated = ReplayScanner.objects.filter(pk=inputs.scanner_id).update(**updates)
if updated == 0:
activity.logger.info(
"advance_scanner_watermark: scanner no longer exists",
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index 624891cb34c5..58cb7fe89e1b 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -1,14 +1,25 @@
+import datetime as dt
+
+from django.utils import timezone
+
from pydantic import ValidationError
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog.schema import RecordingsQuery
+
from posthog.rbac.user_access_control import UserAccessControl
+from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.queries.scanner_candidate_query import (
DEFAULT_CANDIDATE_LIMIT,
+ SWEEP_EVENTS_LOOKBACK,
+ BackfillCandidateQuery,
+ CandidateSession,
ScannerCandidateQuery,
)
+from products.replay_vision.backend.temporal.constants import DEEP_SWEEP_INTERVAL, DEEP_SWEEP_MAX_EXECUTION_SECONDS
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.metrics import record_sweep_outcome
from products.replay_vision.backend.temporal.sweep_types import (
@@ -53,13 +64,89 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
sampling_mode=scanner.sampling_mode,
last_seen_session_id=scanner.last_seen_session_id or None,
candidate_limit=limit,
+ events_lookback=SWEEP_EVENTS_LOOKBACK,
)
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
- record_sweep_outcome("candidates_found" if candidates else "no_candidates", candidates=len(candidates))
+ # 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
+ # also covers the case where the fast batch used the budget on its own.
+ deep_candidates: list[CandidateSession] = []
+ deep_swept_through: dt.datetime | None = None
+ deep_limit = limit - len(candidates)
+ if scanner.last_deep_swept_at is None:
+ # Seed the deep clock at the fast watermark; everything before this deploy was swept
+ # full-width. This happens whatever the headroom, because the fast watermark advances on every
+ # tick: seeding only once headroom frees up would leave the range in between with no deep pass.
+ deep_swept_through = scanner.last_swept_at
+ elif deep_limit > 0:
+ deep_candidates, deep_swept_through = _deep_sweep(scanner, query, deep_limit)
+
+ record_sweep_outcome(
+ "candidates_found" if candidates or deep_candidates else "no_candidates",
+ candidates=len(candidates) + len(deep_candidates),
+ )
return FindScannerCandidatesOutput(
candidates=[CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in candidates],
- # A full batch means there may be more past the keyset; the next sweep resumes from the last candidate.
- saturated=len(candidates) == limit,
+ saturated=saturated,
swept_through=candidate_query.settle_cutoff,
+ deep_candidates=[
+ CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in deep_candidates
+ ],
+ deep_swept_through=deep_swept_through,
+ )
+
+
+# Past this the exclusion list stops being complete, so holding the watermark could stall the walk.
+_DEEP_SWEEP_MAX_EXCLUSIONS = 20_000
+
+
+def _deep_sweep(
+ scanner: ReplayScanner, query: RecordingsQuery, limit: int
+) -> tuple[list[CandidateSession], dt.datetime | None]:
+ """Catch-up pass behind the fast watermark with the full events lookback.
+
+ The fast sweep's narrow events window can miss a session whose only matching event happened hours
+ before it ended; this pass re-walks the already-swept range with full-width windows every
+ `DEEP_SWEEP_INTERVAL`, excluding sessions the scanner already observed. Bounded above by
+ `last_swept_at` so it never overlaps the fast keyset's territory.
+ """
+ assert scanner.last_deep_swept_at is not None # seeded by the caller before the first pass runs
+ now = timezone.now()
+ if now - scanner.last_deep_swept_at < DEEP_SWEEP_INTERVAL or scanner.last_deep_swept_at >= scanner.last_swept_at:
+ return [], None
+
+ # 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.
+ observed_session_ids = list(
+ ReplayObservation.objects.filter(
+ team_id=scanner.team_id,
+ scanner_id=scanner.id,
+ created_at__gte=scanner.last_deep_swept_at,
+ ).values_list("session_id", flat=True)[:_DEEP_SWEEP_MAX_EXCLUSIONS]
+ )
+
+ deep_query = BackfillCandidateQuery(
+ team=scanner.team,
+ query=query,
+ window_start=scanner.last_deep_swept_at,
+ window_end=scanner.last_swept_at,
+ sampling_rate=scanner.sampling_rate,
+ sampling_salt=str(scanner.id),
+ sampling_mode=scanner.sampling_mode,
+ exclude_session_ids=observed_session_ids,
+ candidate_limit=limit,
+ max_execution_time_seconds=DEEP_SWEEP_MAX_EXECUTION_SECONDS,
)
+ deep_candidates = deep_query.run()
+ if len(deep_candidates) == limit and len(observed_session_ids) < _DEEP_SWEEP_MAX_EXCLUSIONS:
+ # Truncated by the dispatch headroom rather than by the window running out, so hold the
+ # watermark and cover the rest next time. The walk is newest-first, so advancing here would
+ # drop the oldest stragglers, which are exactly the ones this pass exists to catch. Re-running
+ # is self-limiting: a truncated batch means the headroom is spent, and the next tick
+ # short-circuits on the in-flight cap before it queries anything.
+ return deep_candidates, None
+ return deep_candidates, scanner.last_swept_at
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 6c8fab4cdb3b..f8bf3dc274a9 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -47,6 +47,15 @@ def build_process_vision_action_workflow_id(vision_action_id: UUID) -> str:
SCANNER_SCHEDULE_INTERVAL = dt.timedelta(minutes=5)
+# Minimum age of the deep-sweep watermark before a sweep tick runs the full-events-lookback catch-up
+# pass that picks up sessions whose matching events were older than the fast pass's narrow window.
+# Paired with SWEEP_EVENTS_LOOKBACK: that sets what the fast pass can miss, this sets how long a miss
+# waits, so tuning either one moves the same cost-against-latency tradeoff.
+DEEP_SWEEP_INTERVAL = dt.timedelta(hours=6)
+# The deep pass shares the sweep activity's time budget with the fast query, so it gets the smaller
+# share: it is catch-up work, and a tick that overruns retries both queries.
+DEEP_SWEEP_MAX_EXECUTION_SECONDS = 60
+
# Children are ABANDONed and don't count against this budget, but activities do: this must cover the
# prompt-suggestion refresh worst case plus the candidate scan, or a slow refresh kills the whole sweep.
# Overlap SKIP means a slow run absorbs later ticks instead of stacking.
diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.py
index 283c450a8775..42af7d6ea340 100644
--- a/products/replay_vision/backend/temporal/sweep_types.py
+++ b/products/replay_vision/backend/temporal/sweep_types.py
@@ -41,6 +41,11 @@ class FindScannerCandidatesOutput(BaseModel, frozen=True):
# Settle horizon the query covered; None on short-circuit paths and pre-deploy histories,
# which keeps replays deterministic since the empty-sweep advance is gated on it.
swept_through: dt.datetime | None = None
+ # Stragglers from the periodic full-events-lookback catch-up pass; dispatch-only, never drive
+ # the fast watermark. Defaults keep pre-deploy histories replaying deterministically.
+ 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
class RefreshPromptSuggestionInputs(BaseModel, frozen=True):
@@ -53,3 +58,5 @@ class AdvanceScannerWatermarkInputs(BaseModel, frozen=True):
new_last_swept_at: dt.datetime
# Empty clears the keyset tiebreaker.
new_last_seen_session_id: str = Field(max_length=MAX_SESSION_ID_LENGTH)
+ # None leaves the deep-sweep watermark untouched.
+ new_last_deep_swept_at: dt.datetime | None = None
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index 0aca771b02ba..461d9ed44397 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -139,28 +139,40 @@ class SweepScannerWorkflow(PostHogWorkflow):
maximum_attempts=4,
),
)
- if not find_result.candidates:
+ # A no-op when both lists are empty. First failure aborts the gather and skips the advance;
+ # UNIQUE(scanner_id, session_id) dedups retries.
+ await asyncio.gather(
+ *(self._start_child(inputs, c) for c in (*find_result.candidates, *find_result.deep_candidates))
+ )
+
+ if find_result.candidates:
+ 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:
# Advance through the covered settle horizon so `last_swept_at` reflects sweep liveness
- # instead of freezing on low-yield scanners; skipped when swept_through is None.
- if find_result.swept_through is not None:
- await self._advance_watermark(inputs.scanner_id, find_result.swept_through)
+ # instead of freezing on low-yield scanners.
+ swept_at, last_seen_session_id = find_result.swept_through, ""
+ else:
return
- # First failure aborts the gather and skips the advance; UNIQUE(scanner_id, session_id) dedups retries.
- await asyncio.gather(*(self._start_child(inputs, c) for c in find_result.candidates))
-
- last = find_result.candidates[-1]
await self._advance_watermark(
- inputs.scanner_id, last.session_end, last.session_id if find_result.saturated else ""
+ inputs.scanner_id, swept_at, last_seen_session_id, deep_swept_through=find_result.deep_swept_through
)
- async def _advance_watermark(self, scanner_id: UUID, swept_at: dt.datetime, last_seen_session_id: str = "") -> None:
+ async def _advance_watermark(
+ self,
+ scanner_id: UUID,
+ swept_at: dt.datetime,
+ last_seen_session_id: str = "",
+ deep_swept_through: dt.datetime | None = None,
+ ) -> None:
await wf.execute_activity(
advance_scanner_watermark_activity,
AdvanceScannerWatermarkInputs(
scanner_id=scanner_id,
new_last_swept_at=swept_at,
new_last_seen_session_id=last_seen_session_id,
+ new_last_deep_swept_at=deep_swept_through,
),
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=common.RetryPolicy(maximum_attempts=3),
diff --git a/products/replay_vision/backend/tests/test_models.py b/products/replay_vision/backend/tests/test_models.py
index fef418c5cd9a..c61db90ab59b 100644
--- a/products/replay_vision/backend/tests/test_models.py
+++ b/products/replay_vision/backend/tests/test_models.py
@@ -136,12 +136,16 @@ class TestReplayScanner(BaseTest):
def test_reenabling_resets_sweep_watermark(self, _label: str, update_fields: list[str] | None) -> None:
# Without the reset, a re-enabled scanner backfills every session since it was disabled.
stale = timezone.now() - timedelta(days=21)
- scanner = self._create_scanner(enabled=False, last_swept_at=stale, last_seen_session_id="sess-tie")
+ scanner = self._create_scanner(
+ enabled=False, last_swept_at=stale, last_seen_session_id="sess-tie", last_deep_swept_at=stale
+ )
scanner.enabled = True
scanner.save(update_fields=update_fields)
scanner.refresh_from_db()
self.assertGreater(scanner.last_swept_at, timezone.now() - timedelta(hours=1))
self.assertEqual(scanner.last_seen_session_id, "")
+ # The deep pass sweeps from here to last_swept_at, so a stale value would cover the whole gap.
+ self.assertEqual(scanner.last_deep_swept_at, scanner.last_swept_at)
@parameterized.expand(
[
@@ -153,7 +157,11 @@ class TestReplayScanner(BaseTest):
def test_watermark_is_kept_unless_reenabled(self, label: str, enabled_before: bool, enabled_after: bool) -> None:
stale = timezone.now() - timedelta(days=21)
scanner = self._create_scanner(
- name=label, enabled=enabled_before, last_swept_at=stale, last_seen_session_id="sess-tie"
+ name=label,
+ enabled=enabled_before,
+ last_swept_at=stale,
+ last_seen_session_id="sess-tie",
+ last_deep_swept_at=stale,
)
scanner.enabled = enabled_after
scanner.description = "touched"
@@ -161,6 +169,7 @@ class TestReplayScanner(BaseTest):
scanner.refresh_from_db()
self.assertEqual(scanner.last_swept_at, stale)
self.assertEqual(scanner.last_seen_session_id, "sess-tie")
+ self.assertEqual(scanner.last_deep_swept_at, stale)
class TestReplayObservation(BaseTest):
diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
index 8dd8386840ec..3131f9283f21 100644
--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py
+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
@@ -2,7 +2,7 @@ import datetime as dt
import pytest
from freezegun import freeze_time
-from posthog.test.base import ClickhouseTestMixin
+from posthog.test.base import ClickhouseTestMixin, _create_event
from posthog.schema import EventPropertyFilter, PropertyOperator, RecordingPropertyFilter, RecordingsQuery
@@ -18,6 +18,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
DEFAULT_CANDIDATE_LIMIT,
FOCUSED_SURFACING_THRESHOLD,
SETTLE_INTERVAL,
+ SWEEP_EVENTS_LOOKBACK,
BackfillCandidateQuery,
ScannerCandidateQuery,
surfacing_score_predicate,
@@ -633,6 +634,56 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2))
assert results == []
+ @pytest.mark.django_db
+ def test_events_lookback_bounds_positive_event_matching(self, team) -> None:
+ last_swept_at = _NOW - dt.timedelta(hours=1)
+ floor = last_swept_at - SWEEP_EVENTS_LOOKBACK
+ for session_id, event_ts in (
+ ("recent-event", floor + dt.timedelta(hours=1)),
+ ("old-event", floor - dt.timedelta(hours=1)),
+ ):
+ self._produce(team.id, session_id, _NOW - dt.timedelta(hours=8), _NOW - dt.timedelta(minutes=50))
+ _create_event(
+ team=team,
+ event="$pageview",
+ distinct_id="d1",
+ timestamp=event_ts,
+ properties={"$session_id": session_id},
+ )
+
+ query = RecordingsQuery(events=[{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"}])
+
+ narrow = self._run(team=team, query=query, last_swept_at=last_swept_at, events_lookback=SWEEP_EVENTS_LOOKBACK)
+ assert [r.session_id for r in narrow] == ["recent-event"]
+
+ full_width = self._run(team=team, query=query, last_swept_at=last_swept_at)
+ assert sorted(r.session_id for r in full_width) == ["old-event", "recent-event"]
+
+ @pytest.mark.django_db
+ def test_events_lookback_keeps_negative_filters_full_width(self, team) -> None:
+ last_swept_at = _NOW - dt.timedelta(hours=1)
+ old_ts = last_swept_at - SWEEP_EVENTS_LOOKBACK - dt.timedelta(hours=1)
+ for session_id, host in (("blocked", "internal.example.com"), ("kept", "app.example.com")):
+ self._produce(team.id, session_id, _NOW - dt.timedelta(hours=8), _NOW - dt.timedelta(minutes=50))
+ _create_event(
+ team=team,
+ event="$pageview",
+ distinct_id="d1",
+ timestamp=old_ts,
+ properties={"$session_id": session_id, "$host": host},
+ )
+
+ query = RecordingsQuery(
+ properties=[
+ EventPropertyFilter(
+ key="$host", value=["internal.example.com"], operator=PropertyOperator.IS_NOT, type="event"
+ )
+ ]
+ )
+
+ results = self._run(team=team, query=query, last_swept_at=last_swept_at, events_lookback=SWEEP_EVENTS_LOOKBACK)
+ assert [r.session_id for r in results] == ["kept"]
+
@staticmethod
def _run(
*,
@@ -643,6 +694,7 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
sampling_salt: str = "scanner-1",
candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,
last_seen_session_id: str | None = None,
+ events_lookback: dt.timedelta | None = None,
):
return ScannerCandidateQuery(
team=team,
@@ -652,6 +704,7 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):
sampling_salt=sampling_salt,
candidate_limit=candidate_limit,
last_seen_session_id=last_seen_session_id,
+ events_lookback=events_lookback,
).run()
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index a5cb7649260a..a073b2ab3f15 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -5,12 +5,22 @@ from typing import Any
import pytest
from unittest.mock import MagicMock, patch
+from parameterized import parameterized
from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
from posthog.models import Organization, Team
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ ReplayObservation,
+)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
-from products.replay_vision.backend.queries.scanner_candidate_query import DEFAULT_CANDIDATE_LIMIT, CandidateSession
+from products.replay_vision.backend.queries.scanner_candidate_query import (
+ DEFAULT_CANDIDATE_LIMIT,
+ SWEEP_EVENTS_LOOKBACK,
+ CandidateSession,
+)
from products.replay_vision.backend.temporal import SweepScannerWorkflow
from products.replay_vision.backend.temporal.activities.advance_scanner_watermark import (
advance_scanner_watermark_activity,
@@ -130,6 +140,7 @@ class TestFindScannerCandidatesActivity:
assert query_kwargs["last_swept_at"] == watermark_arg
assert query_kwargs["last_seen_session_id"] is None
assert query_kwargs["sampling_rate"] == scanner.sampling_rate
+ assert query_kwargs["events_lookback"] == SWEEP_EVENTS_LOOKBACK
def test_threads_last_seen_session_id_when_set(self) -> None:
scanner = _make_scanner(last_seen_session_id="prev-id")
@@ -166,6 +177,207 @@ class TestFindScannerCandidatesActivity:
assert result.saturated is True
assert 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
+
+ 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"
+ ) as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = []
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ MockDeep.assert_not_called()
+ assert result.deep_candidates == []
+ assert result.deep_swept_through == scanner.last_swept_at
+
+ 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)
+ straggler = CandidateSession(
+ session_id="deep-sess", session_end=dt.datetime(2026, 5, 1, 6, 0, 0, tzinfo=dt.UTC)
+ )
+
+ 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"
+ ) as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = []
+ MockDeep.return_value.run.return_value = [straggler]
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ _, deep_kwargs = MockDeep.call_args
+ assert deep_kwargs["window_start"] == deep_watermark
+ assert deep_kwargs["window_end"] == scanner.last_swept_at
+ assert deep_kwargs["exclude_session_ids"] == []
+ assert [c.session_id for c in result.deep_candidates] == ["deep-sess"]
+ assert result.deep_swept_through == scanner.last_swept_at
+
+ @parameterized.expand(
+ [
+ ("fresh_watermark_skips", dt.timedelta(hours=1), False),
+ ("stale_watermark_runs", dt.timedelta(hours=7), True),
+ ]
+ )
+ def test_deep_pass_gated_on_watermark_age(self, _name: str, watermark_age: dt.timedelta, expect_run: bool) -> None:
+ scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - watermark_age)
+ straggler = CandidateSession(session_id="deep-a", session_end=dt.datetime(2026, 5, 1, 6, 0, tzinfo=dt.UTC))
+
+ 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"
+ ) as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = []
+ MockDeep.return_value.run.return_value = [straggler]
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=5)
+ )
+
+ assert MockDeep.called is expect_run
+ if not expect_run:
+ assert result.deep_candidates == []
+ assert result.deep_swept_through is None
+ return
+ assert [c.session_id for c in result.deep_candidates] == ["deep-a"]
+ assert result.deep_swept_through == scanner.last_swept_at
+
+ def test_deep_watermark_seeds_even_when_fast_batch_takes_all_headroom(self) -> None:
+ scanner = _make_scanner()
+ assert scanner.last_deep_swept_at is None
+ fast = [
+ CandidateSession(session_id=f"sess-{i}", session_end=dt.datetime(2026, 5, 1, 10, 0, i, tzinfo=dt.UTC))
+ for i in range(2)
+ ]
+
+ 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"
+ ) as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = fast
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=2)
+ )
+
+ MockDeep.assert_not_called()
+ # Without this the fast watermark keeps advancing while the deep clock stays unset, and the
+ # range in between never gets a full-width pass.
+ assert result.deep_swept_through == scanner.last_swept_at
+
+ @parameterized.expand(
+ [
+ ("headroom_left_over", 3, 5, 2),
+ ("fast_batch_took_it_all", 5, 5, None),
+ ]
+ )
+ def test_deep_pass_limited_to_headroom_left_by_fast_pass(
+ self, _name: str, fast_count: int, limit: int, expected_deep_limit: int | None
+ ) -> None:
+ scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))
+ fast = [
+ CandidateSession(session_id=f"sess-{i}", session_end=dt.datetime(2026, 5, 1, 10, 0, i, tzinfo=dt.UTC))
+ for i in range(fast_count)
+ ]
+
+ 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"
+ ) as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = fast
+ MockDeep.return_value.run.return_value = []
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=limit)
+ )
+
+ if expected_deep_limit is None:
+ MockDeep.assert_not_called()
+ return
+ # Both lists dispatch together, so exceeding this would put the tick over the in-flight caps.
+ assert MockDeep.call_args.kwargs["candidate_limit"] == expected_deep_limit
+
+ def test_deep_pass_excludes_sessions_with_terminal_observations(self) -> None:
+ # The $recording_observed event only lands on success, so excluding on it would hand these
+ # sessions back on every tick and the walk would never move past them.
+ scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))
+ for session_id, status in (("failed-sess", ObservationStatus.FAILED), ("ok-sess", ObservationStatus.SUCCEEDED)):
+ ReplayObservation.objects.create(
+ scanner=scanner,
+ team=scanner.team,
+ session_id=session_id,
+ status=status,
+ scanner_snapshot={"model": scanner.model},
+ triggered_by=ObservationTrigger.SCHEDULE,
+ completed_at=dt.datetime.now(dt.UTC),
+ )
+
+ 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"
+ ) as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = []
+ MockDeep.return_value.run.return_value = []
+ find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=5)
+ )
+
+ excluded = MockDeep.call_args.kwargs["exclude_session_ids"]
+ assert sorted(excluded) == ["failed-sess", "ok-sess"]
+ # The ingested event is no longer consulted, so it cannot suppress a candidate either.
+ assert "exclude_observed_by_scanner" not in MockDeep.call_args.kwargs
+
+ def test_truncated_deep_batch_holds_watermark(self) -> None:
+ scanner = _make_scanner(last_deep_swept_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=7))
+ stragglers = [
+ CandidateSession(session_id=f"deep-{i}", session_end=dt.datetime(2026, 5, 1, 6, 0, i, tzinfo=dt.UTC))
+ for i in range(3)
+ ]
+
+ 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"
+ ) as MockDeep,
+ ):
+ MockQuery.return_value.run.return_value = []
+ MockDeep.return_value.run.return_value = stragglers
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id, candidate_limit=3)
+ )
+
+ assert [c.session_id for c in result.deep_candidates] == ["deep-0", "deep-1", "deep-2"]
+ # The walk is newest-first, so advancing on a truncated batch would drop the oldest for good.
+ assert result.deep_swept_through is None
+
def test_raises_non_retryable_on_malformed_query(self) -> None:
scanner = _make_scanner()
scanner.query = {"kind": "TrendsQuery"}
@@ -214,6 +426,32 @@ class TestAdvanceScannerWatermarkActivity:
scanner.refresh_from_db()
assert scanner.last_seen_session_id == ""
+ def test_advances_deep_watermark_only_when_provided(self) -> None:
+ existing_deep = dt.datetime(2026, 5, 1, 6, 0, 0, tzinfo=dt.UTC)
+ scanner = _make_scanner(last_deep_swept_at=existing_deep)
+ new_deep = dt.datetime(2026, 5, 1, 11, 0, 0, tzinfo=dt.UTC)
+
+ advance_scanner_watermark_activity(
+ AdvanceScannerWatermarkInputs(
+ scanner_id=scanner.id,
+ new_last_swept_at=dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC),
+ new_last_seen_session_id="",
+ )
+ )
+ scanner.refresh_from_db()
+ assert scanner.last_deep_swept_at == existing_deep
+
+ advance_scanner_watermark_activity(
+ AdvanceScannerWatermarkInputs(
+ scanner_id=scanner.id,
+ new_last_swept_at=dt.datetime(2026, 5, 1, 12, 5, 0, tzinfo=dt.UTC),
+ new_last_seen_session_id="",
+ new_last_deep_swept_at=new_deep,
+ )
+ )
+ scanner.refresh_from_db()
+ assert scanner.last_deep_swept_at == new_deep
+
def test_no_op_when_scanner_deleted(self) -> None:
advance_scanner_watermark_activity(
AdvanceScannerWatermarkInputs(
@@ -380,6 +618,59 @@ async def test_saturated_batch_carries_session_id_as_tiebreaker() -> None:
assert advance_call.new_last_seen_session_id == "sess-02"
+async def test_deep_candidates_dispatch_alongside_fast_and_forward_deep_watermark() -> None:
+ deep_horizon = dt.datetime(2026, 5, 1, 9, 0, 0, tzinfo=dt.UTC)
+ fast = [_build_payload("sess-a", dt.datetime(2026, 5, 1, 10, 0, 0, tzinfo=dt.UTC))]
+ deep = [_build_payload("deep-a", dt.datetime(2026, 5, 1, 4, 0, 0, tzinfo=dt.UTC))]
+ mocks = _SweepMocks(
+ activity_results={
+ find_scanner_candidates_activity: FindScannerCandidatesOutput(
+ candidates=fast, saturated=False, deep_candidates=deep, deep_swept_through=deep_horizon
+ ),
+ }
+ )
+ inputs = _sweep_inputs()
+
+ await _run_sweep(mocks, inputs)
+
+ dispatched = {c["id"] for c in mocks.child_calls}
+ assert dispatched == {
+ f"replay-vision-apply-scanner-{inputs.scanner_id}-sess-a",
+ f"replay-vision-apply-scanner-{inputs.scanner_id}-deep-a",
+ }
+ advance_call = next(call for fn, call in mocks.activity_calls if fn == advance_scanner_watermark_activity)
+ # Deep candidates never drive the fast watermark — their session_end predates it.
+ assert advance_call.new_last_swept_at == fast[-1].session_end
+ assert advance_call.new_last_deep_swept_at == deep_horizon
+
+
+async def test_deep_candidates_dispatch_even_when_fast_batch_is_empty() -> None:
+ horizon = dt.datetime(2026, 5, 1, 11, 0, 0, tzinfo=dt.UTC)
+ deep_horizon = dt.datetime(2026, 5, 1, 9, 0, 0, tzinfo=dt.UTC)
+ deep = [_build_payload("deep-a", dt.datetime(2026, 5, 1, 4, 0, 0, tzinfo=dt.UTC))]
+ mocks = _SweepMocks(
+ activity_results={
+ find_scanner_candidates_activity: FindScannerCandidatesOutput(
+ candidates=[],
+ saturated=False,
+ swept_through=horizon,
+ deep_candidates=deep,
+ deep_swept_through=deep_horizon,
+ ),
+ }
+ )
+ inputs = _sweep_inputs()
+
+ await _run_sweep(mocks, inputs)
+
+ assert [c["id"] for c in mocks.child_calls] == [f"replay-vision-apply-scanner-{inputs.scanner_id}-deep-a"]
+ advance_call = next(call for fn, call in mocks.activity_calls if fn == advance_scanner_watermark_activity)
+ assert advance_call.new_last_swept_at == horizon
+ assert advance_call.new_last_deep_swept_at == deep_horizon
+
+
@pytest.mark.asyncio
async def test_already_started_child_is_silently_skipped() -> None:
candidates = [