:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): scope negative-filter exclusion to backfill candidates (#83444)
Tue Haulunda964b13cd2de
diff --git a/products/replay_vision/backend/queries/excluded_sessions.py b/products/replay_vision/backend/queries/excluded_sessions.pyindex 2c4bc3e93bba..44323c899686 100644--- a/products/replay_vision/backend/queries/excluded_sessions.py+++ b/products/replay_vision/backend/queries/excluded_sessions.py@@ -27,11 +27,15 @@ from opentelemetry import tracefrom posthog.models import Teamfrom products.replay_vision.backend.queries.scanner_candidate_query import (+ BackfillCandidateQuery,CandidateSession,ScannerCandidateQuery,execute_candidate_query,)+# Both fetch candidates with the in-query blocklists off, so both owe the caller this question.+CandidateQuery = ScannerCandidateQuery | BackfillCandidateQuery+tracer = trace.get_tracer(__name__)# Bounded by the caller's candidate batch, so it only has to outlast a scan over named session ids.@@ -50,7 +54,7 @@ _MAX_IDS_PER_QUERY = 1_000def excluded_session_ids(*,team: Team,- candidate_query: ScannerCandidateQuery,+ candidate_query: CandidateQuery,candidates: list[CandidateSession],scanner_id: str | None = None,seconds_remaining: float | None = None,diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pyindex 8a10152e8917..300013769faa 100644--- a/products/replay_vision/backend/queries/scanner_candidate_query.py+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -201,11 +201,7 @@ class ScannerCandidateQuery:@tracer.start_as_current_span("ScannerCandidateQuery.run")def excluded_sessions_queries(self, session_ids: list[str]) -> list[ast.SelectQuery]:- """Which of `session_ids` this scanner's negative filters exclude, as queries to run.-- Delegates so the exclusion inherits the window and preprocessed filters this query fetched- with. Empty when nothing is excluded.- """+ """Delegates, so the exclusion inherits the window and filters this query fetched with."""return self._inner.excluded_sessions_queries(session_ids)def run(self) -> list[CandidateSession]:@@ -326,6 +322,9 @@ class BackfillCandidateQuery:# 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,+ # Only for callers that drop negative-filter matches from the rows they fetched. The quote+ # path counts rather than dispatching, so it keeps the in-query blocklist and stays exact.+ skip_negative_blocklists: bool = False,candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,scanner_id: str | None = None,@@ -371,8 +370,13 @@ class BackfillCandidateQuery:query=inner_query,extra_having_predicates=extra_having,session_ids_to_exclude=exclude_session_ids,+ skip_negative_blocklists=skip_negative_blocklists,)+ 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)+@tracer.start_as_current_span("BackfillCandidateQuery.run")def run(self) -> list[CandidateSession]:rows = execute_candidate_query(diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.pyindex c79b5e2c9a2b..c68cfb84bdf4 100644--- a/products/replay_vision/backend/temporal/activities/backfill.py+++ b/products/replay_vision/backend/temporal/activities/backfill.py@@ -1,5 +1,6 @@"""Activities for the per-backfill tick workflow: gatekeeping, candidate walk, cursor advance, schedule ops."""+import timeimport asynciofrom uuid import UUID@@ -24,6 +25,7 @@ from products.replay_vision.backend.models.replay_scanner_backfill import (BackfillStatus,ReplayScannerBackfill,)+from products.replay_vision.backend.queries import excluded_sessionsfrom products.replay_vision.backend.queries.scanner_candidate_query import BackfillCandidateQueryfrom products.replay_vision.backend.quota import compute_scanner_budget, quota_statefrom products.replay_vision.backend.temporal.activities.count_in_flight_applies import (@@ -43,6 +45,7 @@ from products.replay_vision.backend.temporal.backfill_types import (from products.replay_vision.backend.temporal.constants import (BACKFILL_SCHEDULE_ID_PREFIX,BACKFILL_SCHEDULE_TYPE,+ FIND_BACKFILL_CANDIDATES_TIMEOUT,backfill_dispatch_budget,build_apply_scanner_workflow_id,)@@ -154,7 +157,7 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> Ff"ReplayScannerBackfill {inputs.backfill_id} has malformed frozen query: {exc}", non_retryable=True) from exc- candidates = BackfillCandidateQuery(+ candidate_query = BackfillCandidateQuery(team=backfill.team,query=query,window_start=backfill.window_start,@@ -167,7 +170,10 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> Fcursor_end_time=backfill.cursor_end_time,cursor_session_id=backfill.cursor_session_id or None,candidate_limit=inputs.candidate_limit,- ).run()+ skip_negative_blocklists=True,+ )+ started_at = time.monotonic()+ candidates = candidate_query.run()# Succeeded only, matching the `$recording_observed` event the creation-time count excludes on.# Postgres rather than that count's fail-soft ClickHouse read, whose hiccup would report every session@@ -180,7 +186,16 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> Fsession_id__in=[c.session_id for c in candidates],).values_list("session_id", "completed_at"))- dispatchable = [c for c in candidates if c.session_id not in succeeded_at]+ unobserved = [c for c in candidates if c.session_id not in succeeded_at]+ # After the Postgres filter, so the scan covers only ids that could still be dispatched.+ excluded = excluded_sessions.excluded_session_ids(+ team=backfill.team,+ candidate_query=candidate_query,+ candidates=unobserved,+ scanner_id=str(backfill.scanner_id),+ seconds_remaining=FIND_BACKFILL_CANDIDATES_TIMEOUT.total_seconds() - (time.monotonic() - started_at),+ )+ dispatchable = [c for c in unobserved if c.session_id not in excluded]# Only sessions the live sweep reached after this backfill was quoted were in its total, so only those# count as work done; earlier successes were already excluded at creation.overtaken = {diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.pyindex 52f2a39639bd..8a20eb9a6747 100644--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py@@ -190,6 +190,10 @@ def _deep_sweep(max_execution_time_seconds=DEEP_SWEEP_MAX_EXECUTION_SECONDS,scanner_id=str(scanner.id),)+ # Deliberately still on the in-query blocklist. This pass holds its watermark when a batch+ # saturates, which assumes a full batch spent the headroom; scoped exclusion breaks that, since a+ # fully excluded batch dispatches nothing and the same rows return forever. It has no keyset to+ # resume from, so it cannot advance instead.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 thediff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.pyindex 3bb011ad50ae..2c1744fcd18f 100644--- a/products/replay_vision/backend/tests/test_backfills.py+++ b/products/replay_vision/backend/tests/test_backfills.py@@ -30,6 +30,8 @@ from products.replay_vision.backend.models.replay_scanner import (ScannerType,)from products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill+from products.replay_vision.backend.queries import excluded_sessions+from products.replay_vision.backend.queries.scanner_candidate_query import CandidateSessionfrom products.replay_vision.backend.quota import QuotaState, compute_quota_snapshot, spend_projectionfrom products.replay_vision.backend.temporal.activities.backfill import (advance_backfill_cursor_activity,@@ -494,6 +496,45 @@ class TestBackfillTickActivities:assert result.next_cursor_end_time is Noneassert result.skipped_delta == 0+ def test_excluded_sessions_are_walked_over_not_dispatched(self) -> None:+ # The cursor must pass an excluded session exactly as it passes an already-succeeded one.+ # Filtering before the walk would leave the cursor short and refetch the same rows forever.+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ fetched = [+ CandidateSession(session_id="keep", session_end=timezone.now() - dt.timedelta(hours=2)),+ 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.object(excluded_sessions, "excluded_session_ids", return_value={"blocked"}),+ ):+ query_cls.return_value.run.return_value = fetched+ result = find_backfill_candidates_activity(+ FindBackfillCandidatesInputs(backfill_id=backfill.id, team_id=backfill.team_id, candidate_limit=50)+ )++ assert query_cls.call_args.kwargs["skip_negative_blocklists"] is True+ assert [c.session_id for c in result.candidates] == ["keep"]+ # walked past the excluded row, not stopped at the survivor+ assert result.next_cursor_session_id == "blocked"++ def test_exclusion_failure_fails_the_tick_rather_than_dispatching(self) -> None:+ # In-query blocklists are off by this point, so swallowing would dispatch unfiltered.+ scanner = _make_scanner()+ backfill = _make_backfill(scanner)+ with (+ patch("products.replay_vision.backend.temporal.activities.backfill.BackfillCandidateQuery") as query_cls,+ patch.object(excluded_sessions, "excluded_session_ids", side_effect=RuntimeError("clickhouse down")),+ ):+ query_cls.return_value.run.return_value = [+ CandidateSession(session_id="s1", session_end=timezone.now() - dt.timedelta(hours=1))+ ]+ with pytest.raises(RuntimeError):+ find_backfill_candidates_activity(+ FindBackfillCandidatesInputs(backfill_id=backfill.id, team_id=backfill.team_id, candidate_limit=50)+ )+def test_advance_loses_to_concurrent_cancel(self) -> None:scanner = _make_scanner()backfill = _make_backfill(scanner, status=BackfillStatus.CANCELLED, finished_at=timezone.now())