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.

fix(replay-vision): harden scan pipeline against transient failures and low-yield sweeps (#77127)

Tue Haulund992a94f67d78
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index 947fea82ef31..ff1cdade6014 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -75,6 +75,7 @@ class ClickHouseUser(StrEnum):
ERROR_TRACKING = "error_tracking"
ENDPOINTS = "endpoints"
BILLING = "billing"
+ REPLAY_VISION = "replay_vision"
# Backups - used by Dagster backup jobs
BACKUPS = "backups"
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index 074f1b1048c9..a4212e7fe36e 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -134,6 +134,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
connection_id=self.query.connectionId,
limit_context=self.limit_context,
workload=self.workload,
+ ch_user=self.ch_user,
settings=self.settings,
send_raw_query=True,
)
@@ -164,6 +165,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
connection_id=self.query.connectionId,
limit_context=self.limit_context,
workload=self.workload,
+ ch_user=self.ch_user,
settings=self.settings,
)
if paginator:
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 7d13816fbe46..9742c69357ee 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -101,7 +101,7 @@ from posthog.hogql.warehouse_warnings import accumulator_scope
from posthog import settings
from posthog.caching.utils import ThresholdMode, cache_target_age, is_stale, last_refresh_from_cached_result
-from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.client.connection import ClickHouseUser, Workload
from posthog.clickhouse.client.execute_async import QueryNotFoundError, enqueue_process_query_task, get_query_status
from posthog.clickhouse.client.limit import (
get_api_team_rate_limiter,
@@ -1384,6 +1384,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# query service means programmatic access and /query endpoint
is_query_service: bool = False
workload: Workload
+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT
# Opt-in (set by process_query_model): on a cache hit, keep the results segment of the
# cached response as raw JSON bytes in raw_cached_results_bytes instead of parsing it,
# leaving a `results=[]` placeholder on the returned model.
@@ -1401,6 +1402,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
workload: Workload = Workload.DEFAULT,
extract_modifiers=lambda query: query.modifiers if hasattr(query, "modifiers") else None,
user: Optional[User] = None,
+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,
):
self.team = team
self.user = user
@@ -1408,6 +1410,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
self.limit_context = limit_context or LimitContext.QUERY
self.query_id = query_id
self.workload = workload
+ self.ch_user = ch_user
if not self.is_query_node(query):
if isinstance(self.query_type, UnionType):
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 98a279edf781..18609307bf4f 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -41,6 +41,11 @@ logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
+# Neutral mid-pack score for sessions the surfacing scorer has not reached; shared with the
+# replay-vision sweep so list eligibility and sweep eligibility agree on unscored sessions.
+UNSCORED_SURFACING_SCORE = 0.36
+
+
class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
SESSION_RECORDINGS_DEFAULT_LIMIT = 50
@@ -73,7 +78,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
((sum(s.mouse_activity_count) + dateDiff('SECOND', start_time, end_time) + sum(s.console_error_count) + sum(s.console_log_count) + sum(s.console_warn_count)))
* 100
), 2) as activity_score,
- coalesce(max(s.surfacing_score), 0.36) as surfacing_score
+ coalesce(max(s.surfacing_score), {unscored_surfacing_score}) as surfacing_score
FROM raw_session_replay_events s
WHERE {where_predicates}
GROUP BY session_id
@@ -249,6 +254,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
"where_predicates": self._where_predicates(),
"having_predicates": self._having_predicates() or ast.Constant(value=True),
"python_now": ast.Constant(value=datetime.now(UTC)),
+ "unscored_surfacing_score": ast.Constant(value=UNSCORED_SURFACING_SCORE),
},
)
if isinstance(parsed_query, ast.SelectSetQuery):
diff --git a/posthog/session_recordings/queries/session_replay_events.py b/posthog/session_recordings/queries/session_replay_events.py
index e4ce8fa61c17..fe65cab89c7b 100644
--- a/posthog/session_recordings/queries/session_replay_events.py
+++ b/posthog/session_recordings/queries/session_replay_events.py
@@ -11,6 +11,7 @@ import pytz
from posthog.schema import HogQLQuery
from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.models.team import Team
from posthog.session_recordings.models.metadata import ONGOING_SESSION_WINDOW_MINUTES, RecordingMetadata
@@ -503,18 +504,19 @@ class SessionReplayEvents:
session_id: str,
team: Team,
recording_start_time: Optional[datetime] = None,
+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,
) -> Optional[RecordingMetadata]:
if recording_start_time is not None:
- return self._get_metadata_from(session_id, team, recording_start_time)
+ return self._get_metadata_from(session_id, team, recording_start_time, ch_user=ch_user)
# Most callers don't know the recording's start time (it is only persisted
# for pinned recordings); derive a lower bound from the session id instead.
# Unlike a real start time it carries clock-skew slack, so on a miss fall
# back to the unbounded scan rather than reporting not-found.
derived_lower_bound = uuidv7_session_lower_bound(session_id)
- metadata = self._get_metadata_from(session_id, team, derived_lower_bound)
+ metadata = self._get_metadata_from(session_id, team, derived_lower_bound, ch_user=ch_user)
if metadata is None and derived_lower_bound is not None:
- metadata = self._get_metadata_from(session_id, team, None)
+ metadata = self._get_metadata_from(session_id, team, None, ch_user=ch_user)
return metadata
def _get_metadata_from(
@@ -522,6 +524,7 @@ class SessionReplayEvents:
session_id: str,
team: Team,
lower_bound: Optional[datetime],
+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,
) -> Optional[RecordingMetadata]:
query = self.get_metadata_query(lower_bound)
tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)
@@ -533,6 +536,7 @@ class SessionReplayEvents:
"recording_start_time": lower_bound,
"python_now": datetime.now(pytz.timezone("UTC")),
},
+ ch_user=ch_user,
)
recording_metadata = self.build_recording_metadata(session_id, replay_response)
return recording_metadata
@@ -678,6 +682,7 @@ class SessionReplayEvents:
extra_fields: list[str] | None = None,
limit: int | None = None,
page: int = 0,
+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,
) -> SessionEventsPage:
"""Return one page of events. When `limit` is set, fetches one extra row internally to detect whether more pages exist."""
from posthog.schema import HogQLQueryResponse
@@ -696,6 +701,7 @@ class SessionReplayEvents:
result: HogQLQueryResponse = HogQLQueryRunner(
team=team,
query=hq,
+ ch_user=ch_user,
).calculate()
columns, rows = result.columns, result.results
if limit is not None and limit > 0 and rows is not None and len(rows) > limit:
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.py
index 28461ad9feb9..a31693d04272 100644
--- a/posthog/temporal/common/utils.py
+++ b/posthog/temporal/common/utils.py
@@ -16,6 +16,17 @@ P = ParamSpec("P")
T = TypeVar("T")
+def close_stale_db_connections() -> None:
+ """Close expired or errored Postgres connections accumulated by long-lived worker threads.
+
+ Unlike django.db.close_old_connections, skips connections inside an atomic block, so it is
+ safe to call from activities running under test transactions.
+ """
+ for conn in django.db.connections.all(initialized_only=True):
+ if not conn.in_atomic_block:
+ conn.close_if_unusable_or_obsolete()
+
+
def make_sync_retryable_with_exponential_backoff(
func: Callable[P, T],
max_attempts: int = 5,
diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.py
index 92f126e472bf..434f99a443ae 100644
--- a/products/replay_vision/backend/queries/scanner_candidate_query.py
+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py
@@ -13,9 +13,13 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.query import execute_hogql_query
+from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models import Team
-from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
+from posthog.session_recordings.queries.session_recording_list_from_query import (
+ UNSCORED_SURFACING_SCORE,
+ SessionRecordingListFromQuery,
+)
from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, SamplingMode
from products.replay_vision.backend.temporal.constants import (
@@ -40,9 +44,6 @@ DEFAULT_MAX_EXECUTION_SECONDS = 180
# Calibrated from the prod score distribution: focused keeps roughly the top 25% of sessions, balanced the top 65%.
FOCUSED_SURFACING_THRESHOLD = 0.30
BALANCED_SURFACING_THRESHOLD = 0.10
-# Below balanced so unscored sessions are skipped by both filtered modes.
-NULL_SURFACING_SCORE_FALLBACK = 0.0
-
_SURFACING_THRESHOLDS = {
SamplingMode.FOCUSED: FOCUSED_SURFACING_THRESHOLD,
SamplingMode.BALANCED: BALANCED_SURFACING_THRESHOLD,
@@ -60,7 +61,9 @@ def surfacing_score_predicate(sampling_mode: SamplingMode | str) -> ast.Expr | N
name="coalesce",
args=[
ast.Call(name="max", args=[ast.Field(chain=["s", "surfacing_score"])]),
- ast.Constant(value=NULL_SURFACING_SCORE_FALLBACK),
+ # Unscored sessions get the same neutral score the recordings list shows, so a session
+ # visible as eligible in the UI is also eligible to the sweep.
+ ast.Constant(value=UNSCORED_SURFACING_SCORE),
],
),
right=ast.Constant(value=threshold),
@@ -130,6 +133,8 @@ class ScannerCandidateQuery:
self._sampling_salt = sampling_salt
self._candidate_limit = candidate_limit
self._max_execution_time_seconds = max_execution_time_seconds
+ # Fixed at construction and exposed so callers can persist exactly the horizon the query filtered on.
+ self.settle_cutoff = dt.datetime.now(dt.UTC) - SETTLE_INTERVAL
# The schedule owns the time window, not the user.
inner_query = query.model_copy(deep=True)
@@ -157,6 +162,8 @@ class ScannerCandidateQuery:
team=self._team,
query_type="ReplayVisionScannerCandidateQuery",
settings=HogQLGlobalSettings(max_execution_time=self._max_execution_time_seconds),
+ # Dedicated user keeps sweep admission out of the contended shared `default` pool.
+ ch_user=ClickHouseUser.REPLAY_VISION,
)
return [CandidateSession(session_id=row[0], session_end=row[1]) for row in (response.results or [])]
@@ -170,7 +177,7 @@ class ScannerCandidateQuery:
ast.CompareOperation(
op=ast.CompareOperationOp.LtEq,
left=ast.Field(chain=["sessions", "end_time"]),
- right=ast.Constant(value=dt.datetime.now(dt.UTC) - SETTLE_INTERVAL),
+ right=ast.Constant(value=self.settle_cutoff),
),
# Excludes attacker-supplied over-length session_ids that would later wedge wire-payload validation.
ast.CompareOperation(
diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.py
index 76e2653fc16d..096ea23e4137 100644
--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py
+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py
@@ -9,6 +9,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.query import execute_hogql_query
+from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.models import Team
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
@@ -48,6 +49,7 @@ def estimate_scanner_session_volume(
query: RecordingsQuery,
sampling_mode: SamplingMode | str = SamplingMode.COMPREHENSIVE,
max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS,
+ ch_user: ClickHouseUser = ClickHouseUser.APP,
) -> ScannerVolumeEstimate:
"""Count sessions matching `query` over the last 30 days, for the scanner cost preview.
@@ -112,6 +114,7 @@ def estimate_scanner_session_volume(
team=team,
query_type="ReplayVisionScannerEstimateQuery",
settings=HogQLGlobalSettings(max_execution_time=max_execution_seconds),
+ ch_user=ch_user,
)
results = response.results or []
matched = int(results[0][0]) if results else 0
@@ -129,7 +132,10 @@ def project_monthly_observations(estimate: ScannerVolumeEstimate, sampling_rate:
def refresh_scanner_estimate(
- scanner: ReplayScanner, *, max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS
+ scanner: ReplayScanner,
+ *,
+ max_execution_seconds: int = _ESTIMATE_MAX_EXECUTION_TIME_SECONDS,
+ ch_user: ClickHouseUser = ClickHouseUser.APP,
) -> None:
"""Recompute and persist the scanner's projected monthly volume. Raises on failure; callers decide severity."""
estimate = estimate_scanner_session_volume(
@@ -137,6 +143,7 @@ def refresh_scanner_estimate(
query=scanner.recordings_query(),
sampling_mode=scanner.sampling_mode,
max_execution_seconds=max_execution_seconds,
+ ch_user=ch_user,
)
projection = project_monthly_observations(estimate, scanner.sampling_rate)
estimated_at = timezone.now()
diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
index e04e0a824e6f..361f4f78508f 100644
--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py
+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py
@@ -8,6 +8,7 @@ import structlog
from asgiref.sync import sync_to_async
from temporalio import activity
+from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.models import Team
from posthog.models.person.util import get_person_by_distinct_id
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
@@ -112,7 +113,7 @@ def _persist_session_identity(observation_id: Any, payload: ScannerLlmInputs) ->
def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:
team = Team.objects.get(pk=team_id)
events_obj = SessionReplayEvents()
- metadata = events_obj.get_metadata(session_id=session_id, team=team)
+ metadata = events_obj.get_metadata(session_id=session_id, team=team, ch_user=ClickHouseUser.REPLAY_VISION)
if metadata is None:
raise IneligibleSessionError(
"No replay metadata found",
@@ -149,6 +150,7 @@ def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:
extra_fields=_EXTRA_FIELDS,
limit=_EVENTS_PER_PAGE,
page=page_number,
+ ch_user=ClickHouseUser.REPLAY_VISION,
)
if page.columns and columns is None:
columns = list(page.columns)
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 6a0b5e8fa92a..624891cb34c5 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -61,4 +61,5 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
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,
+ swept_through=candidate_query.settle_cutoff,
)
diff --git a/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py
index c3718163e240..65da733bb181 100644
--- a/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py
+++ b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py
@@ -2,6 +2,8 @@ from django.utils import timezone
from temporalio import activity
+from posthog.clickhouse.client.connection import ClickHouseUser
+
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER, refresh_scanner_estimate
from products.replay_vision.backend.temporal.decorators import track_activity
@@ -17,5 +19,5 @@ def refresh_scanner_estimate_activity(inputs: RefreshScannerEstimateInputs) -> b
return False
if scanner.estimated_at is not None and timezone.now() - scanner.estimated_at < ESTIMATE_STALE_AFTER:
return False
- refresh_scanner_estimate(scanner)
+ refresh_scanner_estimate(scanner, ch_user=ClickHouseUser.REPLAY_VISION)
return True
diff --git a/products/replay_vision/backend/temporal/decorators.py b/products/replay_vision/backend/temporal/decorators.py
index 0fb13ea52e0c..ba2e246ca371 100644
--- a/products/replay_vision/backend/temporal/decorators.py
+++ b/products/replay_vision/backend/temporal/decorators.py
@@ -6,6 +6,8 @@ from collections.abc import Callable
from functools import wraps
from typing import Any, TypeVar, cast
+from posthog.temporal.common.utils import close_stale_db_connections
+
from products.replay_vision.backend.temporal.metrics import record_activity_duration, record_side_effect_failure
F = TypeVar("F", bound=Callable[..., Any])
@@ -44,6 +46,8 @@ def track_activity(name: str | None = None, side_effect: str | None = None) -> C
@wraps(fn)
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
+ # Long-lived worker threads accumulate expired Postgres connections between activity runs.
+ close_stale_db_connections()
started = time.monotonic()
try:
result = fn(*args, **kwargs)
diff --git a/products/replay_vision/backend/temporal/sweep_types.py b/products/replay_vision/backend/temporal/sweep_types.py
index fd5993bc408a..93e7dda67445 100644
--- a/products/replay_vision/backend/temporal/sweep_types.py
+++ b/products/replay_vision/backend/temporal/sweep_types.py
@@ -38,6 +38,9 @@ class CandidateSessionPayload(BaseModel, frozen=True):
class FindScannerCandidatesOutput(BaseModel, frozen=True):
candidates: list[CandidateSessionPayload]
saturated: bool
+ # 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
class RefreshPromptSuggestionInputs(BaseModel, frozen=True):
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index af634a483b40..0aca771b02ba 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -2,6 +2,7 @@
import asyncio
import datetime as dt
+from uuid import UUID
import temporalio.workflow as wf
from temporalio import common
@@ -123,25 +124,43 @@ class SweepScannerWorkflow(PostHogWorkflow):
)
return
+ # Retries target fast ClickHouse admission rejections (code 202); schedule_to_close deliberately
+ # cuts slow timeout-bound attempts off after two rounds so the tick fails with ~10 minutes of the
+ # 15-minute workflow budget left, instead of burning it on a query that keeps timing out.
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),
- retry_policy=common.RetryPolicy(maximum_attempts=1),
+ schedule_to_close_timeout=dt.timedelta(seconds=450),
+ retry_policy=common.RetryPolicy(
+ initial_interval=dt.timedelta(seconds=5),
+ backoff_coefficient=2.0,
+ maximum_interval=dt.timedelta(seconds=30),
+ maximum_attempts=4,
+ ),
)
if not find_result.candidates:
+ # 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)
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 ""
+ )
+
+ async def _advance_watermark(self, scanner_id: UUID, swept_at: dt.datetime, last_seen_session_id: str = "") -> None:
await wf.execute_activity(
advance_scanner_watermark_activity,
AdvanceScannerWatermarkInputs(
- scanner_id=inputs.scanner_id,
- new_last_swept_at=last.session_end,
- new_last_seen_session_id=last.session_id if find_result.saturated else "",
+ scanner_id=scanner_id,
+ new_last_swept_at=swept_at,
+ new_last_seen_session_id=last_seen_session_id,
),
start_to_close_timeout=dt.timedelta(seconds=30),
retry_policy=common.RetryPolicy(maximum_attempts=3),
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 aa40726f5002..c7482b89cb36 100644
--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py
+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py
@@ -17,7 +17,6 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
BALANCED_SURFACING_THRESHOLD,
DEFAULT_CANDIDATE_LIMIT,
FOCUSED_SURFACING_THRESHOLD,
- NULL_SURFACING_SCORE_FALLBACK,
SETTLE_INTERVAL,
ScannerCandidateQuery,
surfacing_score_predicate,
@@ -158,8 +157,10 @@ def test_surfacing_score_predicate_rejects_unknown_mode():
surfacing_score_predicate("focussed")
-def test_null_fallback_stays_below_balanced_threshold():
- assert NULL_SURFACING_SCORE_FALLBACK < BALANCED_SURFACING_THRESHOLD
+def test_unscored_fallback_passes_filtered_thresholds():
+ from posthog.session_recordings.queries.session_recording_list_from_query import UNSCORED_SURFACING_SCORE
+
+ assert UNSCORED_SURFACING_SCORE >= FOCUSED_SURFACING_THRESHOLD
@pytest.mark.parametrize(
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index fed90cce958a..a5cb7649260a 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -320,6 +320,25 @@ async def test_empty_batch_skips_dispatch_and_advance() -> None:
assert mocks.child_calls == []
+async def test_empty_batch_with_horizon_advances_watermark_without_dispatch() -> None:
+ horizon = dt.datetime(2026, 8, 4, 12, 0, 0, tzinfo=dt.UTC)
+ mocks = _SweepMocks(
+ activity_results={
+ find_scanner_candidates_activity: FindScannerCandidatesOutput(
+ candidates=[], saturated=False, swept_through=horizon
+ ),
+ }
+ )
+
+ await _run_sweep(mocks)
+
+ assert mocks.child_calls == []
+ 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_seen_session_id == ""
+
+
@pytest.mark.asyncio
async def test_non_saturated_batch_dispatches_and_clears_tiebreaker() -> None:
candidates = [