: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): add ranked watch-feed endpoint for observations (#97966)
Kim Svatos Dugan6680776e8d6d
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex a1ea2f0dee00..15d12de0026d 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -733,6 +733,19 @@ class ReplayVisionEstimateSustainedRateThrottle(_TeamBucketRateThrottle):rate = "200/hour"+# The watch feed windows, ranks and hydrates a slice of the team's observation history per call, and+# its primary caller is the session-authenticated home tab, which the default Burst/Sustained+# throttles bypass. Team-wide bucket so minting keys doesn't multiply the budget.+class ReplayVisionWatchFeedBurstRateThrottle(_TeamBucketRateThrottle):+ scope = "replay_vision_watch_feed_burst"+ rate = "60/minute"+++class ReplayVisionWatchFeedSustainedRateThrottle(_TeamBucketRateThrottle):+ scope = "replay_vision_watch_feed_sustained"+ rate = "600/hour"++# Each observation search makes a synchronous embedding request and a brute-force cosine scan over# the team's embedding rows, and its primary caller is the session-authenticated Search tab, which# the default Burst/Sustained throttles bypass. The burst bucket is per credential so one userdiff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex db3cf14398b9..6e14c19b4611 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1,10 +1,25 @@import json+from datetime import timedeltafrom typing import Any, NoReturn, castfrom uuid import UUIDfrom django.db import IntegrityError, models, transaction-from django.db.models import CharField, Count, F, IntegerField, OuterRef, Prefetch, Q, QuerySet, Subquery, Sum, Value-from django.db.models.functions import Coalesce, NullIf+from django.db.models import (+ CharField,+ Count,+ Exists,+ F,+ IntegerField,+ OuterRef,+ Prefetch,+ Q,+ QuerySet,+ Subquery,+ Sum,+ Value,+ Window,+)+from django.db.models.functions import Coalesce, NullIf, RowNumberfrom django.utils import timezoneimport structlog@@ -45,6 +60,8 @@ from posthog.rate_limit import (AISustainedRateThrottle,ReplayVisionEstimateBurstRateThrottle,ReplayVisionEstimateSustainedRateThrottle,+ ReplayVisionWatchFeedBurstRateThrottle,+ ReplayVisionWatchFeedSustainedRateThrottle,)from products.access_control.backend.presentation.access_control import (@@ -59,6 +76,7 @@ from products.replay_vision.backend.api.filters import (split_csv,validate_csv_choices,)+from products.replay_vision.backend.api.observations import ReplayObservationSerializerfrom products.replay_vision.backend.api.trigger import (WorkflowStartOutcome,check_observation_quota,@@ -82,7 +100,9 @@ from products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,ReplayObservation,+ hydrate_for_serialization,)+from products.replay_vision.backend.models.replay_observation_view import ReplayObservationViewfrom products.replay_vision.backend.models.replay_scanner import (ReplayScanner,SamplingMode,@@ -109,7 +129,11 @@ from products.replay_vision.backend.quota import (current_period_bounds,spend_projection,)-from products.replay_vision.backend.scanner_access import is_experiment_accessible+from products.replay_vision.backend.scanner_access import (+ accessible_observations,+ is_experiment_accessible,+ readable_observation_scanner_ids,+)from products.replay_vision.backend.scanner_config import (MAX_PROMPT_LENGTH,MAX_TAG_LENGTH,@@ -123,10 +147,12 @@ from products.replay_vision.backend.scanning import (scan_existing_scanner,scan_outcome_counts,)+from products.replay_vision.backend.search import parse_date_boundfrom products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tagsfrom products.replay_vision.backend.temporal.constants import VISION_SIGNALS_SOURCE_PRODUCT, VISION_SIGNALS_SOURCE_TYPEfrom products.replay_vision.backend.temporal.metrics import record_estimate_outcome, record_scanner_limit_reached+from products.replay_vision.backend.watch_feed import rank_watch_feed_candidatesfrom products.signals.backend.facade.api import get_outcomes_for_signal_source_slice# Date is set by the schedule at trigger time, not by the user — strip on save.@@ -1329,6 +1355,141 @@ class ScannerStatsResponseSerializer(serializers.Serializer):)+WATCH_FEED_DEFAULT_LIMIT = 20+WATCH_FEED_MAX_LIMIT = 50+WATCH_FEED_DEFAULT_DATE_FROM = "-7d"+# Widest window one request may rank. An arbitrarily early `date_from` would make Postgres partition+# and sort the team's entire observation history before the row caps apply.+WATCH_FEED_MAX_WINDOW_DAYS = 90+# Rank at most this many of the newest succeeded observations in the window. A very high-volume+# team ranks only the newest slice, which recency-biases the feed — acceptable for a preview surface.+WATCH_FEED_CANDIDATE_CAP = 1000+# Within that slice, one scanner contributes at most this many rows. Without it, a busy scanner fills+# the whole cap and quiet scanners lose not just feed slots but their own baselines — "unusual for+# this scanner lately" silently stops firing for exactly the scanners the cap crowded out.+WATCH_FEED_PER_SCANNER_CAP = 100+++class WatchFeedReason(models.TextChoices):+ SIGNAL_EMITTED = "signal_emitted"+ UNUSUAL_VERDICT = "unusual_verdict"+ VERDICT_YES = "verdict_yes"+ OUTLIER_SCORE = "outlier_score"+ RARE_TAG = "rare_tag"+ NOVEL_SUMMARY = "novel_summary"+ FRICTION = "friction"+ UNVIEWED_RECENT = "unviewed_recent"+ RECENT = "recent"+++class WatchFeedQuerySerializer(serializers.Serializer):+ """Query parameters of GET /vision/scanners/watch_feed/."""++ date_from = serializers.CharField(+ required=False,+ default=WATCH_FEED_DEFAULT_DATE_FROM,+ help_text=(+ "Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, "+ "or `now`; values without an explicit offset are interpreted in the project's timezone. The window "+ f"between `date_from` and `date_to` may span at most {WATCH_FEED_MAX_WINDOW_DAYS} days."+ ),+ )+ date_to = serializers.CharField(+ required=False,+ help_text=(+ "Only observations created at or before this time. Same formats as `date_from`; omit it to "+ "query through the current time."+ ),+ )+ scanner_ids = serializers.CharField(+ required=False,+ help_text="Comma-separated scanner UUIDs to restrict the feed to. Defaults to every scanner you can read.",+ )+ scanner_type = serializers.ChoiceField(+ required=False,+ choices=ScannerType.choices,+ help_text="Restrict the feed to observations from scanners of this type.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=WATCH_FEED_DEFAULT_LIMIT,+ min_value=1,+ max_value=WATCH_FEED_MAX_LIMIT,+ help_text=f"Feed items to return, at most {WATCH_FEED_MAX_LIMIT}. The feed is bounded, not paginated.",+ )++ def validate_scanner_ids(self, value: str) -> list[UUID]:+ raw_ids = split_csv(value)+ if not raw_ids:+ raise serializers.ValidationError("At least one scanner id is required when the filter is set.")+ try:+ return [UUID(raw_id) for raw_id in raw_ids]+ except ValueError:+ raise serializers.ValidationError("Scanner ids must be UUIDs.")+++class WatchFeedReasonSerializer(serializers.Serializer):+ """Machine-readable reason an observation made the feed; the frontend renders the copy."""++ kind = serializers.ChoiceField(+ choices=WatchFeedReason.choices,+ help_text=(+ "Highest-priority rule the observation satisfied: `signal_emitted` (it pushed a signal), "+ "`unusual_verdict` (a monitor answer that is the minority for that scanner this window), "+ "`verdict_yes` (a monitor hit, when the window is too thin to know which answer is unusual), "+ "`outlier_score` (far from the scanner's window average), "+ "`rare_tag` (a tag uncommon for the scanner this window), `novel_summary` (a summary that "+ "reads unlike the scanner's other sessions this window), `friction` (the scan describes "+ "errors, retries, or dead ends), `unviewed_recent` (new to you), "+ "`recent` (nothing special, newest available)."+ ),+ )+ signals_count = serializers.IntegerField(+ required=False, allow_null=True, help_text="Signals this observation emitted, for `signal_emitted`."+ )+ verdict = serializers.CharField(+ required=False, allow_null=True, help_text="The monitor's answer, for `unusual_verdict`."+ )+ verdict_share = serializers.FloatField(+ required=False,+ allow_null=True,+ help_text="Share (0-1) of the scanner's window observations with this answer, for `unusual_verdict`.",+ )+ score = serializers.FloatField(+ required=False, allow_null=True, help_text="The observation's score, for `outlier_score`."+ )+ window_mean = serializers.FloatField(+ required=False, allow_null=True, help_text="The scanner's mean score in the window, for `outlier_score`."+ )+ tag = serializers.CharField(+ required=False, allow_null=True, help_text="The rare tag that ranked the observation, for `rare_tag`."+ )+ tag_share = serializers.FloatField(+ required=False,+ allow_null=True,+ help_text="Share (0-1) of the scanner's window observations carrying `tag`, for `rare_tag`.",+ )+++class WatchFeedItemSerializer(serializers.Serializer):+ """One feed entry: the observation plus why it ranked."""++ observation = ReplayObservationSerializer(help_text="The observation, in the standard shape.")+ reason = WatchFeedReasonSerializer(help_text="Why this observation made the feed.")+++class WatchFeedResponseSerializer(serializers.Serializer):+ """Response of GET /vision/scanners/watch_feed/."""++ results = WatchFeedItemSerializer(+ many=True,+ help_text=(+ "Succeeded observations in the window worth watching, most interesting first: signal emitters, "+ "then type-specific hits, then unviewed before viewed, then newest."+ ),+ )++class ScannerCreatorsResponseSerializer(serializers.Serializer):"""Distinct creators across all scanners on the team — feeds the `Created by` filter dropdown."""@@ -1672,7 +1833,14 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viscope_object = "replay_scanner"# Custom actions must be listed explicitly or personal-API-key callers 403 silently.- scope_object_read_actions = ["list", "retrieve", "creators", "stats", "self_driving_stats"]+ scope_object_read_actions = [+ "list",+ "retrieve",+ "creators",+ "stats",+ "self_driving_stats",+ "watch_feed",+ ]scope_object_write_actions = ["create","update",@@ -1863,6 +2031,95 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vienabled += row["c"]return Response({"total": total, "enabled": enabled, "by_type": by_type})+ @extend_schema(+ parameters=[WatchFeedQuerySerializer],+ responses={200: WatchFeedResponseSerializer},+ )+ @action(+ detail=False,+ methods=["get"],+ pagination_class=None,+ required_scopes=["replay_scanner:read", "session_recording:read"],+ throttle_classes=[ReplayVisionWatchFeedBurstRateThrottle, ReplayVisionWatchFeedSustainedRateThrottle],+ )+ def watch_feed(self, request: Request, **kwargs: Any) -> Response:+ """Succeeded observations in the window worth watching, ranked — feeds the What to watch tab."""+ query = WatchFeedQuerySerializer(data=request.query_params)+ query.is_valid(raise_exception=True)+ params = query.validated_data+ # Observations expose recording-derived output, so reading them requires session_recording read.+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):+ raise PermissionDenied("Reading replay observations requires session_recording read access.")+ try:+ date_from = parse_date_bound(params["date_from"], self.team.timezone_info, end_of_range=False)+ date_to = (+ parse_date_bound(params["date_to"], self.team.timezone_info, end_of_range=True)+ if params.get("date_to")+ else None+ )+ except ValueError as e:+ raise ValidationError(str(e))+ window_end = date_to if date_to is not None else timezone.now()+ if window_end - date_from > timedelta(days=WATCH_FEED_MAX_WINDOW_DAYS):+ raise ValidationError(+ f"The window between date_from and date_to may span at most {WATCH_FEED_MAX_WINDOW_DAYS} days."+ )+ # Scanner RBAC plus current experiment targeting; unreadable ids drop out silently so the+ # response never confirms which of the requested scanners exist.+ allowed_ids = readable_observation_scanner_ids(self.user_access_control, self.team_id)+ if params.get("scanner_ids"):+ requested = set(params["scanner_ids"])+ allowed_ids = [scanner_id for scanner_id in allowed_ids if scanner_id in requested]+ candidates = ReplayObservation.objects.filter(+ team_id=self.team_id,+ scanner_id__in=allowed_ids,+ status=ObservationStatus.SUCCEEDED,+ created_at__gte=date_from,+ )+ if date_to is not None:+ candidates = candidates.filter(created_at__lte=date_to)+ if params.get("scanner_type"):+ candidates = candidates.filter(scanner_snapshot__scanner_type=params["scanner_type"])+ # Row-gate on each row's snapshot experiment before ranking, so a restricted row can't take a slot.+ candidates = accessible_observations(self.user_access_control, self.team_id, candidates)+ viewer_id = cast(User, request.user).id+ viewed = Exists(ReplayObservationView.objects.filter(observation_id=OuterRef("id"), user_id=viewer_id))+ candidate_rows = list(+ candidates.annotate(+ feed_viewed=viewed,+ scanner_recency_rank=Window(+ RowNumber(),+ partition_by=F("scanner_id"),+ order_by=[F("created_at").desc(), F("id").desc()],+ ),+ )+ .filter(scanner_recency_rank__lte=WATCH_FEED_PER_SCANNER_CAP)+ .values("id", "scanner_id", "created_at", "scanner_result", "feed_viewed")+ .order_by("-created_at", "-id")[:WATCH_FEED_CANDIDATE_CAP]+ )+ ranked = rank_watch_feed_candidates(candidate_rows)[: params["limit"]]+ reasons_by_id = {entry.observation_id: entry.reason for entry in ranked}+ rows = {+ row.id: row+ for row in hydrate_for_serialization(+ # team_id is redundant with the already-scoped candidate query these ids came from,+ # but keeps the re-fetch fail-closed on its own.+ ReplayObservation.objects.filter(team_id=self.team_id, id__in=list(reasons_by_id)),+ viewer_id=request.user.id,+ )+ }+ # A row deleted between the ranking query and this re-fetch just drops out, so `limit` is a+ # soft ceiling rather than a guarantee — harmless for a feed, not worth a retry loop.+ results = [+ {+ "observation": ReplayObservationSerializer(rows[entry.observation_id]).data,+ "reason": entry.reason,+ }+ for entry in ranked+ if entry.observation_id in rows+ ]+ return Response({"results": results})+@extend_schema(request=ObserveRequestSerializer,responses={diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex d9668ecf0c50..ea57a48bf2f2 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -28,7 +28,7 @@ from posthog.redis import get_clientfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom products.experiments.backend.models.experiment import Experiment-from products.replay_vision.backend.api.scanners import ReplayScannerSerializer+from products.replay_vision.backend.api.scanners import ReplayScannerSerializer, WatchFeedQuerySerializerfrom products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_apply_scanner_workflowfrom products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.enqueue_claims import _scanner_key, _team_key, pending_enqueue_claims_for_team@@ -4056,6 +4056,504 @@ class TestInlineScanAction(_VisionAPITestCase):start_workflow.assert_not_called()+class TestWatchFeedQueryValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("empty_scanner_ids", {"scanner_ids": ""}),+ ("not_uuid", {"scanner_ids": "not-a-uuid"}),+ ("bad_scanner_type", {"scanner_type": "nonsense"}),+ ("limit_too_high", {"limit": "51"}),+ ("limit_zero", {"limit": "0"}),+ ]+ )+ def test_rejects_invalid_query(self, _name: str, params: dict[str, str]) -> None:+ serializer = WatchFeedQuerySerializer(data=params)+ assert not serializer.is_valid()++ def test_defaults_apply(self) -> None:+ serializer = WatchFeedQuerySerializer(data={})+ assert serializer.is_valid()+ assert serializer.validated_data["date_from"] == "-7d"+ assert serializer.validated_data["limit"] == 20+++class TestWatchFeedAPI(_VisionAPITestCase):+ @property+ def feed_url(self) -> str:+ return f"{self.scanners_url}watch_feed/"++ def _succeeded_observation(+ self,+ scanner: ReplayScanner,+ session_id: str,+ minutes_ago: int,+ scanner_result: dict[str, Any] | None = None,+ ) -> ReplayObservation:+ obs = ReplayObservation.objects.create(+ scanner=scanner,+ session_id=session_id,+ scanner_snapshot=_snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ scanner_result=scanner_result+ or {+ "model_output": {"scanner_type": "monitor", "verdict": "no", "reasoning": "r", "confidence": 0.5},+ "signals_count": 0,+ },+ )+ # auto_now_add ignores a passed created_at, so stagger recency with an update.+ ReplayObservation.objects.filter(pk=obs.pk).update(created_at=timezone.now() - timedelta(minutes=minutes_ago))+ return obs++ def _monitor_result(self, verdict: str, signals: int = 0) -> dict[str, Any]:+ return {+ "model_output": {"scanner_type": "monitor", "verdict": verdict, "reasoning": "r", "confidence": 0.9},+ "signals_count": signals,+ }++ def test_ranks_signal_then_hit_then_friction_then_recency_with_reasons(self) -> None:+ scanner = self._create_scanner(name="m")+ summarizer = self._create_scanner(+ name="s", scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p", "length": "short"}+ )+ plain_new = self._succeeded_observation(scanner, "plain-new", 1, self._monitor_result("no"))+ hit = self._succeeded_observation(scanner, "hit", 10, self._monitor_result("yes"))+ signal = self._succeeded_observation(scanner, "signal", 20, self._monitor_result("no", signals=2))+ plain_old = self._succeeded_observation(scanner, "plain-old", 30, self._monitor_result("no"))+ # Friction prose outranks a fresher happy-path row, despite being older.+ self._succeeded_observation(+ scanner,+ "friction-sess",+ 25,+ {+ "model_output": {+ "scanner_type": "summarizer",+ "title": "Checkout gone wrong",+ "summary": "The user hit an error at checkout and retried payment twice.",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ assert summarizer++ resp = self.client.get(self.feed_url)+ self.assertEqual(resp.status_code, 200, resp.json())+ items = resp.json()["results"]+ self.assertEqual(+ [item["observation"]["session_id"] for item in items],+ ["signal", "hit", "friction-sess", "plain-new", "plain-old"],+ )+ self.assertEqual(items[0]["reason"], {"kind": "signal_emitted", "signals_count": 2})+ self.assertEqual(items[1]["reason"], {"kind": "verdict_yes"})+ self.assertEqual(items[2]["reason"], {"kind": "friction"})+ self.assertEqual(items[3]["reason"], {"kind": "unviewed_recent"})+ assert plain_new and hit and signal and plain_old++ def test_minority_verdict_is_the_hit_regardless_of_prompt_polarity(self) -> None:+ # "Was the experience good?" answers yes almost always, so its rare "no" is the notable+ # one; a majority "yes" must not rank as a hit just for being yes.+ scanner = self._create_scanner(name="good-experience")+ for i in range(6):+ self._succeeded_observation(scanner, f"good-{i}", 10 + i, self._monitor_result("yes"))+ self._succeeded_observation(scanner, "bad-one", 1, self._monitor_result("no"))++ resp = self.client.get(f"{self.feed_url}?limit=50")+ items = resp.json()["results"]+ self.assertEqual(items[0]["observation"]["session_id"], "bad-one")+ self.assertEqual(items[0]["reason"]["kind"], "unusual_verdict")+ self.assertEqual(items[0]["reason"]["verdict"], "no")+ reasons = {item["observation"]["session_id"]: item["reason"]["kind"] for item in items}+ self.assertEqual(reasons["good-0"], "unviewed_recent")++ def test_no_verdict_monitor_negation_is_not_friction(self) -> None:+ # "Did they struggle? No" reasoning restates the question; keyword matching must not+ # read the negation as a friction hit.+ scanner = self._create_scanner(name="m")+ self._succeeded_observation(+ scanner,+ "calm",+ 1,+ {+ "model_output": {+ "scanner_type": "monitor",+ "verdict": "no",+ "reasoning": "The user did not struggle and saw no errors.",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ resp = self.client.get(self.feed_url)+ self.assertEqual(resp.json()["results"][0]["reason"], {"kind": "unviewed_recent"})++ def test_viewed_orders_within_tiers_but_never_sinks_a_signal_below_plain_rows(self) -> None:+ # Seen-state is a within-tier order, not a top-level one: a signal the reader saw yesterday+ # still outranks unviewed routine rows, while among plain rows unviewed comes first.+ scanner = self._create_scanner(name="m")+ viewed_signal = self._succeeded_observation(scanner, "viewed-signal", 1, self._monitor_result("no", signals=3))+ viewed_plain = self._succeeded_observation(scanner, "viewed-plain", 10, self._monitor_result("no"))+ self._succeeded_observation(scanner, "fresh-plain", 30, self._monitor_result("no"))+ for viewed in (viewed_signal, viewed_plain):+ self.assertEqual(+ self.client.post(f"{self.observations_url(str(scanner.id))}{viewed.id}/viewed/").status_code, 204+ )++ resp = self.client.get(self.feed_url)+ items = resp.json()["results"]+ self.assertEqual(+ [item["observation"]["session_id"] for item in items],+ ["viewed-signal", "fresh-plain", "viewed-plain"],+ )+ self.assertEqual(items[0]["reason"]["kind"], "signal_emitted")+ self.assertTrue(items[0]["observation"]["viewed"])++ def test_outlier_score_and_rare_tag_reasons(self) -> None:+ scorer = self._create_scanner(+ name="s", scanner_type=ScannerType.SCORER, scanner_config={"prompt": "p", "scale": {"min": 0, "max": 10}}+ )+ for i in range(5):+ self._succeeded_observation(+ scorer,+ f"score-{i}",+ 10 + i,+ {+ "model_output": {"scanner_type": "scorer", "score": 5.0, "reasoning": "r", "confidence": 0.9},+ "signals_count": 0,+ },+ )+ self._succeeded_observation(+ scorer,+ "score-outlier",+ 1,+ {+ "model_output": {"scanner_type": "scorer", "score": 9.5, "reasoning": "r", "confidence": 0.9},+ "signals_count": 0,+ },+ )+ classifier = self._create_scanner(+ name="c",+ scanner_type=ScannerType.CLASSIFIER,+ scanner_config={"prompt": "p", "tags": ["common", "rare"], "multi_label": True},+ )+ for i in range(9):+ self._succeeded_observation(+ classifier,+ f"tag-{i}",+ 10 + i,+ {+ "model_output": {+ "scanner_type": "classifier",+ "tags": ["common"],+ "reasoning": "r",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ self._succeeded_observation(+ classifier,+ "tag-rare",+ 1,+ {+ "model_output": {+ "scanner_type": "classifier",+ "tags": ["common", "rare"],+ "reasoning": "r",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )++ summarizer = self._create_scanner(+ name="sum-novel",+ scanner_type=ScannerType.SUMMARIZER,+ scanner_config={"prompt": "p", "length": "short"},+ )+ for i in range(5):+ self._succeeded_observation(+ summarizer,+ f"sum-{i}",+ 10 + i,+ {+ "model_output": {+ "scanner_type": "summarizer",+ "title": "Browsed the pricing page",+ "summary": "The user browsed the pricing page and compared the available plans.",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ self._succeeded_observation(+ summarizer,+ "sum-novel-sess",+ 1,+ {+ "model_output": {+ "scanner_type": "summarizer",+ "title": "Deleted every project",+ "summary": "Removed all workspaces then immediately churned out.",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )++ resp = self.client.get(f"{self.feed_url}?limit=50")+ reasons = {item["observation"]["session_id"]: item["reason"] for item in resp.json()["results"]}+ self.assertEqual(reasons["score-outlier"]["kind"], "outlier_score")+ self.assertEqual(reasons["score-outlier"]["score"], 9.5)+ self.assertEqual(reasons["tag-rare"]["kind"], "rare_tag")+ self.assertEqual(reasons["tag-rare"]["tag"], "rare")+ self.assertEqual(reasons["sum-novel-sess"]["kind"], "novel_summary")+ # Near-identical summaries are the baseline, not novel.+ self.assertEqual(reasons["sum-0"]["kind"], "unviewed_recent")+ self.assertEqual(reasons["score-0"]["kind"], "unviewed_recent")++ def test_singleton_tag_is_rare_even_in_a_thin_window(self) -> None:+ # A pure share cutoff makes rarity impossible below 10 rows and then fire on every singleton+ # at exactly 10 — the feed would change character as a scanner accumulates data.+ classifier = self._create_scanner(+ name="c-thin",+ scanner_type=ScannerType.CLASSIFIER,+ scanner_config={"prompt": "p", "tags": ["common", "rare"], "multi_label": True},+ )+ for i in range(4):+ self._succeeded_observation(+ classifier,+ f"thin-{i}",+ 10 + i,+ {+ "model_output": {+ "scanner_type": "classifier",+ "tags": ["common"],+ "reasoning": "r",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ self._succeeded_observation(+ classifier,+ "thin-rare",+ 1,+ {+ "model_output": {+ "scanner_type": "classifier",+ "tags": ["common", "rare"],+ "reasoning": "r",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ resp = self.client.get(f"{self.feed_url}?limit=50")+ reasons = {item["observation"]["session_id"]: item["reason"] for item in resp.json()["results"]}+ self.assertEqual(reasons["thin-rare"]["kind"], "rare_tag")+ self.assertEqual(reasons["thin-rare"]["tag"], "rare")++ def test_rare_tag_suppressed_when_the_vocabulary_never_repeats(self) -> None:+ # Freeform tagging that never repeats makes every tag a singleton; rarity means nothing+ # there, and without the guard every row would rank as a top-tier hit.+ classifier = self._create_scanner(+ name="c-chaos",+ scanner_type=ScannerType.CLASSIFIER,+ scanner_config={"prompt": "p", "tags": [], "multi_label": True, "allow_freeform_tags": True},+ )+ for i in range(5):+ self._succeeded_observation(+ classifier,+ f"chaos-{i}",+ 10 + i,+ {+ "model_output": {+ "scanner_type": "classifier",+ "tags": [],+ "tags_freeform": [f"unique_{i}"],+ "reasoning": "r",+ "confidence": 0.9,+ },+ "signals_count": 0,+ },+ )+ resp = self.client.get(f"{self.feed_url}?limit=50")+ kinds = {item["reason"]["kind"] for item in resp.json()["results"]}+ self.assertEqual(kinds, {"unviewed_recent"})++ def test_per_scanner_cap_keeps_quiet_scanners_in_the_candidate_slice(self) -> None:+ # Without the per-scanner cap a busy scanner fills the global slice and quiet scanners lose+ # both feed slots and their own baselines.+ busy = self._create_scanner(name="busy")+ quiet = self._create_scanner(name="quiet")+ for i in range(4):+ self._succeeded_observation(busy, f"busy-{i}", i, self._monitor_result("no"))+ self._succeeded_observation(quiet, "quiet-sess", 30, self._monitor_result("no"))++ with patch("products.replay_vision.backend.api.scanners.WATCH_FEED_PER_SCANNER_CAP", 2):+ resp = self.client.get(f"{self.feed_url}?limit=50")+ sessions = [item["observation"]["session_id"] for item in resp.json()["results"]]+ self.assertIn("quiet-sess", sessions)+ self.assertEqual(len([s for s in sessions if s.startswith("busy-")]), 2)++ def test_window_type_filter_and_limit(self) -> None:+ monitor = self._create_scanner(name="m")+ summarizer = self._create_scanner(+ name="sum", scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p", "length": "short"}+ )+ self._succeeded_observation(monitor, "in-window", 60, self._monitor_result("no"))+ old = self._succeeded_observation(monitor, "too-old", 1, self._monitor_result("yes"))+ ReplayObservation.objects.filter(pk=old.pk).update(created_at=timezone.now() - timedelta(days=10))+ self._succeeded_observation(+ summarizer,+ "summary",+ 5,+ {+ "model_output": {"scanner_type": "summarizer", "title": "t", "summary": "s", "confidence": 0.9},+ "signals_count": 0,+ },+ )++ resp = self.client.get(self.feed_url)+ sessions = [item["observation"]["session_id"] for item in resp.json()["results"]]+ self.assertEqual(sessions, ["summary", "in-window"])++ # The wider window admits the old row, whose verdict-yes hit outranks plain recency.+ resp = self.client.get(f"{self.feed_url}?date_from=-30d&scanner_type=monitor")+ sessions = [item["observation"]["session_id"] for item in resp.json()["results"]]+ self.assertEqual(sessions, ["too-old", "in-window"])++ resp = self.client.get(f"{self.feed_url}?limit=1")+ self.assertEqual(len(resp.json()["results"]), 1)++ def test_scanner_ids_filter_restricts_between_readable_scanners(self) -> None:+ wanted = self._create_scanner(name="wanted")+ other = self._create_scanner(name="other")+ self._succeeded_observation(wanted, "wanted-sess", 1, self._monitor_result("no"))+ self._succeeded_observation(other, "other-sess", 2, self._monitor_result("no"))++ resp = self.client.get(f"{self.feed_url}?scanner_ids={wanted.id}")+ self.assertEqual(+ [item["observation"]["session_id"] for item in resp.json()["results"]],+ ["wanted-sess"],+ )++ def test_date_to_excludes_newer_observations(self) -> None:+ scanner = self._create_scanner(name="m")+ self._succeeded_observation(scanner, "inside", 120, self._monitor_result("no"))+ self._succeeded_observation(scanner, "after-cutoff", 1, self._monitor_result("no"))+ cutoff = (timezone.now() - timedelta(minutes=60)).isoformat()++ resp = self.client.get(self.feed_url, {"date_to": cutoff})+ self.assertEqual(+ [item["observation"]["session_id"] for item in resp.json()["results"]],+ ["inside"],+ )++ def test_global_candidate_cap_keeps_the_newest_rows(self) -> None:+ scanner = self._create_scanner(name="m")+ for i in range(3):+ self._succeeded_observation(scanner, f"sess-{i}", i + 1, self._monitor_result("no"))++ with patch("products.replay_vision.backend.api.scanners.WATCH_FEED_CANDIDATE_CAP", 2):+ resp = self.client.get(f"{self.feed_url}?limit=50")+ self.assertEqual(+ [item["observation"]["session_id"] for item in resp.json()["results"]],+ ["sess-0", "sess-1"],+ )++ def test_window_wider_than_the_maximum_is_rejected(self) -> None:+ resp = self.client.get(f"{self.feed_url}?date_from=-365d")+ self.assertEqual(resp.status_code, 400, resp.json())+ self.assertIn("at most", resp.json()["detail"])++ def test_personal_api_key_needs_both_read_scopes(self) -> None:+ scanner = self._create_scanner(name="m")+ self._succeeded_observation(scanner, "scoped-sess", 1, self._monitor_result("no"))+ value = generate_random_token_personal()+ key = PersonalAPIKey.objects.create(+ label="feed-scope-test",+ user=self.user,+ secure_value=hash_key_value(value),+ scopes=["replay_scanner:read"],+ )++ denied = self.client.get(self.feed_url, HTTP_AUTHORIZATION=f"Bearer {value}")+ self.assertEqual(denied.status_code, 403, denied.json())++ key.scopes = ["replay_scanner:read", "session_recording:read"]+ key.save()+ allowed = self.client.get(self.feed_url, HTTP_AUTHORIZATION=f"Bearer {value}")+ self.assertEqual(allowed.status_code, 200, allowed.json())+ self.assertEqual(allowed.json()["results"][0]["observation"]["session_id"], "scoped-sess")++ def test_malformed_scanner_result_ranks_by_recency_instead_of_500(self) -> None:+ scanner = self._create_scanner(name="m")+ self._succeeded_observation(scanner, "broken", 1, {"model_output": "not-a-dict"})+ resp = self.client.get(self.feed_url)+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual(resp.json()["results"][0]["reason"]["kind"], "unviewed_recent")++ def test_unreadable_and_cross_team_scanners_are_dropped_silently(self) -> None:+ visible = self._create_scanner(name="visible")+ hidden = self._create_scanner(name="hidden")+ self._succeeded_observation(visible, "visible-sess", 1, self._monitor_result("no"))+ self._succeeded_observation(hidden, "hidden-sess", 1, self._monitor_result("no"))+ other_team = Team.objects.create(organization=self.organization, name="other")+ foreign = ReplayScanner.objects.create(+ team=other_team,+ name="foreign",+ scanner_type=ScannerType.MONITOR,+ scanner_config={"prompt": "p"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ with patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level",+ side_effect=lambda qs, **_: qs.exclude(pk=hidden.pk) if qs.model is ReplayScanner else qs,+ ):+ resp = self.client.get(f"{self.feed_url}?scanner_ids={visible.id},{hidden.id},{foreign.id}")+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual([item["observation"]["session_id"] for item in resp.json()["results"]], ["visible-sess"])++ def test_restricted_snapshot_rows_are_excluded(self) -> None:+ experiment = create_experiment(self.team, "restricted-flag")+ scanner = self._create_scanner(name="retargeted", experiment_targeting={"experiment_id": experiment.id})+ self._succeeded_observation(scanner, "restricted-sess", 1, self._monitor_result("yes"))+ scanner.experiment_targeting = None+ scanner.save()+ self._succeeded_observation(scanner, "open-sess", 2, self._monitor_result("no"))++ with patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level",+ side_effect=lambda qs, **_: qs.exclude(pk=experiment.pk) if qs.model is Experiment else qs,+ ):+ resp = self.client.get(self.feed_url)+ self.assertEqual([item["observation"]["session_id"] for item in resp.json()["results"]], ["open-sess"])++ def test_requires_session_recording_read(self) -> None:+ with patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_resource",+ return_value=False,+ ):+ resp = self.client.get(self.feed_url)+ self.assertEqual(resp.status_code, 403, resp.json())++ def test_query_count_stays_flat_as_data_grows(self) -> None:+ scanner = self._create_scanner(name="m")+ self._succeeded_observation(scanner, "s-0", 1, self._monitor_result("no"))+ self.client.get(self.feed_url) # warm request-scoped caches+ with CaptureQueriesContext(connection) as one:+ self.assertEqual(self.client.get(self.feed_url).status_code, 200)+ for i in range(1, 6):+ other = self._create_scanner(name=f"m{i}")+ self._succeeded_observation(other, f"s-{i}", i, self._monitor_result("yes", signals=i % 2))+ with CaptureQueriesContext(connection) as six:+ self.assertEqual(self.client.get(self.feed_url).status_code, 200)+ self.assertEqual(len(one.captured_queries), len(six.captured_queries))++class TestScannerSelfDrivingStatsAPI(_VisionAPITestCase):def test_returns_the_scanners_signal_outcomes(self) -> None:# Wiring guard: the endpoint must query the signals facade for this scanner's slice anddiff --git a/products/replay_vision/backend/watch_feed.py b/products/replay_vision/backend/watch_feed.pynew file mode 100644index 000000000000..1de74bb4b2ed--- /dev/null+++ b/products/replay_vision/backend/watch_feed.py@@ -0,0 +1,244 @@+"""Ranking for the What to watch feed: which succeeded observations in a window are worth a look.++Deterministic v1, no model calls. Baselines come from the candidate rows themselves (the scanner's+own window), so "outlier" and "rare" mean unusual for that scanner lately, not against all history.+"""++import re+from datetime import datetime+from statistics import fmean, stdev+from typing import Any+from uuid import UUID++from posthog.dataclasses import frozen++# Below this many rows a scanner's window baseline is noise, so the scanner gets no type hit.+MIN_BASELINE_ROWS = 5+OUTLIER_STDDEVS = 1.5+RARE_TAG_MAX_SHARE = 0.1+# When more than this share of a scanner's tagged rows carry a "rare" tag, the vocabulary isn't+# discriminating (e.g. freeform tags that never repeat) and rarity means nothing — suppress the rule.+RARE_TAG_MAX_HIT_SHARE = 0.5+# A monitor verdict carried by at most this share of the scanner's window rows is the unusual+# answer, whatever the prompt's polarity ("did they struggle?" vs "was the experience good?").+UNUSUAL_VERDICT_MAX_SHARE = 0.35+# A summary whose best token overlap with the scanner's other summaries stays at or below this is+# treated as an unusual session. Conservative on purpose: prose varies, so only clear outliers hit.+NOVEL_SUMMARY_MAX_SIMILARITY = 0.15+# Jaccard divides by the union, so a very short summary reads as "novel" against any longer one+# regardless of content. Below this many tokens the comparison measures length, not meaning.+NOVEL_SUMMARY_MIN_TOKENS = 8+# Compare against at most this many of the scanner's newest summaries. Bounds the novelty pass to+# O(rows x this) — all-pairs would be quadratic in the scanner's window, which an authenticated+# viewer could lean on by hammering the broad feed.+NOVEL_SUMMARY_MAX_SIBLINGS = 40++_TOKEN_RE = re.compile(r"[a-z0-9]+")++# Friction language in the model's own prose about the session. Stems, so "retried"/"retrying",+# "failed"/"failure", "confused"/"confusing" all hit. Known weakness, not fixable with keywords: a team+# whose product is about errors (error tracking, debugging) matches on happy sessions too, which is why+# friction ranks below seen-state and never reaches the top tiers. Widen with care.+_FRICTION_RE = re.compile(+ r"\b(error|errors|fail(?:ed|ing|ure|s)?|stuck|struggl\w*|confus\w*|frustrat\w*|abandon\w*|"+ r"rage.?click\w*|dead.?end\w*|broken|crash\w*|bug|bugs|retr(?:y|ied|ies|ying)|time(?:d|s)?.?out|"+ r"gave up|give up|churn\w*|unable|couldn.?t|blocked|glitch\w*|freez\w*|froze|unresponsive)\b",+ re.IGNORECASE,+)+++@frozen+class WatchFeedEntry:+ observation_id: UUID+ reason: dict[str, Any]+++@frozen+class _Candidate:+ observation_id: UUID+ scanner_id: UUID+ created_at: datetime+ viewed: bool+ signals_count: int+ scanner_type: str | None+ verdict: str | None+ score: float | None+ tags: tuple[str, ...]+ summary_tokens: frozenset[str]+ friction: bool+++def _parse_candidate(row: dict[str, Any]) -> _Candidate:+ """Read the ranking features off a raw row, tolerating malformed `scanner_result` — a bad row+ ranks by recency only rather than failing the whole feed."""+ result = row.get("scanner_result")+ output = result.get("model_output") if isinstance(result, dict) else None+ if not isinstance(output, dict):+ output = {}+ signals_count = result.get("signals_count") if isinstance(result, dict) else 0+ score = output.get("score")+ raw_tags = output.get("tags")+ raw_freeform = output.get("tags_freeform")+ tags = [+ *(raw_tags if isinstance(raw_tags, list) else []),+ *(raw_freeform if isinstance(raw_freeform, list) else []),+ ]+ title = output.get("title")+ summary = output.get("summary")+ reasoning = output.get("reasoning")+ summary_text = " ".join(part for part in (title, summary) if isinstance(part, str))+ prose = " ".join(part for part in (title, summary, reasoning) if isinstance(part, str))+ scanner_type = output.get("scanner_type") if isinstance(output.get("scanner_type"), str) else None+ verdict = output.get("verdict") if isinstance(output.get("verdict"), str) else None+ # A no-verdict monitor's reasoning restates its question in the negative ("did not struggle"),+ # so keyword matching there reads negations as friction; the scan already judged it a non-event.+ friction_eligible = not (scanner_type == "monitor" and verdict == "no")+ return _Candidate(+ observation_id=row["id"],+ scanner_id=row["scanner_id"],+ created_at=row["created_at"],+ viewed=bool(row.get("feed_viewed")),+ signals_count=signals_count if isinstance(signals_count, int) else 0,+ scanner_type=scanner_type,+ verdict=verdict,+ score=float(score) if isinstance(score, int | float) else None,+ tags=tuple(tag for tag in tags if isinstance(tag, str)),+ summary_tokens=frozenset(_TOKEN_RE.findall(summary_text.lower())),+ friction=friction_eligible and bool(_FRICTION_RE.search(" ".join([prose, *tags]))),+ )+++@frozen+class _ScannerBaseline:+ row_count: int+ score_mean: float | None+ score_stddev: float | None+ tag_shares: dict[str, float]+ rare_tags: frozenset[str]+ verdict_shares: dict[str, float]+++def _baselines(candidates: list[_Candidate]) -> dict[UUID, _ScannerBaseline]:+ by_scanner: dict[UUID, list[_Candidate]] = {}+ for candidate in candidates:+ by_scanner.setdefault(candidate.scanner_id, []).append(candidate)+ baselines: dict[UUID, _ScannerBaseline] = {}+ for scanner_id, rows in by_scanner.items():+ scores = [row.score for row in rows if row.score is not None]+ tag_counts: dict[str, int] = {}+ verdict_counts: dict[str, int] = {}+ tagged_rows = [row for row in rows if row.tags]+ for row in rows:+ for tag in set(row.tags):+ tag_counts[tag] = tag_counts.get(tag, 0) + 1+ if row.verdict is not None:+ verdict_counts[row.verdict] = verdict_counts.get(row.verdict, 0) + 1+ verdict_total = sum(verdict_counts.values())+ # Shares are over rows that carry tags at all, so untagged/malformed rows don't make every+ # real tag look rarer than it is (verdict_shares already divides by verdict_total for the+ # same reason). A singleton always counts as rare: a pure share cutoff makes rarity+ # impossible below 1/RARE_TAG_MAX_SHARE rows and then fire on every singleton at exactly+ # that size, so the feed would change character as a scanner accumulates data.+ tag_shares = {tag: count / len(tagged_rows) for tag, count in tag_counts.items()} if tagged_rows else {}+ rare_tags = (+ frozenset(tag for tag, count in tag_counts.items() if count == 1 or tag_shares[tag] <= RARE_TAG_MAX_SHARE)+ if len(tagged_rows) >= MIN_BASELINE_ROWS+ else frozenset()+ )+ if rare_tags:+ rare_rows = sum(1 for row in tagged_rows if rare_tags & set(row.tags))+ if rare_rows / len(tagged_rows) > RARE_TAG_MAX_HIT_SHARE:+ rare_tags = frozenset()+ baselines[scanner_id] = _ScannerBaseline(+ row_count=len(rows),+ score_mean=fmean(scores) if len(scores) >= MIN_BASELINE_ROWS else None,+ score_stddev=stdev(scores) if len(scores) >= MIN_BASELINE_ROWS else None,+ tag_shares=tag_shares,+ rare_tags=rare_tags,+ verdict_shares=(+ {verdict: count / verdict_total for verdict, count in verdict_counts.items()}+ if verdict_total >= MIN_BASELINE_ROWS+ else {}+ ),+ )+ return baselines+++def _max_summary_similarity(candidate: _Candidate, siblings: list[_Candidate]) -> float | None:+ """Best token-set Jaccard similarity of this summary against the scanner's newest other summaries+ (at most NOVEL_SUMMARY_MAX_SIBLINGS — siblings arrive newest-first from the candidate query).+ None when the window is too thin to say what "usual" reads like."""+ others = [+ row.summary_tokens for row in siblings if row.observation_id != candidate.observation_id and row.summary_tokens+ ][:NOVEL_SUMMARY_MAX_SIBLINGS]+ if len(candidate.summary_tokens) < NOVEL_SUMMARY_MIN_TOKENS or len(others) < MIN_BASELINE_ROWS - 1:+ return None+ return max(len(candidate.summary_tokens & other) / len(candidate.summary_tokens | other) for other in others)+++def _type_hit(candidate: _Candidate, baseline: _ScannerBaseline, siblings: list[_Candidate]) -> dict[str, Any] | None:+ """The type-specific reason this row stands out for its scanner, or None."""+ if candidate.scanner_type == "monitor" and candidate.verdict in ("yes", "no"):+ # With a baseline, the notable answer is the scanner's own minority verdict — prompt+ # polarity doesn't matter ("did they struggle?" vs "was the experience good?"). Without+ # one, fall back to yes, the conventional something-happened phrasing.+ if baseline.verdict_shares:+ share = baseline.verdict_shares.get(candidate.verdict, 0.0)+ if share <= UNUSUAL_VERDICT_MAX_SHARE:+ return {"kind": "unusual_verdict", "verdict": candidate.verdict, "verdict_share": round(share, 3)}+ elif candidate.verdict == "yes":+ return {"kind": "verdict_yes"}+ if candidate.scanner_type == "summarizer":+ similarity = _max_summary_similarity(candidate, siblings)+ if similarity is not None and similarity <= NOVEL_SUMMARY_MAX_SIMILARITY:+ return {"kind": "novel_summary"}+ if (+ candidate.scanner_type == "scorer"+ and candidate.score is not None+ and baseline.score_mean is not None+ and baseline.score_stddev is not None+ # A flat window (every score identical) makes any deviation infinite sigmas; skip it.+ and baseline.score_stddev > 0+ and abs(candidate.score - baseline.score_mean) >= OUTLIER_STDDEVS * baseline.score_stddev+ ):+ return {"kind": "outlier_score", "score": candidate.score, "window_mean": round(baseline.score_mean, 2)}+ if candidate.scanner_type == "classifier" and baseline.rare_tags:+ rare = [(baseline.tag_shares[tag], tag) for tag in set(candidate.tags) if tag in baseline.rare_tags]+ if rare:+ share, tag = min(rare)+ return {"kind": "rare_tag", "tag": tag, "tag_share": round(share, 3)}+ return None+++def rank_watch_feed_candidates(rows: list[dict[str, Any]]) -> list[WatchFeedEntry]:+ """Rank candidate rows (`id`, `scanner_id`, `created_at`, `scanner_result`, `feed_viewed`) most+ watchable first: signal emitters, then type-specific hits, then unviewed before viewed, then+ sessions whose prose reads as friction, then newest.++ Signals and type hits encode what the user configured the scanner to find, so a strong hit they+ saw yesterday still outranks unviewed routine rows — seen-state orders rows within those tiers+ rather than above them. Friction is only a keyword heuristic, so it stays below seen-state:+ it may lift unread rows, never resurface ones a reader already dismissed."""+ candidates = [_parse_candidate(row) for row in rows]+ baselines = _baselines(candidates)+ by_scanner: dict[UUID, list[_Candidate]] = {}+ for candidate in candidates:+ by_scanner.setdefault(candidate.scanner_id, []).append(candidate)+ scored: list[tuple[tuple[bool, bool, bool, bool, datetime], WatchFeedEntry]] = []+ for candidate in candidates:+ hit = _type_hit(candidate, baselines[candidate.scanner_id], by_scanner[candidate.scanner_id])+ has_signal = candidate.signals_count > 0+ if has_signal:+ reason: dict[str, Any] = {"kind": "signal_emitted", "signals_count": candidate.signals_count}+ elif hit is not None:+ reason = hit+ elif candidate.friction:+ reason = {"kind": "friction"}+ elif not candidate.viewed:+ reason = {"kind": "unviewed_recent"}+ else:+ reason = {"kind": "recent"}+ sort_key = (has_signal, hit is not None, not candidate.viewed, candidate.friction, candidate.created_at)+ scored.append((sort_key, WatchFeedEntry(observation_id=candidate.observation_id, reason=reason)))+ scored.sort(key=lambda item: item[0], reverse=True)+ return [entry for _, entry in scored]diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex db99b2387c80..0efbcfcb18f5 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2307,6 +2307,102 @@ export interface SuggestTagsResponseApi {suggestions: TagSuggestionApi[]}+/**+ * * `signal_emitted` - Signal Emitted+ * * `unusual_verdict` - Unusual Verdict+ * * `verdict_yes` - Verdict Yes+ * * `outlier_score` - Outlier Score+ * * `rare_tag` - Rare Tag+ * * `novel_summary` - Novel Summary+ * * `friction` - Friction+ * * `unviewed_recent` - Unviewed Recent+ * * `recent` - Recent+ */+export type WatchFeedReasonEnumApi = (typeof WatchFeedReasonEnumApi)[keyof typeof WatchFeedReasonEnumApi]++export const WatchFeedReasonEnumApi = {+ SignalEmitted: 'signal_emitted',+ UnusualVerdict: 'unusual_verdict',+ VerdictYes: 'verdict_yes',+ OutlierScore: 'outlier_score',+ RareTag: 'rare_tag',+ NovelSummary: 'novel_summary',+ Friction: 'friction',+ UnviewedRecent: 'unviewed_recent',+ Recent: 'recent',+} as const++/**+ * Machine-readable reason an observation made the feed; the frontend renders the copy.+ */+export interface WatchFeedReasonApi {+ /** Highest-priority rule the observation satisfied: `signal_emitted` (it pushed a signal), `unusual_verdict` (a monitor answer that is the minority for that scanner this window), `verdict_yes` (a monitor hit, when the window is too thin to know which answer is unusual), `outlier_score` (far from the scanner's window average), `rare_tag` (a tag uncommon for the scanner this window), `novel_summary` (a summary that reads unlike the scanner's other sessions this window), `friction` (the scan describes errors, retries, or dead ends), `unviewed_recent` (new to you), `recent` (nothing special, newest available).+ *+ * * `signal_emitted` - Signal Emitted+ * * `unusual_verdict` - Unusual Verdict+ * * `verdict_yes` - Verdict Yes+ * * `outlier_score` - Outlier Score+ * * `rare_tag` - Rare Tag+ * * `novel_summary` - Novel Summary+ * * `friction` - Friction+ * * `unviewed_recent` - Unviewed Recent+ * * `recent` - Recent */+ kind: WatchFeedReasonEnumApi+ /**+ * Signals this observation emitted, for `signal_emitted`.+ * @nullable+ */+ signals_count?: number | null+ /**+ * The monitor's answer, for `unusual_verdict`.+ * @nullable+ */+ verdict?: string | null+ /**+ * Share (0-1) of the scanner's window observations with this answer, for `unusual_verdict`.+ * @nullable+ */+ verdict_share?: number | null+ /**+ * The observation's score, for `outlier_score`.+ * @nullable+ */+ score?: number | null+ /**+ * The scanner's mean score in the window, for `outlier_score`.+ * @nullable+ */+ window_mean?: number | null+ /**+ * The rare tag that ranked the observation, for `rare_tag`.+ * @nullable+ */+ tag?: string | null+ /**+ * Share (0-1) of the scanner's window observations carrying `tag`, for `rare_tag`.+ * @nullable+ */+ tag_share?: number | null+}++/**+ * One feed entry: the observation plus why it ranked.+ */+export interface WatchFeedItemApi {+ /** The observation, in the standard shape. */+ observation: ReplayObservationApi+ /** Why this observation made the feed. */+ reason: WatchFeedReasonApi+}++/**+ * Response of GET /vision/scanners/watch_feed/.+ */+export interface WatchFeedResponseApi {+ /** Succeeded observations in the window worth watching, most interesting first: signal emitters, then type-specific hits, then unviewed before viewed, then newest. */+ results: WatchFeedItemApi[]+}+export type VisionAlertsListParams = {/*** Number of results to return per page.@@ -2739,3 +2835,47 @@ export type VisionScannersPromptSuggestionsListParams = {*/offset?: number}++export type VisionScannersWatchFeedRetrieveParams = {+ /**+ * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone. The window between `date_from` and `date_to` may span at most 90 days.+ * @minLength 1+ */+ date_from?: string+ /**+ * Only observations created at or before this time. Same formats as `date_from`; omit it to query through the current time.+ * @minLength 1+ */+ date_to?: string+ /**+ * Feed items to return, at most 50. The feed is bounded, not paginated.+ * @minimum 1+ * @maximum 50+ */+ limit?: number+ /**+ * Comma-separated scanner UUIDs to restrict the feed to. Defaults to every scanner you can read.+ * @minLength 1+ */+ scanner_ids?: string+ /**+ * Restrict the feed to observations from scanners of this type.+ *+ * * `monitor` - Monitor+ * * `classifier` - Classifier+ * * `scorer` - Scorer+ * * `summarizer` - Summarizer+ * @minLength 1+ */+ scanner_type?: VisionScannersWatchFeedRetrieveScannerType+}++export type VisionScannersWatchFeedRetrieveScannerType =+ (typeof VisionScannersWatchFeedRetrieveScannerType)[keyof typeof VisionScannersWatchFeedRetrieveScannerType]++export const VisionScannersWatchFeedRetrieveScannerType = {+ Monitor: 'monitor',+ Classifier: 'classifier',+ Scorer: 'scorer',+ Summarizer: 'summarizer',+} as constdiff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 3681a06bec93..bb947dcc7505 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -73,7 +73,9 @@ import type {VisionScannersObservationsRetrieveParams,VisionScannersObservationsStatsRetrieveParams,VisionScannersPromptSuggestionsListParams,+ VisionScannersWatchFeedRetrieveParams,VisionSpendSeriesApi,+ WatchFeedResponseApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -1513,3 +1515,36 @@ export const visionScannersSuggestTagsCreate = async (body: JSON.stringify(suggestTagsRequestApi),})}++export const getVisionScannersWatchFeedRetrieveUrl = (+ projectId: string,+ params?: VisionScannersWatchFeedRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/vision/scanners/watch_feed/?${stringifiedParams}`+ : `/api/projects/${projectId}/vision/scanners/watch_feed/`+}++/**+ * Succeeded observations in the window worth watching, ranked — feeds the What to watch tab.+ */+export const visionScannersWatchFeedRetrieve = async (+ projectId: string,+ params?: VisionScannersWatchFeedRetrieveParams,+ options?: RequestInit+): Promise<WatchFeedResponseApi> => {+ return apiMutator<WatchFeedResponseApi>(getVisionScannersWatchFeedRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 9b9581372f31..3a2641240918 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -666,3 +666,6 @@ tools:- created_by- updated_atrequires_ai_consent: true+ vision-scanners-watch-feed-retrieve:+ operation: vision_scanners_watch_feed_retrieve+ enabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 84ea0b329d95..51655e0d125c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -90767,6 +90767,103 @@ export namespace Schemas {run_id: string;}+ /**+ * * `signal_emitted` - Signal Emitted+ * * `unusual_verdict` - Unusual Verdict+ * * `verdict_yes` - Verdict Yes+ * * `outlier_score` - Outlier Score+ * * `rare_tag` - Rare Tag+ * * `novel_summary` - Novel Summary+ * * `friction` - Friction+ * * `unviewed_recent` - Unviewed Recent+ * * `recent` - Recent+ */+ export type WatchFeedReasonEnum = typeof WatchFeedReasonEnum[keyof typeof WatchFeedReasonEnum];+++ export const WatchFeedReasonEnum = {+ SignalEmitted: 'signal_emitted',+ UnusualVerdict: 'unusual_verdict',+ VerdictYes: 'verdict_yes',+ OutlierScore: 'outlier_score',+ RareTag: 'rare_tag',+ NovelSummary: 'novel_summary',+ Friction: 'friction',+ UnviewedRecent: 'unviewed_recent',+ Recent: 'recent',+ } as const;++ /**+ * Machine-readable reason an observation made the feed; the frontend renders the copy.+ */+ export interface WatchFeedReason {+ /** Highest-priority rule the observation satisfied: `signal_emitted` (it pushed a signal), `unusual_verdict` (a monitor answer that is the minority for that scanner this window), `verdict_yes` (a monitor hit, when the window is too thin to know which answer is unusual), `outlier_score` (far from the scanner's window average), `rare_tag` (a tag uncommon for the scanner this window), `novel_summary` (a summary that reads unlike the scanner's other sessions this window), `friction` (the scan describes errors, retries, or dead ends), `unviewed_recent` (new to you), `recent` (nothing special, newest available).+ *+ * * `signal_emitted` - Signal Emitted+ * * `unusual_verdict` - Unusual Verdict+ * * `verdict_yes` - Verdict Yes+ * * `outlier_score` - Outlier Score+ * * `rare_tag` - Rare Tag+ * * `novel_summary` - Novel Summary+ * * `friction` - Friction+ * * `unviewed_recent` - Unviewed Recent+ * * `recent` - Recent */+ kind: WatchFeedReasonEnum;+ /**+ * Signals this observation emitted, for `signal_emitted`.+ * @nullable+ */+ signals_count?: number | null;+ /**+ * The monitor's answer, for `unusual_verdict`.+ * @nullable+ */+ verdict?: string | null;+ /**+ * Share (0-1) of the scanner's window observations with this answer, for `unusual_verdict`.+ * @nullable+ */+ verdict_share?: number | null;+ /**+ * The observation's score, for `outlier_score`.+ * @nullable+ */+ score?: number | null;+ /**+ * The scanner's mean score in the window, for `outlier_score`.+ * @nullable+ */+ window_mean?: number | null;+ /**+ * The rare tag that ranked the observation, for `rare_tag`.+ * @nullable+ */+ tag?: string | null;+ /**+ * Share (0-1) of the scanner's window observations carrying `tag`, for `rare_tag`.+ * @nullable+ */+ tag_share?: number | null;+ }++ /**+ * One feed entry: the observation plus why it ranked.+ */+ export interface WatchFeedItem {+ /** The observation, in the standard shape. */+ observation: ReplayObservation;+ /** Why this observation made the feed. */+ reason: WatchFeedReason;+ }++ /**+ * Response of GET /vision/scanners/watch_feed/.+ */+ export interface WatchFeedResponse {+ /** Succeeded observations in the window worth watching, most interesting first: signal emitters, then type-specific hits, then unviewed before viewed, then newest. */+ results: WatchFeedItem[];+ }+export interface WebAnalyticsBotCondition {/*** Stable id for the condition. Generated when omitted.@@ -105120,6 +105217,50 @@ export namespace Schemas {offset?: number;};+ export type VisionScannersWatchFeedRetrieveParams = {+ /**+ * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone. The window between `date_from` and `date_to` may span at most 90 days.+ * @minLength 1+ */+ date_from?: string;+ /**+ * Only observations created at or before this time. Same formats as `date_from`; omit it to query through the current time.+ * @minLength 1+ */+ date_to?: string;+ /**+ * Feed items to return, at most 50. The feed is bounded, not paginated.+ * @minimum 1+ * @maximum 50+ */+ limit?: number;+ /**+ * Comma-separated scanner UUIDs to restrict the feed to. Defaults to every scanner you can read.+ * @minLength 1+ */+ scanner_ids?: string;+ /**+ * Restrict the feed to observations from scanners of this type.+ *+ * * `monitor` - Monitor+ * * `classifier` - Classifier+ * * `scorer` - Scorer+ * * `summarizer` - Summarizer+ * @minLength 1+ */+ scanner_type?: VisionScannersWatchFeedRetrieveScannerType;+ };++ export type VisionScannersWatchFeedRetrieveScannerType = typeof VisionScannersWatchFeedRetrieveScannerType[keyof typeof VisionScannersWatchFeedRetrieveScannerType];+++ export const VisionScannersWatchFeedRetrieveScannerType = {+ Monitor: 'monitor',+ Classifier: 'classifier',+ Scorer: 'scorer',+ Summarizer: 'summarizer',+ } as const;+export type VisualReviewReposListParams = {/*** Number of results to return per page.