: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
fix(replay-vision): bound the embedding read for observation search (#105036)
Hayne Ryu2a0c3312032c
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex c2f73e8df75f..49604eba6ffc 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -1568,7 +1568,6 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):)response = search_observations(self.team,- cast(User, request.user),self.user_access_control,scanner_ids,query_vector,diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex ebc8da5b8759..4d1083dcb790 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -500,10 +500,8 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):"""Sync ClickHouse rank + ORM fetch + format — runs after the embedding HTTP call has resolved."""empty = (f"No recordings from {scope_label} matched that search yet.", {"result_count": 0})- # Filter + rank in one ClickHouse query: the structured outcome filters run against the embedding- # metadata, so the semantic ranking only ever sees recordings that already match the exact outcome.response = search_observations(- self._team, self._user, self.user_access_control, scanner_ids, query_vector, capped_limit, filters+ self._team, self.user_access_control, scanner_ids, query_vector, capped_limit, filters)lines: list[str] = []diff --git a/products/replay_vision/backend/search.py b/products/replay_vision/backend/search.pyindex 59e0f02ae0fe..574479f28e2a 100644--- a/products/replay_vision/backend/search.py+++ b/products/replay_vision/backend/search.py@@ -2,8 +2,8 @@The write side (`embed_observation`) stamps each embedding row with the scanner id and the structuredoutcome (monitor `verdict`, scorer `score`, classifier `tags`), so filtering and cosine ranking happen in-a single ClickHouse query here. Callers resolve scanner scope and access control themselves and pass the-readable scanner ids in.+ClickHouse here. Callers resolve scanner scope and access control themselves and pass the readable+scanner ids in."""import hashlib@@ -18,14 +18,11 @@ from django.db.models import Fimport requestsfrom asgiref.sync import sync_to_async-from posthog.hogql import ast-from posthog.hogql.query import execute_hogql_query-from posthog.api.embedding_worker import generate_embedding+from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import ClickHouseUser-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.team import Team-from posthog.models.user import Userfrom posthog.utils import relative_date_parse_with_delta_mappingfrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -67,12 +64,20 @@ _EMBEDDING_TIMEOUT_S = 10.0# ranks over. Set well above realistic per-team volume so it only bites a runaway team, keeping latency# predictable without an HNSW index (which our mandatory tenant/scanner metadata filters wouldn't engage anyway)._MAX_CANDIDATE_ROWS = 50_000+_QUERY_TIMEOUT_S = 60++_EMBEDDINGS_TABLE = f"distributed_posthog_document_embeddings_{OBSERVATION_EMBEDDING_MODEL.value.replace('-', '_')}"+_SCOPE_PREWHERE = """team_id = %(team_id)s+ AND product = %(product)s+ AND document_type = %(document_type)s+ AND JSONExtractString(metadata, 'scanner_id') IN %(scanner_ids)s"""+_CANDIDATE_QUERY_TYPE = "replay_vision_search_candidates"+_RANK_QUERY_TYPE = "replay_vision_search_rank"# Slugify each stored metadata tag before `hasAny`, so the case/format-insensitive match works against rows-# whose fixed-vocab tags were stamped verbatim, with no backfill. The caller passes already-slugified values in-# `{tags}`. Built from hardcoded literals only (no user/LLM input), preserving the `_append_filter` invariant.+# whose fixed-vocab tags were stamped verbatim, with no backfill. Static literals only, see `_append_filter`._TAGS_FILTER_CLAUSE = (- f"hasAny(arrayMap(t -> {clickhouse_slugify_sql('t')}, JSONExtract(metadata, 'tags', 'Array(String)')), {{tags}})"+ f"hasAny(arrayMap(t -> {clickhouse_slugify_sql('t')}, JSONExtract(metadata, 'tags', 'Array(String)')), %(tags)s)")@@ -123,133 +128,150 @@ class ObservationSearchFilters:date_to=parse_date_bound(date_to, timezone_info, end_of_range=True) if date_to else None,)- def where_clauses(self, placeholders: dict[str, "ast.Expr"]) -> list[str]:- """HogQL predicates over `metadata`, registering their values into `placeholders`. The metadata key is- absent for scanner types that don't carry it, so each predicate naturally matches only the right type.+ def where_clauses(self, params: dict[str, Any]) -> list[str]:+ """ClickHouse predicates over `metadata`, registering their values into `params` as `%(name)s` query+ parameters. The metadata key is absent for scanner types that don't carry it, so each predicate+ naturally matches only the right type.Every clause MUST be added via `_append_filter`, the only path that pairs a hardcoded-literal- clause string with a parameterized placeholder. Never append a clause built from anything other- than a static string literal. User/LLM-controlled input belongs in `value`, not in `clause`."""+ clause string with a query parameter. Never append a clause built from anything other than a+ static string literal. User/LLM-controlled input belongs in `value`, not in `clause`."""clauses: list[str] = []if self.verdict:self._append_filter(- clauses, placeholders, "verdict", self.verdict, "JSONExtractString(metadata, 'verdict') IN {verdict}"+ clauses, params, "verdict", self.verdict, "JSONExtractString(metadata, 'verdict') IN %(verdict)s")if self.tags:- self._append_filter(clauses, placeholders, "tags", self.tags, _TAGS_FILTER_CLAUSE)+ self._append_filter(clauses, params, "tags", self.tags, _TAGS_FILTER_CLAUSE)if self.min_score is not None:self._append_filter(clauses,- placeholders,+ params,"min_score",self.min_score,- "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') >= {min_score}",+ "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') >= %(min_score)s",)if self.max_score is not None:self._append_filter(clauses,- placeholders,+ params,"max_score",self.max_score,- "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') <= {max_score}",+ "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') <= %(max_score)s",)# `timestamp` is when the observation was embedded, which tracks when it was created.if self.date_from is not None:- self._append_filter(clauses, placeholders, "date_from", self.date_from, "timestamp >= {date_from}")+ self._append_filter(clauses, params, "date_from", self.date_from, "timestamp >= %(date_from)s")if self.date_to is not None:- self._append_filter(clauses, placeholders, "date_to", self.date_to, "timestamp <= {date_to}")+ self._append_filter(clauses, params, "date_to", self.date_to, "timestamp <= %(date_to)s")return clauses@staticmethoddef _append_filter(clauses: list[str],- placeholders: dict[str, "ast.Expr"],+ params: dict[str, Any],key: str,value: Any,clause: str,) -> None:- """Register one filter atomically: the value goes into `placeholders` (parameterized), the clause is- the hardcoded literal that references it. The structure/value split lives in one place so callers- can't half-do it. Any future filter must come through here, which makes the "clause is a static- literal" invariant impossible to break by accident."""- placeholders[key] = ast.Constant(value=value)+ """Register one filter atomically: the value goes into `params` (parameterized), the clause is the+ hardcoded literal that references it. The structure/value split lives in one place so callers can't+ half-do it. Any future filter must come through here, which makes the "clause is a static literal"+ invariant impossible to break by accident."""+ params[key] = valueclauses.append(clause)def rank_observations(team: Team,- user: User,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, so filter and rank happen in a single query.+ 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 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 eachobservation appears once. Only rows written before summarizers embedded one document per observationhave several renderings; once those age past the candidate cap the GROUP BY can go.-- The distance scan is exact (brute-force), so we bound it: the inner query takes the most recent- `_MAX_CANDIDATE_ROWS` matching embedding rows before ranking. Below that volume (all teams at launch- scale) it's a no-op. A high-volume team is capped to its most recent embeddings, keeping latency- predictable at the cost of not ranking its oldest observations."""- placeholders: dict[str, ast.Expr] = {- "embedding": ast.Constant(value=query_vector),- "model_name": ast.Constant(value=OBSERVATION_EMBEDDING_MODEL.value),- "product": ast.Constant(value=EMBEDDING_PRODUCT),- "document_type": ast.Constant(value=EMBEDDING_DOCUMENT_TYPE),- "team_id": ast.Constant(value=team.id),- "scanner_ids": ast.Constant(value=scanner_ids),- "candidate_cap": ast.Constant(value=_MAX_CANDIDATE_ROWS),- "limit": ast.Constant(value=limit),- "snippet_chars": ast.Constant(value=_MATCHED_CONTENT_MAX_CHARS),- "max_distance": ast.Constant(value=MAX_MATCH_DISTANCE),+ 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,}- filter_clause = "".join(f"\n AND {clause}" for clause in filters.where_clauses(placeholders))- # The distance layer wraps the capped candidate subquery so the 3072-dim dot product runs once per- # candidate row (min and argMin share the alias) and never on rows the cap already discarded. The ceiling- # sits on that layer too, so the aggregate only ever sees rows that are matches.- hogql_query = f"""- SELECT- document_id,- min(row_distance) AS distance,- argMin(snippet, row_distance) AS matched_content- FROM (- SELECT document_id, cosineDistance(embedding, {{embedding}}) AS row_distance, snippet+ scope = _SCOPE_PREWHERE + "".join(f"\n AND {clause}" for clause in filters.where_clauses(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(+ f"""+ SELECT minOrNull(timestamp)FROM (- SELECT document_id, embedding, substring(content, 1, {{snippet_chars}}) AS snippet- FROM document_embeddings- WHERE model_name = {{model_name}}- AND product = {{product}}- AND document_type = {{document_type}}- AND team_id = {{team_id}}- AND JSONExtractString(metadata, 'scanner_id') IN {{scanner_ids}}{filter_clause}+ SELECT timestamp+ FROM {_EMBEDDINGS_TABLE}+ PREWHERE {scope}ORDER BY timestamp DESC- LIMIT {{candidate_cap}}+ LIMIT %(candidate_cap)s)- WHERE cosineDistance(embedding, {{embedding}}) <= {{max_distance}}+ """,+ params,+ team_id=team.id,+ readonly=True,+ ch_user=ClickHouseUser.REPLAY_VISION,+ settings={"max_execution_time": _QUERY_TIMEOUT_S},)- GROUP BY document_id- ORDER BY distance ASC- LIMIT {{limit}}- """- tag_queries(product=Product.REPLAY_VISION, feature=Feature.SEMANTIC_SEARCH)- result = execute_hogql_query(- query=hogql_query,- team=team,- user=user,- placeholders=placeholders,- ch_user=ClickHouseUser.REPLAY_VISION,- )- return [- ObservationMatch(observation_id=row[0], distance=row[1], matched_content=row[2])- for row in (result.results or [])- ]+ cutoff = cutoff_rows[0][0] if cutoff_rows else None+ if cutoff is None:+ return []++ 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+ rows = sync_execute(+ f"""+ SELECT+ document_id,+ min(row_distance) AS distance,+ argMin(snippet, row_distance) AS matched_content+ FROM (+ SELECT+ document_id,+ cosineDistance(embedding, %(embedding)s) AS row_distance,+ substring(content, 1, %(snippet_chars)s) AS snippet+ FROM {_EMBEDDINGS_TABLE}+ PREWHERE {scope}+ AND timestamp >= %(cutoff)s+ WHERE row_distance <= %(max_distance)s+ )+ GROUP BY document_id+ ORDER BY distance ASC+ LIMIT %(limit)s+ """,+ {+ **params,+ "cutoff": cutoff,+ "embedding": query_vector,+ "snippet_chars": _MATCHED_CONTENT_MAX_CHARS,+ "max_distance": MAX_MATCH_DISTANCE,+ "limit": limit,+ },+ team_id=team.id,+ readonly=True,+ ch_user=ClickHouseUser.REPLAY_VISION,+ settings={"max_execution_time": _QUERY_TIMEOUT_S},+ )+ return [ObservationMatch(observation_id=row[0], distance=row[1], matched_content=row[2]) for row in rows]def fetch_ranked_observations(@@ -308,7 +330,6 @@ class ObservationSearchResponse:def search_observations(team: Team,- user: User,access: UserAccessControl,scanner_ids: list[str],query_vector: list[float],@@ -318,7 +339,7 @@ def search_observations("""Rank, hydrate, and slice: the one path both the HTTP endpoint and the Max tool call once they haveresolved their scanner scope and query vector."""rank_limit = limit * RANK_OVERFETCH_FACTOR- matches = rank_observations(team, user, scanner_ids, query_vector, rank_limit, filters)+ matches = rank_observations(team, scanner_ids, query_vector, rank_limit, filters)match_by_id = {match.observation_id: match for match in matches}observations = fetch_ranked_observations(team.id, scanner_ids, list(match_by_id), access)results = [diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 79551bbe589d..77414bc6c180 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -3534,7 +3534,7 @@ class TestObservationSearchAction(_VisionAPITestCase):mock_embed.return_value = MagicMock(embedding=[0.1])resp = self.client.get(f"{self.search_url}?q=anything&date_from=-7d&date_to=2026-09-01")self.assertEqual(resp.status_code, 200, resp.json())- filters = mock_rank.call_args[0][5]+ filters = mock_rank.call_args[0][4]self.assertIsNotNone(filters.date_from)# A date-only upper bound covers its whole day, like the observation list filter.self.assertEqual((filters.date_to.hour, filters.date_to.minute, filters.date_to.second), (23, 59, 59))@@ -3543,7 +3543,7 @@ class TestObservationSearchAction(_VisionAPITestCase):before = timezone.now()resp = self.client.get(f"{self.search_url}?q=anything&date_from=-7d&date_to=now")self.assertEqual(resp.status_code, 200, resp.json())- self.assertGreaterEqual(mock_rank.call_args[0][5].date_to, before)+ self.assertGreaterEqual(mock_rank.call_args[0][4].date_to, before)@patch("products.replay_vision.backend.search.rank_observations", return_value=[])@patch("products.replay_vision.backend.search.generate_embedding")@@ -3594,7 +3594,7 @@ class TestObservationSearchAction(_VisionAPITestCase):resp = self.client.get(f"{self.search_url}?q=confused users&limit=1")self.assertEqual(resp.status_code, 200, resp.json())- self.assertGreater(mock_rank.call_args[0][4], 1)+ self.assertGreater(mock_rank.call_args[0][3], 1)self.assertEqual([r["observation"]["id"] for r in resp.json()["results"]], [str(first.id)])self.assertTrue(resp.json()["truncated"])@@ -3648,7 +3648,7 @@ class TestObservationSearchAction(_VisionAPITestCase):# Not-found rather than 403, so the response never leaks the experiment's existence.self.assertEqual(scoped.status_code, 404)self.assertEqual(cross.status_code, 200)- searched_scanner_ids = mock_rank.call_args[0][2]+ searched_scanner_ids = mock_rank.call_args[0][1]self.assertNotIn(str(denied.id), searched_scanner_ids)self.assertIn(str(self.scanner.id), searched_scanner_ids)diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.pyindex 77f2ab4d5433..48cb837c4906 100644--- a/products/replay_vision/backend/tests/test_max_tools.py+++ b/products/replay_vision/backend/tests/test_max_tools.py@@ -51,7 +51,14 @@ _SCANNER_LOOKUP_PATH = "products.replay_vision.backend.max_tools.scanner_for_rea# The estimate refresh runs a ClickHouse query; these tests are about the tool, not the query._REFRESH_ESTIMATE_PATH = "products.replay_vision.backend.api.scanners._refresh_estimate_fail_soft"_GENERATE_EMBEDDING_PATH = "products.replay_vision.backend.search.generate_embedding"-_EXECUTE_HOGQL_PATH = "products.replay_vision.backend.search.execute_hogql_query"+_SYNC_EXECUTE_PATH = "products.replay_vision.backend.search.sync_execute"+++def _two_pass(rows: list[tuple]):+ def _side_effect(query: str, *_args, **_kwargs):+ return rows if "cosineDistance" in query else [(timezone.now(),)]++ return _side_effectclass TestDraftReplayVisionScannerPromptTool(BaseTest):@@ -110,7 +117,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch("products.replay_vision.backend.max_tools.is_ai_data_processing_approved", return_value=False),patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock) as mock_embed,- patch(_EXECUTE_HOGQL_PATH) as mock_execute,+ patch(_SYNC_EXECUTE_PATH) as mock_execute,):content, artifact = await self._tool()._arun_impl(query="anything", scanner_id=str(scanner.id))assert artifact["error"] == "ai_consent_required"@@ -168,36 +175,31 @@ class TestSearchReplayVisionObservationsTool(BaseTest):@staticmethoddef _ch_stub(ranked: list[tuple[ReplayObservation, float]]):"""Simulate the ClickHouse ranking, honoring the structured metadata filters (verdict/tags/score) the- real query applies — so a row only survives if its model_output matches the filter placeholders."""+ real query applies — so a row only survives if its model_output matches the filter parameters."""- def _matches(output: dict, placeholders: dict) -> bool:- if "verdict" in placeholders and output.get("verdict") not in placeholders["verdict"].value:+ def _matches(output: dict, params: dict) -> bool:+ if "verdict" in params and output.get("verdict") not in params["verdict"]:return False- if "tags" in placeholders:- # Mirror the real query: it slugifies the stored metadata tags before `hasAny`, and the tool- # passes already-slugified values in the placeholder.+ if "tags" in params:obs_tags = {slugify_tag(t) for t in (*(output.get("tags") or []), *(output.get("tags_freeform") or []))}- if not any(tag in obs_tags for tag in placeholders["tags"].value):+ if not any(tag in obs_tags for tag in params["tags"]):return Falsescore = output.get("score")- if "min_score" in placeholders and (- not isinstance(score, int | float) or score < placeholders["min_score"].value- ):+ if "min_score" in params and (not isinstance(score, int | float) or score < params["min_score"]):return False- if "max_score" in placeholders and (- not isinstance(score, int | float) or score > placeholders["max_score"].value- ):+ if "max_score" in params and (not isinstance(score, int | float) or score > params["max_score"]):return Falsereturn True- def _side_effect(*_args, **kwargs):- placeholders = kwargs.get("placeholders", {})+ def _side_effect(query: str, params: dict, **_kwargs):+ if "cosineDistance" not in query:+ return [(timezone.now(),)]rows = [(str(obs.id), distance, "")for obs, distance in ranked- if _matches(obs.scanner_result["model_output"], placeholders)+ if _matches(obs.scanner_result["model_output"], params)]- return MagicMock(results=rows)+ return rowsreturn _side_effect@@ -208,13 +210,13 @@ class TestSearchReplayVisionObservationsTool(BaseTest):obs_far = await self._observation(scanner, "sess-far", "user smoothly completed checkout", score=5)obs_near = await self._observation(scanner, "sess-near", "user rage-clicked the broken submit button", score=0)# ClickHouse returns ids ordered by ascending cosine distance (nearest first).- hogql_results = MagicMock(results=[(str(obs_near.id), 0.1, ""), (str(obs_far.id), 0.4, "")])+ rows = [(str(obs_near.id), 0.1, ""), (str(obs_far.id), 0.4, "")]with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1, 0.2, 0.3])) as mock_embed,- patch(_EXECUTE_HOGQL_PATH, return_value=hogql_results),+ patch(_SYNC_EXECUTE_PATH, side_effect=_two_pass(rows)),):content, artifact = await self._tool()._arun_impl(query="broken submit button", scanner_id=str(scanner.id))@@ -234,7 +236,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1, "")])),+ patch(_SYNC_EXECUTE_PATH, side_effect=_two_pass([(str(obs.id), 0.1, "")])),):_, artifact = await self._tool(context={"scanner_id": str(scanner.id)})._arun_impl(query="button")@@ -249,7 +251,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1, "")])),+ patch(_SYNC_EXECUTE_PATH, side_effect=_two_pass([(str(obs.id), 0.1, "")])),):_, artifact = await self._tool(context={"scanner_id": str(context_scanner.id)})._arun_impl(query="button", scanner_id=str(target_scanner.id)@@ -264,7 +266,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):scanner = await self._scanner()with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[])),+ patch(_SYNC_EXECUTE_PATH, side_effect=_two_pass([])),):content, artifact = await self._tool()._arun_impl(query="anything", scanner_id=str(scanner.id))@@ -290,10 +292,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(- _EXECUTE_HOGQL_PATH,- return_value=MagicMock(results=[(str(obs_a.id), 0.1, ""), (str(obs_b.id), 0.2, "")]),- ),+ patch(_SYNC_EXECUTE_PATH, side_effect=_two_pass([(str(obs_a.id), 0.1, ""), (str(obs_b.id), 0.2, "")])),):content, artifact = await self._tool()._arun_impl(query="checkout problems")@@ -313,7 +312,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),# Both would rank highly; filter-first restricts the ClickHouse ranking to the YES result only.- patch(_EXECUTE_HOGQL_PATH, side_effect=self._ch_stub([(obs_no, 0.1), (obs_yes, 0.2)])),+ patch(_SYNC_EXECUTE_PATH, side_effect=self._ch_stub([(obs_no, 0.1), (obs_yes, 0.2)])),):content, artifact = await self._tool()._arun_impl(query="broken button", scanner_id=str(scanner.id), verdict=["yes"]@@ -332,7 +331,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, side_effect=self._ch_stub([(obs_yes, 0.1)])),+ patch(_SYNC_EXECUTE_PATH, side_effect=self._ch_stub([(obs_yes, 0.1)])),):_, artifact = await self._tool()._arun_impl(query="broken button", scanner_id=str(scanner.id), verdict=["Yes"]@@ -357,7 +356,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, side_effect=self._ch_stub([(obs_completed, 0.1), (obs_abandoned, 0.2)])),+ patch(_SYNC_EXECUTE_PATH, side_effect=self._ch_stub([(obs_completed, 0.1), (obs_abandoned, 0.2)])),):content, artifact = await self._tool()._arun_impl(query="left mid-flow", scanner_id=str(scanner.id), tags=["abandoned"]@@ -385,7 +384,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, side_effect=self._ch_stub([(obs, 0.1)])),+ patch(_SYNC_EXECUTE_PATH, side_effect=self._ch_stub([(obs, 0.1)])),):content, artifact = await self._tool()._arun_impl(query="lost users", scanner_id=str(scanner.id), tags=["Frustrated Or Confused"]@@ -403,7 +402,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, side_effect=self._ch_stub([(obs_five, 0.1), (obs_zero, 0.2)])),+ patch(_SYNC_EXECUTE_PATH, side_effect=self._ch_stub([(obs_five, 0.1), (obs_zero, 0.2)])),):content, artifact = await self._tool()._arun_impl(query="checkout", scanner_id=str(scanner.id), max_score=0)@@ -420,7 +419,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):with (patch(_GENERATE_EMBEDDING_PATH, new_callable=MagicMock, return_value=MagicMock(embedding=[0.1])),- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1, "")])),+ patch(_SYNC_EXECUTE_PATH, side_effect=_two_pass([(str(obs.id), 0.1, "")])),):content, _ = await self._tool()._arun_impl(query="x", scanner_id=str(scanner.id))diff --git a/products/replay_vision/backend/tests/test_search.py b/products/replay_vision/backend/tests/test_search.pyindex 8ba290ddc282..cc3e1b46c291 100644--- a/products/replay_vision/backend/tests/test_search.py+++ b/products/replay_vision/backend/tests/test_search.py@@ -1,3 +1,4 @@+import reimport jsonimport uuidfrom datetime import UTC, datetime, timedelta@@ -41,15 +42,14 @@ class TestObservationFiltersTagClause:])def test_tags_clause_normalizes_stored_side_and_registers_values(self, _name: str, tags: list[str]) -> None:- placeholders: dict = {}- clauses = ObservationSearchFilters(tags=tags).where_clauses(placeholders)+ params: dict = {}+ clauses = ObservationSearchFilters(tags=tags).where_clauses(params)assert len(clauses) == 1# Stored metadata tags are slugified inside the clause (arrayMap) so verbatim-stored tags still match.assert clauses[0].startswith("hasAny(")assert "arrayMap" in clauses[0]- # The clause carries no inlined tag value. It lives only in the parameterized placeholder, verbatim.- assert placeholders["tags"].value == tags+ assert params["tags"] == tagsclass TestParseDateBound:@@ -73,7 +73,6 @@ class TestParseDateBound:parse_date_bound(value, None, end_of_range=False)-# Runs the ranking SQL against real ClickHouse. Everything else mocks `execute_hogql_query`.class TestRankObservationsQuery(ClickhouseTestMixin, APIBaseTest):def _insert_embedding_rows(self, rows: list[tuple]) -> None:# Reads for this model route to its model-specific table. Named inline to avoid a cross-product import.@@ -125,19 +124,66 @@ class TestRankObservationsQuery(ClickhouseTestMixin, APIBaseTest):row("reasoning", other, "x" * 2000, vector(0.6, 0.8)),# Opposite direction: past the distance ceiling, so never a match however few rows exist.row("reasoning", str(uuid.uuid4()), "unrelated", vector(-1.0, 0.0)),+ (self.team.pk + 1, *row("intent", str(uuid.uuid4()), "user wanted to check out", vector(1.0, 0.0))[1:]),])- matches = rank_observations(- self.team, self.user, [scanner_id], vector(1.0, 0.0), 10, ObservationSearchFilters()- )+ with self.capture_select_queries() as queries:+ matches = rank_observations(self.team, [scanner_id], vector(1.0, 0.0), 10, ObservationSearchFilters())self.assertEqual([m.observation_id for m in matches], [best, other])+ self.assertEqual(len(queries), 2)+ self.assertIsNone(re.search(r"\bembedding\b", queries[0]))# `best` has two renderings and the hit carries the closest one's text.self.assertEqual(matches[0].matched_content, "user wanted to check out")self.assertAlmostEqual(matches[0].distance, 0.0, places=5)self.assertEqual(len(matches[1].matched_content), 1500)+ @parameterized.expand(+ [+ ("unfiltered_keeps_newest", ObservationSearchFilters(), "newest_no"),+ ("filtered_rows_do_not_consume_the_cap", ObservationSearchFilters(verdict=["yes"]), "newer_yes"),+ ]+ )+ def test_candidate_cap_keeps_the_most_recent_matching_rows(+ self, _name: str, filters: ObservationSearchFilters, expected: str+ ) -> None:+ scanner_id = str(uuid.uuid4())+ now = timezone.now()+ embedding = [1.0, *([0.0] * 3071)]++ def row(document_id: str, age: timedelta, verdict: str) -> tuple:+ timestamp = now - age+ metadata = json.dumps({"scanner_id": scanner_id, "verdict": verdict})+ return (+ self.team.pk,+ EMBEDDING_PRODUCT,+ EMBEDDING_DOCUMENT_TYPE,+ "reasoning",+ document_id,+ timestamp,+ timestamp,+ "some content",+ metadata,+ embedding,+ timestamp,+ 0,+ 0,+ )++ self._insert_embedding_rows(+ [+ row("older_yes", timedelta(minutes=2), "yes"),+ row("newer_yes", timedelta(minutes=1), "yes"),+ row("newest_no", timedelta(0), "no"),+ ]+ )++ with patch("products.replay_vision.backend.search._MAX_CANDIDATE_ROWS", 1):+ matches = rank_observations(self.team, [scanner_id], embedding, 10, filters)++ self.assertEqual([m.observation_id for m in matches], [expected])+def test_every_filter_clause_compiles_and_applies_inside_the_candidate_subquery(self) -> None:scanner_id = str(uuid.uuid4())kept = str(uuid.uuid4())@@ -171,7 +217,6 @@ class TestRankObservationsQuery(ClickhouseTestMixin, APIBaseTest):matches = rank_observations(self.team,- self.user,[scanner_id],embedding,10,@@ -190,7 +235,6 @@ class TestRankObservationsQuery(ClickhouseTestMixin, APIBaseTest):# The same rows fall outside a window that ends before they were embedded.stale = rank_observations(self.team,- self.user,[scanner_id],embedding,10,