Skip to content

🤯 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.

♻️ refactor(search): remove pg_search hybrid routing (#18961)

YuTengjing9fbf55f924ae
diff --git a/.agents/skills/full-text-search/SKILL.md b/.agents/skills/full-text-search/SKILL.md
index 5472cacc744..6f925279f0e 100644
--- a/.agents/skills/full-text-search/SKILL.md
+++ b/.agents/skills/full-text-search/SKILL.md
@@ -41,8 +41,8 @@ router/service -> createFtsSearchRepo -> FtsSearchRepo -> selected backend -> ex
provider is implemented end to end.
- Elasticsearch errors, missing configuration, and unsupported candidate behavior must remain
visible. Never silently retry through PostgreSQL or add an `ilike` fallback.
-- Deliberate routing of an entity that has not been migrated to Elasticsearch is not an error
- fallback. Changing the migrated entity set is a product and migration decision.
+- Before selecting Elasticsearch, require coverage tests proving that it supports every entity in
+ the provider-neutral backend contract. Do not add per-entity routing between providers.
- Preserve `userId`, `workspaceId`, and caller-agent visibility throughout every provider. Candidate
retrieval must not broaden the caller's scope.
- Where Elasticsearch only supplies candidate IDs, PostgreSQL hydration and parent checks remain
diff --git a/apps/server/src/services/ftsSearch/index.test.ts b/apps/server/src/services/ftsSearch/index.test.ts
index f26bc6df247..dc18460d2de 100644
--- a/apps/server/src/services/ftsSearch/index.test.ts
+++ b/apps/server/src/services/ftsSearch/index.test.ts
@@ -95,11 +95,12 @@ describe('full-text search provider selection', () => {
candidates: [],
items: [],
});
+ const createPgSearchBackend = vi.fn(() => ({ key: 'pg_search', search: pgSearch }));
const repo = await createFtsSearchRepo(
{ db, userId: 'allowed-user' },
{
createElasticsearchClient: () => ({ search: elasticsearchSearch }),
- createPgSearchBackend: () => ({ key: 'pg_search', search: pgSearch }),
+ createPgSearchBackend,
loadElasticsearchConfig: () => ({
apiKey: 'test-api-key',
indexNamespace: 'lobehub-dev',
@@ -111,6 +112,7 @@ describe('full-text search provider selection', () => {
await expect(repo.search({ query: 'candidate' })).resolves.toEqual([]);
expect(elasticsearchSearch).toHaveBeenCalledTimes(9);
+ expect(createPgSearchBackend).not.toHaveBeenCalled();
expect(pgSearch).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/ftsSearch/index.ts b/apps/server/src/services/ftsSearch/index.ts
index ac84995d9f4..7ad94add5d9 100644
--- a/apps/server/src/services/ftsSearch/index.ts
+++ b/apps/server/src/services/ftsSearch/index.ts
@@ -7,7 +7,6 @@ import {
type FtsSearchBackendScope,
FtsSearchRepo,
type FtsSearchRepoOptions,
- isElasticsearchFtsSearchEntity,
PgSearchFtsSearchBackend,
} from '@/database/repositories/ftsSearch';
import { ftsSearchEnv } from '@/envs/ftsSearch';
@@ -83,14 +82,12 @@ const createFtsSearchBackendForProvider = (
{ db, provider, scope }: FtsSearchBackendFactoryContext,
dependencies: FtsSearchBackendFactoryDependencies,
): FtsSearchBackend | undefined => {
- const createPgSearchBackend =
- dependencies.createPgSearchBackend ??
- ((context: FtsSearchBackendFactoryContext) =>
- new PgSearchFtsSearchBackend(context.db, context.scope));
- const pgSearchBackend = createPgSearchBackend({ db, provider, scope });
-
if (provider === FTS_SEARCH_PROVIDERS.pgSearch) {
- return pgSearchBackend;
+ const createPgSearchBackend =
+ dependencies.createPgSearchBackend ??
+ ((context: FtsSearchBackendFactoryContext) =>
+ new PgSearchFtsSearchBackend(context.db, context.scope));
+ return createPgSearchBackend({ db, provider, scope });
}
const config = (dependencies.loadElasticsearchConfig ?? loadElasticsearchFtsSearchConfig)();
@@ -100,20 +97,11 @@ const createFtsSearchBackendForProvider = (
dependencies.createElasticsearchClient ??
((input) => new ElasticsearchFtsSearchHttpClient(input))
)(config);
- const elasticsearchBackend = new ElasticsearchFtsSearchBackend(db, {
+ return new ElasticsearchFtsSearchBackend(db, {
client,
indexNamespace: config.indexNamespace,
observer: createElasticsearchFtsSearchObserver(),
});
-
- return {
- key: `${elasticsearchBackend.key}+${pgSearchBackend.key}`,
- /** Unmigrated entities stay on pg_search; Elasticsearch failures on migrated entities remain fatal. */
- search: (request) =>
- isElasticsearchFtsSearchEntity(request.entity)
- ? elasticsearchBackend.search(request)
- : pgSearchBackend.search(request),
- };
};
export const resolveFtsSearchProvider = (
@@ -146,12 +134,7 @@ export const createFtsSearchRepo = async (
if (!backend) throw new FtsSearchBackendUnavailableError(provider);
- const observedBackend = withFtsSearchBackendObservability(backend, (request) =>
- provider === FTS_SEARCH_PROVIDERS.elasticsearch &&
- !isElasticsearchFtsSearchEntity(request.entity)
- ? FTS_SEARCH_PROVIDERS.pgSearch
- : provider,
- );
+ const observedBackend = withFtsSearchBackendObservability(backend, () => provider);
return new FtsSearchRepo(input.db, input.userId, input.workspaceId, input.callerAgentVisibility, {
...input.options,
diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.test.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.test.ts
new file mode 100644
index 00000000000..477d43ebf49
--- /dev/null
+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/query-fields.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest';
+
+import { FTS_SEARCH_BACKEND_ENTITIES } from '../types';
+import { isElasticsearchFtsSearchEntity } from './query-fields';
+
+describe('Elasticsearch query field coverage', () => {
+ it('covers every full-text search backend entity', () => {
+ expect(
+ FTS_SEARCH_BACKEND_ENTITIES.filter((entity) => !isElasticsearchFtsSearchEntity(entity)),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/database/src/repositories/ftsSearch/types.ts b/packages/database/src/repositories/ftsSearch/types.ts
index c7a0a95f5c9..6d0fff6c80e 100644
--- a/packages/database/src/repositories/ftsSearch/types.ts
+++ b/packages/database/src/repositories/ftsSearch/types.ts
@@ -168,21 +168,24 @@ export interface FtsSearchOptions {
}
/** Entities implemented by the current product search repository contract. */
-export type FtsSearchBackendEntity =
- | 'agents'
- | 'chatGroups'
- | 'documents'
- | 'files'
- | 'knowledgeBases'
- | 'memoryActivities'
- | 'memoryContexts'
- | 'memoryExperiences'
- | 'memoryIdentities'
- | 'memoryPreferences'
- | 'messages'
- | 'personaDocuments'
- | 'topics'
- | 'userMemories';
+export const FTS_SEARCH_BACKEND_ENTITIES = [
+ 'agents',
+ 'chatGroups',
+ 'documents',
+ 'files',
+ 'knowledgeBases',
+ 'memoryActivities',
+ 'memoryContexts',
+ 'memoryExperiences',
+ 'memoryIdentities',
+ 'memoryPreferences',
+ 'messages',
+ 'personaDocuments',
+ 'topics',
+ 'userMemories',
+] as const;
+
+export type FtsSearchBackendEntity = (typeof FTS_SEARCH_BACKEND_ENTITIES)[number];
export interface FtsSearchBackendScope {
/** Visibility of the agent initiating a KB search, when applicable. */
diff --git a/packages/env/src/__tests__/ftsSearch.test.ts b/packages/env/src/__tests__/ftsSearch.test.ts
index 49e8e952a2d..c4410ff25fa 100644
--- a/packages/env/src/__tests__/ftsSearch.test.ts
+++ b/packages/env/src/__tests__/ftsSearch.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { getFtsSearchConfig } from '../ftsSearch';
+import { getElasticsearchFtsSearchConfig, getFtsSearchConfig } from '../ftsSearch';
afterEach(() => {
vi.unstubAllEnvs();
@@ -46,3 +46,19 @@ describe('getFtsSearchConfig', () => {
expect(() => getFtsSearchConfig()).toThrow();
});
});
+
+describe('getElasticsearchFtsSearchConfig', () => {
+ it('does not expose the deployment provider selector', () => {
+ vi.stubEnv('ES_API_KEY', 'test-api-key');
+ vi.stubEnv('ES_INDEX_NAMESPACE', 'lobehub-dev');
+ vi.stubEnv('ES_URL', 'https://search.example.com');
+ vi.stubEnv('FTS_SEARCH_PROVIDER', 'pg_search');
+
+ expect(getElasticsearchFtsSearchConfig()).toEqual({
+ ES_API_KEY: 'test-api-key',
+ FTS_SEARCH_SYNC_ENABLED: undefined,
+ ES_INDEX_NAMESPACE: 'lobehub-dev',
+ ES_URL: 'https://search.example.com',
+ });
+ });
+});
diff --git a/packages/env/src/ftsSearch.ts b/packages/env/src/ftsSearch.ts
index d3da59be2ed..39f7e7f8195 100644
--- a/packages/env/src/ftsSearch.ts
+++ b/packages/env/src/ftsSearch.ts
@@ -1,23 +1,34 @@
import { createEnv } from '@t3-oss/env-core';
import { z } from 'zod';
-export const getFtsSearchConfig = () => {
+export const getElasticsearchFtsSearchConfig = () => {
return createEnv({
runtimeEnv: {
ES_API_KEY: process.env.ES_API_KEY,
FTS_SEARCH_SYNC_ENABLED: process.env.FTS_SEARCH_SYNC_ENABLED,
ES_INDEX_NAMESPACE: process.env.ES_INDEX_NAMESPACE,
ES_URL: process.env.ES_URL,
- FTS_SEARCH_PROVIDER: process.env.FTS_SEARCH_PROVIDER,
},
server: {
ES_API_KEY: z.string().min(1).optional(),
FTS_SEARCH_SYNC_ENABLED: z.enum(['true', 'false']).optional(),
ES_INDEX_NAMESPACE: z.string().min(1).optional(),
ES_URL: z.string().url().optional(),
+ },
+ });
+};
+
+export const getFtsSearchConfig = () => {
+ const providerConfig = createEnv({
+ runtimeEnv: {
+ FTS_SEARCH_PROVIDER: process.env.FTS_SEARCH_PROVIDER,
+ },
+ server: {
FTS_SEARCH_PROVIDER: z.enum(['elasticsearch', 'pg_search']).default('pg_search'),
},
});
+
+ return { ...getElasticsearchFtsSearchConfig(), ...providerConfig };
};
export const ftsSearchEnv = getFtsSearchConfig();