: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(insights): exact-first saved insights search (#61611)
Paul D'Ambra64cb252c654b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f9746369b617..2dba0701db4b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5870,6 +5870,10 @@ snapshots:hash: v1.k794b7964.f1ad5aaa8dabaefd9ac8900920c56eb029656d9bd570bf4edd25fb6c135d9e44.pfgonEC2aj4XbTFzo4VbAFE68EwPYux9GdsZ_fk_y78scenes-app-saved-insights--list-view--light:hash: v1.k794b7964.84949542f060e8a4bb51b32c447be267827eefe820cb4fb64043bf816c8c5ffa.2A1ZaEwm2EE1w8Vq_2S87UR7FQ5Cv5UqYLE9xPF7CO4+ scenes-app-saved-insights--search-results--dark:+ hash: v1.k794b7964.497c4c623ad39c00e7222da92d036c2d3244dcc2a646b544e901f0cb76fc6769.R5MvpFQDADYd-3yCZYToSZIkYXvTD2M88dv__O_rLKY+ scenes-app-saved-insights--search-results--light:+ hash: v1.k794b7964.2987eff3c77b7e9c3cd868a266843d2bdf810831df871c8633dbea916bf20ee0.8ckgttcb_kZYo5kDcebDA61TOfupN5W1Mqx6oTuKfmAscenes-app-sessionattributionexplorer--session-attribution-explorer--dark:hash: v1.k794b7964.de73dd95fc63c967333c2d0caae609d6fb4d5c1dcd976397ca9541194ae9dfb1.Q4eLDuHYUsFUb8pTFD4Z10fXX_a0s_tSqKejQyNPTMMscenes-app-sessionattributionexplorer--session-attribution-explorer--light:diff --git a/frontend/src/scenes/saved-insights/SavedInsights.stories.tsx b/frontend/src/scenes/saved-insights/SavedInsights.stories.tsxindex be542409c61f..afec193c0f0e 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.stories.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.stories.tsx@@ -51,3 +51,29 @@ export const EmptyState: Story = {}),],}++export const SearchResults: Story = {+ parameters: {+ pageUrl: urls.savedInsights() + '?search=revenue',+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/environments/:team_id/insights': toPaginatedResponse(+ insightsJson.results.slice(0, 5).map((result, i) => {+ const exactNames = ['Revenue by region', 'Weekly revenue']+ const similarNames = ['Reveneu trends', 'Q4 reveue', 'Revanue dashboard']+ const isExact = i < exactNames.length+ return {+ ...result,+ name: isExact ? exactNames[i] : similarNames[i - exactNames.length],+ query: insights[i % insights.length].query,+ result: insights[i % insights.length].result,+ search_match_type: isExact ? 'exact' : 'similar',+ }+ })+ ),+ },+ }),+ ],+}diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsxindex fa4e44607080..e01bc2e045a7 100644--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx@@ -52,7 +52,9 @@ import { LemonMenu, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { LemonTag } from 'lib/lemon-ui/LemonTag'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { Tooltip } from 'lib/lemon-ui/Tooltip'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { isNonEmptyObject } from 'lib/utils'import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'@@ -83,7 +85,7 @@ import {} from '~/types'import { ReloadInsight } from './ReloadInsight'-import { savedInsightsLogic } from './savedInsightsLogic'+import { SavedInsightListItem, savedInsightsLogic } from './savedInsightsLogic'export interface InsightTypeMetadata {name: string@@ -768,7 +770,7 @@ export function SavedInsights(): JSX.Element {const { tab } = filters- const columns: LemonTableColumns<QueryBasedInsightModel> = [+ const columns: LemonTableColumns<SavedInsightListItem> = [{key: 'id',width: 32,@@ -806,6 +808,15 @@ export function SavedInsights(): JSX.Element {tooltip={`${insight.favorited ? 'Remove from' : 'Add to'} favorite insights`}/></AccessControlAction>+ {insight.search_match_type === 'similar' && (+ <span className="ml-auto">+ <Tooltip title="Not an exact match for your search, but a close one">+ <LemonTag type="muted" size="small">+ similar+ </LemonTag>+ </Tooltip>+ </span>+ )}</div>)},@@ -813,7 +824,7 @@ export function SavedInsights(): JSX.Element {},{title: 'Tags',- dataIndex: 'tags' as keyof QueryBasedInsightModel,+ dataIndex: 'tags' as keyof SavedInsightListItem,key: 'tags',render: function renderTags(tags: string[]) {return <ObjectTags tags={[...tags].sort()} staticOnly />@@ -821,8 +832,8 @@ export function SavedInsights(): JSX.Element {},{title: 'Created by',- dataIndex: 'created_by' as keyof QueryBasedInsightModel,- render: function Render(_: any, item: QueryBasedInsightModel) {+ dataIndex: 'created_by' as keyof SavedInsightListItem,+ render: function Render(_: any, item: SavedInsightListItem) {const { created_by } = itemreturn (<div className="flex flex-row items-center flex-nowrap">@@ -1031,8 +1042,8 @@ export function SavedInsights(): JSX.Element {) : undefined}bulkSelection={{- getKey: (insight: QueryBasedInsightModel): number => insight.id,- isRowSelectable: (insight: QueryBasedInsightModel) =>+ getKey: (insight: SavedInsightListItem): number => insight.id,+ isRowSelectable: (insight: SavedInsightListItem) =>accessLevelSatisfied(AccessControlResourceType.Insight,insight.user_access_level,@@ -1040,7 +1051,7 @@ export function SavedInsights(): JSX.Element {)? true: { disabledReason: "You don't have permission to edit this insight." },- rowAriaLabel: (insight: QueryBasedInsightModel) =>+ rowAriaLabel: (insight: SavedInsightListItem) =>`Select insight ${insight.name || 'Untitled'}`,headerAriaLabel: 'Select all insights on this page',renderActions: (ctx) => (diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.tsindex 8e9f7158d511..9b668ea1bb19 100644--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts@@ -191,6 +191,38 @@ describe('savedInsightsLogic', () => {})})+ it('carries per-row search_match_type through to the results', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/insights/': () => {+ const base = createSavedInsights('hello', 0)+ return [+ 200,+ {+ ...base,+ results: base.results.map((r, i) => ({+ ...r,+ search_match_type: i === 0 ? 'exact' : 'similar',+ })),+ },+ ]+ },+ },+ })++ logic.actions.setSavedInsightsFilters({ search: 'hello' })+ await expectLogic(logic)+ .toDispatchActions(['loadInsights', 'loadInsightsSuccess'])+ .toMatchValues({+ insights: partial({+ results: partial([+ partial({ name: 'hello 1', search_match_type: 'exact' }),+ partial({ name: 'hello 2', search_match_type: 'similar' }),+ ]),+ }),+ })+ })+it('can duplicate and does not use derived name for name', async () => {const sourceInsight = createInsight(123, 'hello')sourceInsight.name = ''diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.tsindex ede3d8c217af..5d776ffbfb9a 100644--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts@@ -31,7 +31,11 @@ import type { savedInsightsLogicType } from './savedInsightsLogicType'export const INSIGHTS_PER_PAGE = 30-export interface InsightsResult extends CountedPaginatedResponse<QueryBasedInsightModel> {+export interface SavedInsightListItem extends QueryBasedInsightModel {+ search_match_type?: 'exact' | 'similar' | null+}++export interface InsightsResult extends CountedPaginatedResponse<SavedInsightListItem> {/* not in the API response */filters?: SavedInsightFilters | null/* not in the API response */@@ -142,7 +146,7 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([results: [insight, ...response.results],filters,offset: params.offset,- } as CountedPaginatedResponse<QueryBasedInsightModel> & { offset: number }+ } as InsightsResult} catch {// no insight with this ID found, discard}@@ -161,7 +165,7 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([...response,filters,offset: params.offset,- } as CountedPaginatedResponse<QueryBasedInsightModel> & { offset: number }+ } as InsightsResult},updateFavoritedInsight: async ({ insight, favorited }) => {const response = await insightsApi.update(insight.id, {diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex eefd67ca7d4e..3a143a00957d 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -7274,6 +7274,13 @@ export interface DashboardTileBasicApi {deleted?: boolean | null}+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+/*** @nullable*/@@ -7381,6 +7388,8 @@ export interface InsightApi {readonly alerts: readonly unknown[]/** @nullable */readonly last_viewed_at: string | null+ /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type: SearchMatchTypeEnumApi | null}export interface TextApi {diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex fa5b29d99188..20ce175255ee 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -7,7 +7,20 @@ from typing import Any, Union, castfrom django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarityfrom django.db import transaction-from django.db.models import Count, Exists, F, Max, OuterRef, Prefetch, QuerySet, Subquery, Value+from django.db.models import (+ Case,+ Count,+ Exists,+ F,+ IntegerField,+ Max,+ OuterRef,+ Prefetch,+ QuerySet,+ Subquery,+ Value,+ When,+)from django.db.models.functions import Coalescefrom django.db.models.query_utils import Qfrom django.http import HttpResponse@@ -327,6 +340,14 @@ class InsightBasicSerializer(dashboards = serializers.SerializerMethodField(read_only=True)created_by = UserBasicSerializer(read_only=True)last_viewed_at = serializers.SerializerMethodField(read_only=True)+ search_match_type = serializers.SerializerMethodField(+ read_only=True,+ help_text=(+ "How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the "+ "name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are "+ "ordered exact-first. Null when the list is not filtered by `search`."+ ),+ )class Meta:model = Insight@@ -351,6 +372,7 @@ class InsightBasicSerializer("favorited","user_access_level","last_viewed_at",+ "search_match_type",]read_only_fields = ("short_id", "updated_at", "last_refresh", "refreshing")@@ -366,6 +388,13 @@ class InsightBasicSerializer("""Get the last viewed timestamp for this insight by any user in the team."""return getattr(instance, "last_viewed_at", None)+ @extend_schema_field(serializers.ChoiceField(choices=["exact", "similar"], allow_null=True))+ def get_search_match_type(self, instance: Insight) -> str | None:+ is_exact = getattr(instance, "_is_exact", None)+ if is_exact is None:+ return None+ return "exact" if is_exact else "similar"+def to_representation(self, instance):representation = super().to_representation(instance)@@ -381,6 +410,11 @@ class InsightBasicSerializer(# upgrade the query to the latest versionrepresentation["query"] = upgrade(representation["query"])+ # search_match_type is a per-row search annotation — only surface it on search results, not on+ # every serialized insight (unfiltered lists, dashboard-embedded tiles, retrieve, etc.)+ if getattr(instance, "_is_exact", None) is None:+ representation.pop("search_match_type", None)+return representation@lru_cache(maxsize=1) # noqa: B019 - short-lived serializer@@ -553,6 +587,7 @@ class InsightSerializer(InsightBasicSerializer):"_create_in_folder","alerts","last_viewed_at",+ "search_match_type",]read_only_fields = ("created_at",@@ -1236,7 +1271,11 @@ Background calculation can be tracked using the `query_status` response field.""OpenApiParameter(name="search",type=OpenApiTypes.STR,- description="Case-insensitive substring match across name, derived_name, description, and tag names.",+ description=(+ "Search term matched across name, derived_name, description, and tag names. Returns case-insensitive "+ "substring matches and fuzzy trigram matches together in one list, ordered exact-first; each "+ "result's `search_match_type` is `exact` or `similar`."+ ),),OpenApiParameter(name="created_by",@@ -1603,51 +1642,52 @@ class InsightViewSet(return Response({"count": len(data), "next": None, "previous": None, "results": data})@staticmethod+ def _annotate_search_scores(queryset: QuerySet, search: str) -> QuerySet:+ zero = Value(0.0)+ return queryset.annotate(+ _name_word=Coalesce(TrigramWordSimilarity(search, "name"), zero),+ _name_full=Coalesce(TrigramSimilarity("name", search), zero),+ _derived_name_word=Coalesce(TrigramWordSimilarity(search, "derived_name"), zero),+ _description_word=Coalesce(TrigramWordSimilarity(search, "description"), zero),+ ).annotate(+ _search_score=F("_name_word")+ + F("_name_full")+ + F("_derived_name_word")+ + F("_description_word") * DESCRIPTION_SCORE_WEIGHT+ )+@tracer.start_as_current_span("InsightViewSet._apply_search")- def _apply_search(queryset: QuerySet, search: str) -> QuerySet:+ def _apply_search(self, queryset: QuerySet, search: str) -> QuerySet:search = normalize_search_term(search)span = trace.get_current_span()span.set_attribute("insight.search.length", len(search))if not search:return queryset- zero = Value(0.0)- name_word_score = Coalesce(TrigramWordSimilarity(search, "name"), zero)- name_full_score = Coalesce(TrigramSimilarity("name", search), zero)- derived_name_word_score = Coalesce(TrigramWordSimilarity(search, "derived_name"), zero)- description_word_score = Coalesce(TrigramWordSimilarity(search, "description"), zero)-+ scored = self._annotate_search_scores(queryset, search)matching_tag_ids = queryset.filter(tagged_items__tag__name__icontains=search).values("id")+ exact_q = (+ Q(name__icontains=search)+ | Q(derived_name__icontains=search)+ | Q(description__icontains=search)+ | Q(id__in=matching_tag_ids)+ )+ similar_q = (+ Q(_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)+ | Q(_derived_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)+ | Q(_description_word__gt=MIN_DESCRIPTION_TRIGRAM_SIMILARITY)+ )return (- queryset.annotate(- _name_word=name_word_score,- _name_full=name_full_score,- _derived_name_word=derived_name_word_score,- _description_word=description_word_score,- )- .filter(- Q(_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)- | Q(_derived_name_word__gt=MIN_NAME_TRIGRAM_SIMILARITY)- | Q(_description_word__gt=MIN_DESCRIPTION_TRIGRAM_SIMILARITY)- | Q(id__in=matching_tag_ids)- )- .annotate(- _name_match_score=F("_name_word") + F("_name_full"),- _derived_name_match_score=F("_derived_name_word"),- _description_match_score=F("_description_word"),- )- .annotate(- _search_score=F("_name_match_score")- + F("_derived_name_match_score")- + F("_description_match_score") * DESCRIPTION_SCORE_WEIGHT- )- .order_by("-_search_score", "name")+ scored.annotate(_is_exact=Case(When(exact_q, then=Value(1)), default=Value(0), output_field=IntegerField()))+ .filter(exact_q | similar_q)+ .order_by("-_is_exact", "-_search_score", "name").distinct())def _filter_request(self, request: request.Request, queryset: QuerySet) -> QuerySet:filters = request.GET.dict()+ search_term: str | None = Nonefor key in filters:if key == "saved":@@ -1732,7 +1772,7 @@ class InsightViewSet(term = request.GET["search"]if len(term) > MAX_SEARCH_LENGTH:raise ValidationError({"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."})- queryset = self._apply_search(queryset, term)+ search_term = termelif key == "dashboards":dashboards_filter = request.GET["dashboards"]if dashboards_filter:@@ -1775,6 +1815,9 @@ class InsightViewSet(last_viewed_at__lt=relative_date_parse(request.GET["last_viewed_date_to"], self.team.timezone_info))+ if search_term is not None:+ queryset = self._apply_search(queryset, search_term)+return queryset@extend_schema(diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex 7e13a91c93c6..95d29780b240 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -881,6 +881,64 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):"explicit order=-id should override relevance ranking and put newer insight first")+ def test_list_filter_by_search_returns_union_exact_first_with_match_type(self):+ for name in ("dashboard overview", "sales dashboard", "dahsboard metrics", "Engineering metrics"):+ Insight.objects.create(name=name, team=self.team, filters={"events": [{"id": "$pageview"}]})++ response = self.client.get(f"/api/projects/{self.team.id}/insights/?search=dashboard")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ match_type_by_name = {r["name"]: r["search_match_type"] for r in results}+ assert match_type_by_name == {+ "dashboard overview": "exact",+ "sales dashboard": "exact",+ "dahsboard metrics": "similar",+ }++ match_types = [r["search_match_type"] for r in results]+ assert match_types == ["exact", "exact", "similar"], f"exact matches must rank first, got {match_types}"++ def test_list_filter_by_search_match_type_absent_without_search(self):+ Insight.objects.create(name="Alpha", team=self.team, filters={"events": [{"id": "$pageview"}]})++ response = self.client.get(f"/api/projects/{self.team.id}/insights/")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ assert results+ assert all("search_match_type" not in r for r in results)++ def test_list_filter_by_search_matches_substring_below_trigram_threshold(self):+ matching = Insight.objects.create(+ name="experimentation overview", team=self.team, filters={"events": [{"id": "$pageview"}]}+ )+ Insight.objects.create(name="Totally unrelated", team=self.team, filters={"events": [{"id": "$pageview"}]})++ response = self.client.get(f"/api/projects/{self.team.id}/insights/?search=ment")+ assert response.status_code == status.HTTP_200_OK+ results = response.json()["results"]++ match_type_by_id = {r["id"]: r["search_match_type"] for r in results}+ assert match_type_by_id.get(matching.id) == "exact", (+ "a literal substring must match and be labelled exact even when it scores below the trigram thresholds"+ )+ assert all(r["name"] != "Totally unrelated" for r in results)++ def test_list_filter_by_search_runs_a_single_filtering_query(self):+ for name in ("revenue overview", "reveneu trends", "Unrelated"):+ Insight.objects.create(name=name, team=self.team, filters={"events": [{"id": "$pageview"}]})++ with capture_db_queries() as capture_query_context:+ response = self.client.get(f"/api/projects/{self.team.id}/insights/?search=revenue&basic=true")+ assert response.status_code == status.HTTP_200_OK++ trigram_queries = [q for q in capture_query_context.captured_queries if "word_similarity" in q["sql"].lower()]+ assert len(trigram_queries) <= 2, (+ "search must stay one filtering query (+ pagination count); extra trigram queries mean a per-row or "+ f"per-phase probe crept back in, got {len(trigram_queries)}"+ )+# :KLUDGE: avoid making extra queries that are explicitly not cached in tests. Avoids false N+1-s.@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)@snapshot_postgres_queriesdiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 0c08bcdbd36e..ae501b751aa8 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -7030,6 +7030,13 @@ export const EffectivePrivilegeLevelEnumApi = {Number37: 37,} as const+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]++export const SearchMatchTypeEnumApi = {+ Exact: 'exact',+ Similar: 'similar',+} as const+/*** @nullable*/@@ -7137,6 +7144,8 @@ export interface InsightApi {readonly alerts: readonly unknown[]/** @nullable */readonly last_viewed_at: string | null+ /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type: SearchMatchTypeEnumApi | null}export interface PaginatedInsightListApi {@@ -7255,6 +7264,8 @@ export interface PatchedInsightApi {readonly alerts?: readonly unknown[]/** @nullable */readonly last_viewed_at?: string | null+ /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type?: SearchMatchTypeEnumApi | null}export interface ChangeApi {@@ -7400,6 +7411,8 @@ export interface TrendingInsightApi {readonly user_access_level: string | null/** @nullable */readonly last_viewed_at: string | null+ /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type: SearchMatchTypeEnumApi | null/** Number of distinct viewers in the time window. Higher values indicate insights that more people in the project actively look at, which is a strong proxy for which insights matter. */readonly view_count: number/** Up to 3 of the most recent users who viewed this insight in the time window. */@@ -7518,7 +7531,7 @@ Background calculation can be tracked using the `query_status` response field.*/saved?: boolean/**- * Case-insensitive substring match across name, derived_name, description, and tag names.+ * Search term matched across name, derived_name, description, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches together in one list, ordered exact-first; each result's `search_match_type` is `exact` or `similar`.*/search?: stringshort_id?: stringdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9c3f14c5550f..b2270eb81b65 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -6734,6 +6734,14 @@ export namespace Schemas {Number37: 37,} as const;+ export type SearchMatchTypeEnum = typeof SearchMatchTypeEnum[keyof typeof SearchMatchTypeEnum];+++ export const SearchMatchTypeEnum = {+ Exact: 'exact',+ Similar: 'similar',+ } as const;+/*** @nullable*/@@ -6841,6 +6849,8 @@ export namespace Schemas {readonly alerts: readonly unknown[];/** @nullable */readonly last_viewed_at: string | null;+ /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type: SearchMatchTypeEnum | null;}export interface Text {@@ -26448,6 +26458,8 @@ export namespace Schemas {readonly user_access_level: string | null;/** @nullable */readonly last_viewed_at: string | null;+ /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type: SearchMatchTypeEnum | null;/** Number of distinct viewers in the time window. Higher values indicate insights that more people in the project actively look at, which is a strong proxy for which insights matter. */readonly view_count: number;/** Up to 3 of the most recent users who viewed this insight in the time window. */@@ -29161,6 +29173,8 @@ export namespace Schemas {readonly alerts?: readonly unknown[];/** @nullable */readonly last_viewed_at?: string | null;+ /** How this row matched the `search` term: `exact` (the term is a case-insensitive substring of the name, derived_name, description, or a tag name) or `similar` (a fuzzy trigram match only). Results are ordered exact-first. Null when the list is not filtered by `search`. */+ readonly search_match_type?: SearchMatchTypeEnum | null;}export interface PatchedInsightVariable {@@ -42466,7 +42480,7 @@ export namespace Schemas {*/saved?: boolean;/**- * Case-insensitive substring match across name, derived_name, description, and tag names.+ * Search term matched across name, derived_name, description, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches together in one list, ordered exact-first; each result's `search_match_type` is `exact` or `similar`.*/search?: string;short_id?: string;@@ -48049,7 +48063,7 @@ export namespace Schemas {*/saved?: boolean;/**- * Case-insensitive substring match across name, derived_name, description, and tag names.+ * Search term matched across name, derived_name, description, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches together in one list, ordered exact-first; each result's `search_match_type` is `exact` or `similar`.*/search?: string;short_id?: string;diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.tsindex 142d08069f98..58c47f3e137d 100644--- a/services/mcp/src/generated/product_analytics/api.ts+++ b/services/mcp/src/generated/product_analytics/api.ts@@ -100,7 +100,9 @@ export const InsightsListQueryParams = /* @__PURE__ */ zod.object({search: zod.string().optional()- .describe('Case-insensitive substring match across name, derived_name, description, and tag names.'),+ .describe(+ "Search term matched across name, derived_name, description, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches together in one list, ordered exact-first; each result's `search_match_type` is `exact` or `similar`."+ ),short_id: zod.string().optional(),tags: zod.string()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.jsonindex f682d8ca9baa..372766afce8d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json@@ -55,7 +55,7 @@"type": "boolean"},"search": {- "description": "Case-insensitive substring match across name, derived_name, description, and tag names.",+ "description": "Search term matched across name, derived_name, description, and tag names. Returns case-insensitive substring matches and fuzzy trigram matches together in one list, ordered exact-first; each result's `search_match_type` is `exact` or `similar`.","type": "string"},"short_id": {