🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(search): add cost attribution metrics (#19012)
YuTengjing4cce7b5cf17e
diff --git a/apps/server/src/routers/lambda/__tests__/search.test.ts b/apps/server/src/routers/lambda/__tests__/search.test.tsindex 4e994687675..203b564f6e3 100644--- a/apps/server/src/routers/lambda/__tests__/search.test.ts+++ b/apps/server/src/routers/lambda/__tests__/search.test.ts@@ -95,7 +95,11 @@ describe('searchRouter', () => {type: 'message',});expect(createFtsSearchRepo).toHaveBeenCalledWith(- expect.objectContaining({ userId: 'test-user', workspaceId: undefined }),+ expect.objectContaining({+ usage: 'unified_search',+ userId: 'test-user',+ workspaceId: undefined,+ }),);expect(UserModel.findById).not.toHaveBeenCalled();expect(getUserSettings).not.toHaveBeenCalled();diff --git a/apps/server/src/routers/lambda/home.ts b/apps/server/src/routers/lambda/home.tsindex 4aebae65ec3..4113df92c5d 100644--- a/apps/server/src/routers/lambda/home.ts+++ b/apps/server/src/routers/lambda/home.ts@@ -32,6 +32,7 @@ const homeSearchProcedure = homeProcedure.use(async (opts) => {const ftsSearchRepo = await createFtsSearchRepo({db: ctx.serverDB,userId: ctx.userId,+ usage: 'home_search',workspaceId,});diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex c2338e80bb6..6ece866b249 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -62,6 +62,7 @@ const messageSearchProcedure = messageProcedure.use(async (opts) => {const ftsSearchRepo = await createFtsSearchRepo({db: ctx.serverDB,userId: ctx.userId,+ usage: 'message_search',workspaceId,});diff --git a/apps/server/src/routers/lambda/search.ts b/apps/server/src/routers/lambda/search.tsindex 1f5ecb50156..495323161ff 100644--- a/apps/server/src/routers/lambda/search.ts+++ b/apps/server/src/routers/lambda/search.ts@@ -133,6 +133,7 @@ export const searchRouter = router({createFtsSearchRepo({db: ctx.serverDB,userId: ctx.userId,+ usage: 'unified_search',workspaceId: ctx.workspaceId ?? undefined,}),]);diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.tsindex bcf5c580353..ad502002451 100644--- a/apps/server/src/routers/lambda/session.ts+++ b/apps/server/src/routers/lambda/session.ts@@ -72,6 +72,7 @@ const sessionSearchProcedure = sessionProcedure.use(async (opts) => {const ftsSearchRepo = await createFtsSearchRepo({db: ctx.serverDB,userId: ctx.userId,+ usage: 'session_search',workspaceId,});diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 2ad9d818e0e..3991375aba2 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -88,6 +88,7 @@ const topicSearchProcedure = topicProcedure.use(async (opts) => {const ftsSearchRepo = await createFtsSearchRepo({db: ctx.serverDB,userId: ctx.userId,+ usage: 'topic_search',workspaceId,});diff --git a/apps/server/src/routers/lambda/userMemories.ts b/apps/server/src/routers/lambda/userMemories.tsindex 50b7348600c..de05bdbcfa4 100644--- a/apps/server/src/routers/lambda/userMemories.ts+++ b/apps/server/src/routers/lambda/userMemories.ts@@ -276,7 +276,11 @@ const memoryProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>});const memorySearchProcedure = memoryProcedure.use(async (opts) => {const { ctx } = opts;- const ftsSearchRepo = await createFtsSearchRepo({ db: ctx.serverDB, userId: ctx.userId });+ const ftsSearchRepo = await createFtsSearchRepo({+ db: ctx.serverDB,+ userId: ctx.userId,+ usage: 'memory',+ });return opts.next({ctx: {diff --git a/apps/server/src/services/ftsSearch/elasticsearch.test.ts b/apps/server/src/services/ftsSearch/elasticsearch.test.tsindex acad084d942..6f959d3a4bd 100644--- a/apps/server/src/services/ftsSearch/elasticsearch.test.ts+++ b/apps/server/src/services/ftsSearch/elasticsearch.test.ts@@ -115,6 +115,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {serverTookMs: 12,traceContext: expect.any(String),truncated: false,+ usage: 'unattributed',});});@@ -175,6 +176,7 @@ describe('ElasticsearchFtsSearchHttpClient', () => {traceContext: expect.any(String),traceId: expect.any(String),truncated: true,+ usage: 'unattributed',});expect(JSON.stringify(errorSpy.mock.calls)).not.toContain('secret-query-fragment');});diff --git a/apps/server/src/services/ftsSearch/elasticsearch.ts b/apps/server/src/services/ftsSearch/elasticsearch.tsindex 2d856671cd8..ae785e1898d 100644--- a/apps/server/src/services/ftsSearch/elasticsearch.ts+++ b/apps/server/src/services/ftsSearch/elasticsearch.ts@@ -15,6 +15,7 @@ import type {ElasticsearchFtsSearchErrorCode,ElasticsearchFtsSearchRequestResult,ElasticsearchFtsSearchTraceContext,+ FtsSearchUsage,} from './observability';import { recordElasticsearchFtsSearchRequest } from './observability';@@ -113,6 +114,7 @@ export interface ElasticsearchFtsSearchHttpClientOptions {apiKey: string;requestTimeoutMs?: number;url: string;+ usage?: FtsSearchUsage;}export interface ElasticsearchFtsSearchSyncIndexIdentity {@@ -237,11 +239,18 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchCprivate readonly apiKey: string;private readonly requestTimeoutMs: number;private readonly url: URL;-- constructor({ apiKey, requestTimeoutMs = 10_000, url }: ElasticsearchFtsSearchHttpClientOptions) {+ private readonly usage: FtsSearchUsage;++ constructor({+ apiKey,+ requestTimeoutMs = 10_000,+ url,+ usage = 'unattributed',+ }: ElasticsearchFtsSearchHttpClientOptions) {this.apiKey = apiKey;this.requestTimeoutMs = requestTimeoutMs;this.url = parseElasticsearchUrl(url);+ this.usage = usage;}/** Fails closed unless every incremental destination is a writable alias with tombstone support. */@@ -496,6 +505,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchC'fts.search.elasticsearch.query_field_count': input.queryFieldCount,'fts.search.elasticsearch.query_truncated': input.truncated,'fts.search.elasticsearch.trace_context': traceContext,+ 'fts.search.elasticsearch.usage': this.usage,});const record = (result: ElasticsearchFtsSearchRequestResult,@@ -520,6 +530,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchCserverTookMs,traceContext,truncated: input.truncated,+ usage: this.usage,});};const logFailure = (errorCode: ElasticsearchFtsSearchErrorCode, status?: number) => {@@ -538,6 +549,7 @@ export class ElasticsearchFtsSearchHttpClient implements ElasticsearchFtsSearchCtraceContext,traceId,truncated: input.truncated,+ usage: this.usage,});};diff --git a/apps/server/src/services/ftsSearch/index.test.ts b/apps/server/src/services/ftsSearch/index.test.tsindex dc18460d2de..6b2ace4fedf 100644--- a/apps/server/src/services/ftsSearch/index.test.ts+++ b/apps/server/src/services/ftsSearch/index.test.ts@@ -51,7 +51,7 @@ describe('full-text search provider selection', () => {});const createBackend = vi.fn(({ provider }): FtsSearchBackend => ({ key: provider, search }));const repo = await createFtsSearchRepo(- { db, userId: 'allowed-user' },+ { db, userId: 'allowed-user', usage: 'unified_search' },{createBackend,loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,@@ -76,7 +76,7 @@ describe('full-text search provider selection', () => {url: 'https://search.example.com',};const repo = await createFtsSearchRepo(- { db, userId: 'allowed-user' },+ { db, userId: 'allowed-user', usage: 'unified_search' },{createElasticsearchClient,loadElasticsearchConfig: () => config,@@ -85,7 +85,7 @@ describe('full-text search provider selection', () => {);await expect(repo.search({ query: 'candidate', type: 'agent' })).resolves.toEqual([]);- expect(createElasticsearchClient).toHaveBeenCalledWith(config);+ expect(createElasticsearchClient).toHaveBeenCalledWith(config, 'unified_search');expect(search).toHaveBeenCalledWith(expect.objectContaining({ index: 'lobehub-dev-agents' }));});@@ -97,7 +97,7 @@ describe('full-text search provider selection', () => {});const createPgSearchBackend = vi.fn(() => ({ key: 'pg_search', search: pgSearch }));const repo = await createFtsSearchRepo(- { db, userId: 'allowed-user' },+ { db, userId: 'allowed-user', usage: 'unattributed' },{createElasticsearchClient: () => ({ search: elasticsearchSearch }),createPgSearchBackend,@@ -123,7 +123,7 @@ describe('full-text search provider selection', () => {items: [],});const repo = await createFtsSearchRepo(- { db, userId: 'allowed-user' },+ { db, userId: 'allowed-user', usage: 'unattributed' },{createElasticsearchClient: () => ({search: vi.fn().mockRejectedValue(providerError),@@ -145,7 +145,7 @@ describe('full-text search provider selection', () => {it('fails explicitly when the selected provider is not configured', async () => {await expect(createFtsSearchRepo(- { db, userId: 'user-1' },+ { db, userId: 'user-1', usage: 'unattributed' },{loadElasticsearchConfig: () => undefined,loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,@@ -159,7 +159,7 @@ describe('full-text search provider selection', () => {const search = vi.fn<FtsSearchBackend['search']>().mockRejectedValue(providerError);const createBackend = vi.fn(({ provider }): FtsSearchBackend => ({ key: provider, search }));const repo = await createFtsSearchRepo(- { db, userId: 'user-1' },+ { db, userId: 'user-1', usage: 'unattributed' },{createBackend,loadFtsSearchProvider: () => FTS_SEARCH_PROVIDERS.elasticsearch,diff --git a/apps/server/src/services/ftsSearch/index.ts b/apps/server/src/services/ftsSearch/index.tsindex 7ad94add5d9..01b320298e0 100644--- a/apps/server/src/services/ftsSearch/index.ts+++ b/apps/server/src/services/ftsSearch/index.ts@@ -14,6 +14,7 @@ import { ftsSearchEnv } from '@/envs/ftsSearch';import { ElasticsearchFtsSearchHttpClient } from './elasticsearch';import {createElasticsearchFtsSearchObserver,+ type FtsSearchUsage,withFtsSearchBackendObservability,} from './observability';@@ -21,6 +22,7 @@ export interface CreateFtsSearchRepoInput {callerAgentVisibility?: 'private' | 'public' | null;db: LobeChatDatabase;options?: FtsSearchRepoOptions;+ usage: FtsSearchUsage;userId: string;workspaceId?: string;}@@ -37,12 +39,14 @@ interface FtsSearchBackendFactoryContext {db: CreateFtsSearchRepoInput['db'];provider: FtsSearchProvider;scope: FtsSearchBackendScope;+ usage: FtsSearchUsage;}interface FtsSearchBackendFactoryDependencies {createBackend?: (context: FtsSearchBackendFactoryContext) => FtsSearchBackend | undefined;createElasticsearchClient?: (config: ElasticsearchFtsSearchConfig,+ usage: FtsSearchUsage,) => ElasticsearchFtsSearchClient;createPgSearchBackend?: (context: FtsSearchBackendFactoryContext) => FtsSearchBackend;loadElasticsearchConfig?: () => ElasticsearchFtsSearchConfig | undefined;@@ -79,7 +83,7 @@ export const loadElasticsearchFtsSearchConfig = (): ElasticsearchFtsSearchConfig};const createFtsSearchBackendForProvider = (- { db, provider, scope }: FtsSearchBackendFactoryContext,+ { db, provider, scope, usage }: FtsSearchBackendFactoryContext,dependencies: FtsSearchBackendFactoryDependencies,): FtsSearchBackend | undefined => {if (provider === FTS_SEARCH_PROVIDERS.pgSearch) {@@ -87,7 +91,7 @@ const createFtsSearchBackendForProvider = (dependencies.createPgSearchBackend ??((context: FtsSearchBackendFactoryContext) =>new PgSearchFtsSearchBackend(context.db, context.scope));- return createPgSearchBackend({ db, provider, scope });+ return createPgSearchBackend({ db, provider, scope, usage });}const config = (dependencies.loadElasticsearchConfig ?? loadElasticsearchFtsSearchConfig)();@@ -95,12 +99,12 @@ const createFtsSearchBackendForProvider = (const client = (dependencies.createElasticsearchClient ??- ((input) => new ElasticsearchFtsSearchHttpClient(input))- )(config);+ ((input, inputUsage) => new ElasticsearchFtsSearchHttpClient({ ...input, usage: inputUsage }))+ )(config, usage);return new ElasticsearchFtsSearchBackend(db, {client,indexNamespace: config.indexNamespace,- observer: createElasticsearchFtsSearchObserver(),+ observer: createElasticsearchFtsSearchObserver(usage),});};@@ -127,6 +131,7 @@ export const createFtsSearchRepo = async (db: input.db,provider,scope,+ usage: input.usage,};const backend = dependencies.createBackend? dependencies.createBackend(context)@@ -134,7 +139,7 @@ export const createFtsSearchRepo = async (if (!backend) throw new FtsSearchBackendUnavailableError(provider);- const observedBackend = withFtsSearchBackendObservability(backend, () => provider);+ const observedBackend = withFtsSearchBackendObservability(backend, () => provider, input.usage);return new FtsSearchRepo(input.db, input.userId, input.workspaceId, input.callerAgentVisibility, {...input.options,diff --git a/apps/server/src/services/ftsSearch/observability.test.ts b/apps/server/src/services/ftsSearch/observability.test.tsindex 54d4bfee34e..29eacd570a3 100644--- a/apps/server/src/services/ftsSearch/observability.test.ts+++ b/apps/server/src/services/ftsSearch/observability.test.ts@@ -61,12 +61,14 @@ describe('full-text search backend observability', () => {operation: 'pg_hydration',provider: 'elasticsearch',result: 'success',+ usage: 'message_search',}),).toEqual({entity: 'messages',operation: 'pg_hydration',provider: 'elasticsearch',result: 'success',+ usage: 'message_search',});});@@ -77,7 +79,7 @@ describe('full-text search backend observability', () => {search: vi.fn().mockResolvedValue(response),};const resolveProvider = vi.fn(() => 'pg_search' as const);- const observed = withFtsSearchBackendObservability(backend, resolveProvider);+ const observed = withFtsSearchBackendObservability(backend, resolveProvider, 'unified_search');const request = {entity: 'agents',filters: {},@@ -108,6 +110,7 @@ describe('full-text search backend observability', () => {'fts.search.backend.entity': 'agents','fts.search.backend.operation': 'product_path','fts.search.backend.provider': 'pg_search',+ 'fts.search.backend.usage': 'unified_search',},},expect.any(Function),@@ -121,7 +124,7 @@ describe('full-text search backend observability', () => {key: 'pg_search',search: vi.fn().mockResolvedValue(response),};- const observed = withFtsSearchBackendObservability(backend, () => 'pg_search');+ const observed = withFtsSearchBackendObservability(backend, () => 'pg_search', 'unattributed');await expect(observed.search({@@ -166,6 +169,7 @@ describe('full-text search backend observability', () => {serverTookMs: 12,traceContext: 'recording',truncated: true,+ usage: 'unified_search',});const requestAttributes = {@@ -175,31 +179,42 @@ describe('full-text search backend observability', () => {query_truncated: true,result: 'success',trace_context: 'recording',+ usage: 'unified_search',};const histogramAttributes = {entity: 'messages',pagination: 'bounded',result: 'success',};+ const costAttributes = { ...histogramAttributes, usage: 'unified_search' };expect(mocks.counters.get('fts_search_elasticsearch_requests_total')?.add).toHaveBeenCalledWith(1,requestAttributes,);expect(mocks.histograms.get('fts_search_elasticsearch_server_took')?.record,- ).toHaveBeenCalledWith(12, histogramAttributes);+ ).toHaveBeenCalledWith(12, costAttributes);expect(mocks.histograms.get('fts_search_elasticsearch_response_decoded_size')?.record,- ).toHaveBeenCalledWith(2048, histogramAttributes);+ ).toHaveBeenCalledWith(2048, costAttributes);+ expect(+ mocks.histograms.get('fts_search_elasticsearch_response_content_length')?.record,+ ).toHaveBeenCalledWith(1024, costAttributes);+ expect(+ mocks.histograms.get('fts_search_elasticsearch_request_size')?.record,+ ).toHaveBeenCalledWith(512, costAttributes);+ expect(+ mocks.histograms.get('fts_search_elasticsearch_response_hits')?.record,+ ).toHaveBeenCalledWith(20, costAttributes);expect(mocks.histograms.get('fts_search_elasticsearch_original_query_characters')?.record,- ).toHaveBeenCalledWith(64, histogramAttributes);+ ).toHaveBeenCalledWith(64, costAttributes);expect(mocks.histograms.get('fts_search_elasticsearch_executed_query_characters')?.record,- ).toHaveBeenCalledWith(32, histogramAttributes);+ ).toHaveBeenCalledWith(32, costAttributes);expect(mocks.histograms.get('fts_search_elasticsearch_request_duration')?.record,- ).toHaveBeenCalledWith(40, histogramAttributes);+ ).toHaveBeenCalledWith(40, costAttributes);expect(Object.keys(requestAttributes)).toEqual(['entity','error_code',@@ -207,8 +222,9 @@ describe('full-text search backend observability', () => {'query_truncated','result','trace_context',+ 'usage',]);- expect(Object.keys(histogramAttributes)).toEqual(['entity', 'pagination', 'result']);+ expect(Object.keys(costAttributes)).toEqual(['entity', 'pagination', 'result', 'usage']);});it('records when long user-memory context skips conjunction-based lexical search', () => {@@ -233,7 +249,11 @@ describe('full-text search backend observability', () => {key: 'elasticsearch',search: vi.fn().mockRejectedValue(providerError),};- const observed = withFtsSearchBackendObservability(backend, () => 'elasticsearch');+ const observed = withFtsSearchBackendObservability(+ backend,+ () => 'elasticsearch',+ 'message_search',+ );await expect(observed.search({@@ -253,7 +273,7 @@ describe('full-text search backend observability', () => {key: 'pg_search',search: vi.fn().mockResolvedValue(response),};- const observed = withFtsSearchBackendObservability(backend, () => 'pg_search');+ const observed = withFtsSearchBackendObservability(backend, () => 'pg_search', 'unattributed');mocks.span.end.mockImplementationOnce(() => {throw new Error('telemetry unavailable');});diff --git a/apps/server/src/services/ftsSearch/observability.ts b/apps/server/src/services/ftsSearch/observability.tsindex b1ff08ce407..9183c3a58e3 100644--- a/apps/server/src/services/ftsSearch/observability.ts+++ b/apps/server/src/services/ftsSearch/observability.ts@@ -31,6 +31,18 @@ export type ElasticsearchFtsSearchErrorCode =| 'transport_error'| 'unknown_http_error';export type ElasticsearchFtsSearchTraceContext = 'missing' | 'non_recording' | 'recording';+export type FtsSearchUsage =+ | 'home_search'+ | 'knowledge_base'+ | 'memory'+ | 'memory_extraction'+ | 'memory_tool'+ | 'message_search'+ | 'message_search_mobile'+ | 'session_search'+ | 'topic_search'+ | 'unattributed'+ | 'unified_search';export type UserMemoryLexicalSearchDecision = 'executed' | 'skipped_long_context';export type UserMemoryLexicalSearchSource ='api' | 'memory_extraction' | 'tool' | 'topic_retrieval';@@ -40,6 +52,7 @@ export interface FtsSearchBackendOperationAttributes {operation: FtsSearchBackendOperation;provider: FtsSearchProvider;result: FtsSearchBackendOperationResult;+ usage: FtsSearchUsage;}type FtsSearchBackendOperationBaseAttributes = Omit<FtsSearchBackendOperationAttributes, 'result'>;@@ -155,6 +168,7 @@ export const buildFtsSearchBackendMetricAttributes = (operation: attributes.operation,provider: attributes.provider,result: attributes.result,+ usage: attributes.usage,});const finishOperation = (@@ -193,6 +207,7 @@ export const recordElasticsearchFtsSearchRequest = (input: {serverTookMs?: number;traceContext: ElasticsearchFtsSearchTraceContext;truncated: boolean;+ usage: FtsSearchUsage;}): void => {recordSafely('Elasticsearch search request', () => {const histogramAttributes: Attributes = {@@ -200,28 +215,32 @@ export const recordElasticsearchFtsSearchRequest = (input: {pagination: input.pagination,result: input.result,};- const requestAttributes: Attributes = {+ const costAttributes: Attributes = {...histogramAttributes,+ usage: input.usage,+ };+ const requestAttributes: Attributes = {+ ...costAttributes,error_code: input.errorCode,query_truncated: input.truncated,trace_context: input.traceContext,};elasticsearchRequests.add(1, requestAttributes);- elasticsearchRequestDuration.record(input.durationMs, histogramAttributes);- elasticsearchRequestBytes.record(input.requestBytes, histogramAttributes);- elasticsearchOriginalQueryCharacters.record(input.originalQueryChars, histogramAttributes);- elasticsearchExecutedQueryCharacters.record(input.executedQueryChars, histogramAttributes);+ elasticsearchRequestDuration.record(input.durationMs, costAttributes);+ elasticsearchRequestBytes.record(input.requestBytes, costAttributes);+ elasticsearchOriginalQueryCharacters.record(input.originalQueryChars, costAttributes);+ elasticsearchExecutedQueryCharacters.record(input.executedQueryChars, costAttributes);if (input.contentLength !== undefined) {- elasticsearchResponseContentLength.record(input.contentLength, histogramAttributes);+ elasticsearchResponseContentLength.record(input.contentLength, costAttributes);}if (input.decodedBytes !== undefined) {- elasticsearchResponseDecodedBytes.record(input.decodedBytes, histogramAttributes);+ elasticsearchResponseDecodedBytes.record(input.decodedBytes, costAttributes);}if (input.hits !== undefined) {- elasticsearchResponseHits.record(input.hits, histogramAttributes);+ elasticsearchResponseHits.record(input.hits, costAttributes);}if (input.serverTookMs !== undefined) {- elasticsearchServerTook.record(input.serverTookMs, histogramAttributes);+ elasticsearchServerTook.record(input.serverTookMs, costAttributes);}});};@@ -274,6 +293,7 @@ export const observeFtsSearchBackendOperation = async <Result>('fts.search.backend.entity': attributes.entity,'fts.search.backend.operation': attributes.operation,'fts.search.backend.provider': attributes.provider,+ 'fts.search.backend.usage': attributes.usage,},},async (span) => {@@ -289,14 +309,20 @@ export const observeFtsSearchBackendOperation = async <Result>(},);-export const createElasticsearchFtsSearchObserver = (): ElasticsearchFtsSearchObserver => ({+export const createElasticsearchFtsSearchObserver = (+ usage: FtsSearchUsage,+): ElasticsearchFtsSearchObserver => ({observe: (entity, operation, callback) =>- observeFtsSearchBackendOperation({ entity, operation, provider: 'elasticsearch' }, callback),+ observeFtsSearchBackendOperation(+ { entity, operation, provider: 'elasticsearch', usage },+ callback,+ ),});export const withFtsSearchBackendObservability = (backend: FtsSearchBackend,resolveProvider: (request: FtsSearchBackendRequest) => FtsSearchProvider,+ usage: FtsSearchUsage,): FtsSearchBackend => ({key: backend.key,search: (request) => {@@ -306,6 +332,7 @@ export const withFtsSearchBackendObservability = (entity: request.entity,operation: 'product_path',provider,+ usage,},async () => {const response = await backend.search(request);diff --git a/apps/server/src/services/ftsSearchSync/service.test.ts b/apps/server/src/services/ftsSearchSync/service.test.tsindex 0870e631846..644f73eb33b 100644--- a/apps/server/src/services/ftsSearchSync/service.test.ts+++ b/apps/server/src/services/ftsSearchSync/service.test.ts@@ -21,10 +21,10 @@ const createHarness = (sources: Map<string, Record<string, unknown>>,) => {const builder = {- buildByIds: vi.fn(async (_entity: string, ids: readonly string[]) =>+ buildByIds: vi.fn(async (entity: string, ids: readonly string[]) =>ids.flatMap((id) => {const source = sources.get(id);- return source ? [{ entity: 'agents', id, source }] : [];+ return source ? [{ entity, id, source }] : [];}),),};@@ -104,6 +104,47 @@ describe('FtsSearchSyncService', () => {failed: 2,});expect(result.bulkBytes).toBeGreaterThan(0);+ expect(result.bulkRequestSamples[0].entities).toEqual({+ agents: {+ bytes: expect.any(Number),+ items: 4,+ result: 'mixed',+ },+ });+ });++ it('attributes malformed bulk responses to every entity in the request', async () => {+ const works: FtsSearchSyncWork[] = [+ { documentId: 'message', entity: 'messages', leaseToken: '1', revision: 1 },+ { documentId: 'agent', entity: 'agents', leaseToken: '2', revision: 2 },+ ];+ const harness = createHarness(+ works,+ new Map(works.map((item) => [item.documentId, { id: item.documentId, title: 'title' }])),+ );+ harness.client.bulk.mockResolvedValue({+ errors: false,+ items: [{ index: { status: 201 } }],+ });+ const service = new FtsSearchSyncService(+ harness.builder as never,+ harness.outbox as never,+ harness.client,+ 'lobehub-test',+ );++ const result = await service.drainOnce();++ expect(result.bulkRequestSamples).toEqual([+ expect.objectContaining({+ entities: {+ agents: { bytes: expect.any(Number), items: 1, result: 'response_error' },+ messages: { bytes: expect.any(Number), items: 1, result: 'response_error' },+ },+ items: 2,+ result: 'response_error',+ }),+ ]);});it('writes a soft tombstone when the PostgreSQL row no longer exists', async () => {@@ -233,7 +274,7 @@ describe('FtsSearchSyncService', () => {'lobehub-test',);- await service.drainOnce();+ const result = await service.drainOnce();const body = harness.client.bulk.mock.calls[0][0] as string;const documentIds = body@@ -242,6 +283,10 @@ describe('FtsSearchSyncService', () => {.filter((_, index) => index % 2 === 0).map((line) => JSON.parse(line).index._id);expect(documentIds).toEqual(['urgent-message', 'ordinary-agent']);+ expect(result.bulkRequestSamples[0].entities).toEqual({+ agents: { bytes: expect.any(Number), items: 1, result: 'success' },+ messages: { bytes: expect.any(Number), items: 1, result: 'success' },+ });});it('releases unprocessed claims after exhausting the bulk-request budget', async () => {diff --git a/apps/server/src/services/ftsSearchSync/service.ts b/apps/server/src/services/ftsSearchSync/service.tsindex e9e54a42297..307288fa60c 100644--- a/apps/server/src/services/ftsSearchSync/service.ts+++ b/apps/server/src/services/ftsSearchSync/service.ts@@ -48,11 +48,21 @@ export interface FtsSearchSyncDrainResult {released: number;}+export type FtsSearchSyncBulkRequestResult =+ 'item_error' | 'mixed' | 'request_error' | 'response_error' | 'success';++export interface FtsSearchSyncBulkEntitySample {+ bytes: number;+ items: number;+ result: FtsSearchSyncBulkRequestResult;+}+export interface FtsSearchSyncBulkRequestSample {bytes: number;durationMs: number;+ entities: Partial<Record<FtsSearchSyncWork['entity'], FtsSearchSyncBulkEntitySample>>;items: number;- result: 'item_error' | 'mixed' | 'request_error' | 'response_error' | 'success';+ result: FtsSearchSyncBulkRequestResult;}const workKey = (work: FtsSearchSyncWork) => `${work.entity}:${work.documentId}:${work.revision}`;@@ -87,6 +97,45 @@ const buildOperation = (return { body, bytes: Buffer.byteLength(body), work };};+const summarizeBulkEntities = (+ operations: FtsSearchSyncOperation[],+ result: FtsSearchSyncBulkRequestResult,+ failedWorkKeys?: Set<string>,+): FtsSearchSyncBulkRequestSample['entities'] => {+ const summaries = new Map<+ FtsSearchSyncWork['entity'],+ { bytes: number; failed: number; items: number }+ >();++ for (const operation of operations) {+ const entity = operation.work.entity;+ const current = summaries.get(entity) ?? { bytes: 0, failed: 0, items: 0 };+ current.bytes += operation.bytes;+ current.items += 1;+ if (failedWorkKeys?.has(workKey(operation.work))) current.failed += 1;+ summaries.set(entity, current);+ }++ const entitySamples: FtsSearchSyncBulkRequestSample['entities'] = {};+ for (const [entity, summary] of summaries) {+ const entityResult =+ failedWorkKeys === undefined+ ? result+ : summary.failed === 0+ ? 'success'+ : summary.failed === summary.items+ ? 'item_error'+ : 'mixed';+ entitySamples[entity] = {+ bytes: summary.bytes,+ items: summary.items,+ result: entityResult,+ };+ }++ return entitySamples;+};+/** Bounded PostgreSQL projection → byte-aware Elasticsearch bulk drain. */export class FtsSearchSyncService {private readonly options: FtsSearchSyncServiceOptions;@@ -181,6 +230,7 @@ export class FtsSearchSyncService {result.bulkRequestSamples.push({bytes: requestBytes,durationMs: Date.now() - startedAt,+ entities: summarizeBulkEntities(operations, 'request_error'),items: operations.length,result: 'request_error',});@@ -193,6 +243,7 @@ export class FtsSearchSyncService {result.bulkRequestSamples.push({bytes: requestBytes,durationMs: Date.now() - startedAt,+ entities: summarizeBulkEntities(operations, 'response_error'),items: operations.length,result: 'response_error',});@@ -228,12 +279,14 @@ export class FtsSearchSyncService {}}+ const bulkResult =+ failures.length === 0 ? 'success' : acknowledged.length === 0 ? 'item_error' : 'mixed';result.bulkRequestSamples.push({bytes: requestBytes,durationMs: Date.now() - startedAt,+ entities: summarizeBulkEntities(operations, bulkResult, new Set(failures.map(workKey))),items: operations.length,- result:- failures.length === 0 ? 'success' : acknowledged.length === 0 ? 'item_error' : 'mixed',+ result: bulkResult,});const deleted = await this.outbox.acknowledgeMany(acknowledged);diff --git a/apps/server/src/services/knowledgeBase/index.test.ts b/apps/server/src/services/knowledgeBase/index.test.tsindex 0fe43e9355e..bb0b23ea724 100644--- a/apps/server/src/services/knowledgeBase/index.test.ts+++ b/apps/server/src/services/knowledgeBase/index.test.ts@@ -204,6 +204,7 @@ describe('KnowledgeBaseSearchService', () => {expect(createFtsSearchRepo).toHaveBeenCalledWith({callerAgentVisibility: 'public',db: serverDB,+ usage: 'knowledge_base',userId,workspaceId: 'workspace-1',});diff --git a/apps/server/src/services/knowledgeBase/index.ts b/apps/server/src/services/knowledgeBase/index.tsindex 7bb38add59d..dc13bd05dde 100644--- a/apps/server/src/services/knowledgeBase/index.ts+++ b/apps/server/src/services/knowledgeBase/index.ts@@ -183,6 +183,7 @@ export class KnowledgeBaseSearchService {callerAgentVisibility: this.callerAgentVisibility,db: this.serverDB,userId: this.userId,+ usage: 'knowledge_base',workspaceId: this.workspaceId,});return ftsSearchRepo.searchKnowledgeBaseDocuments(input.query, knowledgeIds, topK);diff --git a/apps/server/src/services/memory/userMemory/extract.ts b/apps/server/src/services/memory/userMemory/extract.tsindex decdb602c93..05b4e648692 100644--- a/apps/server/src/services/memory/userMemory/extract.ts+++ b/apps/server/src/services/memory/userMemory/extract.ts@@ -1410,7 +1410,7 @@ export class MemoryExtractionExecutor {tokenLimit?: number,): Promise<UserMemoryHybridSearchAggregatedResult> {const db = await this.db;- const ftsSearchRepo = await createFtsSearchRepo({ db, userId });+ const ftsSearchRepo = await createFtsSearchRepo({ db, userId, usage: 'memory_extraction' });const userMemoryModel = new UserMemoryModel(db, userId, ftsSearchRepo);// TODO: make topK configurableconst topK = 10;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts b/apps/server/src/services/toolExecution/serverRuntimes/memory.tsindex b6cc3482703..2eb7a8ff741 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts@@ -888,6 +888,7 @@ export const memoryRuntime: ServerRuntimeRegistration = {const ftsSearchRepo = await createFtsSearchRepo({db: context.serverDB,userId: context.userId,+ usage: 'memory_tool',});const memoryModel = new UserMemoryModel(context.serverDB, context.userId, ftsSearchRepo);