: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): make Max observation tag/verdict search format-insensitive (#63464)
Kim Svatos Dugan065179102ef8
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.pyindex c80d63651433..2d2d2afe1eaa 100644--- a/products/replay_vision/backend/max_tools.py+++ b/products/replay_vision/backend/max_tools.py@@ -22,6 +22,7 @@ from posthog.sync import database_sync_to_asyncfrom products.replay_vision.backend.feature_flag import is_replay_vision_enabledfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservationfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType+from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tagfrom ee.hogai.tool import MaxTool@@ -124,7 +125,9 @@ SEARCH_OBSERVATIONS_TOOL_DESCRIPTION = dedent("""applied first, then the semantic ranking runs only over the matching recordings — so always pass these whenthe user states an exact result:- `verdict` for monitor scanners (e.g. ["yes"] for "recordings that had a YES result because of ...")- - `tags` for classifier scanners (e.g. ["abandoned"] for "sessions classified as abandoned because of ...")+ - `tags` for classifier scanners (e.g. ["abandoned"] for "sessions classified as abandoned because of ...").+ Pass the tag as the user phrases it — matching is case/format-insensitive (e.g. "Frustrated Or Confused"+ matches the stored `frustrated_or_confused`).- `min_score` / `max_score` for scorer scanners (e.g. max_score=0 for "scored 0 because of ...")Put only the meaning in `query` (e.g. "broken checkout button"), and the exact outcome in these filters.@@ -283,6 +286,14 @@ class SummarizeReplayVisionSummariesTool(MaxTool):return content, {"scanner_id": scanner_id, "summary_count": len(lines)}+# Slugify each stored metadata tag before `hasAny`, so the case/format-insensitive match works against rows+# whose fixed-vocab tags were stamped verbatim — no backfill. The caller passes already-slugified values in+# `{tags}`. Built from hardcoded literals only (no user/LLM input), preserving the `_append_filter` invariant.+_TAGS_FILTER_CLAUSE = (+ f"hasAny(arrayMap(t -> {clickhouse_slugify_sql('t')}, JSONExtract(metadata, 'tags', 'Array(String)')), {{tags}})"+)++@dataclass(frozen=True)class _ObservationFilters:"""Exact-outcome filters, applied inside the ClickHouse ranking query against the embedding metadata@@ -307,13 +318,7 @@ class _ObservationFilters:clauses, placeholders, "verdict", self.verdict, "JSONExtractString(metadata, 'verdict') IN {verdict}")if self.tags:- self._append_filter(- clauses,- placeholders,- "tags",- self.tags,- "hasAny(JSONExtract(metadata, 'tags', 'Array(String)'), {tags})",- )+ self._append_filter(clauses, placeholders, "tags", self.tags, _TAGS_FILTER_CLAUSE)if self.min_score is not None:self._append_filter(clauses,@@ -363,7 +368,8 @@ class SearchObservationsArgs(BaseModel):)tags: list[str] | None = Field(default=None,- description='Keep only classifier results carrying any of these tags. e.g. ["abandoned"].',+ description='Keep only classifier results carrying any of these tags. e.g. ["abandoned"]. '+ "Matching is case/format-insensitive, so pass the tag as the user phrases it.",)min_score: float | None = Field(default=None, description="Keep only scorer results whose score is at least this value."@@ -403,7 +409,15 @@ class SearchReplayVisionObservationsTool(MaxTool):if not query or not query.strip():return "No search query provided. Please describe what to look for.", {"error": "empty_query"}- filters = _ObservationFilters(verdict=verdict, tags=tags, min_score=min_score, max_score=max_score)+ # Slugify Max's tag guess ("Frustrated Or Confused" -> "frustrated_or_confused") so it matches the+ # normalized stored side; order-preserving dedup, dropping anything that slugs to empty.+ normalized_tags = list(dict.fromkeys(s for t in (tags or []) if (s := slugify_tag(t)))) or None+ # Verdicts are a closed lowercase enum (yes/no/inconclusive) stored verbatim, so lowercase Max's input+ # to absorb a casing slip ("Yes") that would otherwise silently match nothing.+ normalized_verdict = list(dict.fromkeys(v.strip().lower() for v in (verdict or []) if v.strip())) or None+ filters = _ObservationFilters(+ verdict=normalized_verdict, tags=normalized_tags, min_score=min_score, max_score=max_score+ )try:return await self._search(str(resolved_id) if resolved_id else None, query.strip(), filters, limit)except Exception as e:diff --git a/products/replay_vision/backend/tags.py b/products/replay_vision/backend/tags.pynew file mode 100644index 000000000000..f354e37e27bf--- /dev/null+++ b/products/replay_vision/backend/tags.py@@ -0,0 +1,24 @@+"""Tag slug normalization shared across Replay Vision (classifier output, embedding metadata, Max search)."""++import re++# Anything that isn't a-z, 0-9, underscore, or dash collapses to a single underscore.+_SLUG_COLLAPSE_PATTERN = r"[^a-z0-9_-]+"+_SLUG_COLLAPSE_RE = re.compile(_SLUG_COLLAPSE_PATTERN)+# Mirrors `.strip("_")` for the ClickHouse expression below.+_SLUG_STRIP_PATTERN = r"^_+|_+$"+++def slugify_tag(value: str) -> str:+ """Lowercase + replace non-[a-z0-9_-] runs with `_` + strip leading/trailing underscores."""+ return _SLUG_COLLAPSE_RE.sub("_", value.lower()).strip("_")+++def clickhouse_slugify_sql(column_expr: str) -> str:+ """ClickHouse expression applying `slugify_tag`'s normalization to a string column, so the stored side of a+ tag comparison matches the Python-slugified query side. Built from the same patterns as `slugify_tag` so the+ two stay in sync — edit both here together (one is a regex sub + `.strip`, the other its SQL mirror)."""+ return (+ f"replaceRegexpAll(replaceRegexpAll(lower({column_expr}), '{_SLUG_COLLAPSE_PATTERN}', '_'), "+ f"'{_SLUG_STRIP_PATTERN}', '')"+ )diff --git a/products/replay_vision/backend/temporal/activities/embed_observation.py b/products/replay_vision/backend/temporal/activities/embed_observation.pyindex 6b85d44490c8..4a80acbea304 100644--- a/products/replay_vision/backend/temporal/activities/embed_observation.py+++ b/products/replay_vision/backend/temporal/activities/embed_observation.py@@ -24,6 +24,7 @@ from posthog.kafka_client.client import ProduceResultfrom posthog.kafka_client.routing import producer_scopefrom posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC+from products.replay_vision.backend.tags import slugify_tagfrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.scanners.classifier import ClassifierOutputfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorOutput@@ -65,7 +66,10 @@ def _result_metadata(model_output: AnyScannerOutput) -> dict[str, Any]:if isinstance(model_output, ScorerOutput):return {"score": model_output.score}if isinstance(model_output, ClassifierOutput):- return {"tags": [*model_output.tags, *model_output.tags_freeform]}+ # Slugify fixed-vocab tags too (freeform are already slug) so the stored side is canonical and search+ # filters match case/format-insensitively. Order-preserving dedup across both lists.+ tags = [*model_output.tags, *model_output.tags_freeform]+ return {"tags": list(dict.fromkeys(s for t in tags if (s := slugify_tag(t))))}return {}diff --git a/products/replay_vision/backend/temporal/scanners/classifier.py b/products/replay_vision/backend/temporal/scanners/classifier.pyindex ba4dd975460e..4db31227522b 100644--- a/products/replay_vision/backend/temporal/scanners/classifier.py+++ b/products/replay_vision/backend/temporal/scanners/classifier.py@@ -1,6 +1,5 @@"""Classifier scanner: assigns one or more tags from a fixed vocabulary, optionally plus freeform tags."""-import reimport typingfrom functools import cached_propertyfrom typing import Any, ClassVar, Literal@@ -8,16 +7,10 @@ from typing import Any, ClassVar, Literalfrom pydantic import BaseModel, Field, create_model, field_validatorfrom products.replay_vision.backend.models.replay_scanner import ScannerType+from products.replay_vision.backend.tags import slugify_tagfrom products.replay_vision.backend.temporal.scanners.base import BaseScanner, BaseScannerOutput, Segment_MAX_FREEFORM_TAGS = 5-# Anything that isn't a-z, 0-9, underscore, or dash collapses to a single underscore.-_FREEFORM_NORMALIZE_RE = re.compile(r"[^a-z0-9_-]+")---def _slugify_tag(value: str) -> str:- """Lowercase + replace non-[a-z0-9_-] runs with `_` + strip leading/trailing underscores."""- return _FREEFORM_NORMALIZE_RE.sub("_", value.lower()).strip("_")class ClassifierOutput(BaseScannerOutput, frozen=True):@@ -36,7 +29,7 @@ class ClassifierOutput(BaseScannerOutput, frozen=True):@classmethoddef _normalize_freeform(cls, value: list[str]) -> list[str]:# Lowercase + snake-case + order-preserving dedup so the unbounded freeform space stays consistent.- return list(dict.fromkeys(slug for tag in value if (slug := _slugify_tag(tag))))+ return list(dict.fromkeys(slug for tag in value if (slug := slugify_tag(tag))))class ClassifierScanner(BaseScanner, frozen=True):@@ -87,7 +80,7 @@ class ClassifierScanner(BaseScanner, frozen=True):@cached_propertydef _fixed_vocab_slugs(self) -> frozenset[str]:"""Slug-normalized fixed-vocab tags; cached so per-observation finalize doesn't re-walk the regex."""- return frozenset(_slugify_tag(t) for t in self.tags)+ return frozenset(slugify_tag(t) for t in self.tags)def finalize(self, llm_response: BaseModel) -> BaseScannerOutput:# Cast the dynamic `Literal`-typed response to the static `ClassifierOutput` for downstream consumers.diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.pyindex 7a1a99ddf859..07381a21ba4d 100644--- a/products/replay_vision/backend/tests/test_max_tools.py+++ b/products/replay_vision/backend/tests/test_max_tools.py@@ -13,6 +13,7 @@ from parameterized import parameterizedfrom products.replay_vision.backend.max_tools import (DraftReplayVisionScannerPromptTool,SearchReplayVisionObservationsTool,+ _ObservationFilters,)from products.replay_vision.backend.models.replay_observation import (ObservationStatus,@@ -20,6 +21,7 @@ from products.replay_vision.backend.models.replay_observation import (ReplayObservation,)from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.tags import slugify_tag_FLAG_PATH = "products.replay_vision.backend.feature_flag.posthoganalytics.feature_enabled"_GENERATE_EMBEDDING_PATH = "products.replay_vision.backend.max_tools.async_generate_embedding"@@ -140,7 +142,9 @@ class TestSearchReplayVisionObservationsTool(BaseTest):if "verdict" in placeholders and output.get("verdict") not in placeholders["verdict"].value:return Falseif "tags" in placeholders:- obs_tags = [*(output.get("tags") or []), *(output.get("tags_freeform") or [])]+ # Mirror the real query: it slugifies the stored metadata tags before `hasAny`, and the tool+ # passes already-slugified values in the placeholder.+ 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):return Falsescore = output.get("score")@@ -272,6 +276,24 @@ class TestSearchReplayVisionObservationsTool(BaseTest):assert "sess-yes" in content and "sess-no" not in contentassert "verdict=yes" in content+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_verdict_filter_is_case_insensitive(self):+ # Verdicts are stored lowercase; a casing slip from Max ("Yes") must still match.+ scanner = await self._scanner(scanner_type=ScannerType.MONITOR)+ obs_yes = await self._monitor_observation(scanner, "sess-yes", "user hit the broken button", verdict="yes")++ with (+ patch(_FLAG_PATH, return_value=True),+ patch(_GENERATE_EMBEDDING_PATH, new_callable=AsyncMock, return_value=MagicMock(embedding=[0.1])),+ patch(_EXECUTE_HOGQL_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"]+ )++ assert artifact["observation_ids"] == [str(obs_yes.id)]+@pytest.mark.django_db@pytest.mark.asyncioasync def test_tag_filter_keeps_only_matching_results(self):@@ -299,6 +321,35 @@ class TestSearchReplayVisionObservationsTool(BaseTest):assert artifact["observation_ids"] == [str(obs_abandoned.id)]assert "sess-abandoned" in content and "sess-completed" not in content+ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_tag_filter_matches_normalized_form(self):+ # The reported bug: Max passes the user's phrasing ("Frustrated Or Confused") while the stored tag is+ # the slug `frustrated_or_confused`. Matching must be case/format-insensitive.+ scanner = await self._scanner(scanner_type=ScannerType.CLASSIFIER)+ obs = await self._create_observation_async(+ scanner,+ "sess-frustrated",+ {+ "scanner_type": "classifier",+ "tags": ["frustrated_or_confused"],+ "reasoning": "user looked lost",+ "confidence": 0.8,+ },+ )++ with (+ patch(_FLAG_PATH, return_value=True),+ patch(_GENERATE_EMBEDDING_PATH, new_callable=AsyncMock, return_value=MagicMock(embedding=[0.1])),+ patch(_EXECUTE_HOGQL_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"]+ )++ assert artifact["observation_ids"] == [str(obs.id)]+ assert "sess-frustrated" in content+@pytest.mark.django_db@pytest.mark.asyncioasync def test_score_range_filter_keeps_only_matching_results(self):@@ -372,3 +423,27 @@ class TestSearchReplayVisionObservationsTool(BaseTest):assert artifact["error"] == "not_enabled"assert "not enabled" in content+++class TestObservationFiltersTagClause:+ """Pure-logic clause construction — no DB/ClickHouse, so it runs without the full test stack."""++ @parameterized.expand(+ [+ ("single", ["frustrated_or_confused"]),+ ("multiple", ["abandoned", "completed"]),+ # `_ObservationFilters` registers values verbatim — pre-slugifying is the caller's (tool's) job. The+ # SQL slugifies the *stored* side; passing a non-slug here proves the value is not re-normalized.+ ("verbatim_not_renormalized", ["Frustrated Or Confused"]),+ ]+ )+ def test_tags_clause_normalizes_stored_side_and_registers_values(self, _name: str, tags: list[str]) -> None:+ placeholders: dict = {}+ clauses = _ObservationFilters(tags=tags).where_clauses(placeholders)++ 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 == tagsdiff --git a/products/replay_vision/backend/tests/test_tags.py b/products/replay_vision/backend/tests/test_tags.pynew file mode 100644index 000000000000..0cc84be37a1a--- /dev/null+++ b/products/replay_vision/backend/tests/test_tags.py@@ -0,0 +1,30 @@+from parameterized import parameterized++from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tag+++class TestSlugifyTag:+ @parameterized.expand(+ [+ ("title_case", "Frustrated Or Confused", "frustrated_or_confused"),+ ("already_slug", "abandoned", "abandoned"),+ ("upper", "RAGE", "rage"),+ ("runs_of_specials", "Rage!! Click??", "rage_click"),+ ("leading_trailing_specials", " --rage-- ", "--rage--"),+ ("leading_trailing_underscores", "__rage__", "rage"),+ ("preserves_internal_dash", "rage-click", "rage-click"),+ ("all_special_collapses_to_empty", "!!! ???", ""),+ ("empty", "", ""),+ ("unicode_stripped", "café déjà", "caf_d_j"),+ ]+ )+ def test_slugify_tag(self, _name: str, value: str, expected: str) -> None:+ assert slugify_tag(value) == expected++ def test_clickhouse_mirror_uses_shared_patterns(self) -> None:+ # The SQL mirror is generated for an arbitrary column expression and embeds the same collapse/strip+ # patterns `slugify_tag` uses, so the two normalizations stay in lockstep.+ sql = clickhouse_slugify_sql("t")+ assert "lower(t)" in sql+ assert "[^a-z0-9_-]+" in sql+ assert "^_+|_+$" in sql