:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(taxonomic-filter): record why event match returns no suggestion (#111764)
Paul D'Ambraf2f45d6cee33
diff --git a/posthog/api/taxonomic_search_intent.py b/posthog/api/taxonomic_search_intent.pyindex 81abdcf576f2..b9ce4782ecf9 100644--- a/posthog/api/taxonomic_search_intent.py+++ b/posthog/api/taxonomic_search_intent.py@@ -17,10 +17,16 @@ from rest_framework.throttling import UserRateThrottlefrom posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.event_usage import report_user_actionfrom posthog.llm.system_one import SystemOneNotConfigured, SystemOneRequestFailedfrom posthog.models import Userfrom posthog.taxonomic_search_intent.classify import classify_search_intent, search_intent_enabled-from posthog.taxonomic_search_intent.contracts import EventMatchRequest, SearchIntentRequest, SearchIntentSource+from posthog.taxonomic_search_intent.contracts import (+ EventMatchOutcome,+ EventMatchRequest,+ SearchIntentRequest,+ SearchIntentSource,+)from posthog.taxonomic_search_intent.event_match import EVENT_MATCH_FEATURE_FLAG, match_core_eventslogger = structlog.get_logger(__name__)@@ -208,17 +214,29 @@ class SearchIntentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):team_id=self.team_id, project_id=self.team.project_id, query=request.validated_data["query"])try:- matches = match_core_events(search)+ answer = match_core_events(search)except (SystemOneNotConfigured, SystemOneRequestFailed) as error:logger.warning("taxonomic_event_match_unavailable", team_id=self.team_id, reason=type(error).__name__)+ self._report_event_match(request, EventMatchOutcome.UNAVAILABLE)raise SearchIntentUnavailable() from error+ self._report_event_match(request, answer.outcome)return Response(EventMatchResponseSerializer({"matches": [{"name": match.name, "display_name": match.label, "probability": match.probability}- for match in matches+ for match in answer.matches]}).data)++ def _report_event_match(self, request: Request, outcome: EventMatchOutcome) -> None:+ # The picker counts only the answers it shows, so only this event says which step left an answer empty.+ report_user_action(+ cast(User, request.user),+ "taxonomic filter event match answered",+ {"outcome": outcome.value},+ team=self.team,+ request=request,+ )diff --git a/posthog/api/test/test_taxonomic_search_intent.py b/posthog/api/test/test_taxonomic_search_intent.pyindex 8a14354e1d78..6684ded1da93 100644--- a/posthog/api/test/test_taxonomic_search_intent.py+++ b/posthog/api/test/test_taxonomic_search_intent.py@@ -9,7 +9,7 @@ from rest_framework import statusfrom posthog.llm.gateway_client import team_distinct_idfrom posthog.llm.system_one import ChoiceAnswer, SystemOneNotConfigured, SystemOneRequestFailed, SystemOneResult-from posthog.taxonomic_search_intent.contracts import EventMatch+from posthog.taxonomic_search_intent.contracts import EventMatch, EventMatchAnswer, EventMatchOutcomefrom posthog.taxonomic_search_intent.prompt import BUNDLED_SEARCH_INTENT_PROMPTALL_TABS = ("suggested_filters", "events", "event_properties", "person_properties", "pageview_urls", "email_addresses")@@ -101,12 +101,28 @@ class TestSearchIntentEndpoint(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUEST- @parameterized.expand([("enabled", True, status.HTTP_200_OK), ("flag_off", False, status.HTTP_404_NOT_FOUND)])- def test_matches_events_behind_its_own_flag(self, _name, enabled, expected_status) -> None:+ @parameterized.expand(+ [+ ("enabled", True, None, status.HTTP_200_OK, "matched"),+ ("flag_off", False, None, status.HTTP_404_NOT_FOUND, None),+ (+ "model_unreachable",+ True,+ SystemOneRequestFailed("timeout"),+ status.HTTP_503_SERVICE_UNAVAILABLE,+ "unavailable",+ ),+ ]+ )+ def test_matches_events_behind_its_own_flag(self, _name, enabled, error, expected_status, expected_outcome) -> None:match = EventMatch(name="$autocapture", label="Autocapture", probability=0.95)+ answer = EventMatchAnswer(matches=[match], outcome=EventMatchOutcome.MATCHED)with (patch(FLAG_CHECK, return_value=enabled) as flag,- patch("posthog.api.taxonomic_search_intent.match_core_events", return_value=[match]) as matcher,+ patch(+ "posthog.api.taxonomic_search_intent.match_core_events", return_value=answer, side_effect=error+ ) as matcher,+ patch("posthog.api.taxonomic_search_intent.report_user_action") as report,):response = self.client.post(f"/api/projects/{self.team.id}/taxonomic_search_intent/match_events/",@@ -116,8 +132,12 @@ class TestSearchIntentEndpoint(APIBaseTest):assert response.status_code == expected_statusassert flag.call_args.args[0] == "taxonomic-filter-event-match"- if enabled:+ if expected_status == status.HTTP_200_OK:assert response.json() == {"matches": [{"name": "$autocapture", "display_name": "Autocapture", "probability": 0.95}]}assert matcher.call_args.args[0].project_id == self.team.project_id+ if expected_outcome:+ assert report.call_args.args[1:] == ("taxonomic filter event match answered", {"outcome": expected_outcome})+ else:+ report.assert_not_called()diff --git a/posthog/taxonomic_search_intent/contracts.py b/posthog/taxonomic_search_intent/contracts.pyindex a4d085851017..69d501b73b34 100644--- a/posthog/taxonomic_search_intent/contracts.py+++ b/posthog/taxonomic_search_intent/contracts.py@@ -9,6 +9,16 @@ class SearchIntentSource(models.TextChoices):SKIPPED = "skipped", "Not classified"+class EventMatchOutcome(models.TextChoices):+ WRONG_LENGTH = "wrong_length", "The search is too short or too long to ask about"+ ONLY_VALUES = "only_values", "Nothing but values is left for the model to read"+ UNAVAILABLE = "unavailable", "The model could not answer at all"+ PARTIAL = "partial", "Some model requests failed, so an event it never asked about might have matched"+ NOTHING_LIKELY = "nothing_likely", "The model found no core event likely"+ NOT_INGESTED = "not_ingested", "The project never sent the likely events"+ MATCHED = "matched", "At least one likely event has data"++@frozenclass SearchIntentRequest:"""What a person typed into the filter picker, and the tabs the picker shows them."""@@ -51,3 +61,11 @@ class EventMatch:name: strlabel: strprobability: float+++@frozen+class EventMatchAnswer:+ """The suggestions for a search, and the step that decided them, so an empty answer says why it is empty."""++ matches: list[EventMatch]+ outcome: EventMatchOutcomediff --git a/posthog/taxonomic_search_intent/event_match.py b/posthog/taxonomic_search_intent/event_match.pyindex c3805ea6c643..e92b8483538f 100644--- a/posthog/taxonomic_search_intent/event_match.py+++ b/posthog/taxonomic_search_intent/event_match.py@@ -26,7 +26,7 @@ from posthog.models import EventDefinitionfrom posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUPfrom .classify import CACHE_TTL_SECONDS, MAX_QUERY_CHARS, MIN_QUERY_CHARS, SEARCH_INTENT_TIMEOUT_SECONDS, redact_values-from .contracts import EventMatch, EventMatchRequest+from .contracts import EventMatch, EventMatchAnswer, EventMatchOutcome, EventMatchRequestlogger = structlog.get_logger(__name__)@@ -160,6 +160,20 @@ def likely_core_events(model_query = redact_values(query)if model_query is None:return []+ likely, _complete = _likely_core_events(+ team_id, model_query, use_cache=use_cache, require_complete=require_complete, model=model+ )+ return likely+++def _likely_core_events(+ team_id: int, model_query: str, *, use_cache: bool, require_complete: bool, model: str | None+) -> tuple[list[EventMatch], bool]:+ """Same as `likely_core_events`, plus whether every core event was actually asked about.++ Takes the redacted query, so `match_core_events` can name the `ONLY_VALUES` outcome without redacting twice.+ A cache hit is always complete, since a partial answer is never cached (see below).+ """model = model or EVENT_MATCH_MODEL.current()key = _cache_key(team_id, model_query, model)if use_cache:@@ -167,7 +181,7 @@ def likely_core_events(# The Django cache pickles what it stores, so matches go in as JSON text and come out schema-validated.if isinstance(cached, str):try:- return _CACHED_MATCHES.validate_json(cached)+ return _CACHED_MATCHES.validate_json(cached), Trueexcept ValidationError:passanswers = _probabilities(team_id, model_query, model)@@ -185,7 +199,7 @@ def likely_core_events(# A partial answer is not cached, so the next search asks again for the events that failed.if use_cache and answers.complete:cache.set(key, _CACHED_MATCHES.dump_json(likely).decode(), CACHE_TTL_SECONDS)- return likely+ return likely, answers.completedef _ingested(project_id: int, names: Sequence[str]) -> set[str]:@@ -197,17 +211,30 @@ def _ingested(project_id: int, names: Sequence[str]) -> set[str]:)-def match_core_events(request: EventMatchRequest, *, use_cache: bool = True) -> list[EventMatch]:+def match_core_events(request: EventMatchRequest, *, use_cache: bool = True) -> EventMatchAnswer:"""The core events the search most likely means, strongest first, limited to events the project has ingested.Raises the System One errors; the caller decides whether a failed answer matters."""query = " ".join(request.query.split())if not MIN_QUERY_CHARS <= len(query) <= MAX_QUERY_CHARS:- return []- likely = likely_core_events(request.team_id, query, use_cache=use_cache)+ return EventMatchAnswer(matches=[], outcome=EventMatchOutcome.WRONG_LENGTH)+ model_query = redact_values(query)+ if model_query is None:+ return EventMatchAnswer(matches=[], outcome=EventMatchOutcome.ONLY_VALUES)+ likely, complete = _likely_core_events(+ request.team_id, model_query, use_cache=use_cache, require_complete=False, model=None+ )if not likely:- return []+ # A failed chunk leaves its events unasked, so an empty answer is not conclusive unless every chunk answered.+ return EventMatchAnswer(+ matches=[], outcome=EventMatchOutcome.NOTHING_LIKELY if complete else EventMatchOutcome.PARTIAL+ )# A suggestion for an event the project never sent would lead to an empty insight.ingested = _ingested(request.project_id, [match.name for match in likely])- return [match for match in likely if match.name in ingested]+ matches = [match for match in likely if match.name in ingested]+ if matches:+ return EventMatchAnswer(matches=matches, outcome=EventMatchOutcome.MATCHED)+ return EventMatchAnswer(+ matches=[], outcome=EventMatchOutcome.NOT_INGESTED if complete else EventMatchOutcome.PARTIAL+ )diff --git a/posthog/taxonomic_search_intent/test_event_match.py b/posthog/taxonomic_search_intent/test_event_match.pyindex d7f279ac5901..d54a539b3417 100644--- a/posthog/taxonomic_search_intent/test_event_match.py+++ b/posthog/taxonomic_search_intent/test_event_match.py@@ -11,7 +11,7 @@ from parameterized import parameterizedfrom posthog.llm.system_one import NoulAnswer, Question, SystemOneRequestFailed, SystemOneResultfrom posthog.llm.system_one_client import GATEWAY_MAX_QUESTIONSfrom posthog.models import EventDefinition-from posthog.taxonomic_search_intent.contracts import EventMatch, EventMatchRequest+from posthog.taxonomic_search_intent.contracts import EventMatch, EventMatchAnswer, EventMatchOutcome, EventMatchRequestfrom posthog.taxonomic_search_intent.event_match import (CORE_EVENT_CANDIDATES,_question,@@ -25,6 +25,9 @@ CAPTURE = "posthog.taxonomic_search_intent.event_match.capture_exception"SEEN_AT = datetime(2026, 1, 1, tzinfo=UTC)+# The last candidate is asked in a different request from Autocapture, so it survives Autocapture's request failing.+LATE_EVENT_LABEL = CORE_EVENT_CANDIDATES[list(CORE_EVENT_CANDIDATES)[-1]].label+LABEL_BY_INSTRUCTIONS = {_question(candidate).instructions: candidate.label for candidate in CORE_EVENT_CANDIDATES.values()}@@ -63,18 +66,40 @@ class TestMatchCoreEvents(BaseTest):@parameterized.expand([- ("too_short", "a"),- ("email", "[email protected]"),- ("url", "https://example.com/pricing"),- ("path", "/reset?token=abc"),+ ("too_short", "a", EventMatchOutcome.WRONG_LENGTH),+ ("too_long", "browser capture " * 5, EventMatchOutcome.WRONG_LENGTH),+ ("email", "[email protected]", EventMatchOutcome.ONLY_VALUES),+ ("url", "https://example.com/pricing", EventMatchOutcome.ONLY_VALUES),+ ("path", "/reset?token=abc", EventMatchOutcome.ONLY_VALUES),])- def test_never_asks_the_model_about_values_or_unanswerable_searches(self, _name: str, query: str) -> None:+ def test_never_asks_the_model_about_values_or_unanswerable_searches(+ self, _name: str, query: str, outcome: EventMatchOutcome+ ) -> None:with patch(BUILD_CLIENT) as build:- assert match_core_events(self._search(query)) == []+ assert match_core_events(self._search(query)) == EventMatchAnswer(matches=[], outcome=outcome)build.assert_not_called()+ @parameterized.expand(+ [+ ("nothing_above_threshold", {"Autocapture": 0.6}, None, EventMatchOutcome.NOTHING_LIKELY),+ ("likely_but_never_seen", {"Screen": 0.85}, None, EventMatchOutcome.NOT_INGESTED),+ ("likely_and_seen", {"Screen": 0.85, "Autocapture": 0.95}, None, EventMatchOutcome.MATCHED),+ ("failed_chunk_and_nothing_likely", {}, "Autocapture", EventMatchOutcome.PARTIAL),+ ("failed_chunk_and_never_seen", {LATE_EVENT_LABEL: 0.9}, "Autocapture", EventMatchOutcome.PARTIAL),+ ]+ )+ def test_names_the_step_that_decided_the_answer(+ self, _name: str, beliefs: dict[str, float], failing_label: str | None, outcome: EventMatchOutcome+ ) -> None:+ with patch(BUILD_CLIENT, return_value=_model_that_believes(beliefs, failing_label)), patch(CAPTURE):+ answer = match_core_events(self._search("browser capture"))++ assert answer.outcome == outcome+ if outcome != EventMatchOutcome.MATCHED:+ assert answer.matches == []+def test_the_model_reads_placeholders_instead_of_values(self) -> None:client = _model_that_believes({})with patch(BUILD_CLIENT, return_value=client):@@ -120,7 +145,7 @@ class TestMatchCoreEvents(BaseTest):})with patch(BUILD_CLIENT, return_value=client):- matches = match_core_events(self._search("browser capture"))+ matches = match_core_events(self._search("browser capture")).matchesassert matches == [EventMatch(name="$autocapture", label="Autocapture", probability=0.95),@@ -150,7 +175,7 @@ class TestMatchCoreEvents(BaseTest):)requests_per_search = -(-len(CORE_EVENT_CANDIDATES) // GATEWAY_MAX_QUESTIONS)with patch(BUILD_CLIENT, return_value=client), patch(CAPTURE) as capture:- matches = match_core_events(self._search("browser capture"))+ matches = match_core_events(self._search("browser capture")).matchesmatch_core_events(self._search("browser capture"))assert [match.name for match in matches] == [late_event]