: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
"""Semantic search core over observation embeddings, shared by the HTTP API and the Max tool.
The write side (`embed_observation`) stamps each embedding row with the scanner id and the structured
outcome (monitor `verdict`, scorer `score`, classifier `tags`), so filtering and cosine ranking happen in
ClickHouse here. Callers resolve scanner scope and access control themselves and pass the readable
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
from zoneinfo import ZoneInfo
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
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models.team import Team
from posthog.utils import relative_date_parse_with_delta_mapping
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.replay_vision.backend.embeddings import (
OBSERVATION_EMBEDDING_MODEL,
OBSERVATION_EMBEDDINGS_TABLE,
OBSERVATION_SCOPE_PREWHERE,
observation_scope_params,
)
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
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
# Postgres-side hydration re-checks status and access and can drop ranked ids, so a caller that ranks
# exactly `limit` ids can come back short. Callers rank this many times their limit and slice the
# hydrated rows back down, so drops only shorten the response once they exceed the margin.
RANK_OVERFETCH_FACTOR = 3
# Cosine distance above which a row is not a match, so a query about nothing returns nothing rather than
# the closest 50 unrelated observations. For text-embedding-3-large, related prose lands well under this
# and unrelated prose well over it.
MAX_MATCH_DISTANCE = 0.7
# Cut inside the candidate subquery so the sort never carries an unbounded document. Wide enough to hold a
# whole summary, so the client can window its snippet around the matched term.
_MATCHED_CONTENT_MAX_CHARS = 1500
# Query vectors are pure functions of (model, text), so repeated and deep-linked searches skip the embedding
# worker round trip.
_QUERY_VECTOR_CACHE_TTL_S = 3600
# Bound the synchronous embedding call: it pins a request thread, and a searcher will not wait longer.
# requests applies this per read rather than to the whole response, so a worker that dribbles its body
# out can still outlast it.
_EMBEDDING_TIMEOUT_S = 10.0
# The cosine-distance scan is exact (brute-force), so cap how many of a team's most-recent embedding rows it
# 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
_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")
_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. Static literals only, see `_append_filter`.
_TAGS_FILTER_CLAUSE = (
f"hasAny(arrayMap(t -> {clickhouse_slugify_sql('t')}, JSONExtract(metadata, 'tags', 'Array(String)')), %(tags)s)"
)
@dataclass(frozen=True)
class ObservationMatch:
"""One ranked search hit: the observation id and its cosine distance to the query (lower is closer)."""
observation_id: str
distance: float
# Excerpt of the row that ranked this hit. Empty for rows written before `content` was stored.
matched_content: str
@dataclass(frozen=True)
class ObservationSearchFilters:
"""Exact-outcome filters, applied inside the ClickHouse ranking query against the embedding metadata
(monitor `verdict`, scorer `score`, classifier `tags` are stamped onto each embedding row at write time)."""
verdict: list[str] | None = None
tags: list[str] | None = None
min_score: float | None = None
max_score: float | None = None
date_from: datetime | None = None
date_to: datetime | None = None
@classmethod
def from_raw(
cls,
verdict: list[str] | None,
tags: list[str] | None,
min_score: float | None,
max_score: float | None,
date_from: str | None = None,
date_to: str | None = None,
timezone_info: ZoneInfo | None = None,
) -> "ObservationSearchFilters":
"""Normalize caller-supplied values: tags slugified to match the stored side, verdicts lowercased so
a casing slip doesn't silently match nothing. Both are order-preserving deduped. Date bounds parse
like the observation list's, in the project's timezone."""
normalized_tags = list(dict.fromkeys(s for t in (tags or []) if (s := slugify_tag(t)))) or None
normalized_verdict = list(dict.fromkeys(v.strip().lower() for v in (verdict or []) if v.strip())) or None
return cls(
verdict=normalized_verdict,
tags=normalized_tags,
min_score=min_score,
max_score=max_score,
date_from=parse_date_bound(date_from, timezone_info, end_of_range=False) if date_from else None,
date_to=parse_date_bound(date_to, timezone_info, end_of_range=True) if date_to else None,
)
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 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, params, "verdict", self.verdict, "JSONExtractString(metadata, 'verdict') IN %(verdict)s"
)
if self.tags:
self._append_filter(clauses, params, "tags", self.tags, _TAGS_FILTER_CLAUSE)
if self.min_score is not None:
self._append_filter(
clauses,
params,
"min_score",
self.min_score,
"JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') >= %(min_score)s",
)
if self.max_score is not None:
self._append_filter(
clauses,
params,
"max_score",
self.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, params, "date_from", self.date_from, "timestamp >= %(date_from)s")
if self.date_to is not None:
self._append_filter(clauses, params, "date_to", self.date_to, "timestamp <= %(date_to)s")
return clauses
@staticmethod
def _append_filter(
clauses: list[str],
params: dict[str, Any],
key: str,
value: Any,
clause: str,
) -> None:
"""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] = value
clauses.append(clause)
class _CutoffNotComputed:
pass
# Distinct from None, which means the cutoff query ran and found no rows in scope.
_CUTOFF_NOT_COMPUTED = _CutoffNotComputed()
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(
f"""
SELECT minOrNull(timestamp)
FROM (
SELECT timestamp
FROM {OBSERVATION_EMBEDDINGS_TABLE}
PREWHERE {scope}
ORDER BY timestamp DESC
LIMIT %(candidate_cap)s
)
""",
params,
team_id=team.id,
readonly=True,
ch_user=ClickHouseUser.REPLAY_VISION,
settings={"max_execution_time": _QUERY_TIMEOUT_S},
)
return cutoff_rows[0][0] if cutoff_rows else None
def _scope_params(team: Team, scanner_ids: list[str]) -> dict[str, Any]:
return {**observation_scope_params(team.id, scanner_ids), "candidate_cap": _MAX_CANDIDATE_ROWS}
def _scope_clause(filters: ObservationSearchFilters, params: dict[str, Any]) -> str:
return OBSERVATION_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
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 {OBSERVATION_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(
team_id: int, scanner_ids: list[str], ordered_ids: list[str], access: UserAccessControl
) -> list[ReplayObservation]:
"""Hydrate ranked observation ids into rows, preserving rank order. The scanner-id filter and
`accessible_observations` re-apply the caller's access scope here because embedding rows carry
no experiment metadata, so a ranked id alone could leak an observation the caller can't read."""
rows = ReplayObservation.objects.filter(
team_id=team_id,
scanner_id__in=scanner_ids,
status=ObservationStatus.SUCCEEDED,
id__in=ordered_ids,
)
# `scanner_name` feeds the Max tool's line format without joining the scanner row's config blobs.
rows = hydrate_for_serialization(accessible_observations(access, team_id, rows)).annotate(
scanner_name=F("scanner__name")
)
observations = {str(obs.id): obs for obs in rows}
return [obs for observation_id in ordered_ids if (obs := observations.get(observation_id)) is not None]
def parse_date_bound(
value: str, timezone_info: ZoneInfo | None, *, end_of_range: bool, now: datetime | None = None
) -> datetime:
"""Parse a caller-supplied date bound: ISO 8601, `now`, or relative (`-7d`), naive values in the
project's timezone. A date-only upper bound covers its whole day. Shared by the observation list and
search. Raises `ValueError` on text that is none of those, rather than treating it as now."""
timezone_info = timezone_info or ZoneInfo("UTC")
if value.strip().lower() == "now":
# `now` already carries a time of day, so it skips the end-of-range widening below.
return now.astimezone(timezone_info) if now else datetime.now(timezone_info)
parsed, delta_mapping, _ = relative_date_parse_with_delta_mapping(value, timezone_info, now=now)
# The relative branch hands back an empty mapping when nothing in the text matched a period.
if delta_mapping == {}:
raise ValueError(f"Unrecognized date: {value!r}. Use ISO 8601, a relative date like -7d, or 'now'.")
if end_of_range and not value.startswith(("-", "+")) and "T" not in value and ":" not in value:
parsed = parsed.replace(hour=23, minute=59, second=59, microsecond=999999)
return parsed
@dataclass(frozen=True)
class ObservationSearchResult:
"""One hydrated hit, in rank order."""
observation: ReplayObservation
distance: float
matched_content: str
@dataclass(frozen=True)
class ObservationSearchResponse:
results: list[ObservationSearchResult]
# 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: 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. `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
# 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,
distance=match_by_id[str(obs.id)].distance,
matched_content=match_by_id[str(obs.id)].matched_content,
)
for obs in observations[:limit]
]
truncated = len(observations) > limit or len(matches) >= rank_limit
return ObservationSearchResponse(results=results, truncated=truncated, reranked=reranked)
def _query_vector_cache_key(text: str) -> str:
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
return f"replay_vision:query_vector:{OBSERVATION_EMBEDDING_MODEL.value}:{digest}"
def is_transient_embedding_error(error: Exception) -> bool:
"""True for an embedding failure that a later call can clear, which is what a caller offers a retry for.
`ChunkedEncodingError` is what requests raises when the response body stops part way, so a worker that
dies mid-transfer belongs with the other transport failures despite the name. A 5xx is the worker itself
failing, so it joins them. A 4xx is a bad request, and a repeat of it is rejected the same way."""
if isinstance(error, requests.ConnectionError | requests.Timeout | requests.exceptions.ChunkedEncodingError):
return True
return isinstance(error, requests.HTTPError) and getattr(error.response, "status_code", 0) >= 500
def query_vector_for(team: Team, text: str) -> list[float]:
"""Embed search text, serving repeats from cache. Raises the embedding client's transport errors."""
key = _query_vector_cache_key(text)
cached = cache.get(key)
if cached is not None:
return cached
vector = generate_embedding(
team, text, model=OBSERVATION_EMBEDDING_MODEL.value, timeout=_EMBEDDING_TIMEOUT_S
).embedding
cache.set(key, vector, timeout=_QUERY_VECTOR_CACHE_TTL_S)
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)