Skip to content

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

feat(replay-vision): rerank observation search with a decision model (#107372)

Tue Haulundfab1eea02e7a
diff --git a/products/replay_vision/README.md b/products/replay_vision/README.md
index 9c0e1a9b934f..fd1db7953877 100644
--- a/products/replay_vision/README.md
+++ b/products/replay_vision/README.md
@@ -8,6 +8,7 @@ A sub-product of Session Replay. Users configure named **scanners** that PostHog
Carries a prompt, a scanner type (`monitor` / `classifier` / `scorer` / `summarizer`), a `RecordingsQuery` that selects matching sessions, a Gemini model (which sets the per-observation credit price), and two volume levers: `sampling_mode` (a quality pre-filter over the matched sessions) and `sampling_rate` (a random downsample applied after it).
Each enabled scanner has a Temporal schedule that fires every 5 minutes and sweeps for newly settled recordings past the scanner's watermark (`last_swept_at`); disabling a scanner removes its schedule, and re-enabling restarts the sweep from now rather than backfilling the gap (see **Backfill** for the explicit way to cover history).
Every succeeded observation is embedded (the summary, or the reasoning) for downstream free-text search.
+The Search tab ranks observations by embedding distance, then a decision model rereads the query and each of the top 20 together and reorders them by how well they match. The reorder has a two-second budget, and search falls back to the embedding order when the model is slow, failing, or not configured.
A scanner with `emits_signals` also pushes one signal per finding into the Signals inbox (`replay_vision` / `scanner_finding`), which is what the editor's Self-driving step turns on.
**Inline scan** — a prompt pointed at named sessions with nothing saved, for a one-off question (`POST /vision/scanners/inline_scan/`, and the path agents take instead of creating a throwaway scanner). An observation belongs to a scanner, so a scan mints one keyed by a fingerprint of its config: the same question reuses the observations it already has, a different question gets its own. Those rows carry `origin=inline`, are never listed or swept, and are reaped once they have nothing to show. See `backend/inline_scan.py` for why they exist and `backend/scanner_access.py` for how results are read back.
@@ -69,6 +70,7 @@ The template lives in `frontend/src/scenes/experiments/replayVisionScanner.ts` a
- `backend/quota.py` + `backend/billing.py` — credit accounting: the per-model price table, the receipt ledger, the quota snapshot the meter reads, and the per-org credit-limit override described below.
- `backend/enqueue_claims.py` — atomic slot claims that keep on-demand scans inside the in-flight caps.
- `backend/embeddings.py` — the embedding identity shared by the write and search sides.
+- `backend/search.py` + `backend/search_rerank.py` — observation search: embedding rank, access-scoped hydration, and the decision-model rerank of the head.
- `backend/prompt_suggestions.py` + `backend/proposers/` — rating-driven prompt rewrites, one proposer per scanner type. `backend/prompt_evaluation.py` re-runs a suggestion against rated sessions before it's applied, and `backend/feedback_themes.py` clusters written thumbs-down feedback.
- `backend/impact.py` — affected sessions and users per scanner, exportable as a static cohort.
- `backend/tags.py` + `backend/tag_suggestions.py` — tag slug normalization and data-grounded vocabulary suggestions for classifiers.
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 49604eba6ffc..8a2fa9cb2922 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -81,6 +81,7 @@ from products.replay_vision.backend.search import (
parse_date_bound,
query_vector_for,
search_observations,
+ warm_query_vectors,
)
from products.replay_vision.backend.search_suggestions import (
MAX_SUGGESTED_QUERIES,
@@ -1449,6 +1450,10 @@ class ObservationSearchResponseSerializer(serializers.Serializer):
help_text="True when more matches may exist beyond `results`, so the response is a top slice "
"rather than everything that matched."
)
+ reranked = serializers.BooleanField(
+ help_text="True when a relevance model reordered the top results after the embedding match. False when "
+ "the results are in embedding distance order, for example because the model did not answer in time."
+ )
class SearchSuggestionsQuerySerializer(serializers.Serializer):
@@ -1548,15 +1553,6 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
"to search Replay Vision observations.",
code=AI_CONSENT_REQUIRED_CODE,
)
- try:
- query_vector = query_vector_for(self.team, validated["q"])
- except requests.RequestException as error:
- # The embedding worker is unreachable, slow, or failing, so the caller can retry. A rejected
- # request is a bug on our side, not retryable, and should surface as a 500.
- if not is_transient_embedding_error(error):
- raise
- logger.warning("replay_vision.observation_search.embedding_failed", team_id=self.team_id, exc_info=True)
- raise EmbeddingUnavailableError()
filters = ObservationSearchFilters.from_raw(
verdict=_csv_values(validated.get("verdict")),
tags=_csv_values(validated.get("tags")),
@@ -1566,15 +1562,25 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
date_to=validated.get("date_to"),
timezone_info=self.team.timezone_info,
)
- response = search_observations(
- self.team,
- self.user_access_control,
- scanner_ids,
- query_vector,
- validated["limit"],
- filters,
- )
- return self._search_response(response.results, truncated=response.truncated)
+ team, query = self.team, validated["q"]
+ try:
+ response = search_observations(
+ self.team,
+ self.user_access_control,
+ scanner_ids,
+ lambda: query_vector_for(team, query),
+ validated["limit"],
+ filters,
+ rerank_query=validated["q"],
+ )
+ except requests.RequestException as error:
+ # The embedding worker is unreachable, slow, or failing, so the caller can retry. A rejected
+ # request is a bug on our side, not retryable, and should surface as a 500.
+ if not is_transient_embedding_error(error):
+ raise
+ logger.warning("replay_vision.observation_search.embedding_failed", team_id=self.team_id, exc_info=True)
+ raise EmbeddingUnavailableError()
+ return self._search_response(response.results, truncated=response.truncated, reranked=response.reranked)
@extend_schema(
parameters=[SearchSuggestionsQuerySerializer],
@@ -1608,13 +1614,20 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
params = SearchSuggestionsQuerySerializer(data=request.data)
params.is_valid(raise_exception=True)
scanner_ids = self._searchable_scanner_ids(params.validated_data.get("scanner_id"))
+ sources = scope_sources(self.team_id, scanner_ids)
# The same rows that a view shows are the ones it marks as wanted.
- stamp_search_viewed(self.team_id, [scanner_id for scanner_id, _ in scope_sources(self.team_id, scanner_ids)])
+ stamp_search_viewed(self.team_id, [scanner_id for scanner_id, _ in sources])
+ # A suggestion is a likely next search, so its vector is cached before anyone clicks it. The phrases
+ # derive from recordings, so they reach the embedding service only with AI data processing on.
+ if is_ai_data_processing_approved(self.team.id):
+ warm_query_vectors(self.team, merge_suggestions([stored for _, stored in sources]))
return Response(status=status.HTTP_204_NO_CONTENT)
- def _search_response(self, results: list[ObservationSearchResult], truncated: bool = False) -> Response:
+ def _search_response(
+ self, results: list[ObservationSearchResult], truncated: bool = False, reranked: bool = False
+ ) -> Response:
serializer = ObservationSearchResponseSerializer(
- {"results": results, "truncated": truncated}, context=self.get_serializer_context()
+ {"results": results, "truncated": truncated, "reranked": reranked}, context=self.get_serializer_context()
)
return Response(serializer.data)
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 4d1083dcb790..6f0450147e5e 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -501,7 +501,7 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
empty = (f"No recordings from {scope_label} matched that search yet.", {"result_count": 0})
response = search_observations(
- self._team, self.user_access_control, scanner_ids, query_vector, capped_limit, filters
+ self._team, self.user_access_control, scanner_ids, lambda: query_vector, capped_limit, filters
)
lines: list[str] = []
diff --git a/products/replay_vision/backend/search.py b/products/replay_vision/backend/search.py
index 574479f28e2a..9459f758027d 100644
--- a/products/replay_vision/backend/search.py
+++ b/products/replay_vision/backend/search.py
@@ -7,6 +7,9 @@ scanner ids in.
"""
import hashlib
+from collections.abc import Callable
+from concurrent.futures import Future, ThreadPoolExecutor
+from contextvars import copy_context
from dataclasses import dataclass
from datetime import datetime
from typing import Any
@@ -16,6 +19,7 @@ from django.core.cache import cache
from django.db.models import F
import requests
+import structlog
from asgiref.sync import sync_to_async
from posthog.api.embedding_worker import generate_embedding
@@ -36,9 +40,13 @@ from products.replay_vision.backend.models.replay_observation import (
ReplayObservation,
hydrate_for_serialization,
)
+from products.replay_vision.backend.observation_formatting import explanation_text, read_output
from products.replay_vision.backend.scanner_access import accessible_observations
+from products.replay_vision.backend.search_rerank import RERANK_CANDIDATES, RerankCandidate, rerank
from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tag
+logger = structlog.get_logger(__name__)
+
# Default and hard cap on how many observations a search returns.
DEFAULT_SEARCH_LIMIT = 20
MAX_SEARCH_LIMIT = 50
@@ -66,6 +74,10 @@ _EMBEDDING_TIMEOUT_S = 10.0
_MAX_CANDIDATE_ROWS = 50_000
_QUERY_TIMEOUT_S = 60
+_QUERY_VECTOR_EXECUTOR = ThreadPoolExecutor(max_workers=8, thread_name_prefix="replay-vision-query-vector")
+# Warming gets its own pool so a burst of page views never queues a live search behind it.
+_WARM_VECTOR_EXECUTOR = ThreadPoolExecutor(max_workers=2, thread_name_prefix="replay-vision-query-vector-warm")
+
_EMBEDDINGS_TABLE = f"distributed_posthog_document_embeddings_{OBSERVATION_EMBEDDING_MODEL.value.replace('-', '_')}"
_SCOPE_PREWHERE = """team_id = %(team_id)s
AND product = %(product)s
@@ -182,37 +194,19 @@ class ObservationSearchFilters:
clauses.append(clause)
-def rank_observations(
- team: Team,
- scanner_ids: list[str],
- query_vector: list[float],
- limit: int,
- filters: ObservationSearchFilters,
-) -> list[ObservationMatch]:
- """Closest observations by cosine distance, restricted to the given scanners and to the structured
- outcome filters via the embedding metadata. Reads the physical table directly because the HogQL
- `document_embeddings` table pushes only the team filter down to the storage read.
+class _CutoffNotComputed:
+ pass
- The cosine scan is exact, so it is bounded to the most recent `_MAX_CANDIDATE_ROWS` matching rows: a
- timestamp-only pass finds the cutoff, then the ranking pass decodes vectors from that cutoff on. The scope
- sits in PREWHERE so `embedding` and `content` are decoded only for rows that pass it. A high-volume team
- is capped to its most recent embeddings at the cost of not ranking its oldest ones.
- Rows farther than `MAX_MATCH_DISTANCE` are dropped before aggregation, so an off-topic query returns nothing.
+# Distinct from None, which means the cutoff query ran and found no rows in scope.
+_CUTOFF_NOT_COMPUTED = _CutoffNotComputed()
- `min(...)` collapses an observation's multiple renderings to its single best-matching distance, so each
- observation appears once. Only rows written before summarizers embedded one document per observation
- have several renderings; once those age past the candidate cap the GROUP BY can go.
- """
- params: dict[str, Any] = {
- "team_id": team.id,
- "product": EMBEDDING_PRODUCT,
- "document_type": EMBEDDING_DOCUMENT_TYPE,
- "scanner_ids": scanner_ids,
- "candidate_cap": _MAX_CANDIDATE_ROWS,
- }
- scope = _SCOPE_PREWHERE + "".join(f"\n AND {clause}" for clause in filters.where_clauses(params))
+def candidate_cutoff(team: Team, scanner_ids: list[str], filters: ObservationSearchFilters) -> datetime | None:
+ """Timestamp of the oldest of the most recent `_MAX_CANDIDATE_ROWS` rows in scope, or None when none are.
+ Needs no query vector, so a caller can run it while the search text is embedded."""
+ params = _scope_params(team, scanner_ids)
+ scope = _scope_clause(filters, params)
with tags_context(product=Product.REPLAY_VISION, feature=Feature.SEMANTIC_SEARCH, query_type=_CANDIDATE_QUERY_TYPE):
# nosemgrep: clickhouse-fstring-param-audit - static clauses from `_append_filter`, values are params
cutoff_rows = sync_execute(
@@ -232,9 +226,53 @@ def rank_observations(
ch_user=ClickHouseUser.REPLAY_VISION,
settings={"max_execution_time": _QUERY_TIMEOUT_S},
)
- cutoff = cutoff_rows[0][0] if cutoff_rows else None
+ return cutoff_rows[0][0] if cutoff_rows else None
+
+
+def _scope_params(team: Team, scanner_ids: list[str]) -> dict[str, Any]:
+ return {
+ "team_id": team.id,
+ "product": EMBEDDING_PRODUCT,
+ "document_type": EMBEDDING_DOCUMENT_TYPE,
+ "scanner_ids": scanner_ids,
+ "candidate_cap": _MAX_CANDIDATE_ROWS,
+ }
+
+
+def _scope_clause(filters: ObservationSearchFilters, params: dict[str, Any]) -> str:
+ return _SCOPE_PREWHERE + "".join(f"\n AND {clause}" for clause in filters.where_clauses(params))
+
+
+def rank_observations(
+ team: Team,
+ scanner_ids: list[str],
+ query_vector: list[float],
+ limit: int,
+ filters: ObservationSearchFilters,
+ cutoff: datetime | None | _CutoffNotComputed = _CUTOFF_NOT_COMPUTED,
+) -> list[ObservationMatch]:
+ """Closest observations by cosine distance, restricted to the given scanners and to the structured
+ outcome filters via the embedding metadata. Reads the physical table directly because the HogQL
+ `document_embeddings` table pushes only the team filter down to the storage read.
+
+ The cosine scan is exact, so it is bounded to the most recent `_MAX_CANDIDATE_ROWS` matching rows: a
+ timestamp-only pass (`candidate_cutoff`, run here when the caller did not pass its result) finds the cutoff,
+ then the ranking pass decodes vectors from that cutoff on. The scope
+ sits in PREWHERE so `embedding` and `content` are decoded only for rows that pass it. A high-volume team
+ is capped to its most recent embeddings at the cost of not ranking its oldest ones.
+
+ Rows farther than `MAX_MATCH_DISTANCE` are dropped before aggregation, so an off-topic query returns nothing.
+
+ `min(...)` collapses an observation's multiple renderings to its single best-matching distance, so each
+ observation appears once. Only rows written before summarizers embedded one document per observation
+ have several renderings; once those age past the candidate cap the GROUP BY can go.
+ """
+ if isinstance(cutoff, _CutoffNotComputed):
+ cutoff = candidate_cutoff(team, scanner_ids, filters)
if cutoff is None:
return []
+ params = _scope_params(team, scanner_ids)
+ scope = _scope_clause(filters, params)
with tags_context(product=Product.REPLAY_VISION, feature=Feature.SEMANTIC_SEARCH, query_type=_RANK_QUERY_TYPE):
# nosemgrep: clickhouse-fstring-param-audit - static clauses from `_append_filter`, values are params
@@ -326,22 +364,53 @@ class ObservationSearchResponse:
# More matches exist past `results`: either hydration returned more readable rows than the limit, or
# ClickHouse filled its over-fetched limit with rows under the distance ceiling.
truncated: bool
+ reranked: bool = False
+
+
+def _rerank_text(obs: ReplayObservation) -> str:
+ # The scanner's full reasoning or summary. Older observations were embedded as several short renderings, and
+ # the one that matched the query is often a bare tag, but the row always holds the full text.
+ output = read_output(obs)
+ return explanation_text(output) if output is not None else ""
def search_observations(
team: Team,
access: UserAccessControl,
scanner_ids: list[str],
- query_vector: list[float],
+ query_vector: Callable[[], list[float]],
limit: int,
filters: ObservationSearchFilters,
+ rerank_query: str | None = None,
) -> ObservationSearchResponse:
"""Rank, hydrate, and slice: the one path both the HTTP endpoint and the Max tool call once they have
- resolved their scanner scope and query vector."""
+ resolved their scanner scope. `query_vector` runs on a worker thread while ClickHouse finds the candidate
+ cutoff, and any error it raises reaches the caller. With `rerank_query`, the head of the readable results is
+ reordered by `search_rerank`, after hydration so the model reads only observations the caller can see."""
rank_limit = limit * RANK_OVERFETCH_FACTOR
- matches = rank_observations(team, scanner_ids, query_vector, rank_limit, filters)
+ # Copying the context keeps the request's log fields and trace on the embedding call.
+ vector_future = _QUERY_VECTOR_EXECUTOR.submit(copy_context().run, query_vector)
+ try:
+ cutoff = candidate_cutoff(team, scanner_ids, filters)
+ except BaseException:
+ # Frees a still-queued embedding so repeated ClickHouse failures cannot fill the pool.
+ vector_future.cancel()
+ raise
+ # Resolved even when the scope is empty, so an embedding failure still reaches the caller.
+ vector = vector_future.result()
+ matches = rank_observations(team, scanner_ids, vector, rank_limit, filters, cutoff=cutoff)
match_by_id = {match.observation_id: match for match in matches}
observations = fetch_ranked_observations(team.id, scanner_ids, list(match_by_id), access)
+ reranked = False
+ if rerank_query:
+ head = observations[:RERANK_CANDIDATES]
+ candidates = [
+ RerankCandidate(str(obs.id), _rerank_text(obs) or match_by_id[str(obs.id)].matched_content) for obs in head
+ ]
+ outcome = rerank(rerank_query, candidates, team_id=team.id)
+ by_id = {str(obs.id): obs for obs in head}
+ observations = [by_id[observation_id] for observation_id in outcome.order] + observations[len(head) :]
+ reranked = outcome.reranked
results = [
ObservationSearchResult(
observation=obs,
@@ -351,7 +420,7 @@ def search_observations(
for obs in observations[:limit]
]
truncated = len(observations) > limit or len(matches) >= rank_limit
- return ObservationSearchResponse(results=results, truncated=truncated)
+ return ObservationSearchResponse(results=results, truncated=truncated, reranked=reranked)
def _query_vector_cache_key(text: str) -> str:
@@ -383,5 +452,31 @@ def query_vector_for(team: Team, text: str) -> list[float]:
return vector
+def _in_current_context(fn: Callable[[Team, str], list[float]], team: Team, text: str) -> Callable[[], list[float]]:
+ context = copy_context()
+ return lambda: context.run(fn, team, text)
+
+
+def warm_query_vectors(team: Team, texts: list[str]) -> list[Future[list[float]]]:
+ """Embed and cache texts a person is about to search for, such as the suggested searches on screen, so the
+ search skips the embedding round trip. Runs in the background and returns at once. A failure only means the
+ search embeds the text itself."""
+ try:
+ cached = cache.get_many([_query_vector_cache_key(text) for text in texts])
+ except Exception:
+ logger.warning("replay_vision.search.query_vector_warm_setup_failed", exc_info=True)
+ return []
+ misses = [text for text in texts if _query_vector_cache_key(text) not in cached]
+ futures = [_WARM_VECTOR_EXECUTOR.submit(_in_current_context(query_vector_for, team, text)) for text in misses]
+ for future in futures:
+ future.add_done_callback(_log_warm_failure)
+ return futures
+
+
+def _log_warm_failure(future: Future[list[float]]) -> None:
+ if not future.cancelled() and future.exception() is not None:
+ logger.warning("replay_vision.search.query_vector_warm_failed", exc_info=future.exception())
+
+
# The Max tool awaits this so the event loop stays free during the embedding round trip.
async_query_vector_for = sync_to_async(query_vector_for, thread_sensitive=False)
diff --git a/products/replay_vision/backend/search_rerank.py b/products/replay_vision/backend/search_rerank.py
new file mode 100644
index 000000000000..897bddaf75c4
--- /dev/null
+++ b/products/replay_vision/backend/search_rerank.py
@@ -0,0 +1,116 @@
+"""Rerank the head of an observation search with a decision model.
+
+Embedding distance compares the query and each observation separately, so an observation that only shares the
+topic ranks as high as one that shows the thing searched for. The decision model reads the query and each
+observation together and answers whether the observation matches. Only the head of the list is reranked: the
+model reads every question against the whole request state, so its cost grows with the square of the candidates
+it sees, and splitting the head into parallel requests keeps each state small.
+
+Search never waits on the model past `RERANK_DEADLINE_S` and never fails because of it. Any error, timeout, or
+missing gateway returns the embedding order unchanged.
+"""
+
+import time
+from collections.abc import Sequence
+from concurrent.futures import ThreadPoolExecutor, wait
+from contextvars import copy_context
+from dataclasses import dataclass
+
+import structlog
+
+from posthog.llm.gateway_client import team_distinct_id
+from posthog.llm.system_one import JsonValue, NoulAnswer, NoulQuestion, SystemOneNotConfigured
+from posthog.llm.system_one_client import SystemOneClient, build_system_one_client
+
+from products.replay_vision.backend.temporal.metrics import record_search_rerank
+
+logger = structlog.get_logger(__name__)
+
+RERANK_MODEL = "posthog/hogference/jevk5-fp8-0.2"
+RERANK_CANDIDATES = 20
+RERANK_TEXT_CHARS = 500
+RERANK_REQUESTS = 2
+RERANK_DEADLINE_S = 2.0
+
+_QUESTION = "Does `observations.{key}` describe a session that matches what `search` looks for?"
+_CRITERIA_TRUE = "The session shows the thing the search describes actually happening."
+_CRITERIA_FALSE = "The observation only shares the topic, says the thing did not happen, or describes something else."
+
+# Shared so a search does not pay thread start-up. A timed-out request keeps its worker until the HTTP timeout
+# frees it, so the pool is sized for several searches whose requests overlap.
+_EXECUTOR = ThreadPoolExecutor(max_workers=16, thread_name_prefix="replay-vision-rerank")
+
+
+@dataclass(frozen=True)
+class RerankCandidate:
+ observation_id: str
+ text: str
+
+
+@dataclass(frozen=True)
+class RerankOutcome:
+ order: list[str]
+ reranked: bool
+
+
+def _score_chunk(client: SystemOneClient, query: str, chunk: Sequence[RerankCandidate]) -> dict[str, float]:
+ # User and observation text stays in `state`, because interpolating it into `instructions` would let it act
+ # as an instruction.
+ observations: dict[str, JsonValue] = {f"o{i}": c.text[:RERANK_TEXT_CHARS] for i, c in enumerate(chunk)}
+ state: JsonValue = {"search": query, "observations": observations}
+ questions = {
+ f"q{i}": NoulQuestion(
+ instructions=_QUESTION.format(key=f"o{i}"),
+ criteria_true=_CRITERIA_TRUE,
+ criteria_false=_CRITERIA_FALSE,
+ )
+ for i in range(len(chunk))
+ }
+ result = client.decide(state=state, questions=questions)
+ scores: dict[str, float] = {}
+ for i, candidate in enumerate(chunk):
+ answer = result.answers[f"q{i}"]
+ if not isinstance(answer, NoulAnswer):
+ raise ValueError(f"expected a yes/no answer for q{i}")
+ scores[candidate.observation_id] = answer.probability
+ return scores
+
+
+def _outcome(outcome: str, order: list[str], started: float) -> RerankOutcome:
+ record_search_rerank(outcome, time.monotonic() - started)
+ return RerankOutcome(order=order, reranked=outcome == "reranked")
+
+
+def rerank(query: str, candidates: Sequence[RerankCandidate], *, team_id: int) -> RerankOutcome:
+ """Reorder `candidates`, which arrive in embedding order, by the model's match probability. The sort is stable,
+ so equal probabilities keep embedding order. The caller passes only the head it wants reranked."""
+ embedding_order = [c.observation_id for c in candidates]
+ if len(candidates) < 2:
+ return RerankOutcome(order=embedding_order, reranked=False)
+ started = time.monotonic()
+ try:
+ client = build_system_one_client(
+ model=RERANK_MODEL,
+ ai_product="replay_vision",
+ distinct_id=team_distinct_id(team_id),
+ timeout=RERANK_DEADLINE_S,
+ )
+ except SystemOneNotConfigured:
+ return _outcome("not_configured", embedding_order, started)
+ # Interleaved chunks give each request a similar spread of close and far candidates.
+ chunks = [chunk for chunk in (candidates[i::RERANK_REQUESTS] for i in range(RERANK_REQUESTS)) if chunk]
+ futures = [_EXECUTOR.submit(copy_context().run, _score_chunk, client, query, chunk) for chunk in chunks]
+ done, pending = wait(futures, timeout=RERANK_DEADLINE_S)
+ if pending:
+ for future in pending:
+ future.cancel()
+ logger.warning("replay_vision.search_rerank.timeout", team_id=team_id)
+ return _outcome("timeout", embedding_order, started)
+ scores: dict[str, float] = {}
+ for future in done:
+ try:
+ scores.update(future.result())
+ except Exception:
+ logger.warning("replay_vision.search_rerank.failed", team_id=team_id, exc_info=True)
+ return _outcome("error", embedding_order, started)
+ return _outcome("reranked", sorted(embedding_order, key=lambda observation_id: -scores[observation_id]), started)
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index 21ea777fd85b..f6723d081520 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -207,6 +207,19 @@ REPLAY_VISION_GEMINI_CLEANUP_BACKLOG = Gauge(
)
+REPLAY_VISION_SEARCH_RERANK = Counter(
+ "replay_vision_search_rerank_total",
+ "Observation searches by rerank outcome",
+ ["outcome"],
+)
+
+REPLAY_VISION_SEARCH_RERANK_LATENCY = Histogram(
+ "replay_vision_search_rerank_latency_seconds",
+ "Wall-clock time a search waited on the rerank model",
+ buckets=(0.1, 0.2, 0.3, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5),
+)
+
+
def record_observation(status: str, scanner_type: str) -> None:
labels = {"status": status, "scanner_type": scanner_type}
REPLAY_VISION_OBSERVATIONS.labels(**labels).inc()
@@ -357,3 +370,10 @@ def record_enqueue_claim_failure(operation: str) -> None:
def record_gemini_cleanup_backlog(count: int) -> None:
REPLAY_VISION_GEMINI_CLEANUP_BACKLOG.set(count)
_otel.record_gauge_twin(REPLAY_VISION_GEMINI_CLEANUP_BACKLOG, count)
+
+
+def record_search_rerank(outcome: str, seconds: float) -> None:
+ REPLAY_VISION_SEARCH_RERANK.labels(outcome=outcome).inc()
+ _otel.record_counter_twin(REPLAY_VISION_SEARCH_RERANK, 1, {"outcome": outcome})
+ REPLAY_VISION_SEARCH_RERANK_LATENCY.observe(seconds)
+ _otel.record_histogram_twin(REPLAY_VISION_SEARCH_RERANK_LATENCY, seconds, {})
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index f19033ac6968..0fdf4083636d 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -21,6 +21,7 @@ from posthog.schema import ProductIntentContext, ProductKey
from posthog.api.tagged_item import set_tags_on_object
from posthog.event_usage import EventSource
+from posthog.llm.system_one import NoulAnswer, SystemOneResult
from posthog.models import Organization, PersonalAPIKey, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog, changes_between, replay_scanner_machine_fields
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
@@ -3575,6 +3576,46 @@ class TestObservationSearchAction(_VisionAPITestCase):
)
self.assertFalse(resp.json()["truncated"])
+ @patch("products.replay_vision.backend.search.RERANK_CANDIDATES", 2)
+ @patch("products.replay_vision.backend.search_rerank.build_system_one_client")
+ @patch("products.replay_vision.backend.search.rank_observations")
+ @patch("products.replay_vision.backend.search.generate_embedding")
+ def test_search_reranks_only_readable_results(
+ self, mock_embed: MagicMock, mock_rank: MagicMock, mock_client: MagicMock
+ ) -> None:
+ first = self._create_succeeded_observation("sess-1")
+ second = self._create_succeeded_observation("sess-2")
+ tail = self._create_succeeded_observation("sess-3")
+ ReplayObservation.objects.filter(pk=second.id).update(scanner_result={"model_output": {"reasoning": "exact"}})
+ mock_embed.return_value = MagicMock(embedding=[0.1])
+ mock_rank.return_value = [
+ ObservationMatch(observation_id=str(first.id), distance=0.1, matched_content="topic only"),
+ ObservationMatch(observation_id=str(uuid7()), distance=0.2, matched_content="unreadable"),
+ ObservationMatch(observation_id=str(second.id), distance=0.3, matched_content="bare tag"),
+ ObservationMatch(observation_id=str(tail.id), distance=0.4, matched_content="past the head"),
+ ]
+ sent_texts: list[str] = []
+
+ def decide(*, state: dict, questions: dict) -> SystemOneResult:
+ texts = [state["observations"][f"o{i}"] for i in range(len(questions))]
+ sent_texts.extend(texts)
+ return SystemOneResult(
+ model="jev",
+ answers={f"q{i}": NoulAnswer(probability=0.9 if t == "exact" else 0.1) for i, t in enumerate(texts)},
+ input_tokens=1,
+ )
+
+ mock_client.return_value.decide.side_effect = decide
+
+ resp = self.client.get(f"{self.search_url}?q=confused users")
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(
+ [r["observation"]["id"] for r in resp.json()["results"]], [str(second.id), str(first.id), str(tail.id)]
+ )
+ self.assertTrue(resp.json()["reranked"])
+ self.assertEqual(sorted(sent_texts), ["exact", "topic only"])
+
@patch("products.replay_vision.backend.search.rank_observations")
@patch("products.replay_vision.backend.search.generate_embedding")
def test_search_overfetches_then_slices_to_limit_and_flags_truncation(
diff --git a/products/replay_vision/backend/tests/test_search.py b/products/replay_vision/backend/tests/test_search.py
index cc3e1b46c291..2f1eff78eb50 100644
--- a/products/replay_vision/backend/tests/test_search.py
+++ b/products/replay_vision/backend/tests/test_search.py
@@ -25,6 +25,7 @@ from products.replay_vision.backend.search import (
parse_date_bound,
query_vector_for,
rank_observations,
+ warm_query_vectors,
)
from products.replay_vision.backend.tests.helpers import snapshot_for
@@ -297,3 +298,9 @@ class TestQueryVectorCache(APIBaseTest):
self.assertEqual(query_vector_for(self.team, "confused users"), [0.1, 0.2])
query_vector_for(self.team, "happy users")
self.assertEqual(mock_embed.call_count, 2)
+
+ for future in warm_query_vectors(self.team, ["confused users", "gave up at checkout"]):
+ future.result(timeout=5)
+ self.assertEqual(mock_embed.call_count, 3)
+ query_vector_for(self.team, "gave up at checkout")
+ self.assertEqual(mock_embed.call_count, 3)
diff --git a/products/replay_vision/backend/tests/test_search_rerank.py b/products/replay_vision/backend/tests/test_search_rerank.py
new file mode 100644
index 000000000000..5c3612a68b3d
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_search_rerank.py
@@ -0,0 +1,90 @@
+import threading
+from collections.abc import Mapping
+
+from unittest.mock import MagicMock, patch
+
+from posthog.llm.system_one import (
+ JsonValue,
+ NoulAnswer,
+ Question,
+ SystemOneNotConfigured,
+ SystemOneRequestFailed,
+ SystemOneResult,
+)
+
+from products.replay_vision.backend.search_rerank import RerankCandidate, rerank
+
+
+class _FakeClient:
+ def __init__(self, probability_by_text: Mapping[str, float], block: threading.Event | None = None) -> None:
+ self.probability_by_text = probability_by_text
+ self.block = block
+ self.seen_texts: list[str] = []
+
+ def decide(self, *, state: JsonValue, questions: Mapping[str, Question]) -> SystemOneResult:
+ if self.block is not None:
+ self.block.wait(timeout=5)
+ assert isinstance(state, dict)
+ observations = state["observations"]
+ assert isinstance(observations, dict)
+ texts = [str(observations[f"o{i}"]) for i in range(len(questions))]
+ self.seen_texts.extend(texts)
+ return SystemOneResult(
+ model="jev",
+ answers={f"q{i}": NoulAnswer(probability=self.probability_by_text[text]) for i, text in enumerate(texts)},
+ input_tokens=1,
+ )
+
+
+def _candidates(*texts: str) -> list[RerankCandidate]:
+ return [RerankCandidate(observation_id=text, text=text) for text in texts]
+
+
+class TestRerank:
+ def test_orders_by_probability_and_keeps_embedding_order_on_ties(self) -> None:
+ candidates = _candidates("a", "b", "c", "d")
+ client = _FakeClient({"a": 0.2, "b": 0.9, "c": 0.9, "d": 0.95})
+
+ with patch("products.replay_vision.backend.search_rerank.build_system_one_client", return_value=client):
+ outcome = rerank("gave up at checkout", candidates, team_id=1)
+
+ assert outcome.reranked
+ assert outcome.order == ["d", "b", "c", "a"]
+ assert sorted(client.seen_texts) == ["a", "b", "c", "d"]
+
+ def test_falls_back_to_embedding_order_when_no_gateway_is_configured(self) -> None:
+ with patch(
+ "products.replay_vision.backend.search_rerank.build_system_one_client",
+ side_effect=SystemOneNotConfigured("no gateway"),
+ ):
+ outcome = rerank("gave up at checkout", _candidates("a", "b", "c"), team_id=1)
+
+ assert not outcome.reranked
+ assert outcome.order == ["a", "b", "c"]
+
+ def test_falls_back_to_embedding_order_when_the_gateway_errors(self) -> None:
+ client = MagicMock()
+ client.decide.side_effect = SystemOneRequestFailed("HTTP 502", status_code=502)
+
+ with patch("products.replay_vision.backend.search_rerank.build_system_one_client", return_value=client):
+ outcome = rerank("gave up at checkout", _candidates("a", "b", "c"), team_id=1)
+
+ assert not outcome.reranked
+ assert outcome.order == ["a", "b", "c"]
+
+ def test_falls_back_to_embedding_order_when_the_model_misses_the_deadline(self) -> None:
+ candidates = _candidates("a", "b", "c")
+ release = threading.Event()
+ client = _FakeClient({"a": 0.1, "b": 0.5, "c": 0.9}, block=release)
+
+ try:
+ with (
+ patch("products.replay_vision.backend.search_rerank.RERANK_DEADLINE_S", 0.05),
+ patch("products.replay_vision.backend.search_rerank.build_system_one_client", return_value=client),
+ ):
+ outcome = rerank("gave up at checkout", candidates, team_id=1)
+ finally:
+ release.set()
+
+ assert not outcome.reranked
+ assert outcome.order == ["a", "b", "c"]
diff --git a/products/replay_vision/backend/tests/test_search_suggestions.py b/products/replay_vision/backend/tests/test_search_suggestions.py
index f47e1cb02778..fcbe55124962 100644
--- a/products/replay_vision/backend/tests/test_search_suggestions.py
+++ b/products/replay_vision/backend/tests/test_search_suggestions.py
@@ -1,11 +1,13 @@
import uuid
import datetime as dt
-from unittest.mock import MagicMock, patch
+from unittest.mock import ANY, MagicMock, patch
from django.core.cache import cache
from django.utils import timezone
+from parameterized import parameterized
+
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -244,12 +246,22 @@ class TestSearchSuggestionsEndpoint(_SuggestionsTestCase):
self.assertIsNone(scanner.search_last_viewed_at)
mock_generate.assert_not_called()
- def test_posting_a_view_stamps_the_scope(self) -> None:
- scanner = self._scanner("checkout")
+ @parameterized.expand([("ai_processing_on", True), ("ai_processing_off", False)])
+ @patch("products.replay_vision.backend.api.observations.warm_query_vectors")
+ def test_posting_a_view_stamps_the_scope_and_warms_its_suggestions(
+ self, _name: str, ai_processing_approved: bool, mock_warm: MagicMock
+ ) -> None:
+ self.organization.is_ai_data_processing_approved = ai_processing_approved
+ self.organization.save()
+ scanner = self._scanner("checkout", search_suggestions=["coupon rejected at checkout"])
resp = self.client.post(self.viewed_url, {"scanner_id": str(scanner.id)}, format="json")
self.assertEqual(resp.status_code, 204)
scanner.refresh_from_db()
self.assertIsNotNone(scanner.search_last_viewed_at)
+ if ai_processing_approved:
+ mock_warm.assert_called_once_with(ANY, ["coupon rejected at checkout"])
+ else:
+ mock_warm.assert_not_called()
def test_a_scanner_with_nothing_stored_is_an_empty_list(self) -> None:
scanner = self._scanner("new")
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 4580d800966d..8dc0e34840e6 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -894,6 +894,8 @@ export interface ObservationSearchResponseApi {
results: ObservationSearchResultApi[]
/** True when more matches may exist beyond `results`, so the response is a top slice rather than everything that matched. */
truncated: boolean
+ /** True when a relevance model reordered the top results after the embedding match. False when the results are in embedding distance order, for example because the model did not answer in time. */
+ reranked: boolean
}
export interface SearchSuggestionsResponseApi {
diff --git a/products/replay_vision/frontend/search/SearchResults.tsx b/products/replay_vision/frontend/search/SearchResults.tsx
index 3afe3c903950..94aa1c0b32da 100644
--- a/products/replay_vision/frontend/search/SearchResults.tsx
+++ b/products/replay_vision/frontend/search/SearchResults.tsx
@@ -25,6 +25,7 @@ import {
type ObservationSearchLogicProps,
type ResultsView,
SEARCH_PAGE_SIZE,
+ type SearchResultTarget,
observationSearchLogic,
} from './observationSearchLogic'
import { snippetSegments } from './snippetSegments'
@@ -51,16 +52,19 @@ interface ResultProps {
returnParams: Record<string, string>
/** True once the recordings API confirmed this result's recording no longer exists. */
expired: boolean
+ onOpen: (target: SearchResultTarget) => void
}
function WatchLink({
observation,
expired,
compact,
+ onOpen,
}: {
observation: ReplayObservationApi
expired: boolean
compact?: boolean
+ onOpen: (target: SearchResultTarget) => void
}): JSX.Element {
const routerValues = useValues(router)
const citedMs = firstCitedTimestampMs(observation)
@@ -95,6 +99,7 @@ function WatchLink({
return (
<Link
to={watchMomentUrl(observation, citedMs, routerValues)}
+ onClick={() => onOpen('watch')}
className={clsx('relative block text-primary group', compact && 'w-28')}
data-attr="vision-search-result-watch"
>
@@ -184,6 +189,7 @@ function MomentCard({
searchedQuery,
returnParams,
expired,
+ onOpen,
tier,
}: ResultProps & { tier: Tier | null }): JSX.Element {
const observation = result.observation
@@ -191,7 +197,7 @@ function MomentCard({
return (
<LemonCard className="flex flex-col rounded-lg p-0 overflow-hidden" data-attr="vision-search-result">
<div className="relative">
- <WatchLink observation={observation} expired={expired} />
+ <WatchLink observation={observation} expired={expired} onOpen={onOpen} />
<span className="absolute top-2 left-2 flex items-center gap-1">
{snapshot && <ScannerOutputBadge scannerType={snapshot.scanner_type} size="small" />}
{tier === 'top' && <TopMatchTag />}
@@ -210,6 +216,7 @@ function MomentCard({
<SubjectLink observation={observation} />
<Link
to={observationDetailUrl(observation.id, returnParams)}
+ onClick={() => onOpen('detail')}
className="ml-auto shrink-0"
data-attr="vision-search-result-detail"
>
@@ -221,13 +228,13 @@ function MomentCard({
)
}
-function MomentRow({ result, searchedQuery, returnParams, expired }: ResultProps): JSX.Element {
+function MomentRow({ result, searchedQuery, returnParams, expired, onOpen }: ResultProps): JSX.Element {
const observation = result.observation
const snapshot = observation.scanner_snapshot
return (
<LemonCard className="flex gap-3 rounded-lg p-2 min-w-0" data-attr="vision-search-result">
<div className="shrink-0 self-center">
- <WatchLink observation={observation} expired={expired} compact />
+ <WatchLink observation={observation} expired={expired} compact onOpen={onOpen} />
</div>
<div className="flex flex-col gap-1 min-w-0 flex-1">
<div className="flex items-center gap-2 min-w-0">
@@ -238,6 +245,7 @@ function MomentRow({ result, searchedQuery, returnParams, expired }: ResultProps
<TZLabel time={observation.created_at} />
<Link
to={observationDetailUrl(observation.id, returnParams)}
+ onClick={() => onOpen('detail')}
data-attr="vision-search-result-detail"
>
Details
@@ -317,7 +325,7 @@ export function SearchResults(logicProps: ObservationSearchLogicProps): JSX.Elem
scannerId,
sourceObservationId,
truncated,
- topMatchDistanceCutoff,
+ topMatchIds,
view,
page,
pageCount,
@@ -326,14 +334,14 @@ export function SearchResults(logicProps: ObservationSearchLogicProps): JSX.Elem
pageEndIndex,
expiredSessionIds,
} = useValues(logic)
- const { setPage, setView } = useActions(logic)
+ const { setPage, setView, resultOpened } = useActions(logic)
if (!searching && (!results || results.length === 0)) {
return null
}
const returnParams = searchReturnParams(searchedQuery ?? '', scannerId, sourceObservationId)
const tierOf = (result: ObservationSearchResultApi): Tier | null =>
- topMatchDistanceCutoff === null ? null : result.distance <= topMatchDistanceCutoff ? 'top' : 'other'
+ topMatchIds === null ? null : topMatchIds.has(result.observation.id) ? 'top' : 'other'
return (
<div className="flex flex-col">
<div className="flex items-center gap-2 mb-1">
@@ -370,6 +378,7 @@ export function SearchResults(logicProps: ObservationSearchLogicProps): JSX.Elem
searchedQuery={searchedQuery ?? ''}
returnParams={returnParams}
expired={expiredSessionIds.has(result.observation.session_id)}
+ onOpen={(target) => resultOpened(result.observation.id, target)}
tier={tierOf(result)}
/>
))}
@@ -385,6 +394,7 @@ export function SearchResults(logicProps: ObservationSearchLogicProps): JSX.Elem
searchedQuery={searchedQuery ?? ''}
returnParams={returnParams}
expired={expiredSessionIds.has(result.observation.session_id)}
+ onOpen={(target) => resultOpened(result.observation.id, target)}
/>
))}
</div>
diff --git a/products/replay_vision/frontend/search/observationSearchLogic.test.ts b/products/replay_vision/frontend/search/observationSearchLogic.test.ts
index a41b91f8aee7..cbdcb1e5b2b8 100644
--- a/products/replay_vision/frontend/search/observationSearchLogic.test.ts
+++ b/products/replay_vision/frontend/search/observationSearchLogic.test.ts
@@ -164,14 +164,14 @@ describe('observationSearchLogic', () => {
})
it.each([
- ['spread distances split off a top tier', [0.1, 0.12, 0.4], expect.closeTo(0.15)],
- ['clustered distances stay one tier', [0.1, 0.12, 0.14], null],
- ])('%s', (_name, distances, expectedCutoff) => {
+ ['the first three in rank order are top matches', [0.4, 0.1, 0.12, 0.14], new Set(['obs-0', 'obs-1', 'obs-2'])],
+ ['three or fewer results stay one tier', [0.1, 0.12, 0.4], null],
+ ])('%s', (_name, distances, expectedTopMatchIds) => {
const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })
logic.mount()
logic.actions.searchSuccess(searchResults(distances), 'query', false)
- expect(logic.values.topMatchDistanceCutoff).toEqual(expectedCutoff)
+ expect(logic.values.topMatchIds).toEqual(expectedTopMatchIds)
logic.unmount()
})
@@ -278,6 +278,26 @@ describe('observationSearchLogic', () => {
logic.unmount()
})
+ it('opening a result captures its rank and whether the order was reranked', () => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
+ const logic = observationSearchLogic({ teamId: 1, userId: 'user-1' })
+ logic.mount()
+ logic.actions.searchSuccess(searchResults([0.1, 0.2, 0.3]), 'query', false, null, true)
+
+ logic.actions.resultOpened('obs-1', 'watch')
+
+ expect(captureSpy).toHaveBeenCalledWith('replay vision observation search result opened', {
+ rank: 2,
+ target: 'watch',
+ reranked: true,
+ result_count: 3,
+ scope: 'cross-scanner',
+ similar_search: false,
+ })
+ captureSpy.mockRestore()
+ logic.unmount()
+ })
+
it('a superseded failure is dropped, so the rate counts only the searches a person waited for', async () => {
let releaseFirst: () => void = () => {}
const firstHeld = new Promise<void>((resolve) => (releaseFirst = resolve))
diff --git a/products/replay_vision/frontend/search/observationSearchLogic.ts b/products/replay_vision/frontend/search/observationSearchLogic.ts
index 7bed9ae3f618..5c4f59240055 100644
--- a/products/replay_vision/frontend/search/observationSearchLogic.ts
+++ b/products/replay_vision/frontend/search/observationSearchLogic.ts
@@ -37,8 +37,9 @@ const SEARCH_RESULT_LIMIT = 50
// Client-side paging over the single ranked response. Not in the URL, where the observations table owns `page`.
export const SEARCH_PAGE_SIZE = 9
-// Relative to the best match, because distances are only comparable within one response.
-const TOP_MATCH_MARGIN = 0.05
+export type SearchResultTarget = 'watch' | 'detail'
+
+const TOP_MATCH_COUNT = 3
// The server's error code when the organization has not allowed AI data processing.
const AI_CONSENT_REQUIRED_CODE = 'ai_data_processing_not_approved'
const RECENT_QUERIES_LIMIT = 3
@@ -67,6 +68,7 @@ export interface observationSearchLogicValues {
pendingSourceObservationId: string | null
query: string
recentQueries: string[]
+ reranked: boolean
results: ObservationSearchResultApi[] | null
scannerId: string | null
searchedQuery: string | null
@@ -74,7 +76,7 @@ export interface observationSearchLogicValues {
sourceObservationId: string | null
suggestedQueries: string[]
suggestedQueriesLoading: boolean
- topMatchDistanceCutoff: number | null
+ topMatchIds: Set<string> | null
truncated: boolean
unavailableSessionIds: string[]
unavailableSessionIdsLoading: boolean
@@ -116,6 +118,13 @@ export interface observationSearchLogicActions {
suggestedQueries: string[]
payload?: void
}
+ resultOpened: (
+ observationId: string,
+ target: SearchResultTarget
+ ) => {
+ observationId: string
+ target: SearchResultTarget
+ }
search: () => {
value: true
}
@@ -133,9 +142,11 @@ export interface observationSearchLogicActions {
results: ObservationSearchResultApi[],
query: string,
truncated: boolean,
- sourceObservationId?: string | null
+ sourceObservationId?: string | null,
+ reranked?: boolean
) => {
query: string
+ reranked: boolean
results: ObservationSearchResultApi[]
sourceObservationId: string | null
truncated: boolean
@@ -170,7 +181,7 @@ export interface observationSearchLogicMeta {
pageResults: (results: ObservationSearchResultApi[] | null, page: number) => ObservationSearchResultApi[]
pageStartIndex: (page: number) => number
pageEndIndex: (pageStartIndex: number, pageResults: ObservationSearchResultApi[]) => number
- topMatchDistanceCutoff: (results: ObservationSearchResultApi[] | null) => number | null
+ topMatchIds: (results: ObservationSearchResultApi[] | null) => Set<string> | null
}
}
@@ -185,14 +196,24 @@ export type observationSearchLogicType = MakeLogicType<
// The `q` URL parameter still reaches analytics through `$current_url`, as it does for every event on this page.
function captureSearchOutcome(
scannerId: string | null,
- outcome: { succeeded: boolean; result_count?: number; error_status?: number; error_code?: string }
+ outcome: {
+ succeeded: boolean
+ result_count?: number
+ reranked?: boolean
+ error_status?: number
+ error_code?: string
+ }
): void {
posthog.capture('replay vision observation search completed', {
...outcome,
- scope: scannerId ? 'scanner' : 'cross-scanner',
+ scope: searchScope(scannerId),
})
}
+function searchScope(scannerId: string | null): 'scanner' | 'cross-scanner' {
+ return scannerId ? 'scanner' : 'cross-scanner'
+}
+
export const observationSearchLogic = kea<observationSearchLogicType>([
path(['products', 'replay_vision', 'frontend', 'search', 'observationSearchLogic']),
props({} as ObservationSearchLogicProps),
@@ -215,13 +236,16 @@ export const observationSearchLogic = kea<observationSearchLogicType>([
results: ObservationSearchResultApi[],
query: string,
truncated: boolean,
- sourceObservationId: string | null = null
+ sourceObservationId: string | null = null,
+ reranked: boolean = false
) => ({
results,
query,
truncated,
sourceObservationId,
+ reranked,
}),
+ resultOpened: (observationId: string, target: SearchResultTarget) => ({ observationId, target }),
searchFailure: true,
clearSearch: true,
}),
@@ -327,6 +351,13 @@ export const observationSearchLogic = kea<observationSearchLogicType>([
clearSearch: () => false,
},
],
+ reranked: [
+ false,
+ {
+ searchSuccess: (_, { reranked }) => reranked,
+ clearSearch: () => false,
+ },
+ ],
// Stale confirmations must not tag the next search's results while its own check is in flight.
unavailableSessionIds: [
[] as string[],
@@ -415,15 +446,12 @@ export const observationSearchLogic = kea<observationSearchLogicType>([
pageStartIndex + pageResults.length,
],
// Null when the tiers would not separate anything, so a lone tier is never labeled.
- topMatchDistanceCutoff: [
+ topMatchIds: [
(s) => [s.results],
- (results: ObservationSearchResultApi[] | null): number | null => {
- if (!results || results.length < 2) {
- return null
- }
- const cutoff = Math.min(...results.map((r) => r.distance)) + TOP_MATCH_MARGIN
- return results.some((r) => r.distance > cutoff) ? cutoff : null
- },
+ (results: ObservationSearchResultApi[] | null): Set<string> | null =>
+ results && results.length > TOP_MATCH_COUNT
+ ? new Set(results.slice(0, TOP_MATCH_COUNT).map((result) => result.observation.id))
+ : null,
],
}),
@@ -453,6 +481,21 @@ export const observationSearchLogic = kea<observationSearchLogicType>([
actions.checkRecordingAvailability(sessionIds)
},
searchSimilar: () => actions.search(),
+ // Rank against `reranked` tells whether the reranked order puts the results people open higher.
+ resultOpened: ({ observationId, target }) => {
+ const index = values.results?.findIndex((result) => result.observation.id === observationId) ?? -1
+ if (index < 0) {
+ return
+ }
+ posthog.capture('replay vision observation search result opened', {
+ rank: index + 1,
+ target,
+ reranked: values.reranked,
+ result_count: values.results?.length ?? 0,
+ scope: searchScope(values.scannerId),
+ similar_search: values.sourceObservationId !== null,
+ })
+ },
search: async (_, breakpoint) => {
await breakpoint(SEARCH_COALESCE_MS)
const query = values.query.trim()
@@ -478,12 +521,13 @@ export const observationSearchLogic = kea<observationSearchLogicType>([
breakpoint()
// The source of a "find similar" search is its own nearest neighbour.
const results = (response.results ?? []).filter((r) => r.observation.id !== sourceObservationId)
- captureSearchOutcome(values.scannerId, { succeeded: true, result_count: results.length })
+ const reranked = response.reranked ?? false
+ captureSearchOutcome(values.scannerId, { succeeded: true, result_count: results.length, reranked })
// Cleared while in flight: the late response must not refill the card.
if (!values.searching) {
return
}
- actions.searchSuccess(results, query, response.truncated ?? false, sourceObservationId)
+ actions.searchSuccess(results, query, response.truncated ?? false, sourceObservationId, reranked)
} catch (error: any) {
if (error instanceof Error && isBreakpoint(error)) {
throw error
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7e2b015bf8d8..688cffd4e980 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -62058,6 +62058,8 @@ export namespace Schemas {
results: ObservationSearchResult[];
/** True when more matches may exist beyond `results`, so the response is a top slice rather than everything that matched. */
truncated: boolean;
+ /** True when a relevance model reordered the top results after the embedding match. False when the results are in embedding distance order, for example because the model did not answer in time. */
+ reranked: boolean;
}
/**