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(taxonomic-filter): suggest core events for an events search with no results (#107219)

Paul D'Ambracff06953d388
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6a2d7084f161..18d1d8400754 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3152,6 +3152,10 @@ snapshots:
hash: v1.k794b7964.c824be157968e0ef1b8dc82810f4a06dfff364af71722c53823f1d95d4542f7f.D-ZfI3CwGqAa9tdEaUF_psLO6gqWhGZTQnN6Y9i8GRY
filters-taxonomic-filter--dashboard-property-search--light:
hash: v1.k794b7964.d6743ee11d1ef80cc0fb6ceaf465684d2fe455ff2e1c4caa423b255dd9ca6dc3.O0RT-HV6tHeocwL0QPZGUceekoc42axbz0eD_buMRtE
+ filters-taxonomic-filter--empty-events-with-event-match--dark:
+ hash: v1.k794b7964.30d20341622aff37c27fca8216269d839cc72aafd5a9cfb3a195cdde5ba414ed.ioGVHMVBgkAMr11FVdKj-pgx05LSlkwl-vuXRF-t6sw
+ filters-taxonomic-filter--empty-events-with-event-match--light:
+ hash: v1.k794b7964.d07e5394b85d6064eb2e0e92a43e138b71b4248a015af59d6a901874a6c0acca.ViBqvpCMYJ44bOijsqT7TfxMKsAFBtBUnHmRT17SQG4
filters-taxonomic-filter--empty-events-with-stale-toggle--dark:
hash: v1.k794b7964.c9c8b86f1f196faf8bb7ff2fa3a8b662b5da749e9d740979253eefd3caef6d83.Vi2aZn3Sv-3nBjiCPo9tkuX4Dj5bZSq-4KMFkSMAKps
filters-taxonomic-filter--empty-events-with-stale-toggle--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 532a26a9c732..28233a1423d7 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -4430,6 +4430,33 @@ export interface SearchIntentResponseApi {
* @nullable
*/
prompt_version: number | null
+ /**
+ * The search as the decision model read it, with emails, URLs, paths, ids and tokens replaced by placeholders such as <url>. Null when the model did not answer.
+ * @nullable
+ */
+ model_query: string | null
+}
+
+export interface EventMatchRequestApi {
+ /**
+ * What the person typed into the events list search box, which matched no event name.
+ * @maxLength 200
+ */
+ query: string
+}
+
+export interface EventMatchApi {
+ /** The event name to select, such as $autocapture. */
+ name: string
+ /** The event's display name, such as Autocapture. */
+ display_name: string
+ /** How likely the search means this event, from 0 to 1. */
+ probability: number
+}
+
+export interface EventMatchResponseApi {
+ /** PostHog core events the search most likely means, strongest first. Empty when nothing is likely. */
+ matches: EventMatchApi[]
}
export interface UploadedMediaApi {
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 52430429704a..0737ef35f7f5 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -26,6 +26,8 @@ import type {
EmojiSearchSuggestRetrieveParams,
EnterprisePropertyDefinitionApi,
EventIngestionRestrictionApi,
+ EventMatchRequestApi,
+ EventMatchResponseApi,
ExportedAssetApi,
ExportedAssetCreateApi,
ExportsListParams,
@@ -2601,6 +2603,27 @@ export const taxonomicSearchIntentClassifyCreate = async (
})
}
+export const getTaxonomicSearchIntentMatchEventsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/taxonomic_search_intent/match_events/`
+}
+
+/**
+ * Guess which PostHog core events a search that matched no event name describes.
+ * @summary Match an events search to core events
+ */
+export const taxonomicSearchIntentMatchEventsCreate = async (
+ projectId: string,
+ eventMatchRequestApi: EventMatchRequestApi,
+ options?: RequestInit
+): Promise<EventMatchResponseApi> => {
+ return apiMutator<EventMatchResponseApi>(getTaxonomicSearchIntentMatchEventsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(eventMatchRequestApi),
+ })
+}
+
export const getUploadedMediaListUrl = (projectId: string, params: UploadedMediaListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 5e38148882ed..5c3d062665e2 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -1170,6 +1170,19 @@ export const TaxonomicSearchIntentClassifyCreateBody = /* @__PURE__ */ zod.objec
.describe('The id of the scene the picker is open in, such as Insight or Replay.'),
})
+/**
+ * Guess which PostHog core events a search that matched no event name describes.
+ * @summary Match an events search to core events
+ */
+export const taxonomicSearchIntentMatchEventsCreateBodyQueryMax = 200
+
+export const TaxonomicSearchIntentMatchEventsCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .string()
+ .max(taxonomicSearchIntentMatchEventsCreateBodyQueryMax)
+ .describe('What the person typed into the events list search box, which matched no event name.'),
+})
+
/**
*
* When object storage is available this API allows upload of media which can be used, for example, in text cards on dashboards.
diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
index 14a5555fb327..04da7bb0fec4 100644
--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx
@@ -46,6 +46,7 @@ import { getCoreFilterDefinition } from '~/taxonomy/helpers'
import { EntityFilter, EventDefinition, PropertyDefinition } from '~/types'
import { NO_ITEM_SELECTED, infiniteListLogic } from './infiniteListLogic'
+import { TaxonomicEventMatchSuggestions } from './TaxonomicEventMatchSuggestions'
export interface InfiniteListProps {
popupAnchorElement: HTMLDivElement | null
@@ -801,6 +802,9 @@ function InfiniteListEmptyState(): JSX.Element {
</>
)}
</span>
+ {!emptySearchQuery && listGroupType === TaxonomicFilterGroupType.Events && (
+ <TaxonomicEventMatchSuggestions />
+ )}
{canOfferStaleToggle && (
<LemonButton
type="secondary"
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicEventMatchSuggestions.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicEventMatchSuggestions.tsx
new file mode 100644
index 000000000000..63d46bf9ba0a
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicEventMatchSuggestions.tsx
@@ -0,0 +1,37 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { infiniteListLogic } from './infiniteListLogic'
+import { taxonomicEventMatchLogic } from './taxonomicEventMatchLogic'
+
+export function TaxonomicEventMatchSuggestions(): JSX.Element | null {
+ const { props } = useMountedLogic(infiniteListLogic)
+ const logic = taxonomicEventMatchLogic(props)
+ const { suggestedEvents } = useValues(logic)
+ const { selectEventMatch } = useActions(logic)
+
+ if (suggestedEvents.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="flex flex-col items-center gap-y-1" data-attr="taxonomic-event-match">
+ <span className="text-secondary">Did you mean one of these events?</span>
+ <div className="flex flex-wrap justify-center gap-1">
+ {suggestedEvents.map((match) => (
+ <LemonButton
+ key={match.name}
+ type="secondary"
+ size="xsmall"
+ // pinned: data-attr, autocapture and the flag's success metric read it
+ data-attr="taxonomic-event-match-suggestion"
+ onClick={() => selectEventMatch(match)}
+ >
+ {match.display_name}
+ </LemonButton>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
index 86751ebc110e..5eb2f9d2db89 100644
--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx
@@ -846,6 +846,50 @@ export const EmptyEventsWithStaleToggle: Story = {
},
}
+/** A search that matches no event name gets core events the decision model thinks it describes. */
+export const EmptyEventsWithEventMatch: Story = {
+ render: (args) => {
+ useMountedLogic(actionsModel)
+ const { setSearchQuery } = useActions(
+ taxonomicFilterLogic({ ...args, taxonomicFilterLogicKey: args.taxonomicFilterLogicKey as string })
+ )
+
+ useOnMountEffect(() => setSearchQuery('browser capture'))
+
+ return (
+ <div className="w-fit border rounded p-2 bg-surface-primary">
+ <TaxonomicFilter {...args} />
+ </div>
+ )
+ },
+ args: {
+ taxonomicFilterLogicKey: 'events-event-match',
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/event_definitions': [],
+ },
+ post: {
+ '/api/projects/:team_id/taxonomic_search_intent/match_events/': () => [
+ 200,
+ {
+ matches: [
+ { name: '$autocapture', display_name: 'Autocapture', probability: 0.95 },
+ { name: '$rageclick', display_name: 'Rageclick', probability: 0.74 },
+ ],
+ },
+ ],
+ },
+ }),
+ ],
+ parameters: {
+ featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_EVENT_MATCH]: true },
+ testOptions: { waitForSelector: '[data-attr="taxonomic-event-match-suggestion"]' },
+ },
+}
+
// The decision model answers "person properties" for a search of "email" in every search intent story.
const searchIntentPersonPropertiesMock = mswDecorator({
post: {
@@ -862,6 +906,9 @@ const searchIntentPersonPropertiesMock = mswDecorator({
},
})
+// The empty state also carries the list class, so the "All" tab stories wait for a real result row instead.
+const SEARCH_INTENT_ALL_TAB_FIRST_ROW = '[data-attr="prop-filter-suggested_filters-0"]'
+
const SEARCH_INTENT_GROUP_TYPES = [
TaxonomicFilterGroupType.SuggestedFilters,
TaxonomicFilterGroupType.EventProperties,
@@ -925,7 +972,7 @@ export const SearchIntentControlKeepsOrder: Story = {
decorators: [searchIntentPersonPropertiesMock],
parameters: {
featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]: 'control' },
- testOptions: { waitForSelector: '.taxonomic-infinite-list' },
+ testOptions: { waitForSelector: SEARCH_INTENT_ALL_TAB_FIRST_ROW },
},
}
@@ -936,6 +983,6 @@ export const SearchIntentPromotesGroup: Story = {
decorators: [searchIntentPersonPropertiesMock],
parameters: {
featureFlags: { [FEATURE_FLAGS.TAXONOMIC_FILTER_SEARCH_INTENT]: 'promote' },
- testOptions: { waitForSelector: '.taxonomic-infinite-list' },
+ testOptions: { waitForSelector: SEARCH_INTENT_ALL_TAB_FIRST_ROW },
},
}
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicEventMatchLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicEventMatchLogic.test.ts
new file mode 100644
index 000000000000..4c6474629f4c
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicEventMatchLogic.test.ts
@@ -0,0 +1,189 @@
+import { MOCK_TEAM_ID } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { AppContext } from '~/types'
+
+import { resetEventMatchAvailabilityForTests, taxonomicEventMatchLogic } from './taxonomicEventMatchLogic'
+import { taxonomicFilterLogic } from './taxonomicFilterLogic'
+import { TaxonomicFilterGroupType, TaxonomicFilterLogicProps } from './types'
+
+window.POSTHOG_APP_CONTEXT = {
+ current_team: { id: MOCK_TEAM_ID },
+ current_project: { id: MOCK_TEAM_ID },
+} as unknown as AppContext
+
+const PROPS: TaxonomicFilterLogicProps = {
+ taxonomicFilterLogicKey: 'event-match-test',
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],
+}
+
+const AUTOCAPTURE = { name: '$autocapture', display_name: 'Autocapture', probability: 0.95 }
+
+describe('taxonomicEventMatchLogic', () => {
+ let filterLogic: ReturnType<typeof taxonomicFilterLogic.build>
+ let logic: ReturnType<typeof taxonomicEventMatchLogic.build>
+ let matchRequests: Record<string, any>[]
+ let status: number
+ let matches: Record<string, any>[]
+
+ beforeEach(() => {
+ matchRequests = []
+ status = 200
+ matches = [AUTOCAPTURE]
+ resetEventMatchAvailabilityForTests()
+ useMocks({
+ get: {
+ '/api/projects/:team/event_definitions': () => [200, { results: [], count: 0 }],
+ },
+ post: {
+ '/api/projects/:team/taxonomic_search_intent/match_events/': async ({ request }) => {
+ matchRequests.push((await request.json()) as Record<string, any>)
+ return status === 200 ? [200, { matches }] : [status, {}]
+ },
+ },
+ })
+ initKeaTests()
+ filterLogic = taxonomicFilterLogic(PROPS)
+ filterLogic.mount()
+ logic = taxonomicEventMatchLogic(PROPS)
+ logic.mount()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ const search = async (query: string): Promise<void> => {
+ filterLogic.actions.setSearchQuery(query)
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ const enroll = (enabled: boolean): void => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TAXONOMIC_FILTER_EVENT_MATCH], {
+ [FEATURE_FLAGS.TAXONOMIC_FILTER_EVENT_MATCH]: enabled,
+ })
+ }
+
+ it('does not ask the model for a person outside the flag', async () => {
+ enroll(false)
+
+ await search('browser capture')
+
+ expect(matchRequests).toHaveLength(0)
+ expect(logic.values.suggestedEvents).toEqual([])
+ })
+
+ it('suggests the matched events for the current search only, and selects one on click', async () => {
+ enroll(true)
+ const captureSpy = jest.spyOn(posthog, 'capture')
+
+ await search('browser capture')
+
+ expect(matchRequests).toEqual([{ query: 'browser capture' }])
+ expect(logic.values.suggestedEvents).toEqual([AUTOCAPTURE])
+
+ await expectLogic(filterLogic, () => logic.actions.selectEventMatch(AUTOCAPTURE)).toDispatchActions([
+ (action) =>
+ action.type === filterLogic.actionTypes.selectItem &&
+ action.payload.group.type === TaxonomicFilterGroupType.Events &&
+ action.payload.value === '$autocapture' &&
+ action.payload.meta.position === 0,
+ ])
+ expect(captureSpy).toHaveBeenCalledWith('taxonomic filter event match selected', {
+ surface: 'legacy-pill',
+ eventName: '$autocapture',
+ position: 0,
+ })
+
+ filterLogic.actions.setSearchQuery('browser capture events')
+ expect(logic.values.suggestedEvents).toEqual([])
+ })
+
+ it('does not suggest an event the picker excludes', async () => {
+ const excludingProps: TaxonomicFilterLogicProps = {
+ ...PROPS,
+ taxonomicFilterLogicKey: 'event-match-excluding-test',
+ excludedProperties: { [TaxonomicFilterGroupType.Events]: ['$autocapture'] },
+ }
+ const excludingFilterLogic = taxonomicFilterLogic(excludingProps)
+ excludingFilterLogic.mount()
+ const excludingLogic = taxonomicEventMatchLogic(excludingProps)
+ excludingLogic.mount()
+ enroll(true)
+ const captureSpy = jest.spyOn(posthog, 'capture')
+
+ excludingFilterLogic.actions.setSearchQuery('browser capture')
+ await expectLogic(excludingLogic).toFinishAllListeners()
+
+ expect(matchRequests).toHaveLength(1)
+ expect(excludingLogic.values.suggestedEvents).toEqual([])
+ expect(captureSpy).not.toHaveBeenCalledWith('taxonomic filter event match suggested', expect.anything())
+ })
+
+ it('fills the suggestions from the events the picker does not exclude', async () => {
+ const excludingProps: TaxonomicFilterLogicProps = {
+ ...PROPS,
+ taxonomicFilterLogicKey: 'event-match-limit-test',
+ excludedProperties: { [TaxonomicFilterGroupType.Events]: ['$autocapture'] },
+ }
+ const excludingFilterLogic = taxonomicFilterLogic(excludingProps)
+ excludingFilterLogic.mount()
+ const excludingLogic = taxonomicEventMatchLogic(excludingProps)
+ excludingLogic.mount()
+ enroll(true)
+ matches = [
+ AUTOCAPTURE,
+ { name: '$rageclick', display_name: 'Rageclick', probability: 0.9 },
+ { name: '$dead_click', display_name: 'Dead click', probability: 0.85 },
+ { name: '$pageview', display_name: 'Pageview', probability: 0.8 },
+ { name: '$exception', display_name: 'Exception', probability: 0.75 },
+ ]
+
+ excludingFilterLogic.actions.setSearchQuery('browser capture')
+ await expectLogic(excludingLogic).toFinishAllListeners()
+
+ expect(excludingLogic.values.suggestedEvents.map((match) => match.name)).toEqual([
+ '$rageclick',
+ '$dead_click',
+ '$pageview',
+ ])
+ })
+
+ it('stops asking for the project after a 404', async () => {
+ enroll(true)
+ status = 404
+
+ await search('browser capture')
+ await search('page view')
+
+ expect(matchRequests).toHaveLength(1)
+ expect(logic.values.suggestedEvents).toEqual([])
+ })
+
+ it.each([
+ [404, false],
+ [429, false],
+ [503, false],
+ [500, true],
+ ])('reports a %s failure to error tracking: %s', async (failureStatus, reported) => {
+ enroll(true)
+ status = failureStatus
+ const captureExceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
+
+ await search('browser capture')
+
+ expect(logic.values.suggestedEvents).toEqual([])
+ expect(captureExceptionSpy.mock.calls).toEqual(
+ reported
+ ? [[expect.anything(), { feature: 'taxonomic-event-match', projectId: MOCK_TEAM_ID, status: 500 }]]
+ : []
+ )
+ })
+})
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicEventMatchLogic.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicEventMatchLogic.ts
new file mode 100644
index 000000000000..edfb05644fe3
--- /dev/null
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicEventMatchLogic.ts
@@ -0,0 +1,226 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { taxonomicSearchIntentMatchEventsCreate } from '~/generated/core/api'
+import type { EventMatchApi } from '~/generated/core/api.schemas'
+
+import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
+import { SelectItemMeta, taxonomicFilterLogic } from './taxonomicFilterLogic'
+import { legacyTaxonomicSurface } from './taxonomicFilterSurface'
+import {
+ TaxonomicFilterGroup,
+ TaxonomicFilterGroupType,
+ TaxonomicFilterLogicProps,
+ TaxonomicFilterValue,
+} from './types'
+
+// Mirrors MIN_QUERY_CHARS and MAX_QUERY_CHARS in posthog/taxonomic_search_intent/classify.py.
+const MIN_QUERY_LENGTH = 2
+const MAX_QUERY_LENGTH = 64
+// Mirrors MAX_MATCHES in posthog/taxonomic_search_intent/event_match.py. Applied after exclusions, so they never empty the list.
+const MAX_SUGGESTIONS = 3
+// Longer than a keystroke gap, so a person who types a phrase asks once and not once per letter.
+const EVENT_MATCH_DEBOUNCE_MS = 350
+// A throttle returns 429 by design, and the backend reports its own model failures as 503.
+// Other failures are visible only in the browser, so the logic reports them without the search text.
+const UNREPORTED_FAILURE_STATUSES = [429, 503]
+
+export interface EventMatches {
+ projectId: number
+ query: string
+ matches: EventMatchApi[]
+}
+
+// A 404 means the person is not in the flag for this project, so the rest of the page load does not ask again.
+const unavailableProjectIds = new Set<number>()
+
+export function resetEventMatchAvailabilityForTests(): void {
+ unavailableProjectIds.clear()
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taxonomicEventMatchLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentProjectId: number | null // projectLogic
+ searchQuery: string // taxonomicFilterLogic
+ taxonomicGroups: TaxonomicFilterGroup[] // taxonomicFilterLogic
+ eventMatches: EventMatches | null
+ suggestedEvents: EventMatchApi[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taxonomicEventMatchLogicActions {
+ selectItem: (
+ group: TaxonomicFilterGroup,
+ value: TaxonomicFilterValue,
+ item: any,
+ meta?: SelectItemMeta | undefined
+ ) => {
+ group: TaxonomicFilterGroup
+ item: any
+ meta: SelectItemMeta | undefined
+ value: TaxonomicFilterValue
+ } // taxonomicFilterLogic
+ setSearchQuery: (searchQuery: string) => {
+ searchQuery: string
+ } // taxonomicFilterLogic
+ findEventMatches: (searchQuery: string) => {
+ searchQuery: string
+ }
+ selectEventMatch: (match: EventMatchApi) => {
+ match: EventMatchApi
+ }
+ setEventMatches: (eventMatches: EventMatches | null) => {
+ eventMatches: EventMatches | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taxonomicEventMatchLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ suggestedEvents: (
+ eventMatches: EventMatches | null,
+ searchQuery: string,
+ taxonomicGroups: TaxonomicFilterGroup[],
+ currentProjectId: number | null
+ ) => EventMatchApi[]
+ }
+}
+
+export type taxonomicEventMatchLogicType = MakeLogicType<
+ taxonomicEventMatchLogicValues,
+ taxonomicEventMatchLogicActions,
+ TaxonomicFilterLogicProps,
+ taxonomicEventMatchLogicMeta
+>
+
+/**
+ * Asks the decision model which PostHog core events a search that matched no event name describes, for the
+ * `taxonomic-filter-event-match` flag. Mounted only by the events list's empty state. Legacy surface only.
+ */
+export const taxonomicEventMatchLogic = kea<taxonomicEventMatchLogicType>([
+ props({} as TaxonomicFilterLogicProps),
+ key((props) => `${props.taxonomicFilterLogicKey}`),
+ path((key) => ['lib', 'components', 'TaxonomicFilter', 'taxonomicEventMatchLogic', key]),
+ connect((props: TaxonomicFilterLogicProps) => ({
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ projectLogic,
+ ['currentProjectId'],
+ taxonomicFilterLogic(props),
+ ['searchQuery', 'taxonomicGroups'],
+ ],
+ actions: [taxonomicFilterLogic(props), ['selectItem', 'setSearchQuery']],
+ })),
+ actions({
+ findEventMatches: (searchQuery: string) => ({ searchQuery }),
+ setEventMatches: (eventMatches: EventMatches | null) => ({ eventMatches }),
+ selectEventMatch: (match: EventMatchApi) => ({ match }),
+ }),
+ reducers({
+ eventMatches: [
+ null as EventMatches | null,
+ {
+ setEventMatches: (_, { eventMatches }) => eventMatches,
+ },
+ ],
+ }),
+ selectors({
+ suggestedEvents: [
+ (s) => [s.eventMatches, s.searchQuery, s.taxonomicGroups, s.currentProjectId],
+ (
+ eventMatches: EventMatches | null,
+ searchQuery: string,
+ taxonomicGroups: TaxonomicFilterGroup[],
+ currentProjectId: number | null
+ ): EventMatchApi[] => {
+ // An answer for an older search or another project stays hidden, so a suggestion never names the wrong one.
+ if (eventMatches?.query !== searchQuery.trim() || eventMatches.projectId !== currentProjectId) {
+ return []
+ }
+ // A picker that excludes an event from its list must not offer it as a suggestion either.
+ const excluded =
+ taxonomicGroups.find((group) => group.type === TaxonomicFilterGroupType.Events)
+ ?.excludedProperties ?? []
+ return eventMatches.matches.filter((match) => !excluded.includes(match.name)).slice(0, MAX_SUGGESTIONS)
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setSearchQuery: ({ searchQuery }) => {
+ actions.findEventMatches(searchQuery)
+ },
+ findEventMatches: async ({ searchQuery }, breakpoint) => {
+ const query = searchQuery.trim()
+ const projectId = values.currentProjectId
+ if (
+ query.length < MIN_QUERY_LENGTH ||
+ query.length > MAX_QUERY_LENGTH ||
+ projectId === null ||
+ unavailableProjectIds.has(projectId)
+ ) {
+ return
+ }
+ await breakpoint(EVENT_MATCH_DEBOUNCE_MS)
+ // Read after the pause, so flags that load while the person types still count.
+ if (!values.featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_EVENT_MATCH]) {
+ return
+ }
+
+ let matches: EventMatchApi[]
+ try {
+ matches = (await taxonomicSearchIntentMatchEventsCreate(String(projectId), { query })).matches
+ } catch (error: any) {
+ if (error?.status === 404) {
+ unavailableProjectIds.add(projectId)
+ } else if (!UNREPORTED_FAILURE_STATUSES.includes(error?.status)) {
+ posthog.captureException(error, {
+ feature: 'taxonomic-event-match',
+ projectId,
+ status: error?.status,
+ })
+ }
+ breakpoint()
+ actions.setEventMatches(null)
+ return
+ }
+ breakpoint()
+ actions.setEventMatches({ projectId, query, matches })
+ // Only the suggestions the picker shows, after its exclusions, count for the flag's metric.
+ const shown = values.suggestedEvents
+ if (shown.length > 0) {
+ // pinned: analytics event name and properties, the flag's success metric reads them
+ posthog.capture('taxonomic filter event match suggested', {
+ surface: legacyTaxonomicSurface(),
+ suggestedEvents: shown.map((match) => match.name),
+ })
+ }
+ },
+ selectEventMatch: ({ match }) => {
+ const eventsGroup = values.taxonomicGroups.find((group) => group.type === TaxonomicFilterGroupType.Events)
+ if (!eventsGroup) {
+ return
+ }
+ const position = values.suggestedEvents.findIndex((suggested) => suggested.name === match.name)
+ if (position === -1) {
+ return
+ }
+ // pinned: analytics event name and properties, the flag's success metric reads them
+ posthog.capture('taxonomic filter event match selected', {
+ surface: legacyTaxonomicSurface(),
+ eventName: match.name,
+ position,
+ })
+ actions.selectItem(eventsGroup, match.name, { name: match.name }, { position })
+ },
+ })),
+ afterMount(({ actions, values }) => {
+ actions.findEventMatches(values.searchQuery)
+ }),
+])
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.ts
index d5cb0227b717..8ca0e93f6b24 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicSearchIntentLogic.ts
@@ -241,9 +241,7 @@ export const taxonomicSearchIntentLogic = kea<taxonomicSearchIntentLogicType>([
suggestsSwitch: intent.suggests_switch,
wouldPromote: canPromote,
shown: values.variant === 'banner' ? !!values.suggestedSwitch : promoted,
- // Only a model answer carries the query. The server keeps emails, URLs, paths, digit runs and opaque tokens
- // from the model, so those never appear here, but other free text such as a name still does.
- query: intent.method === 'model' ? intent.query : undefined,
+ query: intent.model_query ?? undefined,
})
},
acceptSuggestedSwitch: () => {
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3ff5b70d87c0..bd647c9a9cae 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -529,6 +529,7 @@ export const FEATURE_FLAGS = {
TASKS_STREAM_VIA_PROXY: 'tasks-stream-via-proxy', // owner: #team-ai-observability
TAXONOMIC_FILTER_MENU_REBUILD: 'taxonomic-filter-menu-rebuild', // owner: @adamleith, opt-in to the rebuilt TaxonomicFilter — headless filter panel + new popover menu (column / preview-pane)
TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model, then suggests the right tab (banner) or promotes its group (promote)
+ TAXONOMIC_FILTER_EVENT_MATCH: 'taxonomic-filter-event-match', // owner: @pauldambra, asks the decision model which core events an events search with no results describes, then suggests them in the empty state
TEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cards
TOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analytics
TRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)
diff --git a/posthog/api/taxonomic_search_intent.py b/posthog/api/taxonomic_search_intent.py
index 8db1d41e939e..81abdcf576f2 100644
--- a/posthog/api/taxonomic_search_intent.py
+++ b/posthog/api/taxonomic_search_intent.py
@@ -20,7 +20,8 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.llm.system_one import SystemOneNotConfigured, SystemOneRequestFailed
from posthog.models import User
from posthog.taxonomic_search_intent.classify import classify_search_intent, search_intent_enabled
-from posthog.taxonomic_search_intent.contracts import SearchIntentRequest, SearchIntentSource
+from posthog.taxonomic_search_intent.contracts import EventMatchRequest, SearchIntentRequest, SearchIntentSource
+from posthog.taxonomic_search_intent.event_match import EVENT_MATCH_FEATURE_FLAG, match_core_events
logger = structlog.get_logger(__name__)
@@ -78,6 +79,35 @@ class SearchIntentResponseSerializer(serializers.Serializer):
"a skipped search, or the bundled fallback prompt."
),
)
+ model_query = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "The search as the decision model read it, with emails, URLs, paths, ids and tokens replaced by "
+ "placeholders such as <url>. Null when the model did not answer."
+ ),
+ )
+
+
+class EventMatchRequestSerializer(serializers.Serializer):
+ query = serializers.CharField(
+ max_length=MAX_SEARCH_QUERY_CHARS,
+ allow_blank=True,
+ trim_whitespace=True,
+ help_text="What the person typed into the events list search box, which matched no event name.",
+ )
+
+
+class EventMatchSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="The event name to select, such as $autocapture.")
+ display_name = serializers.CharField(help_text="The event's display name, such as Autocapture.")
+ probability = serializers.FloatField(help_text="How likely the search means this event, from 0 to 1.")
+
+
+class EventMatchResponseSerializer(serializers.Serializer):
+ matches = serializers.ListField(
+ child=EventMatchSerializer(),
+ help_text="PostHog core events the search most likely means, strongest first. Empty when nothing is likely.",
+ )
class SearchIntentUnavailable(APIException):
@@ -98,6 +128,18 @@ class SearchIntentSustainedThrottle(UserRateThrottle):
rate = "3000/day"
+# Each event match miss makes several model requests, and it only runs for a search with no results,
+# so it gets far lower rates than classify.
+class EventMatchBurstThrottle(UserRateThrottle):
+ scope = "taxonomic_event_match_burst"
+ rate = "20/minute"
+
+
+class EventMatchSustainedThrottle(UserRateThrottle):
+ scope = "taxonomic_event_match_sustained"
+ rate = "400/day"
+
+
@extend_schema(extensions={"x-product": "core"})
class SearchIntentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "INTERNAL"
@@ -142,6 +184,41 @@ class SearchIntentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"suggests_switch": intent.suggests_switch,
"method": intent.source,
"prompt_version": intent.prompt_version,
+ "model_query": intent.model_query,
+ }
+ ).data
+ )
+
+ @validated_request(
+ request_serializer=EventMatchRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=EventMatchResponseSerializer, description="The likely core events."),
+ 404: OpenApiResponse(description="Event matching is not enabled for this person."),
+ 503: OpenApiResponse(description="The decision model did not answer in time."),
+ },
+ summary="Match an events search to core events",
+ description="Guess which PostHog core events a search that matched no event name describes.",
+ )
+ @action(detail=False, methods=["POST"], throttle_classes=[EventMatchBurstThrottle, EventMatchSustainedThrottle])
+ def match_events(self, request: Request, **kwargs: Any) -> Response:
+ user = cast(User, request.user)
+ if not search_intent_enabled(str(user.distinct_id), str(self.organization_id), flag=EVENT_MATCH_FEATURE_FLAG):
+ raise NotFound()
+ search = EventMatchRequest(
+ team_id=self.team_id, project_id=self.team.project_id, query=request.validated_data["query"]
+ )
+ try:
+ matches = match_core_events(search)
+ except (SystemOneNotConfigured, SystemOneRequestFailed) as error:
+ logger.warning("taxonomic_event_match_unavailable", team_id=self.team_id, reason=type(error).__name__)
+ raise SearchIntentUnavailable() from error
+ return Response(
+ EventMatchResponseSerializer(
+ {
+ "matches": [
+ {"name": match.name, "display_name": match.label, "probability": match.probability}
+ for match in matches
+ ]
}
).data
)
diff --git a/posthog/api/test/test_taxonomic_search_intent.py b/posthog/api/test/test_taxonomic_search_intent.py
index 50a4f81c0784..8a14354e1d78 100644
--- a/posthog/api/test/test_taxonomic_search_intent.py
+++ b/posthog/api/test/test_taxonomic_search_intent.py
@@ -9,6 +9,7 @@ from rest_framework import status
from posthog.llm.gateway_client import team_distinct_id
from posthog.llm.system_one import ChoiceAnswer, SystemOneNotConfigured, SystemOneRequestFailed, SystemOneResult
+from posthog.taxonomic_search_intent.contracts import EventMatch
from posthog.taxonomic_search_intent.prompt import BUNDLED_SEARCH_INTENT_PROMPT
ALL_TABS = ("suggested_filters", "events", "event_properties", "person_properties", "pageview_urls", "email_addresses")
@@ -55,6 +56,7 @@ class TestSearchIntentEndpoint(APIBaseTest):
"suggests_switch": True,
"method": "model",
"prompt_version": None,
+ "model_query": "email",
}
assert build.call_args.kwargs["distinct_id"] == team_distinct_id(self.team.id)
assert enabled.call_args.args == ("taxonomic-filter-search-intent", str(self.user.distinct_id))
@@ -98,3 +100,24 @@ 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:
+ match = EventMatch(name="$autocapture", label="Autocapture", probability=0.95)
+ with (
+ patch(FLAG_CHECK, return_value=enabled) as flag,
+ patch("posthog.api.taxonomic_search_intent.match_core_events", return_value=[match]) as matcher,
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/taxonomic_search_intent/match_events/",
+ {"query": "browser capture"},
+ format="json",
+ )
+
+ assert response.status_code == expected_status
+ assert flag.call_args.args[0] == "taxonomic-filter-event-match"
+ if enabled:
+ assert response.json() == {
+ "matches": [{"name": "$autocapture", "display_name": "Autocapture", "probability": 0.95}]
+ }
+ assert matcher.call_args.args[0].project_id == self.team.project_id
diff --git a/posthog/taxonomic_search_intent/classify.py b/posthog/taxonomic_search_intent/classify.py
index b4700de01737..17caac02fd4c 100644
--- a/posthog/taxonomic_search_intent/classify.py
+++ b/posthog/taxonomic_search_intent/classify.py
@@ -1,8 +1,10 @@
"""
Classify a filter picker search: which tab (taxonomic group) does the person look for?
-Value-shaped input (an email address, a URL, a path) is matched by pattern and never goes to the model.
-Everything else is one multiple choice question to the decision model, over the tabs the picker shows.
+A search that is one value (an email address, a URL, a path) is matched by pattern. Everything else is one
+multiple choice question to the decision model, over the tabs the picker shows. The model reads the search
+with each value-shaped word replaced by a placeholder, which names the shape and keeps the value itself out of
+model inputs and anything built from them.
"""
import re
@@ -33,7 +35,7 @@ MAX_QUERY_CHARS = 64
SEARCH_INTENT_TIMEOUT_SECONDS = 2.0
CACHE_TTL_SECONDS = 24 * 60 * 60
# Keyed per team: a cache shared across teams lets a fast answer tell one team what another team searched.
-CACHE_KEY_PREFIX = "taxonomic_search_intent:v1"
+CACHE_KEY_PREFIX = "taxonomic_search_intent:v2"
_EMAIL_VALUE = re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$", re.IGNORECASE)
_URL_VALUE = re.compile(r"^(https?://|www\.)", re.IGNORECASE)
@@ -41,6 +43,17 @@ _URL_VALUE = re.compile(r"^(https?://|www\.)", re.IGNORECASE)
_PATH_VALUE = re.compile(r"^/")
# Long digit runs are ids or phone numbers, which are not ours to send.
_DIGIT_RUN = re.compile(r"\d{6,}")
+_MIN_ID_DIGITS = 6
+# A group of digits and separators, such as "+1", "(415)" or "555-2671". A run of them can be one phone number.
+_DIGIT_GROUP = re.compile(r"^\+?[\d.:-]*\d[\d.:-]*$")
+_IPV4 = re.compile(r"^\d{1,3}(\.\d{1,3}){3}$")
+# A bare host such as "example.com". Only common top-level domains, so a dotted property such as "user.plan" still reads.
+_HOSTNAME = re.compile(
+ r"^([a-z0-9-]+\.)+"
+ r"(com|net|org|io|co|ai|app|dev|me|info|biz|xyz|tech|cloud|uk|us|eu|de|fr|es|it|nl|ca|au|in|jp|br)"
+ r"(:\d+)?$",
+ re.IGNORECASE,
+)
# One word of 8+ characters that mixes letters with two or more digits is a token or an id, such as a session id.
_OPAQUE_TOKEN = re.compile(r"^(?=\S*[a-z])(?=\S*\d\S*\d)\S{8,}$", re.IGNORECASE)
_SCENE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
@@ -50,8 +63,8 @@ _QUESTION_ID = "tab"
_CACHED_INTENT = TypeAdapter(SearchIntent)
-def search_intent_enabled(distinct_id: str, organization_id: str) -> bool:
- """The flag assigns the experiment arms. Every arm asks, so any value other than off enables the endpoint.
+def search_intent_enabled(distinct_id: str, organization_id: str, flag: str = SEARCH_INTENT_FEATURE_FLAG) -> bool:
+ """Any flag value other than off enables the endpoint, because every arm of an experiment asks the model.
Dark launch: only local development and the US cloud, so no flag change can bring it up in the EU or on
self-hosted. DEBUG bypasses the flag because the analytics SDK is disabled in local development.
@@ -63,7 +76,7 @@ def search_intent_enabled(distinct_id: str, organization_id: str) -> bool:
try:
return bool(
posthoganalytics.feature_enabled(
- SEARCH_INTENT_FEATURE_FLAG,
+ flag,
distinct_id,
groups={"organization": organization_id},
group_properties={"organization": {"id": organization_id}},
@@ -85,23 +98,84 @@ def _rule_match(group_type: str) -> SearchIntent:
def rule_intent(query: str, available_group_types: tuple[str, ...]) -> SearchIntent | None:
- """Match value-shaped input. None means the query is not a value and the model can read it."""
- if "@" in query:
- if _EMAIL_VALUE.match(query) and "email_addresses" in available_group_types:
+ """Answer a search that is one value by its shape. None means the model reads it, with any values redacted."""
+ if _EMAIL_VALUE.match(query):
+ if "email_addresses" in available_group_types:
return _rule_match("email_addresses")
- if _EMAIL_VALUE.match(query) and "person_properties" in available_group_types:
+ if "person_properties" in available_group_types:
return _rule_match("person_properties")
- # A partial email address is still personal data, so it never goes to the model.
- return _skipped()
- if _URL_VALUE.match(query) or _PATH_VALUE.match(query):
- if "pageview_urls" in available_group_types:
- return _rule_match("pageview_urls")
- return _skipped()
- if _DIGIT_RUN.search(query) or any(_OPAQUE_TOKEN.match(word) for word in query.split()):
- return _skipped()
+ if (_URL_VALUE.match(query) or _PATH_VALUE.match(query)) and "pageview_urls" in available_group_types:
+ return _rule_match("pageview_urls")
return None
+# Brackets, quotes and trailing punctuation around a value would otherwise hide it from the shape checks.
+_WRAPPING_PUNCTUATION = "()[]{}<>.,;:!?\"'`"
+_VALUE_MARKERS = ("@", "=")
+
+
+def _bare(word: str) -> str:
+ return word.strip(_WRAPPING_PUNCTUATION)
+
+
+def _placeholder(word: str) -> str | None:
+ """The shape of a value-shaped word, which the model reads instead of the value. None for an ordinary word."""
+ bare = _bare(word)
+ if "@" in bare:
+ return "<email>"
+ if "://" in bare or "www." in bare.lower() or _HOSTNAME.match(bare):
+ return "<url>"
+ if _IPV4.match(bare):
+ return "<ip>"
+ # A path can carry a token or personal data in any segment, a Windows path included.
+ if "/" in bare or "\\" in bare:
+ return "<path>"
+ if "=" in bare:
+ return "<value>"
+ if _DIGIT_RUN.search(bare):
+ return "<number>"
+ if _OPAQUE_TOKEN.match(bare):
+ return "<id>"
+ return None
+
+
+def redact_values(query: str) -> str | None:
+ """The search with each value-shaped word replaced by a placeholder that names its shape.
+
+ None when only values are left, because the model then has nothing to read.
+ """
+ words = query.split()
+ # A marker at a word's edge, as in "token = sk_live_x" or "ada @ example.com", leaves its value in the next word.
+ if any(bare[:1] in _VALUE_MARKERS or bare[-1:] in _VALUE_MARKERS for bare in map(_bare, words)):
+ return None
+ parts: list[str] = []
+ reads_a_word = False
+ start = 0
+ while start < len(words):
+ placeholder = _placeholder(words[start])
+ end = start if placeholder else _number_run_end(words, start)
+ if end > start:
+ parts.append("<number>")
+ start = end
+ continue
+ reads_a_word = reads_a_word or placeholder is None
+ parts.append(placeholder or words[start])
+ start += 1
+ return " ".join(parts) if reads_a_word else None
+
+
+def _number_run_end(words: list[str], start: int) -> int:
+ """The end of the digit groups from `start` when together they hold an id's worth of digits, else `start`.
+
+ A phone number such as "+1 (415) 555-2671" spreads its digits over several words, and no one word looks like an id.
+ """
+ end = start
+ while end < len(words) and _DIGIT_GROUP.match(_bare(words[end])):
+ end += 1
+ digits = sum(char.isdigit() for word in words[start:end] for char in word)
+ return end if digits >= _MIN_ID_DIGITS else start
+
+
def search_intent_state(query: str, active_group_type: str, scene: str | None) -> str:
lines = ["A person uses the filter picker in PostHog, a product analytics tool."]
if scene and _SCENE.match(scene):
@@ -158,8 +232,11 @@ def _classify(request: SearchIntentRequest, prompt: SearchIntentPrompt, *, use_c
}
if len(options) < 2:
return _skipped()
+ model_query = redact_values(query)
+ if model_query is None:
+ return _skipped()
- state = search_intent_state(query, request.active_group_type, request.scene)
+ state = search_intent_state(model_query, request.active_group_type, request.scene)
key = _cache_key(
request.team_id, SEARCH_INTENT_MODEL, state, prompt.instructions, options, prompt.confident_threshold
)
@@ -188,6 +265,7 @@ def _classify(request: SearchIntentRequest, prompt: SearchIntentPrompt, *, use_c
is_confident=answer.confidence >= prompt.confident_threshold,
source=SearchIntentSource.MODEL,
prompt_version=prompt.version,
+ model_query=model_query,
)
if use_cache:
cache.set(key, _CACHED_INTENT.dump_json(intent).decode(), CACHE_TTL_SECONDS)
diff --git a/posthog/taxonomic_search_intent/contracts.py b/posthog/taxonomic_search_intent/contracts.py
index 0929e4775140..a4d085851017 100644
--- a/posthog/taxonomic_search_intent/contracts.py
+++ b/posthog/taxonomic_search_intent/contracts.py
@@ -31,3 +31,23 @@ class SearchIntent:
suggests_switch: bool = False
# The managed prompt version the model read, or None for a rule match, a skip or the bundled prompt.
prompt_version: int | None = None
+ # The search as the model read it, with values replaced by placeholders. None when the model did not answer.
+ model_query: str | None = None
+
+
+@frozen
+class EventMatchRequest:
+ """A search in the picker's events list that found nothing, to match against the PostHog core events."""
+
+ team_id: int
+ project_id: int
+ query: str
+
+
+@frozen
+class EventMatch:
+ """A core event the search may mean. ``probability`` is the model's confidence that the search names it."""
+
+ name: str
+ label: str
+ probability: float
diff --git a/posthog/taxonomic_search_intent/event_match.py b/posthog/taxonomic_search_intent/event_match.py
new file mode 100644
index 000000000000..4982acf939d3
--- /dev/null
+++ b/posthog/taxonomic_search_intent/event_match.py
@@ -0,0 +1,217 @@
+"""
+Match a filter picker search that found no events to the PostHog core events it may mean.
+
+A person who does not know an event's name types what the event does, such as "browser capture" for
+autocapture. Fuzzy search cannot bridge that gap, so each core event becomes one yes/no question to the
+decision model, with the event's label and description as the meaning to judge.
+"""
+
+import hashlib
+import contextvars
+from collections.abc import Sequence
+from concurrent.futures import ThreadPoolExecutor
+
+from django.core.cache import cache
+
+import structlog
+from pydantic import TypeAdapter, ValidationError
+
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+from posthog.llm.gateway_client import team_distinct_id
+from posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneRequestFailed, SystemOneResult
+from posthog.llm.system_one_client import GATEWAY_MAX_QUESTIONS, SystemOneClient, build_system_one_client
+from posthog.models import EventDefinition
+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
+
+from .classify import (
+ CACHE_TTL_SECONDS,
+ MAX_QUERY_CHARS,
+ MIN_QUERY_CHARS,
+ SEARCH_INTENT_MODEL,
+ SEARCH_INTENT_TIMEOUT_SECONDS,
+ redact_values,
+)
+from .contracts import EventMatch, EventMatchRequest
+
+logger = structlog.get_logger(__name__)
+
+EVENT_MATCH_FEATURE_FLAG = "taxonomic-filter-event-match"
+# The picker shows a suggestion only above this probability. Tune it from the eval suite, not by feel.
+MATCH_THRESHOLD = 0.7
+# The picker shows at most this many, after it removes the events it excludes, so the endpoint returns them all.
+MAX_MATCHES = 3
+CACHE_KEY_PREFIX = "taxonomic_search_intent:event_match:v1"
+
+_CACHED_MATCHES = TypeAdapter(list[EventMatch])
+
+
+@frozen
+class CoreEventCandidate:
+ label: str
+ # The description the model judges the search against.
+ meaning: str
+
+
+def _candidates() -> dict[str, CoreEventCandidate]:
+ """Every core event a picker can select, by event name."""
+ candidates: dict[str, CoreEventCandidate] = {}
+ for name, definition in CORE_FILTER_DEFINITIONS_BY_GROUP["events"].items():
+ # "All events" is not an event. Events hidden from query builders stay in: the picker drops them from
+ # the suggestions when it hides them, which depends on flags only the frontend knows.
+ if name == "All events":
+ continue
+ meaning = definition.get("description_llm") or definition.get("description") or ""
+ candidates[name] = CoreEventCandidate(label=definition["label"], meaning=meaning)
+ return candidates
+
+
+CORE_EVENT_CANDIDATES = _candidates()
+_CANDIDATES_DIGEST = hashlib.sha256(repr(sorted(CORE_EVENT_CANDIDATES.items())).encode()).hexdigest()[:16]
+
+
+def event_match_state(query: str) -> str:
+ return "\n".join(
+ [
+ "A person searches the events list of the filter picker in PostHog, a product analytics tool.",
+ "No event name matches the search, so the person may describe an event instead of naming it.",
+ f"Search: {query}",
+ ]
+ )
+
+
+def _question(candidate: CoreEventCandidate) -> NoulQuestion:
+ return NoulQuestion(
+ instructions=f"Does the search look for the {candidate.label} event? {candidate.meaning}".strip(),
+ criteria_true="The search describes this event, uses a synonym for it, or names what it records.",
+ criteria_false="The search is about something else.",
+ )
+
+
+def _ask(client: SystemOneClient, state: str, names: Sequence[str]) -> SystemOneResult:
+ questions = {f"e{index}": _question(CORE_EVENT_CANDIDATES[name]) for index, name in enumerate(names)}
+ return client.decide(state=state, questions=questions)
+
+
+@frozen
+class _ModelAnswers:
+ probabilities: dict[str, float]
+ # False when some requests failed, so the probabilities cover only part of the core events.
+ complete: bool
+
+
+def _ask_chunk(client: SystemOneClient, state: str, names: Sequence[str], team_id: int) -> SystemOneResult | None:
+ """None when this request fails. The failure goes to error tracking and the logs, and the other chunks still count."""
+ try:
+ return _ask(client, state, names)
+ except SystemOneRequestFailed as error:
+ # Only the team and the failure go out: the error message never carries the search text.
+ logger.warning(
+ "taxonomic_event_match_chunk_failed",
+ team_id=team_id,
+ status_code=error.status_code,
+ chunk_size=len(names),
+ )
+ capture_exception(error, {"team_id": team_id, "chunk_size": len(names)})
+ return None
+
+
+def _probabilities(team_id: int, query: str) -> _ModelAnswers:
+ """The model's probability for every core event it answered. Raises the System One errors when no request succeeds."""
+ names = list(CORE_EVENT_CANDIDATES)
+ # The gateway takes a bounded number of questions per request, so the candidates go out in parallel chunks.
+ chunks = [names[start : start + GATEWAY_MAX_QUESTIONS] for start in range(0, len(names), GATEWAY_MAX_QUESTIONS)]
+ client = build_system_one_client(
+ model=SEARCH_INTENT_MODEL,
+ ai_product="taxonomic_filter",
+ distinct_id=team_distinct_id(team_id),
+ timeout=SEARCH_INTENT_TIMEOUT_SECONDS,
+ )
+ state = event_match_state(query)
+ with ThreadPoolExecutor(max_workers=len(chunks), thread_name_prefix="event-match") as executor:
+ # A fresh copy of the request context per chunk keeps its log and error-tracking tags on the failure reports.
+ futures = [
+ executor.submit(contextvars.copy_context().run, _ask_chunk, client, state, chunk, team_id)
+ for chunk in chunks
+ ]
+ results = [future.result() for future in futures]
+ if all(result is None for result in results):
+ raise SystemOneRequestFailed("Every event match request failed")
+ probabilities: dict[str, float] = {}
+ for chunk, result in zip(chunks, results):
+ if result is None:
+ continue
+ for index, name in enumerate(chunk):
+ answer = result.answers[f"e{index}"]
+ if isinstance(answer, NoulAnswer):
+ probabilities[name] = answer.probability
+ return _ModelAnswers(probabilities=probabilities, complete=None not in results)
+
+
+def _cache_key(team_id: int, query: str) -> str:
+ # Keyed per team, so a fast answer cannot tell one team what another team searched.
+ digest = hashlib.sha256(f"{SEARCH_INTENT_MODEL}\n{MATCH_THRESHOLD}\n{query}".encode()).hexdigest()
+ return f"{CACHE_KEY_PREFIX}:{_CANDIDATES_DIGEST}:{team_id}:{digest}"
+
+
+def likely_core_events(
+ team_id: int, query: str, *, use_cache: bool = True, require_complete: bool = False
+) -> list[EventMatch]:
+ """Every core event the model finds likely, strongest first, before the check against ingested events.
+
+ The model reads the search with its values replaced by placeholders, and nothing when only values are left.
+ With `require_complete`, a failed request raises instead of leaving its events out of the answer.
+ """
+ model_query = redact_values(query)
+ if model_query is None:
+ return []
+ key = _cache_key(team_id, model_query)
+ if use_cache:
+ cached = cache.get(key)
+ # 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)
+ except ValidationError:
+ pass
+ answers = _probabilities(team_id, model_query)
+ if require_complete and not answers.complete:
+ raise SystemOneRequestFailed("Some event match requests failed")
+ likely = sorted(
+ (
+ EventMatch(name=name, label=CORE_EVENT_CANDIDATES[name].label, probability=probability)
+ for name, probability in answers.probabilities.items()
+ if probability >= MATCH_THRESHOLD
+ ),
+ key=lambda match: match.probability,
+ reverse=True,
+ )
+ # 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
+
+
+def _ingested(project_id: int, names: Sequence[str]) -> set[str]:
+ return set(
+ # A definition can exist before its first event arrives, and only a seen event has data to show.
+ EventDefinition.objects.filter(
+ team__project_id=project_id, name__in=names, last_seen_at__isnull=False
+ ).values_list("name", flat=True)
+ )
+
+
+def match_core_events(request: EventMatchRequest, *, use_cache: bool = True) -> list[EventMatch]:
+ """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)
+ if not likely:
+ return []
+ # 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]
diff --git a/posthog/taxonomic_search_intent/test_classify.py b/posthog/taxonomic_search_intent/test_classify.py
index ad35f9f5d996..0d7a38f8a3a5 100644
--- a/posthog/taxonomic_search_intent/test_classify.py
+++ b/posthog/taxonomic_search_intent/test_classify.py
@@ -72,9 +72,15 @@ class TestClassifySearchIntent(SimpleTestCase):
None,
SearchIntentSource.SKIPPED,
),
- ("id_like", "user 12345678", ALL_TABS, None, SearchIntentSource.SKIPPED),
("opaque_token", "sess_a1b2c3d4", ALL_TABS, None, SearchIntentSource.SKIPPED),
- ("opaque_token_in_words", "session sess_a1b2c3d4", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("key_value_pair", "token=abc", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("url_inside_word", "visits:https://example.com/reset", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("only_a_phone", "+1 (415) 555-2671", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("only_a_host", "example.com", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("spaced_key_value", "token = sk_live_abcdefghijklmnop", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("value_after_marker", "token= sk_live_abcdefghijklmnop", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("spaced_email", "ada @ example.com", ALL_TABS, None, SearchIntentSource.SKIPPED),
+ ("email_split_at_domain", "ada@ example.com", ALL_TABS, None, SearchIntentSource.SKIPPED),
("too_short", "e", ALL_TABS, None, SearchIntentSource.SKIPPED),
("one_option_left", "email", ("events", "suggested_filters"), None, SearchIntentSource.SKIPPED),
]
@@ -87,6 +93,35 @@ class TestClassifySearchIntent(SimpleTestCase):
assert (intent.group_type, intent.source) == (expected, source)
self.decide.assert_not_called()
+ @parameterized.expand(
+ [
+ ("id_like", "user 12345678", "user <number>"),
+ ("opaque_token_in_words", "session sess_a1b2c3d4", "session <id>"),
+ ("partial_email_in_words", "emails from ada@exa", "emails from <email>"),
+ ("url_after_words", "visits https://example.com/reset", "visits <url>"),
+ ("path_after_words", "visits /reset?token=abc", "visits <path>"),
+ ("wrapped_url", "visits (https://example.com/reset)", "visits <url>"),
+ ("bare_host_url", "visits example.com/reset/abc", "visits <path>"),
+ ("windows_path", "opened C:\\Users\\ada\\notes.txt", "opened <path>"),
+ ("key_value_in_words", "campaign utm_source=newsletter", "campaign <value>"),
+ ("formatted_phone", "call +1 (415) 555-2671", "call <number>"),
+ ("local_phone", "call 555-2671 today", "call <number> today"),
+ ("ip_address", "show 10.24.8.7", "show <ip>"),
+ ("short_ip_address", "show 10.0.0.1", "show <ip>"),
+ ("bare_host", "visits example.com", "visits <url>"),
+ ("bare_host_with_port", "visits app.example.io:8080", "visits <url>"),
+ ("dotted_property_reads", "user.plan is pro", "user.plan is pro"),
+ ("small_numbers_read", "top 10 events in 2024", "top 10 events in 2024"),
+ ]
+ )
+ def test_asks_the_model_with_values_replaced(self, _name: str, query: str, model_reads: str) -> None:
+ self.decide.return_value = _answer("event_properties", 0.8)
+
+ intent = classify_search_intent(_search(query))
+
+ assert f"Search: {model_reads}\n" in self.decide.call_args.kwargs["state"] + "\n"
+ assert intent.model_query == model_reads
+
def test_offers_only_the_tabs_the_picker_shows(self) -> None:
self.decide.return_value = _answer("person_properties", 0.9)
@@ -98,6 +133,7 @@ class TestClassifySearchIntent(SimpleTestCase):
is_confident=True,
source=SearchIntentSource.MODEL,
suggests_switch=True,
+ model_query="email",
)
sent = self.decide.call_args.kwargs
assert set(sent["questions"]["tab"].criteria) == {
diff --git a/posthog/taxonomic_search_intent/test_event_match.py b/posthog/taxonomic_search_intent/test_event_match.py
new file mode 100644
index 000000000000..ed69c9530010
--- /dev/null
+++ b/posthog/taxonomic_search_intent/test_event_match.py
@@ -0,0 +1,157 @@
+from collections.abc import Mapping
+from datetime import UTC, datetime
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+
+from posthog.llm.system_one import NoulAnswer, Question, SystemOneRequestFailed, SystemOneResult
+from posthog.llm.system_one_client import GATEWAY_MAX_QUESTIONS
+from posthog.models import EventDefinition
+from posthog.taxonomic_search_intent.contracts import EventMatch, EventMatchRequest
+from posthog.taxonomic_search_intent.event_match import (
+ CORE_EVENT_CANDIDATES,
+ _question,
+ likely_core_events,
+ match_core_events,
+)
+
+BUILD_CLIENT = "posthog.taxonomic_search_intent.event_match.build_system_one_client"
+CAPTURE = "posthog.taxonomic_search_intent.event_match.capture_exception"
+# Any past time works: the check only asks whether an event was ever seen.
+SEEN_AT = datetime(2026, 1, 1, tzinfo=UTC)
+
+
+LABEL_BY_INSTRUCTIONS = {
+ _question(candidate).instructions: candidate.label for candidate in CORE_EVENT_CANDIDATES.values()
+}
+
+
+def _model_that_believes(probabilities: Mapping[str, float], failing_label: str | None = None) -> MagicMock:
+ client = MagicMock()
+
+ def decide(*, state: str, questions: Mapping[str, Question]) -> SystemOneResult:
+ labels = {LABEL_BY_INSTRUCTIONS[question.instructions] for question in questions.values()}
+ if failing_label in labels:
+ raise SystemOneRequestFailed("The ai-gateway was not reached: ReadTimeout")
+ answers = {
+ question_id: NoulAnswer(probability=probabilities.get(LABEL_BY_INSTRUCTIONS[question.instructions], 0.01))
+ for question_id, question in questions.items()
+ }
+ return SystemOneResult(model="jevk5-0.2", answers=answers, input_tokens=90)
+
+ client.decide.side_effect = decide
+ return client
+
+
+class TestMatchCoreEvents(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ for name in ("$autocapture", "$rageclick", "$pageview", "$exception"):
+ EventDefinition.objects.create(
+ team=self.team, project_id=self.team.project_id, name=name, last_seen_at=SEEN_AT
+ )
+ # Defined but never seen, so it has no data to show.
+ EventDefinition.objects.create(team=self.team, project_id=self.team.project_id, name="$screen")
+
+ def _search(self, query: str, team_id: int | None = None) -> EventMatchRequest:
+ return EventMatchRequest(team_id=team_id or self.team.id, project_id=self.team.project_id, query=query)
+
+ @parameterized.expand(
+ [
+ ("too_short", "a"),
+ ("email", "[email protected]"),
+ ("url", "https://example.com/pricing"),
+ ("path", "/reset?token=abc"),
+ ]
+ )
+ def test_never_asks_the_model_about_values_or_unanswerable_searches(self, _name: str, query: str) -> None:
+ with patch(BUILD_CLIENT) as build:
+ assert match_core_events(self._search(query)) == []
+
+ build.assert_not_called()
+
+ def test_the_model_reads_placeholders_instead_of_values(self) -> None:
+ client = _model_that_believes({})
+ with patch(BUILD_CLIENT, return_value=client):
+ match_core_events(self._search("visits https://example.com/reset?token=abc"))
+
+ assert {call.kwargs["state"].splitlines()[-1] for call in client.decide.call_args_list} == {
+ "Search: visits <url>"
+ }
+
+ def test_asks_about_every_core_event_within_the_gateway_limit(self) -> None:
+ client = _model_that_believes({})
+ with patch(BUILD_CLIENT, return_value=client):
+ match_core_events(self._search("browser capture"))
+
+ asked = [len(call.kwargs["questions"]) for call in client.decide.call_args_list]
+ assert max(asked) <= GATEWAY_MAX_QUESTIONS
+ assert sum(asked) == len(CORE_EVENT_CANDIDATES)
+ assert "Search: browser capture" in client.decide.call_args.kwargs["state"]
+
+ def test_suggests_the_likely_ingested_events_strongest_first(self) -> None:
+ client = _model_that_believes(
+ {
+ "Rageclick": 0.75,
+ "Autocapture": 0.95,
+ # Likely, but the project never sent it, so a suggestion would lead to an empty insight.
+ "Dead click": 0.9,
+ "Pageview": 0.72,
+ "Exception": 0.71,
+ "Screen": 0.85,
+ }
+ )
+ with patch(BUILD_CLIENT, return_value=client):
+ matches = match_core_events(self._search("browser capture"))
+
+ assert matches == [
+ EventMatch(name="$autocapture", label="Autocapture", probability=0.95),
+ EventMatch(name="$rageclick", label="Rageclick", probability=0.75),
+ EventMatch(name="$pageview", label="Pageview", probability=0.72),
+ EventMatch(name="$exception", label="Exception", probability=0.71),
+ ]
+
+ @parameterized.expand([("same_team", False, 1), ("other_team", True, 2)])
+ def test_the_same_search_is_answered_once_per_team(
+ self, _name: str, other_team: bool, expected_requests: int
+ ) -> None:
+ second_team_id = self.team.id + 1 if other_team else None
+ with patch(BUILD_CLIENT, return_value=_model_that_believes({"Autocapture": 0.95})) as build:
+ match_core_events(self._search("browser capture"))
+ match_core_events(self._search(" browser capture ", team_id=second_team_id))
+
+ assert build.call_count == expected_requests
+
+ def test_keeps_the_answers_of_the_requests_that_succeed(self) -> None:
+ late_event = list(CORE_EVENT_CANDIDATES)[-1]
+ EventDefinition.objects.create(
+ team=self.team, project_id=self.team.project_id, name=late_event, last_seen_at=SEEN_AT
+ )
+ client = _model_that_believes(
+ {"Autocapture": 0.95, CORE_EVENT_CANDIDATES[late_event].label: 0.8}, failing_label="Autocapture"
+ )
+ 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"))
+ match_core_events(self._search("browser capture"))
+
+ assert [match.name for match in matches] == [late_event]
+ assert capture.call_count == 2
+ # A partial answer is not cached, so the second search asks every request again.
+ assert client.decide.call_count == 2 * requests_per_search
+
+ def test_a_partial_answer_fails_when_every_event_must_be_answered(self) -> None:
+ client = _model_that_believes({"Autocapture": 0.95}, failing_label="Autocapture")
+ with patch(BUILD_CLIENT, return_value=client), patch(CAPTURE), self.assertRaises(SystemOneRequestFailed):
+ likely_core_events(self.team.id, "browser capture", use_cache=False, require_complete=True)
+
+ def test_fails_when_every_request_fails(self) -> None:
+ client = MagicMock()
+ client.decide.side_effect = SystemOneRequestFailed("The ai-gateway was not reached: ReadTimeout")
+ with patch(BUILD_CLIENT, return_value=client), patch(CAPTURE), self.assertRaises(SystemOneRequestFailed):
+ match_core_events(self._search("browser capture"))
diff --git a/products/posthog_ai/evals/taxonomic_filter/eval_event_match.py b/products/posthog_ai/evals/taxonomic_filter/eval_event_match.py
new file mode 100644
index 000000000000..254adf90dac3
--- /dev/null
+++ b/products/posthog_ai/evals/taxonomic_filter/eval_event_match.py
@@ -0,0 +1,105 @@
+"""Does the decision model find the core event a person describes when no event name matches their search?
+
+The unit tests in `posthog/taxonomic_search_intent/test_event_match.py` feed the matcher canned answers. They
+cover the value rules, the request chunks, the ingested-event check and the cache, and they pass whatever the
+model says. This suite covers the model itself: given a search that matched no event name, does it pick the
+core events the search describes, and nothing else?
+
+The cases are invented from the shapes people type when they do not know an event's name: a description of
+what the event records ("browser capture"), a synonym ("page visit"), a feeling ("angry clicks"). The no-match
+cases are business events that no core event covers, where any suggestion is wrong.
+
+`EventMatchFound` reads as recall and `NoWrongEventMatch` as precision. Precision is the number to protect,
+because a wrong suggestion is worse than none. `MATCH_THRESHOLD` in `posthog/taxonomic_search_intent/event_match.py`
+decides what the picker shows; tune it from this suite.
+
+The suite scores the model's likely events before the ingested-event check, so the demo project's own events
+do not change the result. It shows at most `MAX_MATCHES` events, like the picker.
+
+No CI job runs this suite. Run it by hand, with AI_GATEWAY_URL and AI_GATEWAY_API_KEY set for the decision
+model, and with the harness's own BRAINTRUST_API_KEY and LLM_GATEWAY_ANTHROPIC_API_KEY:
+ hogli evals eval_event_match
+"""
+
+from __future__ import annotations
+
+import time
+import asyncio
+
+from posthog.llm.system_one_client import system_one_configured
+from posthog.taxonomic_search_intent.classify import SEARCH_INTENT_MODEL
+from posthog.taxonomic_search_intent.event_match import MAX_MATCHES, likely_core_events
+
+from products.posthog_ai.eval_harness.config import BaseEvalCase
+from products.posthog_ai.eval_harness.harness.context import EvalContext
+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind
+from products.posthog_ai.eval_harness.one_shot import OneShotPublicEval
+from products.posthog_ai.evals.taxonomic_filter.scorers import EVENT_MATCH_KEY, EventMatchFound, NoWrongEventMatch
+
+SUITE_KIND = SuiteKind.ONE_SHOT
+
+
+def _case(name: str, query: str, *acceptable: str) -> BaseEvalCase:
+ return BaseEvalCase(name=name, prompt=query, expected={EVENT_MATCH_KEY: {"acceptable": list(acceptable)}})
+
+
+DESCRIBED_CASES = [
+ _case("browser_capture", "browser capture", "$autocapture"),
+ _case("automatic_clicks", "automatic clicks", "$autocapture"),
+ _case("page_visit", "page visit", "$pageview"),
+ _case("left_the_page", "left the page", "$pageleave"),
+ _case("angry_clicks", "angry clicks", "$rageclick"),
+ _case("clicks_that_do_nothing", "clicks that do nothing", "$dead_click"),
+ _case("js_error", "js error", "$exception"),
+ _case("app_screen", "app screen view", "$screen"),
+ _case("page_speed", "page speed", "$web_vitals"),
+ _case("llm_call", "llm call", "$ai_generation"),
+ _case("copied_text", "copied text", "$copy_autocapture"),
+]
+
+NO_MATCH_CASES = [
+ _case("invoice_paid", "invoice paid"),
+ _case("subscription_upgraded", "subscription upgraded"),
+ _case("file_shared", "file shared"),
+]
+
+
+async def eval_event_match(ctx: EvalContext) -> None:
+ # Without a gateway every case errors, which reads as a model regression instead of a setup gap.
+ if not system_one_configured():
+ raise RuntimeError(
+ "eval_event_match needs AI_GATEWAY_URL (https) and AI_GATEWAY_API_KEY to reach the decision model"
+ )
+
+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:
+ if task_ctx.demo_data is None:
+ raise RuntimeError("one-shot suites run against the master Hedgebox team")
+ started = time.monotonic()
+ try:
+ # Sync and blocking on the gateway, so keep it off the event loop. No cache: every run asks the model.
+ # A failed chunk leaves its events out, which would score as a model miss, so a partial answer is an error.
+ likely = await asyncio.to_thread(
+ likely_core_events,
+ task_ctx.demo_data.master_team_id,
+ case.prompt,
+ use_cache=False,
+ require_complete=True,
+ )
+ except Exception as error:
+ return {"model": SEARCH_INTENT_MODEL, "suggested": [], "error": f"{type(error).__name__}: {error}"}
+ suggested = [match.name for match in likely[:MAX_MATCHES]]
+ return {
+ "model": SEARCH_INTENT_MODEL,
+ "suggested": suggested,
+ "probabilities": {match.name: match.probability for match in likely[:MAX_MATCHES]},
+ "latency_ms": round((time.monotonic() - started) * 1000),
+ "last_message": f"{case.prompt!r}: {suggested}",
+ }
+
+ await OneShotPublicEval(
+ experiment_name="taxonomic-filter-event-match",
+ cases=[*DESCRIBED_CASES, *NO_MATCH_CASES],
+ scorers=[EventMatchFound(), NoWrongEventMatch()],
+ task=task,
+ ctx=ctx,
+ )
diff --git a/products/posthog_ai/evals/taxonomic_filter/scorers.py b/products/posthog_ai/evals/taxonomic_filter/scorers.py
index 976fc641558e..7ff1f2620a5c 100644
--- a/products/posthog_ai/evals/taxonomic_filter/scorers.py
+++ b/products/posthog_ai/evals/taxonomic_filter/scorers.py
@@ -83,3 +83,58 @@ class NoWrongSwitch(Scorer):
# A switch away from an acceptable open tab is wrong, because the person is already in the right place.
right = spec["active"] not in spec["acceptable"] and intent.get("group_type") in spec["acceptable"]
return Score(name=self._name(), score=1.0 if right else 0.0, metadata={"intent": intent})
+
+
+EVENT_MATCH_KEY = "event_match"
+
+
+def _event_spec(expected: dict | None) -> list[str] | None:
+ spec = (expected or {}).get(EVENT_MATCH_KEY)
+ return list(spec["acceptable"]) if isinstance(spec, dict) else None
+
+
+def _suggested(output: dict | None) -> list[str]:
+ return list((output or {}).get("suggested") or [])
+
+
+class EventMatchFound(Scorer):
+ """Recall: for a search that describes a core event, does any suggestion the picker shows name it?"""
+
+ def _name(self) -> str:
+ return "event_match_found"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:
+ acceptable = _event_spec(expected)
+ if not acceptable:
+ return Score(name=self._name(), score=None, metadata={"reason": "No core event fits this search"})
+ # A failed gateway call says nothing about the model, so it skips rather than scores as a miss.
+ if output and output.get("error"):
+ return Score(name=self._name(), score=None, metadata={"reason": output["error"]})
+ suggested = _suggested(output)
+ found = any(name in acceptable for name in suggested)
+ return Score(name=self._name(), score=1.0 if found else 0.0, metadata={"suggested": suggested})
+
+
+class NoWrongEventMatch(Scorer):
+ """Precision: does every suggestion the picker would show describe the search?
+
+ A search that fits no core event must get no suggestion at all, because a wrong event is worse than none.
+ """
+
+ def _name(self) -> str:
+ return "no_wrong_event_match"
+
+ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:
+ acceptable = _event_spec(expected)
+ if acceptable is None:
+ return Score(name=self._name(), score=None, metadata={"reason": "No expectation for this case"})
+ if output and output.get("error"):
+ return Score(name=self._name(), score=None, metadata={"reason": output["error"]})
+ suggested = _suggested(output)
+ # No suggestion is right for a search that fits no event, and says nothing about precision for one that does.
+ if not suggested:
+ if acceptable:
+ return Score(name=self._name(), score=None, metadata={"reason": "No suggestion shown"})
+ return Score(name=self._name(), score=1.0, metadata={"suggested": suggested})
+ right = all(name in acceptable for name in suggested)
+ return Score(name=self._name(), score=1.0 if right else 0.0, metadata={"suggested": suggested})
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 36bbc5691eaa..7760d1b2700e 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -539,6 +539,9 @@ tools:
taxonomic-search-intent-classify-create:
operation: taxonomic_search_intent_classify_create
enabled: false
+ taxonomic-search-intent-match-events-create:
+ operation: taxonomic_search_intent_match_events_create
+ enabled: false
uploaded-media-create:
operation: uploaded_media_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a5ca23ec8697..7e2b015bf8d8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -39385,6 +39385,28 @@ export namespace Schemas {
pipelines: IngestionPipelineEnum[];
}
+ export interface EventMatch {
+ /** The event name to select, such as $autocapture. */
+ name: string;
+ /** The event's display name, such as Autocapture. */
+ display_name: string;
+ /** How likely the search means this event, from 0 to 1. */
+ probability: number;
+ }
+
+ export interface EventMatchRequest {
+ /**
+ * What the person typed into the events list search box, which matched no event name.
+ * @maxLength 200
+ */
+ query: string;
+ }
+
+ export interface EventMatchResponse {
+ /** PostHog core events the search most likely means, strongest first. Empty when nothing is likely. */
+ matches: EventMatch[];
+ }
+
/**
* * `DateTime` - DateTime
* * `String` - String
@@ -89797,6 +89819,11 @@ export namespace Schemas {
* @nullable
*/
prompt_version: number | null;
+ /**
+ * The search as the decision model read it, with emails, URLs, paths, ids and tokens replaced by placeholders such as <url>. Null when the model did not answer.
+ * @nullable
+ */
+ model_query: string | null;
}
export interface SearchSuggestionsQuery {