: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): serve the highlight feed from stored builds (#125981)
Tue Haulund6dcff9a8c1da
diff --git a/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.tsindex 7039ad3557a1..c769a6f3a3a8 100644--- a/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts+++ b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts@@ -140,6 +140,24 @@ describe('recording cleanup (integration)', () => {[targetObservationId, teamId],'fixtureAnchorSimilarity')+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_replayobservationrank+ (observation_id, team_id, scanner_id, created_at, anchor_version, contrast, category, person_key,+ experiment_id)+ VALUES ($1, $2, $3, now(), 1, 0.5, 1, 7, 0)`,+ [targetObservationId, teamId, scannerId],+ 'fixtureRank'+ )+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_replayhighlightfeedentry+ (team_id, window_days, generation, place, observation_id, scanner_id, created_at, category,+ experiment_id, percentile, group_root)+ VALUES ($1, 1, 1, 1, $2, $3, now(), 1, 0, 0.9, $2)`,+ [teamId, targetObservationId, scannerId],+ 'fixtureHighlightEntry'+ )await postgres.query(PostgresUse.COMMON_WRITE,`INSERT INTO replay_vision_replayobservationfeeddismissal@@ -198,6 +216,8 @@ describe('recording cleanup (integration)', () => {'replay_vision_replayobservationfeeddismissal','replay_vision_replayobservationfeedimpression','replay_vision_replayobservationanchorsimilarity',+ 'replay_vision_replayobservationrank',+ 'replay_vision_replayhighlightfeedentry',]) {expect(await count(`SELECT count(*) FROM ${table} WHERE observation_id = $1`, [targetObservationId])).toBe(0diff --git a/nodejs/src/session-replay/recording-api/recording-service.ts b/nodejs/src/session-replay/recording-api/recording-service.tsindex 463d9fe598fa..761f42ee3e12 100644--- a/nodejs/src/session-replay/recording-api/recording-service.ts+++ b/nodejs/src/session-replay/recording-api/recording-service.ts@@ -548,6 +548,12 @@ export class RecordingService {), deleted_similarities AS (DELETE FROM replay_vision_replayobservationanchorsimilarityWHERE observation_id IN (SELECT id FROM observations)+ ), deleted_ranks AS (+ DELETE FROM replay_vision_replayobservationrank+ WHERE observation_id IN (SELECT id FROM observations)+ ), deleted_feed_entries AS (+ DELETE FROM replay_vision_replayhighlightfeedentry+ WHERE observation_id IN (SELECT id FROM observations))DELETE FROM replay_vision_replayobservationWHERE id IN (SELECT id FROM observations)`,diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 4007dc3fa3ed..a57a66f38df9 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -8,7 +8,7 @@ from zoneinfo import ZoneInfofrom django.conf import settingsfrom django.db import transaction-from django.db.models import Case, IntegerField, Q, QuerySet, Subquery, Value, When+from django.db.models import Case, Exists, IntegerField, OuterRef, Q, QuerySet, Value, Whenfrom django.db.models.fields.json import KeyTextTransform, KeyTransformfrom django.db.models.functions import Castfrom django.http.response import HttpResponseBase@@ -46,7 +46,13 @@ from posthog.session_recordings.models.session_recording import SessionRecordingfrom products.exports.backend.facade.api import get_export_asset_content_responsefrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.replay_vision.backend.api.errors import ReplayVisionErrorSerializer-from products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enum, split_csv+from products.replay_vision.backend.api.filters import (+ MultiChoiceFilter,+ OrderByFilter,+ ordering_enum,+ split_csv,+ validate_csv_choices,+)from products.replay_vision.backend.api.observation_progress import stream_observation_progressfrom products.replay_vision.backend.api.observation_stats import compute_observation_statsfrom products.replay_vision.backend.consent import AI_CONSENT_REQUIRED_CODE, is_ai_data_processing_approved@@ -60,7 +66,6 @@ from products.replay_vision.backend.models.replay_observation import (annotate_output_number,hydrate_for_serialization,jsonb_typeof,- watch_group_root,)from products.replay_vision.backend.models.replay_observation_feed_dismissal import (FeedDismissalReason,@@ -76,6 +81,7 @@ from products.replay_vision.backend.models.replay_scanner import (ScannerType,)from products.replay_vision.backend.observation_formatting import summarize_observation+from products.replay_vision.backend.observation_ranks import CATEGORY_CODESfrom products.replay_vision.backend.prompt_questions import question_for_snapshot, valence_for_snapshotfrom products.replay_vision.backend.scanner_access import (accessible_observations,@@ -99,7 +105,7 @@ from products.replay_vision.backend.search import (from products.replay_vision.backend.temporal.constants import VISION_SIGNALS_SOURCE_PRODUCT, VISION_SIGNALS_SOURCE_TYPEfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdictfrom products.replay_vision.backend.temporal.types import ScannerResult, ScannerSnapshot-from products.replay_vision.backend.watch_rank import ANCHOR_VERSION, ISSUE_CATEGORIES+from products.replay_vision.backend.watch_rank import ISSUE_CATEGORIES, current_ranksfrom products.replay_vision.backend.watch_themes import MAX_SUGGESTED_QUERIES, theme_suggestionsfrom products.signals.backend.facade.api import get_reports_for_signal_source_slicefrom products.tasks.backend.facade import api as tasks_facade@@ -780,10 +786,8 @@ class ReplayObservationFilter(django_filters.FilterSet):"Pair it with the feed's `date_from` to list the sessions a feed card counts."),)- watch_category = MultiChoiceFilter(- field_name="watch_rank__category",- valid_choices=frozenset(ISSUE_CATEGORIES),- error_key="watch_category",+ watch_category = django_filters.CharFilter(+ method="_filter_watch_category",help_text=("Only observations the watch feed ranks under any of these kinds (comma-separated: ""failure, struggle, revenue). Pair it with `watch_group` and the feed's `categories`."@@ -909,22 +913,29 @@ class ReplayObservationFilter(django_filters.FilterSet):) -> QuerySet[ReplayObservation]:if self._team is None:return queryset.none()- root = watch_group_root()- current = Q(- status=ObservationStatus.SUCCEEDED, watch_rank__isnull=False, watch_rank__anchor_version=ANCHOR_VERSION- )- # The asked row's root comes from a subquery, so the filter adds no statement of its own.- asked_root = Subquery(- ReplayObservation.objects.filter(current, id=value, team_id=self._team.id)- .annotate(_root=root)- .values("_root")[:1]- )+ ranks = current_ranks(self._team.id)+ asked = ranks.filter(observation_id=value).values("feed_group_id").first()+ if asked is None:+ return queryset.none()+ # A row without a group stands for itself, as in the feed's builds.+ root = asked["feed_group_id"] or value# Matches the rows the feed counts for a card, which leaves out routine rows.- return (- queryset.alias(_watch_group_root=root, _watch_category=KeyTextTransform("category", "watch_rank"))- .filter(current, _watch_category__in=ISSUE_CATEGORIES)- .filter(_watch_group_root=asked_root)+ members = ranks.filter(category__in=[CATEGORY_CODES[category] for category in ISSUE_CATEGORIES]).filter(+ Q(feed_group_id=root) | Q(observation_id=root, feed_group_id__isnull=True))+ return queryset.filter(id__in=members.values("observation_id"))++ def _filter_watch_category(+ self, queryset: QuerySet[ReplayObservation], _name: str, value: str+ ) -> QuerySet[ReplayObservation]:+ categories = validate_csv_choices(value, frozenset(ISSUE_CATEGORIES), "watch_category")+ if not categories:+ return queryset+ if self._team is None:+ return queryset.none()+ codes = [CATEGORY_CODES[category] for category in categories]+ ranked = current_ranks(self._team.id).filter(observation_id=OuterRef("id"), category__in=codes)+ return queryset.filter(Exists(ranked))def _filter_variant(self, queryset: QuerySet[ReplayObservation], _name: str, value: strdiff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex a0d0ffb9c318..6b287c4b6460 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1,10 +1,7 @@-import json-import hashlibfrom datetime import UTC, datetime, timedeltafrom typing import Any, NoReturn, castfrom uuid import UUID-from django.core.cache import cachefrom django.db import IntegrityError, models, transactionfrom django.db.models import (CharField,@@ -141,7 +138,6 @@ from products.replay_vision.backend.scanner_access import (accessible_experiment_ids,accessible_observations,is_experiment_accessible,- readable_experiment_ids,readable_observation_scanner_ids,scanner_experiment_scope_q,)@@ -184,6 +180,7 @@ from products.replay_vision.backend.temporal.metrics import record_estimate_outcfrom products.replay_vision.backend.temporal.read_meter_types import current_sweep_throttle_factorfrom products.replay_vision.backend.watch_rank import (ISSUE_CATEGORIES,+ feed_window,rank_highlight_feed_by_embedding,select_embedding_filler,select_embedding_picks,@@ -1635,25 +1632,13 @@ class ScannerStatsResponseSerializer(serializers.Serializer):HIGHLIGHT_FEED_DEFAULT_LIMIT = 20HIGHLIGHT_FEED_MAX_LIMIT = 50HIGHLIGHT_FEED_DEFAULT_DATE_FROM = "-7d"+# The `date_from` values the feed stores builds for, by window in days.+HIGHLIGHT_FEED_PRESETS = {"-24h": 1, "-1d": 1, "-7d": 7, "-30d": 30, "-90d": 90}# Widest window one request may rank.HIGHLIGHT_FEED_MAX_WINDOW_DAYS = 90# The most picks one load ranks, and the furthest `offset` may reach.HIGHLIGHT_FEED_CANDIDATE_CAP = 1000HIGHLIGHT_FEED_IMPRESSIONS_MAX_IDS = 100-# Loads in one bucket share their picks, so a reload or tab switch skips the pick query.-HIGHLIGHT_FEED_PICKS_BUCKET_S = 10 * 60-# Outlives the bucket by long enough to cover a reader scrolling one load.-HIGHLIGHT_FEED_PICKS_CACHE_TTL_S = HIGHLIGHT_FEED_PICKS_BUCKET_S + 15 * 60---def refresh_feed_viewed(rows: list[dict[str, Any]], viewer_id: int, as_of: datetime) -> list[dict[str, Any]]:- """Cached rows with `feed_viewed` as of `as_of`."""- viewed = set(- ReplayObservationView.objects.filter(- user_id=viewer_id, created_at__lte=as_of, observation_id__in=[row["id"] for row in rows]- ).values_list("observation_id", flat=True)- )- return [{**row, "feed_viewed": row["id"] in viewed} for row in rows]class HighlightFeedCategory(models.TextChoices):@@ -1748,7 +1733,7 @@ class HighlightFeedQuerySerializer(serializers.Serializer):categories = set(validate_csv_choices(value, frozenset(ISSUE_CATEGORIES), "categories"))if not categories:raise serializers.ValidationError("Include at least one category.")- # Every category is the unfiltered feed, so it shares that feed's cached picks.+ # Every category is the unfiltered feed, so both spellings read alike.return None if categories == set(ISSUE_CATEGORIES) else sorted(categories)def validate_scanner_ids(self, value: str) -> list[UUID]:@@ -2487,82 +2472,58 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi).values_list("id", flat=True))allowed_ids = [scanner_id for scanner_id in allowed_ids if scanner_id in created_ids]- # The scanner list stays off this base: the pick query adds it once per scanner in its lateral join.- candidates = ReplayObservation.objects.filter(- team_id=self.team_id,- status=ObservationStatus.SUCCEEDED,- created_at__gte=date_from,- created_at__lte=window_end,- completed_at__lte=as_of,- )if params.get("scanner_type"):- candidates = candidates.filter(scanner_snapshot__scanner_type=params["scanner_type"])+ typed_ids = set(+ ReplayScanner.objects.filter(+ team_id=self.team_id, id__in=allowed_ids, scanner_type=params["scanner_type"]+ ).values_list("id", flat=True)+ )+ allowed_ids = [scanner_id for scanner_id in allowed_ids if scanner_id in typed_ids]viewer_id = cast(User, request.user).id# Before ranking, so a row the viewer marked not useful never takes a slot.# Views and dismissals after `as_of` wait for the next load, so later pages of this one do not shift.- dismissed_ids = sorted(+ dismissed_ids = list(ReplayObservationFeedDismissal.objects.filter(user_id=viewer_id, created_at__lte=as_of).values_list("observation_id", flat=True))- walkable = candidates.exclude(id__in=dismissed_ids)viewed = Exists(ReplayObservationView.objects.filter(observation_id=OuterRef("id"), user_id=viewer_id, created_at__lte=as_of))- # Keyed on the bucket `as_of` falls in, so loads in one bucket share picks, and on the dismissals and the- # readable experiments, so a dismissal or an access change ranks afresh.- picks_key = (- "replay_vision:highlight_picks:"- + hashlib.sha256(- json.dumps(- [- self.team_id,- viewer_id,- int(as_of.timestamp()) // HIGHLIGHT_FEED_PICKS_BUCKET_S,- params["date_from"],- params.get("date_to"),- list(map(str, dismissed_ids)),- sorted(readable_experiment_ids(self.user_access_control, self.team_id)),- sorted(map(str, allowed_ids)),- params.get("scanner_type"),- params.get("categories"),- ]- ).encode()- ).hexdigest()- )- cached = cache.get(picks_key)- # Picks ranked as of a later moment may hold rows this load's first page never saw, so they don't serve it.- if cached is not None and cached[0] <= as_of:- picked_as_of, candidate_rows = cached- # An earlier load in the bucket ranked these, so its views may be older than this one's.- if picked_as_of != as_of:- candidate_rows = refresh_feed_viewed(candidate_rows, viewer_id, as_of)- else:- # The embedding ranker reads only a small stored rank, so it picks over the whole window in SQL.- candidate_rows = select_embedding_picks(- walkable,- allowed_ids,- viewed,- self.user_access_control,+ categories = params.get("categories") or ISSUE_CATEGORIES+ candidate_rows = select_embedding_picks(+ feed_window(self.team_id,- HIGHLIGHT_FEED_CANDIDATE_CAP,- params.get("categories") or ISSUE_CATEGORIES,+ date_from,+ window_end,+ as_of,+ None if date_to is not None else HIGHLIGHT_FEED_PRESETS.get(params["date_from"]),+ ),+ allowed_ids,+ viewed,+ self.user_access_control,+ self.team_id,+ HIGHLIGHT_FEED_CANDIDATE_CAP,+ categories,+ dismissed_ids,+ )+ # Picks in one feed group collapse into one card, so the floor counts groups.+ pick_roots = {row["watch_group_root"] for row in candidate_rows}+ if len(pick_roots) < HIGHLIGHT_FEED_MIN_ITEMS:+ walkable = ReplayObservation.objects.filter(+ team_id=self.team_id,+ status=ObservationStatus.SUCCEEDED,+ created_at__gte=date_from,+ created_at__lte=window_end,+ completed_at__lte=as_of,+ ).exclude(id__in=dismissed_ids)+ # Padding must not bring back a session the viewer hid by its category.+ hidden = [category for category in ISSUE_CATEGORIES if category not in categories]+ candidate_rows += select_embedding_filler(+ walkable, allowed_ids, viewed, self.user_access_control, self.team_id, pick_roots, hidden)- # Picks in one feed group collapse into one card, so the floor counts groups.- pick_roots = {row["watch_group_root"] for row in candidate_rows}- if len(pick_roots) < HIGHLIGHT_FEED_MIN_ITEMS:- filler_base = walkable- if params.get("categories"):- # Padding must not bring back a session the viewer hid by its category.- hidden = [category for category in ISSUE_CATEGORIES if category not in params["categories"]]- filler_base = walkable.exclude(watch_rank__category__in=hidden)- candidate_rows += select_embedding_filler(- filler_base, allowed_ids, viewed, self.user_access_control, self.team_id, pick_roots- )- # The first load in the bucket keeps the entry, so concurrent loads never replace it with later picks.- cache.add(picks_key, (as_of, candidate_rows), HIGHLIGHT_FEED_PICKS_CACHE_TTL_S)page_end = params["offset"] + params["limit"]impressions = feed_impression_counts(team_id=self.team_id,diff --git a/products/replay_vision/backend/highlight_builds.py b/products/replay_vision/backend/highlight_builds.pyindex be2a085c03df..67bad1c3961b 100644--- a/products/replay_vision/backend/highlight_builds.py+++ b/products/replay_vision/backend/highlight_builds.py@@ -12,8 +12,11 @@ from datetime import datetime, timedeltafrom typing import Anyfrom django.db import connection, transaction+from django.db.models import F, Qfrom django.utils import timezone+import structlog+from posthog.dataclasses import frozenfrom posthog.models.scoping.manager import resolve_effective_team_id@@ -23,6 +26,9 @@ from products.replay_vision.backend.models.replay_highlight_feed import (ReplayHighlightFeedState,)from products.replay_vision.backend.models.replay_observation_rank import RankCategory+from products.replay_vision.backend.observation_ranks import mark_changed++logger = structlog.get_logger(__name__)# The feed surfaces a scanner's top fifth by score, once the scanner has enough ranked rows to make a percentile mean# something.@@ -35,6 +41,11 @@ ISSUE_CODES = (RankCategory.FAILURE, RankCategory.STRUGGLE, RankCategory.REVENUEBUILD_RETENTION = timedelta(minutes=30)_STATEMENT_TIMEOUT = "120s"_LOCK_TIMEOUT = "10s"+# A build older than this asks for a rebuild when read, so a quiet team's windows still move forward.+STALE_AFTER = timedelta(hours=1)+# A team waits at least this long after its last build, so a busy team rebuilds a few times an hour.+REBUILD_DEBOUNCE = timedelta(minutes=5)+REBUILDS_PER_SWEEP = 20# Namespaces the per-team advisory lock that keeps two builds of one team from running at once._BUILD_LOCK_KEY = 0x52564842@@ -198,3 +209,42 @@ def build_highlight_feed(team_id: int, anchor_version: int, *, wait: bool = Truegeneration=generation, built_at=built_at, builds=kept, built_changes=seen_changes)return generation+++def stored_generation(team_id: int, anchor_version: int, as_of: datetime) -> int | None:+ """The stored build a load at `as_of` reads: the newest kept build that was current by then, so later pages stay on+ the build the first page read. A team without a build gets one first, and a stale build is served as is and asks+ for a rebuild. None when the team's first build is still running elsewhere."""+ state = ReplayHighlightFeedState.objects.for_team(team_id).first()+ if state is None or state.built_at is None:+ # A first build another request already runs is not waited on; this load ranks its window on the spot.+ return build_highlight_feed(team_id, anchor_version, wait=False)+ if state.built_at < timezone.now() - STALE_AFTER and state.changes <= state.built_changes:+ mark_changed(team_id)+ current_by_then = [build[0] for build in state.builds if datetime.fromisoformat(build[1]) <= as_of]+ # A load that began before any kept build reads the oldest one, which its first page built or read.+ return max(current_by_then) if current_by_then else min(build[0] for build in state.builds)+++def rebuild_changed_feeds(anchor_version: int) -> int:+ """Rebuild teams whose ranks changed since their last build, least recently tried first, skipping any team another+ process is building. A team whose build fails waits behind the others. Returns how many it built."""+ now = timezone.now()+ states = ReplayHighlightFeedState.objects.unscoped()+ due = list(+ # Every team's state, since the sweep picks which teams to build.+ states.filter(changes__gt=F("built_changes"))+ .filter(Q(built_at__isnull=True) | Q(built_at__lt=now - REBUILD_DEBOUNCE))+ .filter(Q(attempted_at__isnull=True) | Q(attempted_at__lt=now - REBUILD_DEBOUNCE))+ .order_by(F("attempted_at").asc(nulls_first=True))+ .values_list("team_id", flat=True)[:REBUILDS_PER_SWEEP]+ )+ states.filter(team_id__in=due).update(attempted_at=now)+ built = 0+ for team_id in due:+ try:+ built += build_highlight_feed(team_id, anchor_version, wait=False) is not None+ except Exception:+ # One team's failing build must not hold up every team behind it.+ logger.exception("replay_vision.highlight_builds.rebuild_failed", team_id=team_id)+ return builtdiff --git a/products/replay_vision/backend/observation_ranks.py b/products/replay_vision/backend/observation_ranks.pyindex 030e963ebeb5..f5643a275bbb 100644--- a/products/replay_vision/backend/observation_ranks.py+++ b/products/replay_vision/backend/observation_ranks.py@@ -22,6 +22,7 @@ _WRITE_CHUNK = 500_COPY_SLICE = timedelta(days=1)CATEGORY_CODES: dict[str, int] = {category.name.lower(): category.value for category in RankCategory}+CATEGORY_NAMES: dict[int, str] = {code: name for name, code in CATEGORY_CODES.items()}# A snapshot that names an experiment as anything but a plain integer gets -1, which matches no experiment, so the row# stays hidden from every viewer rather than readable by all.diff --git a/products/replay_vision/backend/tests/helpers.py b/products/replay_vision/backend/tests/helpers.pyindex 23dde1ede31a..922e0119593a 100644--- a/products/replay_vision/backend/tests/helpers.py+++ b/products/replay_vision/backend/tests/helpers.py@@ -14,10 +14,12 @@ from products.replay_vision.backend.models.replay_observation import (ObservationTrigger,ReplayObservation,)+from products.replay_vision.backend.models.replay_observation_rank import ReplayObservationRankfrom products.replay_vision.backend.models.replay_observation_usage import ReplayObservationUsagefrom products.replay_vision.backend.models.replay_scanner import ReplayScanner+from products.replay_vision.backend.observation_ranks import NewRank, record_ranksfrom products.replay_vision.backend.temporal.activities.create_observation import _build_scanner_snapshot-from products.replay_vision.backend.watch_rank import ANCHORS, WatchCategory+from products.replay_vision.backend.watch_rank import ANCHOR_VERSION, ANCHORS, WatchCategorydef snapshot_for(scanner: ReplayScanner) -> dict[str, Any]:@@ -93,3 +95,21 @@ def axis_anchors() -> dict[WatchCategory, np.ndarray]:"routine": [0.0, 0.0, 1.0],}return {category: np.array([axes[category]] * len(ANCHORS[category])) for category in ANCHORS}+++def set_rank(+ observation: ReplayObservation,+ *,+ category: str = "failure",+ contrast: float = 0.5,+ group: Any = None,+ theme: Any = None,+ anchor_version: int = ANCHOR_VERSION,+) -> None:+ """Give an observation the rank row the rank consumer would write, replacing any it has."""+ ranks = ReplayObservationRank.objects.for_team(observation.team_id)+ ranks.filter(observation_id=observation.id).delete()+ record_ranks(+ observation.team_id, anchor_version, {str(observation.id): NewRank(contrast=contrast, category=category)}+ )+ ranks.filter(observation_id=observation.id).update(feed_group_id=group, search_theme_id=theme)diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 457a4fb0a016..cdbf9c46aa1c 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -2,6 +2,7 @@ import uuidfrom datetime import UTC, datetime, timedeltafrom typing import Any, cast+import time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import ANY, MagicMock, patch@@ -35,16 +36,13 @@ from posthog.session_recordings.queries.test.session_replay_sql import produce_rfrom products.access_control.backend.models.access_control import AccessControlfrom products.experiments.backend.models.experiment import Experiment-from products.replay_vision.backend.api.scanners import (- HIGHLIGHT_FEED_PICKS_BUCKET_S,- HighlightFeedQuerySerializer,- ReplayScannerSerializer,-)+from products.replay_vision.backend.api.scanners import HighlightFeedQuerySerializer, ReplayScannerSerializerfrom 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.built_in_scans import BUILT_IN_SCANS, BuiltInScanKeyfrom products.replay_vision.backend.enqueue_claims import _scanner_key, _team_key, pending_enqueue_claims_for_teamfrom products.replay_vision.backend.experiment_launch import start_scanners_of_launched_experiments+from products.replay_vision.backend.highlight_builds import build_highlight_feedfrom products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,@@ -79,6 +77,7 @@ from products.replay_vision.backend.temporal.constants import (from products.replay_vision.backend.tests.helpers import (create_experiment,seed_scanner_spend,+ set_rank,snapshot_for as _snapshot_for,)from products.replay_vision.backend.watch_rank import ANCHOR_VERSION@@ -2273,23 +2272,15 @@ class TestReplayObservationViewSet(_VisionAPITestCase):}root_id = str(rows["root"].id)- def rank(group: str | None, category: str = "failure", anchor_version: int = ANCHOR_VERSION) -> dict[str, Any]:- return {- "category": category,- "contrast": 0.3,- "group": group,- "anchor_version": anchor_version,- }-- for name, watch_rank in {- "root": rank(None),- "copy": rank(root_id),- "struggle": rank(root_id, category="struggle"),- "routine": rank(root_id, category="routine"),- "stale": rank(root_id, anchor_version=ANCHOR_VERSION - 1),- "other": rank(None),+ for name, (member_group, category, anchor_version) in {+ "root": (None, "failure", ANCHOR_VERSION),+ "copy": (root_id, "failure", ANCHOR_VERSION),+ "struggle": (root_id, "struggle", ANCHOR_VERSION),+ "routine": (root_id, "routine", ANCHOR_VERSION),+ "stale": (root_id, "failure", ANCHOR_VERSION - 1),+ "other": (None, "failure", ANCHOR_VERSION),}.items():- ReplayObservation.objects.filter(id=rows[name].id).update(watch_rank=watch_rank)+ set_rank(rows[name], category=category, group=member_group, anchor_version=anchor_version)other_team = Team.objects.create(organization=self.organization, name="other")other_row = ReplayObservation.objects.create(@@ -2298,8 +2289,8 @@ class TestReplayObservationViewSet(_VisionAPITestCase):session_id="other-team",status=ObservationStatus.SUCCEEDED,completed_at=timezone.now(),- watch_rank=rank(root_id),)+ set_rank(other_row, group=root_id)member = {"other_team": str(other_row.id), None: str(uuid.uuid4())}.get(asked) or str(rows[str(asked)].id)query = f"watch_group={member}" + (f"&watch_category={categories}" if categories else "")resp = self.client.get(f"{self.observations_url(str(self.scanner.id))}?{query}")@@ -4812,9 +4803,7 @@ class TestHighlightFeedQueryValidation(SimpleTestCase):@parameterized.expand([("every_category", "struggle,revenue,failure", None), ("subset", "revenue,failure", ["failure", "revenue"])])- def test_categories_normalize_so_equal_choices_share_cached_picks(- self, _name: str, raw: str, expected: list[str] | None- ) -> None:+ def test_categories_normalize_to_one_form(self, _name: str, raw: str, expected: list[str] | None) -> None:serializer = HighlightFeedQuerySerializer(data={"categories": raw})assert serializer.is_valid()assert serializer.validated_data["categories"] == expected@@ -4865,9 +4854,7 @@ class TestHighlightFeedAPI(_VisionAPITestCase):group: str | None = None,) -> ReplayObservation:obs = self._succeeded_observation(scanner, session_id, minutes_ago, self._monitor_result("no"))- ReplayObservation.objects.filter(id=obs.id).update(- watch_rank={"category": category, "contrast": contrast, "group": group, "anchor_version": ANCHOR_VERSION}- )+ set_rank(obs, category=category, contrast=contrast, group=group)return obs@parameterized.expand(@@ -4893,7 +4880,7 @@ class TestHighlightFeedAPI(_VisionAPITestCase):[item["observation"]["session_id"] for item in items], [f"row-{i}" for i in range(len(expected_kinds))])- def test_categories_drop_the_left_out_picks_even_when_picks_are_cached(self) -> None:+ def test_categories_drop_the_left_out_picks_between_loads(self) -> None:scanner = self._create_scanner(name="m")# Of 20 ranked rows the top four clear the percentile cut: two failures and two revenue rows.rows = []@@ -4938,33 +4925,23 @@ class TestHighlightFeedAPI(_VisionAPITestCase):assert sessions == [f"hit-{i}" for i in range(6)]assert second["has_more"] is False- def test_a_later_loads_cached_picks_do_not_serve_an_earlier_loads_pages(self) -> None:+ def test_a_later_page_stays_on_the_build_its_first_page_read(self) -> None:scanner = self._create_scanner(name="m")- bucket_start = datetime.fromtimestamp(- (int(timezone.now().timestamp()) // HIGHLIGHT_FEED_PICKS_BUCKET_S - 1) * HIGHLIGHT_FEED_PICKS_BUCKET_S,- tz=UTC,- )- earlier, later = bucket_start + timedelta(minutes=1), bucket_start + timedelta(minutes=5)for index in range(12):- obs = self._succeeded_observation(scanner, f"row-{index}", 120 + index, self._monitor_result("no"))- # The top-scoring row completes between the two loads, so only the later load can rank it.- completed_at = bucket_start + timedelta(minutes=3) if index == 0 else bucket_start- ReplayObservation.objects.filter(id=obs.id).update(- completed_at=completed_at,- watch_rank={- "category": "failure",- "contrast": 1 - index / 20,- "group": None,- "anchor_version": ANCHOR_VERSION,- },- )+ self._ranked_observation(scanner, f"row-{index}", 120 + index, "failure", 0.9 - index / 20)+ first = self.client.get(self.feed_url, {"limit": "20"}).json()+ # A row that tops the scanner lands, and a later build ranks it.+ self._ranked_observation(scanner, "late-top", 60, "failure", 1.0)+ later = timezone.now() + timedelta(minutes=1)+ with time_machine.travel(later, tick=False):+ build_highlight_feed(self.team.id, ANCHOR_VERSION)def sessions(as_of: datetime) -> list[str]:response = self.client.get(self.feed_url, {"limit": "20", "as_of": as_of.isoformat()}).json()return [item["observation"]["session_id"] for item in response["results"]]- assert "row-0" in sessions(later)- assert "row-0" not in sessions(earlier)+ assert "late-top" not in sessions(datetime.fromisoformat(first["as_of"]))+ assert "late-top" in sessions(later + timedelta(seconds=1))def test_an_embedding_pick_counts_its_hidden_duplicates(self) -> None:scanner = self._create_scanner(name="m")@@ -5005,14 +4982,7 @@ class TestHighlightFeedAPI(_VisionAPITestCase):for scanner, prefix, top in ((busy, "busy", 0.9), (quiet, "quiet", 0.3)):for index in range(12):obs = self._succeeded_observation(scanner, f"{prefix}-{index}", index, self._monitor_result("yes"))- ReplayObservation.objects.filter(id=obs.id).update(- watch_rank={- "category": "failure",- "contrast": top - index / 100,- "group": None,- "anchor_version": ANCHOR_VERSION,- }- )+ set_rank(obs, category="failure", contrast=top - index / 100, group=None)with patch("products.replay_vision.backend.api.scanners.HIGHLIGHT_FEED_CANDIDATE_CAP", 2):items = self.client.get(self.feed_url).json()["results"]@@ -5032,14 +5002,7 @@ class TestHighlightFeedAPI(_VisionAPITestCase):# Of 30 rows only the top six clear the percentile cut: five copies of one finding, then one other finding.for index in range(30):obs = self._succeeded_observation(scanner, f"row-{index}", index, self._monitor_result("yes"))- ReplayObservation.objects.filter(id=obs.id).update(- watch_rank={- "category": "failure",- "contrast": 1 - index / 100,- "group": root_id if 0 < index < 5 else None,- "anchor_version": ANCHOR_VERSION,- }- )+ set_rank(obs, category="failure", contrast=1 - index / 100, group=root_id if 0 < index < 5 else None)root_id = root_id or str(obs.id)with (@@ -5057,14 +5020,7 @@ class TestHighlightFeedAPI(_VisionAPITestCase):obs = self._succeeded_observation(scanner, f"s-{index}", 10 + index, self._monitor_result("no"))# The top two contrasts clear the top-fifth cut; the rest are the scanner's baseline.category = "failure" if index < 2 else "routine"- ReplayObservation.objects.filter(id=obs.id).update(- watch_rank={- "category": category,- "contrast": 0.5 - index * 0.01,- "group": None,- "anchor_version": ANCHOR_VERSION,- }- )+ set_rank(obs, category=category, contrast=0.5 - index * 0.01, group=None)rows[f"s-{index}"] = obsother_team = Team.objects.create(organization=self.organization, name="other")foreign = ReplayObservation.objects.create(@@ -5279,20 +5235,13 @@ class TestHighlightFeedAPI(_VisionAPITestCase):scanner = self._create_scanner(name="retargeted", experiment_targeting={"experiment_id": experiment.id})for index in range(12):obs = self._succeeded_observation(scanner, f"sess-{index}", index, self._monitor_result("yes"))- ReplayObservation.objects.filter(id=obs.id).update(- watch_rank={- "category": "failure",- "contrast": index / 10,- "group": None,- "anchor_version": ANCHOR_VERSION,- }- )+ set_rank(obs, category="failure", contrast=index / 10, group=None)scanner.experiment_targeting = Nonescanner.save()first = self.client.get(self.feed_url, {"limit": 1}).json()self.assertEqual(len(first["results"]), 1)- # The second page reads picks cached by the first, so access has to be checked again on the page itself.+ # The second page reads the same build as the first, so access has to be checked again on the page itself.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,@@ -5335,22 +5284,13 @@ class TestHighlightFeedAPI(_VisionAPITestCase):for i in range(3):self._succeeded_observation(scanner, f"s-0-{i}", i + 1, self._monitor_result("no"))self.client.get(self.feed_url) # warm request-scoped caches- # Both measured loads rank afresh, since a load in the same bucket would reuse the picks cached before it.- real_get = cache.get- uncached_picks = patch.object(- cache,- "get",- side_effect=lambda key, *args, **kwargs: (- None if key.startswith("replay_vision:highlight_picks:") else real_get(key, *args, **kwargs)- ),- )- with uncached_picks, CaptureQueriesContext(connection) as one:+ 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"))self.client.get(self.feed_url)- with uncached_picks, CaptureQueriesContext(connection) as six:+ 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))diff --git a/products/replay_vision/backend/tests/test_highlight_builds.py b/products/replay_vision/backend/tests/test_highlight_builds.pyindex 5606b74b4dc7..5f2220b9e308 100644--- a/products/replay_vision/backend/tests/test_highlight_builds.py+++ b/products/replay_vision/backend/tests/test_highlight_builds.py@@ -5,11 +5,20 @@ from typing import Anyimport time_machinefrom posthog.test.base import BaseTest+from django.utils import timezone+from parameterized import parameterizedfrom posthog.models import Team-from products.replay_vision.backend.highlight_builds import BUILD_RETENTION, build_highlight_feed, rank_window+from products.replay_vision.backend.highlight_builds import (+ BUILD_RETENTION,+ STALE_AFTER,+ build_highlight_feed,+ rank_window,+ rebuild_changed_feeds,+ stored_generation,+)from products.replay_vision.backend.models.replay_highlight_feed import (ReplayHighlightFeedEntry,ReplayHighlightFeedState,@@ -230,3 +239,26 @@ class TestHighlightBuilds(BaseTest):RankCategory.STRUGGLE,group,)++ def test_a_stale_build_is_served_and_the_sweep_rebuilds_it_once(self) -> None:+ self._ranked(10, age=timedelta(hours=1))+ first = build_highlight_feed(self.team.id, ANCHOR_VERSION)++ with time_machine.travel(_NOW + STALE_AFTER + timedelta(minutes=1), tick=False):+ served = stored_generation(self.team.id, ANCHOR_VERSION, timezone.now())+ built = [rebuild_changed_feeds(ANCHOR_VERSION), rebuild_changed_feeds(ANCHOR_VERSION)]++ assert (first, served, built) == (1, 1, [1, 0])+ assert ReplayHighlightFeedState.objects.for_team(self.team.id).get().generation == 2++ def test_a_load_that_began_before_a_rebuild_stays_on_the_build_it_started_on(self) -> None:+ self._ranked(10, age=timedelta(hours=1))++ first = stored_generation(self.team.id, ANCHOR_VERSION, _NOW)+ with time_machine.travel(_NOW + timedelta(minutes=10), tick=False):+ build_highlight_feed(self.team.id, ANCHOR_VERSION, force=True)+ later_page = stored_generation(self.team.id, ANCHOR_VERSION, _NOW)+ new_load = stored_generation(self.team.id, ANCHOR_VERSION, timezone.now())++ assert (first, later_page, new_load) == (1, 1, 2)+ assert ReplayHighlightFeedEntry.objects.for_team(self.team.id).filter(generation=1).exists()diff --git a/products/replay_vision/backend/tests/test_watch_rank.py b/products/replay_vision/backend/tests/test_watch_rank.pyindex 082e4c80dc1e..d3a8f9b5dc67 100644--- a/products/replay_vision/backend/tests/test_watch_rank.py+++ b/products/replay_vision/backend/tests/test_watch_rank.py@@ -3,7 +3,6 @@ from typing import Anyfrom unittest.mock import patch-from django.db.models import Qfrom django.test import SimpleTestCaseimport numpy as np@@ -13,7 +12,6 @@ from posthog.exceptions import ClickHouseAtCapacityfrom products.replay_vision.backend import watch_rank_backfillfrom products.replay_vision.backend.highlight_feed import SESSION_SPACING-from products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.tests.helpers import axis_anchorsfrom products.replay_vision.backend.watch_rank import (ANCHOR_VERSION,@@ -39,36 +37,29 @@ def _row(viewed: bool = False,session: str | None = None,) -> dict[str, Any]:- rank = (- None- if contrast is None- else {- "category": category,- "contrast": contrast,- "anchor_version": anchor_version,- }- | ({"group": group} if group else {})- )+ current = contrast is not None and anchor_version == ANCHOR_VERSIONreturn {"id": observation_id,"scanner_id": scanner,"session_id": session or f"session-{observation_id}","created_at": _NOW - timedelta(minutes=minutes_ago),- "watch_rank": rank,"feed_viewed": viewed,+ "contrast": contrast if current else None,+ "watch_category": category if current else None,+ "watch_group_root": group or observation_id,}def _with_percentiles(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Each row's contrast percentile within its scanner, as the pick query attaches it."""+ """Each row's contrast percentile within its scanner, as a stored build attaches it."""by_scanner: dict[str, list[dict[str, Any]]] = {}for row in rows:- if row["watch_rank"] and row["watch_rank"].get("anchor_version") == ANCHOR_VERSION:+ if row["contrast"] is not None:by_scanner.setdefault(row["scanner_id"], []).append(row)for scanner_rows in by_scanner.values():if len(scanner_rows) < HIGHLIGHT_PICK_MIN_SCANNER_ROWS:continue- scanner_rows.sort(key=lambda row: row["watch_rank"]["contrast"])+ scanner_rows.sort(key=lambda row: row["contrast"])for position, row in enumerate(scanner_rows):row.setdefault("watch_percentile", (position + 0.5) / len(scanner_rows))return rows@@ -89,23 +80,13 @@ class TestClassify(SimpleTestCase):assert reading.rank.category == categoryassert (reading.rank.contrast > 0) is positiveassert set(reading.similarities) == {key for texts in ANCHORS.values() for key in texts}- assert reading.rank.scores["routine"] == max(reading.similarities[key] for key in ANCHORS["routine"])---class TestPickIndexes(SimpleTestCase):- @parameterized.expand([("rlo_ranked_count_idx",), ("rlo_ranked_contrast_idx",)])- def test_pick_index_matches_the_current_anchor_version(self, name: str) -> None:- index = next(index for index in ReplayObservation._meta.indexes if index.name == name)- assert index.condition == Q(- status="succeeded", watch_rank__isnull=False, watch_rank__anchor_version=ANCHOR_VERSION- )class TestRankHighlightFeedByEmbedding(SimpleTestCase):def test_a_finding_that_reached_more_people_outranks_a_stronger_one_off(self) -> None:rows = [_row(f"a-{index}", 0.01 * index, minutes_ago=index + 1) for index in range(10)]rows += [_row("one-off", 0.9), _row("widespread", 0.5)]- # Window percentiles and group reach, as the whole-window pick query supplies them.+ # Window percentiles and group reach, as a stored build supplies them.for row in rows:row["watch_percentile"] = {"one-off": 0.99, "widespread": 0.85}.get(str(row["id"]))row["watch_group_people"] = 6 if row["id"] == "widespread" else 1@@ -187,19 +168,17 @@ class TestBackfillRankScanner(SimpleTestCase):def test_ranks_only_rows_without_a_current_rank(self) -> None:anchors = axis_anchors()error = np.array([1.0, 0.0, 0.0])- current = {"category": "failure", "contrast": 1.0, "anchor_version": ANCHOR_VERSION}rows: list[dict[str, Any]] = [- {"id": "ranked", "watch_rank": current},- {"id": "no-vector", "watch_rank": None},- {"id": "copy", "watch_rank": None},- {"id": "stale", "watch_rank": {**current, "anchor_version": ANCHOR_VERSION - 1}},- {"id": "calm", "watch_rank": None},+ {"id": "ranked", "ranked": True},+ {"id": "no-vector", "ranked": False},+ {"id": "copy", "ranked": False},+ {"id": "calm", "ranked": False},]- vectors = {"ranked": error, "copy": error, "stale": error, "calm": np.array([0.0, 0.0, 1.0])}+ vectors = {"ranked": error, "copy": error, "calm": np.array([0.0, 0.0, 1.0])}written = _rank_scanner(rows, vectors, anchors)- assert set(written) == {"copy", "stale", "calm"}+ assert set(written) == {"copy", "calm"}assert written["copy"].rank.category == "failure"assert written["calm"].rank.category == "routine"diff --git a/products/replay_vision/backend/tests/test_watch_rank_consumer.py b/products/replay_vision/backend/tests/test_watch_rank_consumer.pyindex 24619bbe1b7a..ad53e3e170e2 100644--- a/products/replay_vision/backend/tests/test_watch_rank_consumer.py+++ b/products/replay_vision/backend/tests/test_watch_rank_consumer.py@@ -24,14 +24,13 @@ from products.replay_vision.backend.embeddings import ()from products.replay_vision.backend.models.replay_observation import ObservationTrigger, ReplayObservationfrom products.replay_vision.backend.models.replay_observation_anchor_similarity import ReplayObservationAnchorSimilarity-from products.replay_vision.backend.models.replay_observation_rank import ReplayObservationRank+from products.replay_vision.backend.models.replay_observation_rank import RankCategory, ReplayObservationRankfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType-from products.replay_vision.backend.tests.helpers import axis_anchors, snapshot_for-from products.replay_vision.backend.watch_rank import ANCHOR_VERSION, RankRequest+from products.replay_vision.backend.tests.helpers import axis_anchors, set_rank, snapshot_for+from products.replay_vision.backend.watch_rank import RankRequestfrom products.replay_vision.backend.watch_rank_consumer import WatchRankConsumer, parse_rank_request_WATCH_RANK = "products.replay_vision.backend.watch_rank"-_CURRENT_RANK = {"category": "struggle", "contrast": 0.2, "anchor_version": ANCHOR_VERSION, "group": "g1"}_CONSUMER = "products.replay_vision.backend.watch_rank_consumer"@@ -100,19 +99,19 @@ class TestWatchRankConsumer(BaseTest):@parameterized.expand([- ("issue_row_gets_a_rank_and_a_feed_group", None, None, "ranked", {"category": "failure"}),+ ("issue_row_gets_a_rank_and_a_feed_group", None, None, "ranked", RankCategory.FAILURE),("ranking_failure_leaves_no_rank", None, RuntimeError("cache down"), "failed", None),- ("redelivery_keeps_the_current_rank", _CURRENT_RANK, None, "already_ranked", _CURRENT_RANK),+ ("redelivery_keeps_the_current_rank", "struggle", None, "already_ranked", RankCategory.STRUGGLE),("deleted_observation_is_skipped", None, None, "missing", None),])def test_ranks_the_observation_in_a_result(self,_name: str,- existing_rank: dict[str, Any] | None,+ existing_category: str | None,anchor_error: Exception | None,outcome: str,- expected_rank: dict[str, Any] | None,+ expected_category: int | None,) -> None:scanner = ReplayScanner.objects.create(team=self.team,@@ -121,7 +120,10 @@ class TestWatchRankConsumer(BaseTest):scanner_config={"prompt": "p"},model=ScannerModel.GEMINI_3_8_FLASH,)- observation = self._observation(scanner, "sess-new", watch_rank=existing_rank)+ observation = self._observation(scanner, "sess-new")+ kept_group = uuid.uuid4()+ if existing_category:+ set_rank(observation, category=existing_category, contrast=0.2, group=kept_group)message = _result_message(team_id=self.team.id, observation_id=str(observation.id), scanner_id=str(scanner.id))if outcome == "missing":observation.delete()@@ -137,20 +139,17 @@ class TestWatchRankConsumer(BaseTest):if outcome == "missing":return- assert ReplayObservationRank.objects.for_team(self.team.id).filter(observation_id=observation.id).exists() == (- outcome == "ranked"- )- observation.refresh_from_db()- if expected_rank is None:- assert observation.watch_rank is None- else:- assert observation.watch_rank is not None- assert expected_rank.items() <= observation.watch_rank.items()- assert observation.watch_rank.get("group")- # A redelivery returns before ranking, so only a fresh rank writes the similarity row.- assert ReplayObservationAnchorSimilarity.objects.for_team(self.team.id).filter(- observation=observation- ).exists() == (outcome == "ranked")+ rank = ReplayObservationRank.objects.for_team(self.team.id).filter(observation_id=observation.id).first()+ if expected_category is None:+ assert rank is None+ return+ assert rank is not None+ assert rank.category == expected_category+ assert rank.feed_group_id is not None and (rank.feed_group_id == kept_group) == bool(existing_category)+ # A redelivery returns before ranking, so only a fresh rank writes the similarity row.+ assert ReplayObservationAnchorSimilarity.objects.for_team(self.team.id).filter(+ observation=observation+ ).exists() == (outcome == "ranked")@parameterized.expand([diff --git a/products/replay_vision/backend/tests/test_watch_semantics.py b/products/replay_vision/backend/tests/test_watch_semantics.pyindex 6e98ce8aa49d..f9b84ef24f44 100644--- a/products/replay_vision/backend/tests/test_watch_semantics.py+++ b/products/replay_vision/backend/tests/test_watch_semantics.py@@ -1,3 +1,4 @@+import uuidfrom datetime import timedeltafrom typing import Any@@ -14,6 +15,7 @@ from parameterized import parameterizedfrom products.replay_vision.backend.highlight_feed_groups import feed_group_cachefrom products.replay_vision.backend.models.replay_observation import ObservationTrigger, ReplayObservationfrom products.replay_vision.backend.models.replay_observation_anchor_similarity import ReplayObservationAnchorSimilarity+from products.replay_vision.backend.models.replay_observation_rank import ReplayObservationRankfrom products.replay_vision.backend.models.replay_scanner import (PromptValence,ReplayScanner,@@ -35,7 +37,7 @@ from products.replay_vision.backend.semantic_space import (semantic_vector,unit,)-from products.replay_vision.backend.tests.helpers import axis_anchors, snapshot_for+from products.replay_vision.backend.tests.helpers import axis_anchors, set_rank, snapshot_forfrom products.replay_vision.backend.watch_rank import ANCHOR_VERSIONfrom products.replay_vision.backend.watch_semantics import SemanticItem, assign_semantics, assign_semantics_batchfrom products.replay_vision.backend.watch_semantics_backfill import backfill_team_semantics@@ -45,10 +47,6 @@ _THEMES = "products.replay_vision.backend.watch_themes"_BACKFILL = "products.replay_vision.backend.watch_semantics_backfill"-def _rank(category: str = "failure") -> dict[str, Any]:- return {"category": category, "contrast": 0.2, "anchor_version": ANCHOR_VERSION, "duplicate_of": "retired"}--def _vector(*head: float) -> list[float]:vector = np.zeros(3072)vector[: len(head)] = head@@ -133,15 +131,20 @@ class TestAssignSemantics(BaseTest):self, category: str = "failure", output: dict[str, Any] | None = None, scanner: ReplayScanner | None = None) -> ReplayObservation:scanner = scanner or self.scanner- return ReplayObservation.objects.create(+ observation = ReplayObservation.objects.create(scanner=scanner,team=self.team,session_id=f"sess-{ReplayObservation.objects.count()}",triggered_by=ObservationTrigger.ON_DEMAND,scanner_snapshot=snapshot_for(scanner),- watch_rank=_rank(category),scanner_result={"model_output": output or {"scanner_type": "summarizer", "summary": ""}},)+ set_rank(observation, category=category, contrast=0.2)+ return observation++ def _clusters(self, observation: ReplayObservation) -> tuple[Any, Any]:+ rank = ReplayObservationRank.objects.for_team(self.team.id).get(observation_id=observation.id)+ return rank.feed_group_id, rank.search_theme_iddef _assign(self, observation: ReplayObservation, vector: list[float]) -> Any:return assign_semantics(@@ -201,11 +204,7 @@ class TestAssignSemantics(BaseTest):assert self._counts(ReplayScannerFeedGroup) == [1, 3]assert self._counts(ReplayScannerSearchTheme) == [1, 2]- first.refresh_from_db()- assert first.watch_rank is not None- assert first.watch_rank["group"] == str(joined[0].group_id)- assert first.watch_rank["theme"] == str(joined[0].theme.theme_id)- assert "duplicate_of" not in first.watch_rank+ assert self._clusters(first) == (joined[0].group_id, joined[0].theme.theme_id)@parameterized.expand([@@ -232,10 +231,7 @@ class TestAssignSemantics(BaseTest):assignment = self._assign(observation, _vector(1.0))assert assignment.theme is None- observation.refresh_from_db()- assert observation.watch_rank is not None- assert observation.watch_rank["group"] == str(assignment.group_id)- assert "theme" not in observation.watch_rank+ assert self._clusters(observation) == (assignment.group_id, None)@parameterized.expand([@@ -277,9 +273,8 @@ class TestAssignSemantics(BaseTest):@parameterized.expand([("embedded_on_time", False), ("embedded_late", True)])def test_the_backfill_fills_only_what_a_ranked_row_is_missing(self, _name: str, late: bool) -> None:grouped = self._observation()- ReplayObservation.objects.filter(id=grouped.id).update(- watch_rank={**_rank(), "group": "kept"}, status="succeeded", completed_at=timezone.now()- )+ kept = uuid.uuid4()+ set_rank(grouped, group=kept)vector = np.array([1.0, 0.0, 0.0], dtype=np.float32)def stored(_team_id: int, ids: list[str], _since: Any, until: Any) -> dict[str, np.ndarray]:@@ -291,10 +286,7 @@ class TestAssignSemantics(BaseTest):):backfill_team_semantics(self.team.id, timezone.now() - timedelta(days=1))- grouped.refresh_from_db()- assert grouped.watch_rank is not None- assert grouped.watch_rank["group"] == "kept"- assert set(grouped.watch_rank["scores"]) == {"failure", "struggle", "revenue", "routine"}+ assert self._clusters(grouped)[0] == keptassert (ReplayObservationAnchorSimilarity.objects.for_team(self.team.id).filter(observation_id=grouped.id, anchor_version=ANCHOR_VERSION)diff --git a/products/replay_vision/backend/watch_rank.py b/products/replay_vision/backend/watch_rank.pyindex 900299f30284..a5b859f24562 100644--- a/products/replay_vision/backend/watch_rank.py+++ b/products/replay_vision/backend/watch_rank.py@@ -10,18 +10,14 @@ errors all the time does not fill the feed.import mathimport asynciofrom collections import Counter-from collections.abc import Mapping, Sequence-from dataclasses import asdict-from datetime import timedelta+from collections.abc import Collection, Sequence+from datetime import datetimefrom typing import Any, Literal, castfrom django.core.cache import cache-from django.core.exceptions import EmptyResultSet-from django.db import connections, transaction-from django.db.models import CharField, Count, Exists, F, QuerySet, Value, Window-from django.db.models.expressions import RawSQL-from django.db.models.fields.json import KeyTextTransform, KeyTransform-from django.db.models.functions import Coalesce, NullIf, RowNumber+from django.db import transaction+from django.db.models import Count, Exists, OuterRef, Q, QuerySet+from django.db.models.functions import Coalesceimport numpy as npfrom asgiref.sync import sync_to_async@@ -30,21 +26,17 @@ from posthog.api.embedding_worker import async_generate_embeddingfrom posthog.dataclasses import frozenfrom posthog.models.scoping.manager import resolve_effective_team_idfrom posthog.models.team import Team-from posthog.utils import dict_from_cursor_fetchallfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.replay_vision.backend.embeddings import OBSERVATION_EMBEDDING_MODEL+from products.replay_vision.backend.highlight_builds import RankedEntry, rank_window, stored_generationfrom products.replay_vision.backend.highlight_feed import HIGHLIGHT_FEED_MIN_ITEMS, HighlightFeedEntry, finish_feed-from products.replay_vision.backend.models.replay_observation import (- ObservationStatus,- ReplayObservation,- jsonb_typeof,- watch_group_root,- watch_rank_contrast,-)+from products.replay_vision.backend.models.replay_highlight_feed import ReplayHighlightFeedEntry+from products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.models.replay_observation_anchor_similarity import ReplayObservationAnchorSimilarity-from products.replay_vision.backend.observation_ranks import NewRank, record_ranks-from products.replay_vision.backend.scanner_access import accessible_observations+from products.replay_vision.backend.models.replay_observation_rank import ReplayObservationRank+from products.replay_vision.backend.observation_ranks import CATEGORY_CODES, CATEGORY_NAMES, NewRank, record_ranks+from products.replay_vision.backend.scanner_access import accessible_observations, readable_experiment_idsWatchCategory = Literal["failure", "struggle", "revenue", "routine"]@@ -106,10 +98,8 @@ HIGHLIGHT_PICK_IMPRESSION_DECAY = 0.8# that hit six people outranks an equally strong one-off without burying everything else.HIGHLIGHT_PICK_PEOPLE_BOOST = 0.25HIGHLIGHT_PICK_PEOPLE_BOOST_CAP = 2.0-# Copies of one finding the pick query keeps, so a viewed or restricted top copy does not hide the group.+# Copies of one finding the feed keeps per group, so a viewed or restricted top copy does not hide the group.HIGHLIGHT_PICK_GROUP_CANDIDATES = 3-# Group members older than the feed's longest window before the oldest pick can never fall inside a requested window.-HIGHLIGHT_FEED_MEMBER_LOOKBACK = timedelta(days=90)# How much wider the second pick fetch reads when the first is all copies of a few feed groups.HIGHLIGHT_PICK_REFILL_FACTOR = 10@@ -120,12 +110,6 @@ _ANCHOR_CACHE_TTL_S = 7 * 24 * 3600class WatchRank:category: WatchCategorycontrast: float- # The closest anchor's similarity per category, so a viewer's choice of categories can be scored from the row.- scores: dict[WatchCategory, float]- anchor_version: int = ANCHOR_VERSION-- def to_json(self) -> dict[str, Any]:- return asdict(self)@frozen@@ -189,7 +173,6 @@ def classify(vector: list[float] | np.ndarray, anchors: dict[WatchCategory, np.nrank = WatchRank(category=category if contrast > 0 else "routine",contrast=contrast,- scores={c: round(score, 4) for c, score in closest.items()},)similarities = {key: round(float(sim), 4) for c, sims in by_category.items() for key, sim in zip(ANCHORS[c], sims, strict=True)@@ -197,17 +180,6 @@ def classify(vector: list[float] | np.ndarray, anchors: dict[WatchCategory, np.nreturn AnchorReading(rank=rank, similarities=similarities)-def current_rank(row: dict[str, Any]) -> dict[str, Any] | None:- """The row's rank when it comes from the current anchors, else None."""- rank = row.get("watch_rank")- if not isinstance(rank, dict) or rank.get("anchor_version") != ANCHOR_VERSION:- return None- contrast = rank.get("contrast")- if not isinstance(contrast, int | float) or isinstance(contrast, bool):- return None- return rank--def save_anchor_similarities(team_id: int, similarities: dict[str, dict[str, float]]) -> None:# A bulk insert skips the model's canonical-team rewrite, so the row carries the id reads are scoped to.canonical_team_id = resolve_effective_team_id(team_id)@@ -236,33 +208,40 @@ class RankRequest:async def rank_observation(request: RankRequest) -> Literal["ranked", "already_ranked", "missing"]:- """Rank one observation from its embedding and save the rank on the row, unless it has a current one.+ """Rank one observation from its embedding and save its rank row, unless it has one under the current anchors.Keeping an existing rank makes a redelivered result harmless, and keeps the feed group and search themewritten next to it."""- row = await (- ReplayObservation.objects.filter(team_id=request.team_id, id=request.observation_id)- .values("watch_rank")- .afirst()+ observation = await (+ ReplayObservation.objects.filter(team_id=request.team_id, id=request.observation_id).values("id").afirst())# A deleted observation, or a deleted team, leaves nothing to rank.- if row is None:+ if observation is None:return "missing"- if current_rank({"watch_rank": row["watch_rank"]}) is not None:+ # The scoped manager resolves the team synchronously, so the check runs off the event loop.+ if await sync_to_async(_has_current_rank)(request.team_id, request.observation_id):return "already_ranked"reading = classify(request.vector, await anchor_vectors(request.team_id))- await sync_to_async(_save_rank)(request.team_id, request.observation_id, reading)- return "ranked"+ written = await sync_to_async(_save_rank)(request.team_id, request.observation_id, reading)+ return "ranked" if written else "already_ranked"-def _save_rank(team_id: int, observation_id: str, reading: AnchorReading) -> None:- # One transaction, so a rank on the row always comes with its similarities.- rank = reading.rank+def _save_rank(team_id: int, observation_id: str, reading: AnchorReading) -> bool:+ # One transaction, so a rank row always comes with its similarities.+ rank = NewRank(contrast=reading.rank.contrast, category=reading.rank.category)with transaction.atomic():save_anchor_similarities(team_id, {observation_id: reading.similarities})- ReplayObservation.objects.filter(team_id=team_id, id=observation_id).update(watch_rank=rank.to_json())- record_ranks(team_id, ANCHOR_VERSION, {observation_id: NewRank(contrast=rank.contrast, category=rank.category)})+ return record_ranks(team_id, ANCHOR_VERSION, {observation_id: rank}) > 0+++def _has_current_rank(team_id: int, observation_id: str) -> bool:+ return current_ranks(team_id).filter(observation_id=observation_id).exists()+++def current_ranks(team_id: int) -> QuerySet[ReplayObservationRank]:+ """The team's rank rows written under the current anchors."""+ return ReplayObservationRank.objects.for_team(team_id).filter(anchor_version=ANCHOR_VERSION)def people_boost(people: int) -> float:@@ -271,157 +250,182 @@ def people_boost(people: int) -> float:def _cap_feed_groups(rows: list[dict[str, Any]], cap: int) -> dict[Any, dict[str, Any]]:- """The first `cap` rows, keeping a few per feed group so the ranker can still pick a readable, unseen one.-- A group never spans scanners, so the pick order meets each group's rows best first.- """+ """The first `cap` rows by observation id, keeping a few per feed group so the ranker can still pick a readable,+ unseen one. A group never spans scanners, so pick order meets each group's rows best first."""picked: dict[Any, dict[str, Any]] = {}- group_rows: Counter[str] = Counter()+ group_rows: Counter[Any] = Counter()for row in rows:- if group_rows[row["watch_group_root"]] >= HIGHLIGHT_PICK_GROUP_CANDIDATES:+ if group_rows[row["group_root"]] >= HIGHLIGHT_PICK_GROUP_CANDIDATES:continue- group_rows[row["watch_group_root"]] += 1- picked[row["id"]] = row+ group_rows[row["group_root"]] += 1+ picked[row["observation_id"]] = rowif len(picked) >= cap:breakreturn picked-def _pick_window_rows(- ranked: QuerySet[ReplayObservation],- current_ranks: QuerySet[ReplayObservation],- limit: int,+def _stored_window_entries(+ team_id: int,+ generation: int,+ window_days: int,+ scanner_ids: Sequence[Any],categories: Sequence[str],+ experiment_ids: Collection[int],+ dismissed_ids: Collection[Any],+ limit: int,) -> list[dict[str, Any]]:- """Each scanner's top-fifth issue rows in pick order: every scanner's best first, then every second-best.+ entries = (+ ReplayHighlightFeedEntry.objects.for_team(team_id)+ .filter(+ generation=generation,+ window_days=window_days,+ scanner_id__in=list(scanner_ids),+ category__in=[CATEGORY_CODES[category] for category in categories],+ experiment_id__in=[0, *experiment_ids],+ )+ .exclude(observation_id__in=list(dismissed_ids))+ .order_by("place", "-percentile", "-created_at", "-observation_id")+ .values(*_ENTRY_FIELDS)[:limit]+ )+ return list(entries)- A row's percentile needs only its rank from the top and its scanner's row count, so the query counts each- scanner on a narrow index and then reads just its top fifth by score, instead of sorting the whole window.- """- contrast = watch_rank_contrast()- scanner_counts = (- ranked.values("scanner_id")- .annotate(scanner_rows=Count("id"))- .filter(scanner_rows__gte=HIGHLIGHT_PICK_MIN_SCANNER_ROWS)- .values("scanner_id", "scanner_rows")++def _ranked_window_entries(+ entries: list[RankedEntry],+ scanner_ids: Sequence[Any],+ categories: Sequence[str],+ experiment_ids: Collection[int],+ dismissed_ids: Collection[Any],+ limit: int,+) -> list[dict[str, Any]]:+ scanners = {str(scanner_id) for scanner_id in scanner_ids}+ codes = {CATEGORY_CODES[category] for category in categories}+ readable = {0, *experiment_ids}+ dismissed = {str(observation_id) for observation_id in dismissed_ids}+ kept = [+ entry+ for entry in entries+ if str(entry.scanner_id) in scanners+ and entry.category in codes+ and entry.experiment_id in readable+ and str(entry.observation_id) not in dismissed+ ]+ kept.sort(+ key=lambda entry: (-entry.place, entry.percentile, entry.created_at, str(entry.observation_id)), reverse=True)- scanner_top = (- # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (a fixed column reference to the CTE below)- current_ranks.filter(scanner_id=RawSQL('"scanner_counts"."scanner_id"', ()))- .annotate(- scanner_rank=Window(RowNumber(), order_by=[contrast.desc(), F("id").desc()]),- watch_group_root=watch_group_root(),- pick_category=F("watch_category"),+ return [{field: getattr(entry, field) for field in _ENTRY_FIELDS} for entry in kept[:limit]]+++_ENTRY_FIELDS = (+ "observation_id",+ "scanner_id",+ "created_at",+ "category",+ "percentile",+ "group_root",+)+++@frozen+class FeedWindow:+ """The window a feed load ranks: a preset window read from the team's stored build, or any other range ranked on+ the spot the same way."""++ start: datetime+ end: datetime+ as_of: datetime+ window_days: int | None+ generation: int | None+++def feed_window(team_id: int, start: datetime, end: datetime, as_of: datetime, preset_days: int | None) -> FeedWindow:+ """The feed's window from `start` to `end`. A preset window reads the team's stored build."""+ generation = stored_generation(team_id, ANCHOR_VERSION, as_of) if preset_days is not None else None+ if generation is None:+ return FeedWindow(start=start, end=end, as_of=as_of, window_days=None, generation=None)+ return FeedWindow(start=start, end=end, as_of=as_of, window_days=preset_days, generation=generation)+++@frozen+class GroupReach:+ sessions: int+ people: int+++def _group_reach(+ team_id: int,+ window: FeedWindow,+ roots: Collection[Any],+ scanner_ids: Sequence[Any],+ categories: Sequence[str],+ experiment_ids: Collection[int],+) -> dict[str, GroupReach]:+ """Sessions and distinct people in each feed group, counted over the window's rows the viewer may read in the+ chosen categories, so a card's counts match the group list it opens."""+ root_ids = list(roots)+ members = (+ current_ranks(team_id)+ .filter(Q(feed_group_id__in=root_ids) | Q(observation_id__in=root_ids, feed_group_id__isnull=True))+ .filter(+ ranked_at__lte=window.as_of,+ created_at__gte=window.start,+ created_at__lte=window.end,+ scanner_id__in=list(scanner_ids),+ category__in=[CATEGORY_CODES[category] for category in categories],+ experiment_id__in=[0, *experiment_ids],)- .order_by(contrast.desc(), "-id")- .values("id", "created_at", "scanner_rank", "watch_group_root", "pick_category")- )- try:- counts_sql, counts_params = scanner_counts.query.sql_with_params()- top_sql, top_params = scanner_top.query.sql_with_params()- except EmptyResultSet:- # Django compiles a filter that can match nothing, such as an empty scanner list, to this.- return []- # Only fragments written here join the compiled ORM SQL; every value travels as a parameter.- sql = f"""- WITH scanner_counts AS ({counts_sql})- SELECT id, created_at, watch_percentile, watch_group_root FROM (- SELECT scanner_top.*,- ((scanner_counts.scanner_rows - scanner_top.scanner_rank + 1) - 0.5)- / scanner_counts.scanner_rows::double precision AS watch_percentile- FROM scanner_counts- CROSS JOIN LATERAL ({top_sql} LIMIT floor(scanner_counts.scanner_rows * %s)::int + 1) scanner_top- ) picks- WHERE pick_category = ANY(%s) AND watch_percentile >= %s- ORDER BY scanner_rank, watch_percentile DESC, created_at DESC, id DESC- LIMIT %s- """- params = (- *counts_params,- *top_params,- 1 - HIGHLIGHT_PICK_MIN_PERCENTILE,- list(categories),- HIGHLIGHT_PICK_MIN_PERCENTILE,- limit,+ .values(root=Coalesce("feed_group_id", "observation_id"))+ .annotate(sessions=Count("observation_id"), people=Count("person_key", distinct=True)))- with connections[ranked.db].cursor() as cursor:- cursor.execute(sql, params)- return dict_from_cursor_fetchall(cursor)+ return {str(row["root"]): GroupReach(sessions=row["sessions"], people=row["people"]) for row in members}def select_embedding_picks(- walkable: QuerySet[ReplayObservation],- scanner_ids: list[Any],+ window: FeedWindow,+ scanner_ids: Sequence[Any],viewed: Exists,access: UserAccessControl,team_id: int,cap: int,categories: Sequence[str],+ dismissed_ids: Collection[Any],) -> list[dict[str, Any]]:- """The window's pick rows for the embedding ranker, with each row's percentile and the reach of its feed group.+ """The window's pick rows for the embedding ranker, each with its percentile and its feed group's reach.- The percentile is taken over every ranked row a scanner has in the window, not over a recency slice, so a- longer window reaches further back instead of re-ranking the same newest rows. `categories` narrows the picks- after that ranking, so turning a category off drops its rows without promoting weaker rows of the others. A- group's reach counts only members of those categories, so it matches the similar sessions the card's popover lists.+ A row's percentile is taken over every ranked row its scanner has in the window, so a longer window reaches further+ back instead of re-ranking the same newest rows. `categories` narrows the picks after ranking, so turning a+ category off drops its rows without promoting weaker rows of the others."""- group_root = watch_group_root()- ranked = walkable.filter(- # The explicit null and anchor checks let Postgres match the partial `rlo_ranked_*` indexes.- scanner_id__in=scanner_ids,- watch_rank__isnull=False,- watch_rank__anchor_version=ANCHOR_VERSION,- )- current_ranks = ranked.alias(- watch_category=KeyTextTransform("category", "watch_rank"),- contrast_type=jsonb_typeof(KeyTransform("contrast", "watch_rank")),- ).filter(contrast_type="number")- # Bounds the fetch, since a client-side cursor buffers every row. A window full of copies reads a wider slice- # once, still bounded, and a feed that stays short past it shows fewer picks rather than reading every row.+ experiment_ids = readable_experiment_ids(access, team_id)+ # Bounds the fetch; a window full of copies of a few findings reads a wider slice once.fetch_limit = cap * (HIGHLIGHT_PICK_GROUP_CANDIDATES + 1)- rows = _pick_window_rows(ranked, current_ranks, fetch_limit, categories)+ ranked = (+ rank_window(team_id, ANCHOR_VERSION, window.start, window.end, scanner_ids, ranked_before=window.as_of)+ if window.window_days is None or window.generation is None+ else None+ )++ def window_rows(limit: int) -> list[dict[str, Any]]:+ if ranked is not None:+ return _ranked_window_entries(ranked, scanner_ids, categories, experiment_ids, dismissed_ids, limit)+ assert window.window_days is not None and window.generation is not None+ return _stored_window_entries(+ team_id,+ window.generation,+ window.window_days,+ scanner_ids,+ categories,+ experiment_ids,+ dismissed_ids,+ limit,+ )++ rows = window_rows(fetch_limit)window_values = _cap_feed_groups(rows, cap)if len(window_values) < cap and len(rows) == fetch_limit:- window_values = _cap_feed_groups(- _pick_window_rows(ranked, current_ranks, fetch_limit * HIGHLIGHT_PICK_REFILL_FACTOR, categories), cap- )+ window_values = _cap_feed_groups(window_rows(fetch_limit * HIGHLIGHT_PICK_REFILL_FACTOR), cap)if not window_values:return []- # Counted over readable rows only, so a group never reveals how many restricted sessions it holds. Members- # below the cutoff still count, and a person who hit the problem twice counts once.- person = Coalesce(NullIf("distinct_id", Value("")), "session_id", output_field=CharField())- roots = {row["watch_group_root"] for row in window_values.values()}- # Postgres misjudges the JSON filters and would walk the whole window, so the members come from the group index- # alone. Group ids are random UUIDs, so no other team's row matches; the next query applies the team scope.- oldest = min(row["created_at"] for row in window_values.values()) - HIGHLIGHT_FEED_MEMBER_LOOKBACK- member_ids = list(- ReplayObservation.objects.filter(- status=ObservationStatus.SUCCEEDED, watch_rank__isnull=False, created_at__gte=oldest- )- .alias(member_root=group_root)- .filter(member_root__in=list(roots))- .values_list("id", flat=True)- )- # Read by id with the rank checks in Python, since the rank filters steer Postgres onto the partial rank indexes.- readable_scanners = {str(scanner_id) for scanner_id in scanner_ids}- members = (- accessible_observations(access, team_id, walkable.filter(id__in=member_ids))- .values_list("id", "scanner_id", "watch_rank", person)- .iterator()- )- reach_sessions: Counter[str] = Counter()- reach_people: dict[str, set[str]] = {}- for member_id, scanner_id, watch_rank, member_person in members:- rank = current_rank({"watch_rank": watch_rank})- if str(scanner_id) not in readable_scanners or rank is None or rank.get("category") not in categories:- continue- group = rank.get("group")- root = str(group) if group is not None else str(member_id)- reach_sessions[root] += 1- reach_people.setdefault(root, set()).add(member_person)- group_reach = {- root: {"sessions": sessions, "people": len(reach_people[root])} for root, sessions in reach_sessions.items()- }# The row-gate reads each row's snapshot JSON, so it runs on the picks only.rows = cast(list[dict[str, Any]],@@ -430,16 +434,19 @@ def select_embedding_picks(access, team_id, ReplayObservation.objects.filter(team_id=team_id, id__in=list(window_values))).annotate(feed_viewed=viewed)- .values("id", "scanner_id", "session_id", "created_at", "watch_rank", "feed_viewed")+ .values("id", "scanner_id", "session_id", "created_at", "feed_viewed")),)+ roots = {entry["group_root"] for entry in window_values.values()}+ reach = _group_reach(team_id, window, roots, scanner_ids, categories, experiment_ids)for row in rows:- window = window_values[row["id"]]- reach: Mapping[str, Any] = group_reach.get(window["watch_group_root"], {})- row["watch_percentile"] = window["watch_percentile"]- row["watch_group_root"] = window["watch_group_root"]- row["watch_group_size"] = reach.get("sessions", 1)- row["watch_group_people"] = reach.get("people", 1)+ entry = window_values[row["id"]]+ group = reach.get(str(entry["group_root"]), GroupReach(sessions=1, people=1))+ row["watch_category"] = CATEGORY_NAMES[entry["category"]]+ row["watch_percentile"] = entry["percentile"]+ row["watch_group_root"] = str(entry["group_root"])+ row["watch_group_size"] = group.sessions+ row["watch_group_people"] = group.peoplereturn rows@@ -450,16 +457,27 @@ def select_embedding_filler(access: UserAccessControl,team_id: int,pick_roots: set[str],+ hidden_categories: Sequence[str],) -> list[dict[str, Any]]:- """The newest readable rows outside the picks' feed groups, unwatched first, enough to bring a thin feed up to its floor."""+ """The newest readable rows outside the picks' feed groups, unwatched first, enough to bring a thin feed up to+ its floor."""+ ranks = ReplayObservationRank.objects.for_team(team_id).filter(observation_id=OuterRef("id"))+ roots = list(pick_roots)base = (accessible_observations(access, team_id, walkable.filter(scanner_id__in=scanner_ids))- .annotate(watch_group_root=watch_group_root())- .exclude(watch_group_root__in=pick_roots)+ .exclude(id__in=roots)+ .exclude(+ Exists(+ ranks.filter(+ Q(feed_group_id__in=roots)+ | Q(category__in=[CATEGORY_CODES[category] for category in hidden_categories])+ )+ )+ ).annotate(feed_viewed=viewed))- fields = ("id", "scanner_id", "session_id", "created_at", "watch_rank", "feed_viewed")- # Two short newest-first walks, because ordering by the viewed flag would sort the whole window.+ fields = ("id", "scanner_id", "session_id", "created_at", "feed_viewed")+ # Two short newest-first walks, instead of ordering by the viewed flag, which would sort the whole window.rows = list(base.filter(feed_viewed=False).order_by("-created_at", "-id").values(*fields)[:HIGHLIGHT_FEED_MIN_ITEMS])@@ -473,33 +491,29 @@ def select_embedding_filler(def rank_highlight_feed_by_embedding(rows: list[dict[str, Any]]) -> list[HighlightFeedEntry]:- """Rank candidate rows (`id`, `scanner_id`, `session_id`, `created_at`, `watch_rank`, `feed_viewed`,- and optionally `feed_impressions`) on the embedding rank the watch rank consumer wrote.-- A pick is a row in its scanner's top fifth by score whose category is an issue. Rows of one feed group- collapse to their best-scoring row, which carries the size of the group. Picks sort by weighted- percentile, decayed for each earlier impression, viewed rows docked, one scanner held to a share- of the picks, and one session's picks spaced apart. Every other row is filler, kept only to reach the- feed's floor.+ """Rank candidate rows (`id`, `scanner_id`, `session_id`, `created_at`, `feed_viewed`, optionally+ `feed_impressions`, and for picks the `watch_*` fields `select_embedding_picks` adds).++ A pick is a row with a percentile whose category is an issue. Rows of one feed group collapse to their best-scoring+ row, which carries the size of the group. Picks sort by weighted percentile, decayed for each earlier impression,+ viewed rows docked, one scanner held to a share of the picks, and one session's picks spaced apart. Every other row+ is filler, kept only to reach the feed's floor."""- percentiles = {str(row["id"]): row["watch_percentile"] for row in rows if row.get("watch_percentile") is not None}best_in_group: dict[str, tuple[float, dict[str, Any]]] = {}group_members: dict[str, list[str]] = {}for row in rows:- rank = current_rank(row)- observation_id = str(row["id"])- percentile = percentiles.get(observation_id)- if rank is None or percentile is None or rank.get("category") not in ISSUE_CATEGORIES:+ percentile = row.get("watch_percentile")+ if percentile is None or row.get("watch_category") not in ISSUE_CATEGORIES:continue# Group before the cutoff, so members below it still count toward the group and never return as filler.- group = str(rank.get("group") or observation_id)- group_members.setdefault(group, []).append(observation_id)+ group = row["watch_group_root"]+ group_members.setdefault(group, []).append(str(row["id"]))# Only a member above the cutoff can stand for the group, so the seen penalty never disqualifies it.if percentile < HIGHLIGHT_PICK_MIN_PERCENTILE:continuescore = (percentile- * CATEGORY_WEIGHT[rank["category"]]+ * CATEGORY_WEIGHT[row["watch_category"]]* people_boost(row.get("watch_group_people") or 1)* HIGHLIGHT_PICK_IMPRESSION_DECAY ** row.get("feed_impressions", 0))@@ -511,10 +525,9 @@ def rank_highlight_feed_by_embedding(rows: list[dict[str, Any]]) -> list[Highligpicks: list[tuple[float, Any, Any, HighlightFeedEntry]] = []for group, (score, row) in best_in_group.items():- rank = row["watch_rank"]reason = {"kind": "embedding_pick",- "watch_category": rank["category"],+ "watch_category": row["watch_category"],"similar_count": max(len(group_members[group]), row.get("watch_group_size") or 0) - 1,"affected_people": row.get("watch_group_people") or 1,}diff --git a/products/replay_vision/backend/watch_rank_backfill.py b/products/replay_vision/backend/watch_rank_backfill.pyindex d18050a77ecd..25e69b20c280 100644--- a/products/replay_vision/backend/watch_rank_backfill.py+++ b/products/replay_vision/backend/watch_rank_backfill.py@@ -12,10 +12,8 @@ from collections import defaultdictfrom datetime import datetimefrom itertools import batchedfrom typing import Any-from uuid import UUID-from django.db import transaction-from django.db.models import Count+from django.db.models import Count, Exists, OuterRefimport numpy as npimport structlog@@ -43,7 +41,7 @@ from products.replay_vision.backend.watch_rank import (WatchCategory,anchor_vectors,classify,- current_rank,+ current_ranks,normalize,save_anchor_similarities,)@@ -141,7 +139,7 @@ def _rank_scanner(for row in rows:observation_id = str(row["id"])vector = vectors.get(observation_id)- if vector is None or current_rank(row) is not None:+ if vector is None or row["ranked"]:continuewritten[observation_id] = classify(vector, anchors)return written@@ -158,8 +156,9 @@ def backfill_team_watch_ranks(team_id: int, since: datetime, *, dry_run: bool =for row in ReplayObservation.objects.filter(team_id=team_id, status=ObservationStatus.SUCCEEDED, created_at__gte=since)+ .annotate(ranked=Exists(current_ranks(team_id).filter(observation_id=OuterRef("id")))).order_by("created_at", "id")- .values("id", "scanner_id", "watch_rank")+ .values("id", "scanner_id", "ranked")]by_scanner: dict[str, list[dict[str, Any]]] = defaultdict(list)for row in rows:@@ -177,35 +176,15 @@ def backfill_team_watch_ranks(team_id: int, since: datetime, *, dry_run: bool =save_anchor_similarities(team_id, {observation_id: reading.similarities for observation_id, reading in written.items()})- # Only rows still without a current rank, locked until the write, so a rank the consumer writes meanwhile- # waits for this one and a rank it already wrote, with its group, stays.- with transaction.atomic():- still_unranked = set(- ReplayObservation.objects.select_for_update()- .filter(team_id=team_id, id__in=list(written))- .exclude(watch_rank__anchor_version=ANCHOR_VERSION)- .values_list("id", flat=True)- )- unranked = {- observation_id: reading.rank+ # A rank the consumer wrote meanwhile, with its group, stays: an existing rank row is never replaced.+ record_ranks(+ team_id,+ ANCHOR_VERSION,+ {+ observation_id: NewRank(contrast=reading.rank.contrast, category=reading.rank.category)for observation_id, reading in written.items()- if UUID(observation_id) in still_unranked- }- ReplayObservation.objects.bulk_update(- [- ReplayObservation(id=observation_id, watch_rank=rank.to_json())- for observation_id, rank in unranked.items()- ],- ["watch_rank"],- )- record_ranks(- team_id,- ANCHOR_VERSION,- {- observation_id: NewRank(contrast=rank.contrast, category=rank.category)- for observation_id, rank in unranked.items()- },- )+ },+ )without_embedding = len(rows) - embeddedlogger.info("replay_vision.watch_rank_backfill.team_done",diff --git a/products/replay_vision/backend/watch_rank_consumer.py b/products/replay_vision/backend/watch_rank_consumer.pyindex d8edf5c780b7..c3ecc3e8c201 100644--- a/products/replay_vision/backend/watch_rank_consumer.py+++ b/products/replay_vision/backend/watch_rank_consumer.py@@ -34,8 +34,9 @@ from products.replay_vision.backend.embeddings import (EMBEDDING_PRODUCT,OBSERVATION_EMBEDDING_MODEL,)+from products.replay_vision.backend.highlight_builds import rebuild_changed_feedsfrom products.replay_vision.backend.highlight_feed_groups import feed_group_cache-from products.replay_vision.backend.watch_rank import RankRequest, rank_observation+from products.replay_vision.backend.watch_rank import ANCHOR_VERSION, RankRequest, rank_observationfrom products.replay_vision.backend.watch_semantics import SemanticAssignment, assign_semanticsfrom products.replay_vision.backend.watch_themes import name_theme@@ -55,6 +56,8 @@ _ERROR_RETRY_WINDOW_S = 60.0# Long enough for a naming call that waits behind ranking on the shared database thread, short enough that a hung# model call frees its slot._NAMING_TIMEOUT_S = 120.0+# How often the consumer rebuilds the highlight feeds of teams whose ranks changed.+_REBUILD_INTERVAL_S = 60.0_NAMING_DRAIN_S = 20.0# A due theme left unnamed while this many are in flight is named when its next member arrives._MAX_NAMING_TASKS = 8@@ -73,6 +76,11 @@ BATCH_DURATION = Histogram("Time the highlight feed rank consumer spent on one non-empty batch.",buckets=(0.1, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 240, 300),)+FEED_REBUILDS_TOTAL = Counter(+ "replay_vision_watch_rank_consumer_feed_rebuilds_total",+ "Highlight feed rebuild sweeps of the rank consumer, by outcome.",+ labelnames=["outcome"],+)THEME_NAMING_TOTAL = Counter("replay_vision_watch_rank_consumer_theme_naming_total","Theme naming outcomes of the highlight feed rank consumer, including names dropped while every slot was busy.",@@ -142,6 +150,15 @@ def _assign_with_timeouts(raise+def _rebuild_changed_feeds() -> int:+ # The sweep's thread keeps its own connection, so a broken one is replaced before each sweep.+ close_old_connections()+ try:+ return rebuild_changed_feeds(ANCHOR_VERSION)+ finally:+ close_old_connections()++class BatchConsumer(Protocol):def store_offsets(self, *, message: Message) -> None: ...@@ -302,6 +319,17 @@ class WatchRankConsumer:config.update(helper.ssl_cert_config())return config+ async def _rebuild_feeds(self) -> None:+ """Rebuild changed teams' highlight feeds beside the message loop, on a thread of its own."""+ while await self._wait(_REBUILD_INTERVAL_S):+ try:+ built = await sync_to_async(_rebuild_changed_feeds, thread_sensitive=False)()+ except Exception:+ FEED_REBUILDS_TOTAL.labels(outcome="failed").inc()+ logger.exception("replay_vision.watch_rank_consumer.feed_rebuild_failed")+ else:+ FEED_REBUILDS_TOTAL.labels(outcome="built" if built else "idle").inc()+async def run(self) -> None: # pragma: no cover - exercised in dogfoodloop = asyncio.get_running_loop()for sig in (signal.SIGINT, signal.SIGTERM):@@ -310,6 +338,7 @@ class WatchRankConsumer:consumer = Consumer(self._consumer_config())consumer.subscribe([KAFKA_DOCUMENT_EMBEDDING_RESULTS_TOPIC])logger.info("replay_vision.watch_rank_consumer.started")+ rebuilds = asyncio.create_task(self._rebuild_feeds())try:while not self._stop.is_set():self._liveness.record_heartbeat()@@ -319,6 +348,7 @@ class WatchRankConsumer:with BATCH_DURATION.time():await self.process_batch(consumer, messages)finally:+ rebuilds.cancel()consumer.close()# A theme claimed for naming stays unnamed until it doubles, so in-flight names get a moment to finish.if self._naming:diff --git a/products/replay_vision/backend/watch_semantics.py b/products/replay_vision/backend/watch_semantics.pyindex 7420eb7c2254..5a4c2a46da70 100644--- a/products/replay_vision/backend/watch_semantics.py+++ b/products/replay_vision/backend/watch_semantics.py@@ -5,18 +5,16 @@ already grouped.The embedding consumer assigns one observation per message, and the semantics backfill assigns a scanner's rows inchunks, both through `assign_semantics_batch`. It locks the scanner's semantic centre for the whole chunk, so two-writers never race on its clusters, and writes both ids to each observation's rank in the same transaction, so a+writers never race on its clusters, and writes both ids to each observation's rank row in the same transaction, so aredelivered message finds them already there."""import uuidfrom collections.abc import Sequencefrom datetime import datetime, timedelta-from itertools import batchedfrom typing import Anyfrom django.db import transaction-from django.db.models import Case, F, Func, JSONField, Value, Whenimport numpy as np@@ -30,7 +28,7 @@ from products.replay_vision.backend.models.replay_scanner_semantics import (ReplayScannerSearchTheme,ReplayScannerSemanticCenter,)-from products.replay_vision.backend.observation_ranks import set_rank_clusters+from products.replay_vision.backend.observation_ranks import CATEGORY_NAMES, set_rank_clustersfrom products.replay_vision.backend.scanner_access import scanners_for_reading_observationsfrom products.replay_vision.backend.semantic_space import (SEMANTIC_DIMENSIONS,@@ -40,14 +38,13 @@ from products.replay_vision.backend.semantic_space import (semantic_vector,unpack,)-from products.replay_vision.backend.watch_rank import current_rank+from products.replay_vision.backend.watch_rank import current_ranksfrom products.replay_vision.backend.watch_themes import ThemeAssignment, ThemeBatch, belongs_in_theme# Clusters with no member for this long are deleted, since the feed's longest window no longer reaches them.SEMANTIC_RETENTION = timedelta(days=90)# Pruning runs on one in this many assignments of a scanner, which keeps it rare and still bounds the tables._PRUNE_EVERY = 500-_MERGE_CHUNK = 500@frozen@@ -101,20 +98,27 @@ def assign_semantics_batch())keys = [_as_uuid(item.observation_id) for item in items]+ ids = [key for key in keys if key]rows = {row["id"]: row- for row in ReplayObservation.objects.filter(- team_id=team_id, id__in=[key for key in keys if key]- ).values("id", "watch_rank", "scanner_result", "scanner_snapshot")+ for row in ReplayObservation.objects.filter(team_id=team_id, id__in=ids).values(+ "id", "scanner_result", "scanner_snapshot"+ )}+ ranks = dict(+ current_ranks(team_id)+ .filter(observation_id__in=ids, feed_group_id__isnull=True)+ .values_list("observation_id", "category")+ )center_sum = unpack(center.vector_sum).copy()member_count = center.member_countgroup_writes = ClusterWrites(ReplayScannerFeedGroup, team_id, scanner_id)themes: ThemeBatch | None = Nonefor item, key in zip(items, keys):row = rows.get(key) if key else None- rank = current_rank({"watch_rank": row["watch_rank"]}) if row else None- if row is None or rank is None or rank.get("group"):+ # Only a ranked row without a group yet takes one, so a redelivered message changes nothing.+ category = CATEGORY_NAMES.get(ranks.get(key, 0)) if key else None+ if row is None or category is None:continuev = semantic_vector(item.vector)space = scanner_space(center_sum, member_count, v)@@ -139,7 +143,7 @@ def assign_semantics_batch(row["scanner_snapshot"],)and belongs_in_theme(- category=rank["category"],+ category=category,scanner_type=scanner["scanner_type"],valence=scanner["prompt_valence"],output=output,@@ -162,14 +166,6 @@ def assign_semantics_batch(center.save(update_fields=["vector_sum", "member_count"])if pruning_due:_prune(team_id, scanner_id, items[-1].now)- merge_watch_ranks(- team_id,- {- observation_id: {"group": str(assignment.group_id)}- | ({"theme": str(assignment.theme.theme_id)} if assignment.theme else {})- for observation_id, assignment in assigned.items()- },- )set_rank_clusters(team_id,{@@ -191,31 +187,6 @@ def _as_uuid(observation_id: str) -> uuid.UUID | None:return None-def merge_watch_ranks(team_id: int, keys_by_observation: dict[str, dict[str, Any]]) -> None:- """Add keys to each observation's rank without rewriting what another writer put there, and drop the retired- duplicate link."""- without_duplicate = Func(- F("watch_rank"), Value("duplicate_of"), template="(%(expressions)s)", arg_joiner=" - ", output_field=JSONField()- )- # Postgres tries each CASE branch in turn per row, so one update stays at a few hundred observations.- for chunk in batched(keys_by_observation.items(), _MERGE_CHUNK, strict=False):- keys = Case(- *(- When(id=observation_id, then=Value(observation_keys, output_field=JSONField()))- for observation_id, observation_keys in chunk- ),- default=Value({}, output_field=JSONField()),- output_field=JSONField(),- )- ReplayObservation.objects.filter(- team_id=team_id, id__in=[observation_id for observation_id, _ in chunk]- ).update(- watch_rank=Func(- without_duplicate, keys, template="%(expressions)s", arg_joiner=" || ", output_field=JSONField()- )- )--def _valence_unknown_for_row(scanner_type: str, valence: str, scanner_config: dict[str, Any] | None, snapshot: dict[str, Any] | None) -> bool:diff --git a/products/replay_vision/backend/watch_semantics_backfill.py b/products/replay_vision/backend/watch_semantics_backfill.pyindex 945b31aad73a..4d48bf265390 100644--- a/products/replay_vision/backend/watch_semantics_backfill.py+++ b/products/replay_vision/backend/watch_semantics_backfill.py@@ -1,5 +1,5 @@-"""Brings observations ranked before the consumer wrote everything it writes today up to date: category scores,-anchor similarities, feed groups and search themes, so the feed and the suggestions start from history."""+"""Brings observations ranked before the consumer wrote everything it writes today up to date: anchor similarities,+feed groups and search themes, so the feed and the suggestions start from history."""import uuidfrom collections import defaultdict@@ -15,7 +15,6 @@ from asgiref.sync import async_to_syncfrom posthog.dataclasses import frozen-from products.replay_vision.backend.models.replay_observation import ReplayObservationfrom products.replay_vision.backend.models.replay_observation_anchor_similarity import ReplayObservationAnchorSimilarityfrom products.replay_vision.backend.watch_rank import (ANCHOR_VERSION,@@ -23,10 +22,11 @@ from products.replay_vision.backend.watch_rank import (WatchCategory,anchor_vectors,classify,+ current_ranks,save_anchor_similarities,)from products.replay_vision.backend.watch_rank_backfill import stored_vectors_between-from products.replay_vision.backend.watch_semantics import SemanticItem, assign_semantics_batch, merge_watch_ranks+from products.replay_vision.backend.watch_semantics import SemanticItem, assign_semantics_batchfrom products.replay_vision.backend.watch_themes import name_theme, naming_candidateslogger = structlog.get_logger(__name__)@@ -45,7 +45,6 @@ class _Pending:scanner_id: strcreated_at: datetimeneeds_group: bool- needs_scores: boolneeds_similarities: bool@@ -61,15 +60,14 @@ def backfill_team_semantics(team_id: int, since: datetime, *, dry_run: bool = Fathe Search tab can suggest."""has_similarities = Exists(ReplayObservationAnchorSimilarity.objects.for_team(team_id).filter(- observation_id=OuterRef("id"), anchor_version=ANCHOR_VERSION+ observation_id=OuterRef("observation_id"), anchor_version=ANCHOR_VERSION))pending = (- ReplayObservation.objects.filter(- team_id=team_id, status="succeeded", created_at__gte=since, watch_rank__anchor_version=ANCHOR_VERSION- )+ current_ranks(team_id)+ .filter(created_at__gte=since).annotate(has_similarities=has_similarities)- .filter(Q(watch_rank__group__isnull=True) | Q(watch_rank__scores__isnull=True) | Q(has_similarities=False))+ .filter(Q(feed_group_id__isnull=True) | Q(has_similarities=False)))if dry_run:return SemanticBackfillResult(observations=pending.count(), assigned=0, named=0)@@ -80,13 +78,13 @@ def backfill_team_semantics(team_id: int, since: datetime, *, dry_run: bool = Fa# One page per query and per slice, because a pooled connection buffers a whole result however it is iterated.after: tuple[datetime, uuid.UUID] | None = Nonewhile True:- page = pending.order_by("created_at", "id")+ page = pending.order_by("created_at", "observation_id")if after:- page = page.filter(Q(created_at__gt=after[0]) | Q(created_at=after[0], id__gt=after[1]))+ page = page.filter(Q(created_at__gt=after[0]) | Q(created_at=after[0], observation_id__gt=after[1]))values = list(- page.values_list(- "id", "scanner_id", "created_at", "watch_rank__group", "watch_rank__scores", "has_similarities"- )[:_SLICE_ROWS]+ page.values_list("observation_id", "scanner_id", "created_at", "feed_group_id", "has_similarities")[+ :_SLICE_ROWS+ ])if not values:break@@ -96,10 +94,9 @@ def backfill_team_semantics(team_id: int, since: datetime, *, dry_run: bool = Fascanner_id=str(scanner_id),created_at=created_at,needs_group=group is None,- needs_scores=scores is None,needs_similarities=not has_row,)- for observation_id, scanner_id, created_at, group, scores, has_row in values+ for observation_id, scanner_id, created_at, group, has_row in values]observations += len(slice_rows)assigned += _backfill_slice(team_id, slice_rows, anchors)@@ -122,7 +119,7 @@ def _backfill_slice(team_id: int, slice_rows: list[_Pending], anchors: dict[Watcreadings: dict[str, AnchorReading] = {row.observation_id: classify(vectors[row.observation_id], anchors)for row in slice_rows- if row.observation_id in vectors and (row.needs_scores or row.needs_similarities)+ if row.observation_id in vectors and row.needs_similarities}save_anchor_similarities(team_id,@@ -132,14 +129,6 @@ def _backfill_slice(team_id: int, slice_rows: list[_Pending], anchors: dict[Watcif row.needs_similarities and row.observation_id in readings},)- merge_watch_ranks(- team_id,- {- row.observation_id: {"scores": readings[row.observation_id].rank.scores}- for row in slice_rows- if row.needs_scores and row.observation_id in readings- },- )by_scanner: dict[str, list[SemanticItem]] = defaultdict(list)for row in slice_rows:if row.needs_group and row.observation_id in vectors:diff --git a/products/replay_vision/backend/watch_themes.py b/products/replay_vision/backend/watch_themes.pyindex 314bc14bf1f3..a9575d71bfdd 100644--- a/products/replay_vision/backend/watch_themes.py+++ b/products/replay_vision/backend/watch_themes.py@@ -27,6 +27,7 @@ from products.replay_vision.backend.consent import is_ai_data_processing_approvefrom products.replay_vision.backend.distinct_ids import replay_vision_distinct_idfrom products.replay_vision.backend.gemini_client import AI_PRODUCT, replay_gemini_clientfrom products.replay_vision.backend.models.replay_observation import ReplayObservation+from products.replay_vision.backend.models.replay_observation_rank import ReplayObservationRankfrom products.replay_vision.backend.models.replay_scanner import PromptValence, ReplayScanner, ScannerTypefrom products.replay_vision.backend.models.replay_scanner_semantics import (THEME_FIRST_RENAME_AT,@@ -226,16 +227,16 @@ def _naming_context(team_id: int, theme_id: uuid.UUID) -> tuple[ReplayScanner, ltheme = ReplayScannerSearchTheme.objects.for_team(team_id).filter(id=theme_id).select_related("scanner").first()if theme is None:return None+ member_ids = (+ ReplayObservationRank.objects.for_team(team_id)+ .filter(search_theme_id=theme_id)+ .order_by("-created_at")+ .values("observation_id")[:THEME_NAME_SAMPLES]+ )rows = (- # The window keeps the walk to recent rows of the scanner, since the JSON key has no index of its own.- ReplayObservation.objects.filter(- team_id=team_id,- scanner_id=theme.scanner_id,- created_at__gte=theme.last_member_at - THEME_ACTIVE_WINDOW,- watch_rank__theme=str(theme_id),- )+ ReplayObservation.objects.filter(team_id=team_id, id__in=member_ids).order_by("-created_at")- .values_list("scanner_result", flat=True)[:THEME_NAME_SAMPLES]+ .values_list("scanner_result", flat=True))samples = [text[:_SAMPLE_CHARS] for result in rows if (text := explanation_text((result or {}).get("model_output") or {}))