: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(search): rank server-only cmd+k matches in the weakest tier (#130772)
Shy Alterb1d302de6f81
diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.mdindex 5338987df957..d4287a3d0bcc 100644--- a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md@@ -115,6 +115,7 @@ Results for a search with words rank with one scorer that applies the same rules- Accounts rank with the results when account search is enabled. The Accounts API matches the full search text, so an account can suppress the partial-match or spelling notice even when its display name does not contain the text. Distinct accounts with the same name stay separate. Accounts get no file-system **See all** filter.- The sources only find candidates. The scorer then orders them by words matched, typos, match tier, the person's recent views, word proximity, word position, a type preference, then recency.Match tiers, best first: exact name, exact name in singular, exact search keyword, name starts with the search, the same in singular, every word starts a name word, every word starts a name or keyword word, a match on an identity field (account external ID, website domain or email domain, person distinct ID), a match inside a word, then a match in the folder or type only.+ A saved object that the server matched but the browser cannot match on its name, folder or type ranks in that last tier.Names compare as words, split on hyphens and underscores, so `checkout flow` matches the flags `checkout-flow-redesign` and `checkout_flow_redesign` as names that start with the search.When every source answers and nothing matches, Cmd+K tries the search once more with underscores as spaces and says so ("No matches for **posthog_personal_api_key**. Showing results for **posthog personal api key**."), so a pasted variable name finds Personal API keys.An account whose display name does not contain the search ranks as an identity match or a match inside a word, not as an exact match.diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.tsindex 14da680e1a61..6d5677ccbaaf 100644--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts@@ -12,6 +12,7 @@ import {isIdentityQuery,rankCandidate,searchWords,+ serverOnlyRank,tokenTypos,} from './commandKRanking'import type { CommandKRow, CommandKSection } from './commandKSections'@@ -87,23 +88,12 @@ function candidateFor(item: SearchItem, groupKey: string, query: string): RankCa}}-function rankUnified(items: SearchItem[], query: string, groupKey: (item: SearchItem) => string): RankedItem[] {+function rankItems(items: SearchItem[], query: string, groupKey: (item: SearchItem) => string): RankedItem[] {return items.flatMap((item) => {const key = groupKey(item)- const ranked = rankCandidate(query, candidateFor(item, key, query))- if (!ranked) {- return item.rankKey ? [{ item, rank: item.rankKey, groupKey: key }] : []- }- return [- {- item:- ranked.matchedAlias && !item.hideMatchedKeyword- ? { ...item, matchedSearchKeyword: ranked.matchedAlias }- : item,- rank: ranked.rank,- groupKey: key,- },- ]+ const candidate = candidateFor(item, key, query)+ const rank = rankCandidate(query, candidate) ?? (item.rankKey && serverOnlyRank(item.rankKey, candidate))+ return rank ? [{ item, rank, groupKey: key }] : []})}@@ -262,11 +252,11 @@ export function buildRankedResults({scoped,}: RankedResultsInput): CommandKSection[] {const candidates: RankedItem[] = [- ...rankUnified(results, query, groupKeyFor),- ...rankUnified(products, query, () => 'products'),- ...rankUnified(persons, query, () => 'persons'),- ...rankUnified(settings, query, () => 'settings'),- ...rankUnified(accounts, query, () => 'accounts'),+ ...rankItems(results, query, groupKeyFor),+ ...rankItems(products, query, () => 'products'),+ ...rankItems(persons, query, () => 'persons'),+ ...rankItems(settings, query, () => 'settings'),+ ...rankItems(accounts, query, () => 'accounts'),].sort((a, b) => compareRanks(a.rank, b.rank))if (!candidates.length) {return []diff --git a/frontend/src/lib/components/CommandKSearch/commandKRanking.ts b/frontend/src/lib/components/CommandKSearch/commandKRanking.tsindex 8467baf31c03..398b44b205e2 100644--- a/frontend/src/lib/components/CommandKSearch/commandKRanking.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKRanking.ts@@ -257,11 +257,6 @@ export interface RankCandidate {tierBoost?: number}-interface CandidateRank {- rank: RankKey- matchedAlias: string | null-}-const MatchTier = {Exact: 0,ExactSingular: 1,@@ -284,7 +279,6 @@ interface TokenHit {position: numberfield: FieldwordStart: boolean- alias?: string}const MAX_POSITION_PENALTY = 3@@ -317,7 +311,7 @@ function cleanHit(token: string, candidate: RankCandidate, name: Omit<TokenHit,for (const alias of candidate.aliases ?? []) {const hit = hitInWords(token, unifiedWords(alias))if (hit && isClean(hit)) {- return { ...hit, position: MAX_POSITION_PENALTY, field: 'alias', alias }+ return { ...hit, position: MAX_POSITION_PENALTY, field: 'alias' }}}const inIdentity = (candidate.identity ?? []).some((value) => value.toLowerCase().includes(token))@@ -335,7 +329,7 @@ function tokenHit(token: string, candidate: RankCandidate, nameWords: string[]):...(name ? [{ ...name, field: 'name' as const }] : []),...(candidate.aliases ?? []).flatMap((alias) => {const hit = hitInWords(token, unifiedWords(alias))- return hit ? [{ ...hit, position: MAX_POSITION_PENALTY, field: 'alias' as const, alias }] : []+ return hit ? [{ ...hit, position: MAX_POSITION_PENALTY, field: 'alias' as const }] : []}),...(context ? [{ ...context, position: MAX_POSITION_PENALTY, field: 'context' as const }] : []),// The source already matched the whole search on fields the browser cannot see.@@ -404,7 +398,7 @@ function proximityOf(positions: number[]): number {const usageTier = (frecency: number): number => (frecency >= 1 ? 0 : frecency > 0 ? 1 : 2)-export function rankCandidate(query: string, candidate: RankCandidate): CandidateRank | null {+export function rankCandidate(query: string, candidate: RankCandidate): RankKey | null {const normalizedQuery = query.trim().toLowerCase().replace(/\s+/g, ' ').slice(0, MAX_LOCAL_QUERY_LENGTH)const tokens = [...new Set(unifiedWords(normalizedQuery))]if (!tokens.length) {@@ -418,19 +412,33 @@ export function rankCandidate(query: string, candidate: RankCandidate): Candidat}const positions = found.filter((hit) => hit.field === 'name').map((hit) => hit.position)const frecency = candidate.frecency ?? 0- return {- rank: [- -found.length,- found.reduce((sum, hit) => sum + hit.typos, 0),- Math.max(matchTier(normalizedQuery, hits, candidate) - (candidate.tierBoost ?? 0), 0),- usageTier(frecency),- proximityOf(positions),- Math.min(...positions, MAX_POSITION_PENALTY),- candidate.typePrior ?? 1,- Number(!!candidate.indirect),- -Math.round(frecency * 1000),- -(candidate.createdAt ?? 0),- ],- matchedAlias: found.find((hit) => hit.field === 'alias')?.alias ?? null,- }+ return [+ -found.length,+ found.reduce((sum, hit) => sum + hit.typos, 0),+ Math.max(matchTier(normalizedQuery, hits, candidate) - (candidate.tierBoost ?? 0), 0),+ usageTier(frecency),+ proximityOf(positions),+ Math.min(...positions, MAX_POSITION_PENALTY),+ candidate.typePrior ?? 1,+ Number(!!candidate.indirect),+ -Math.round(frecency * 1000),+ -(candidate.createdAt ?? 0),+ ]+}++// The server matched words the browser cannot find, so the result ranks as a folder or type match.+export function serverOnlyRank(serverRank: RankKey, candidate: RankCandidate): RankKey {+ const frecency = candidate.frecency ?? 0+ return [+ serverRank[0],+ serverRank[1],+ MatchTier.Weak,+ usageTier(frecency),+ Math.min(serverRank[2], MAX_POSITION_PENALTY),+ MAX_POSITION_PENALTY,+ candidate.typePrior ?? 1,+ 1,+ -Math.round(frecency * 1000),+ -(candidate.createdAt ?? 0),+ ]}diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.tsindex 7fd76aafd29c..fa66825b0c6e 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts@@ -440,7 +440,7 @@ describe('buildSections', () => {},],['best-matches'],- 'a',+ 'settings-item',],] as [string, string, string, SearchItem[], string[], string][])('ranks an exact-match setting with the results when %s',