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.

⚑️ perf(search): isolate BM25 scans to restore ParadeDB TopN (#17720)

Rdmclin238eaab8ce38a
diff --git a/packages/database/src/repositories/search/index.test.ts b/packages/database/src/repositories/search/index.test.ts
index f8e00672c14..f45c06fc85d 100644
--- a/packages/database/src/repositories/search/index.test.ts
+++ b/packages/database/src/repositories/search/index.test.ts
@@ -1,17 +1,27 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it } from 'vitest';
+import { eq } from 'drizzle-orm';
+import { drizzle as nodeDrizzle } from 'drizzle-orm/node-postgres';
+import { Pool as NodePool } from 'pg';
+import { afterAll, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { documents } from '../../schemas';
+import * as schema from '../../schemas';
+import { chatGroups, documents, workspaces } from '../../schemas';
import type { NewAgent } from '../../schemas/agent';
import { agents } from '../../schemas/agent';
import type { NewFile } from '../../schemas/file';
-import { files, knowledgeBaseFiles, knowledgeBases } from '../../schemas/file';
+import {
+ DOCUMENT_FOLDER_TYPE,
+ files,
+ knowledgeBaseFiles,
+ knowledgeBases,
+} from '../../schemas/file';
import { messages } from '../../schemas/message';
import type { NewTopic } from '../../schemas/topic';
import { topics } from '../../schemas/topic';
import { users } from '../../schemas/user';
import type { LobeChatDatabase } from '../../type';
+import type { SearchResult } from './index';
import { SearchRepo } from './index';
const userId = 'search-test-user';
@@ -35,6 +45,34 @@ beforeEach(async () => {
// BM25 search requires pg_search extension (ParadeDB), not available in PGlite
const isServerDB = process.env.TEST_SERVER_DB === '1';
+/**
+ * Result types produced by the eight search methods whose BM25 scan was split
+ * into an inner subquery. `memory` is absent on purpose β€” `searchMemories` is
+ * user-scoped with no join, so it was left on its original single-level shape.
+ */
+const REWRITTEN_RESULT_TYPES = [
+ 'agent',
+ 'chatGroup',
+ 'file',
+ 'folder',
+ 'knowledgeBase',
+ 'message',
+ 'page',
+ 'topic',
+] as const;
+
+/** Subquery alias each rewritten method gives its isolated BM25 scan. */
+const SCAN_ALIASES = [
+ 'agent_hits',
+ 'chat_group_hits',
+ 'file_hits',
+ 'folder_hits',
+ 'knowledge_base_hits',
+ 'message_hits',
+ 'page_hits',
+ 'topic_hits',
+];
+
describe.skipIf(!isServerDB)('SearchRepo', () => {
describe('search - empty query', () => {
it('should return empty array for empty query', async () => {
@@ -1082,9 +1120,7 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
it('does not surface another user PDF when querying their KB', async () => {
- const results = await searchRepo.searchKnowledgeBaseDocuments('attention', [
- 'kb-other-1',
- ]);
+ const results = await searchRepo.searchKnowledgeBaseDocuments('attention', ['kb-other-1']);
expect(results).toEqual([]);
});
});
@@ -1291,4 +1327,325 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
}
});
});
+
+ // Regression guard for LOBE-12379: the BM25 scans were split into an inner
+ // single-table subquery (so ParadeDB can pick its TopN custom scan) with the
+ // joins and β€” in personal mode β€” the `workspace_id IS NULL` check moved above
+ // it. These tests pin the two things that split could break: rows leaking
+ // across the personal/workspace boundary, and enrichment lost with the joins.
+ describe('search - workspace scoping', () => {
+ const workspaceId = 'search-test-workspace';
+ let workspaceAgentId: string;
+ let personalAgentId: string;
+
+ beforeEach(async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Search Test Workspace',
+ primaryOwnerId: userId,
+ slug: 'search-test-workspace',
+ });
+
+ const insertedAgents = await serverDB
+ .insert(agents)
+ .values([
+ { title: 'Kubernetes Personal Agent', userId, workspaceId: null },
+ { title: 'Kubernetes Workspace Agent', userId, workspaceId },
+ ])
+ .returning({ id: agents.id, workspaceId: agents.workspaceId });
+
+ personalAgentId = insertedAgents.find((a) => !a.workspaceId)!.id;
+ workspaceAgentId = insertedAgents.find((a) => a.workspaceId)!.id;
+
+ await serverDB.insert(topics).values([
+ { agentId: personalAgentId, title: 'Kubernetes personal topic', userId, workspaceId: null },
+ { agentId: workspaceAgentId, title: 'Kubernetes workspace topic', userId, workspaceId },
+ ]);
+
+ await serverDB.insert(messages).values([
+ {
+ agentId: personalAgentId,
+ content: 'Kubernetes personal message',
+ role: 'user',
+ userId,
+ workspaceId: null,
+ },
+ {
+ agentId: workspaceAgentId,
+ content: 'Kubernetes workspace message',
+ role: 'user',
+ userId,
+ workspaceId,
+ },
+ ]);
+
+ await serverDB.insert(files).values([
+ {
+ fileType: 'text/plain',
+ name: 'kubernetes-personal.txt',
+ size: 10,
+ url: 'file://kubernetes-personal.txt',
+ userId,
+ workspaceId: null,
+ },
+ {
+ fileType: 'text/plain',
+ name: 'kubernetes-workspace.txt',
+ size: 10,
+ url: 'file://kubernetes-workspace.txt',
+ userId,
+ workspaceId,
+ },
+ ]);
+
+ await serverDB.insert(documents).values([
+ {
+ content: 'Kubernetes personal page body',
+ fileType: 'custom/document',
+ filename: 'kubernetes-personal-page',
+ source: 'internal://ws-page-1',
+ sourceType: 'file',
+ title: 'Kubernetes personal page',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ workspaceId: null,
+ },
+ {
+ content: 'Kubernetes workspace page body',
+ fileType: 'custom/document',
+ filename: 'kubernetes-workspace-page',
+ source: 'internal://ws-page-2',
+ sourceType: 'file',
+ title: 'Kubernetes workspace page',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ workspaceId,
+ },
+ {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ filename: 'kubernetes-personal-folder',
+ source: 'internal://ws-folder-1',
+ sourceType: 'file',
+ title: 'Kubernetes personal folder',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ workspaceId: null,
+ },
+ {
+ fileType: DOCUMENT_FOLDER_TYPE,
+ filename: 'kubernetes-workspace-folder',
+ source: 'internal://ws-folder-2',
+ sourceType: 'file',
+ title: 'Kubernetes workspace folder',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ workspaceId,
+ },
+ ]);
+
+ await serverDB.insert(chatGroups).values([
+ { title: 'Kubernetes personal group', userId, workspaceId: null },
+ { title: 'Kubernetes workspace group', userId, workspaceId },
+ ]);
+
+ await serverDB.insert(knowledgeBases).values([
+ { name: 'Kubernetes personal base', userId, workspaceId: null },
+ { name: 'Kubernetes workspace base', userId, workspaceId },
+ ]);
+ });
+
+ /**
+ * Every fixture titles itself after the scope it belongs to, so asserting
+ * that each hit *is* from the expected scope catches a leak whatever its
+ * title says β€” stricter than asserting the other scope's word is absent,
+ * which a differently-worded row could slip past. Case is normalised
+ * because the fixtures are not consistently cased.
+ */
+ const expectEveryHitScopedTo = (results: SearchResult[], scope: 'personal' | 'workspace') => {
+ expect(results.length).toBeGreaterThan(0);
+
+ const foreign = results.filter((r) => !r.title.toLowerCase().includes(scope));
+ expect(foreign.map((r) => `${r.type}: ${r.title}`)).toEqual([]);
+
+ // every rewritten search method is represented
+ expect(new Set(results.map((r) => r.type))).toEqual(new Set(REWRITTEN_RESULT_TYPES));
+ };
+
+ it('should never surface workspace-scoped rows in personal mode', async () => {
+ const results = await new SearchRepo(serverDB, userId).search({ query: 'Kubernetes' });
+
+ expectEveryHitScopedTo(results, 'personal');
+ });
+
+ it('should never surface personal rows in workspace mode', async () => {
+ const results = await new SearchRepo(serverDB, userId, workspaceId).search({
+ query: 'Kubernetes',
+ });
+
+ expectEveryHitScopedTo(results, 'workspace');
+ });
+
+ it('should keep joined agent metadata on topics and messages after the scan split', async () => {
+ const results = await new SearchRepo(serverDB, userId).search({ query: 'Kubernetes' });
+
+ const topic = results.find((r) => r.type === 'topic');
+ expect(topic).toBeDefined();
+ if (topic?.type === 'topic') {
+ expect(topic.agentId).toBe(personalAgentId);
+ expect(topic.agent?.title).toBe('Kubernetes Personal Agent');
+ }
+
+ const message = results.find((r) => r.type === 'message');
+ expect(message).toBeDefined();
+ if (message?.type === 'message') {
+ expect(message.agentId).toBe(personalAgentId);
+ // messages render the owning agent's title as their subtitle
+ expect(message.description).toBe('Kubernetes Personal Agent');
+ }
+ });
+
+ it('should keep knowledgeBaseId on files after the scan split', async () => {
+ const [file] = await serverDB
+ .select({ id: files.id })
+ .from(files)
+ .where(eq(files.name, 'kubernetes-personal.txt'));
+ const [base] = await serverDB
+ .select({ id: knowledgeBases.id })
+ .from(knowledgeBases)
+ .where(eq(knowledgeBases.name, 'Kubernetes personal base'));
+
+ await serverDB
+ .insert(knowledgeBaseFiles)
+ .values({ fileId: file.id, knowledgeBaseId: base.id, userId });
+
+ const results = await new SearchRepo(serverDB, userId).search({
+ query: 'kubernetes',
+ type: 'file',
+ });
+
+ const hit = results.find((r) => r.type === 'file' && r.id === file.id);
+ expect(hit).toBeDefined();
+ if (hit?.type === 'file') expect(hit.knowledgeBaseId).toBe(base.id);
+ });
+ });
+ // The workspace-scoping tests above pin *results*, and this change is
+ // deliberately result-neutral β€” they pass against the pre-fix implementation
+ // too. What actually fixes LOBE-12379 is the *shape* of the emitted SQL, so
+ // it needs its own guard: ParadeDB only picks `TopNScanExecState` when the
+ // scan node itself carries the whole `ORDER BY paradedb.score() LIMIT n`.
+ //
+ // Asserting the plan directly is not an option in CI: the container runs a
+ // newer pg_search than production, and its `heap_filter` keeps TopN even with
+ // a non-indexed qual β€” the exact regression would be invisible. So we assert
+ // the structural invariant that makes TopN reachable instead, which fails on
+ // the pre-fix single-level query regardless of engine version.
+ describe('search - BM25 scan shape', () => {
+ let loggingPool: NodePool | undefined;
+
+ afterAll(async () => {
+ await loggingPool?.end();
+ });
+
+ /** Runs a search against the test DB and returns every BM25 statement it emitted. */
+ const captureScanSql = async (workspaceId?: string): Promise<string[]> => {
+ const captured: string[] = [];
+ loggingPool ??= new NodePool({ connectionString: process.env.DATABASE_TEST_URL });
+ const db = nodeDrizzle(loggingPool, {
+ logger: { logQuery: (query: string) => captured.push(query) },
+ schema,
+ });
+
+ await new SearchRepo(db as unknown as LobeChatDatabase, userId, workspaceId).search({
+ query: 'kubernetes',
+ });
+
+ return captured.filter((query) => query.includes('@@@'));
+ };
+
+ /** Body of the first parenthesised subquery, i.e. the isolated BM25 scan. */
+ const innerScanOf = (query: string): string | undefined => {
+ const open = query.indexOf('from (');
+ if (open === -1) return undefined;
+
+ const start = open + 'from ('.length;
+ let depth = 1;
+ for (let i = start; i < query.length; i++) {
+ if (query[i] === '(') depth++;
+ else if (query[i] === ')' && --depth === 0) return query.slice(start, i);
+ }
+ return undefined;
+ };
+
+ /** Locates one method's statement and returns its isolated scan, failing loudly if absent. */
+ const scanOf = (statements: string[], alias: string): string => {
+ const statement = statements.find((query) => query.includes(`"${alias}"`));
+ expect(statement, `no statement produced the ${alias} subquery`).toBeDefined();
+
+ const scan = innerScanOf(statement!);
+ expect(scan, `${alias}: BM25 scan is not isolated in a subquery`).toBeDefined();
+
+ return scan!;
+ };
+
+ const whereClauseOf = (scan: string): string =>
+ scan.slice(scan.indexOf(' where '), scan.indexOf(' order by '));
+
+ it('gives every rewritten method a join-free single-table BM25 scan', async () => {
+ const statements = await captureScanSql();
+
+ // memories is the one BM25 search that was intentionally left unsplit
+ expect(statements).toHaveLength(SCAN_ALIASES.length + 1);
+
+ for (const alias of SCAN_ALIASES) {
+ const scan = scanOf(statements, alias);
+
+ // the scan node owns the whole ranking clause …
+ expect(scan).toContain('@@@');
+ expect(scan).toContain('order by paradedb.score');
+ expect(scan).toContain('limit');
+
+ // … and nothing sits between it and that clause
+ expect(scan, `${alias}: a join moved back inside the BM25 scan`).not.toContain(' join ');
+ }
+ });
+
+ it('keeps the non-indexed workspace filter above the scan in personal mode', async () => {
+ const statements = await captureScanSql();
+
+ for (const alias of SCAN_ALIASES) {
+ const where = whereClauseOf(scanOf(statements, alias));
+
+ // `workspace_id` is not a BM25 field, so a qual on it inside the scan
+ // is what costs TopN. It is still selected as a column for the outer
+ // filter β€” only the scan's predicate has to stay clear of it.
+ expect(where, `${alias}: workspace qual moved back into the BM25 scan`).not.toContain(
+ 'workspace_id',
+ );
+ expect(where).toContain('user_id');
+
+ // the filter must survive somewhere, or scoping would silently break
+ const statement = statements.find((query) => query.includes(`"${alias}"`))!;
+ expect(statement).toContain(`"${alias}"."workspace_id" is null`);
+ }
+ });
+
+ it('keeps the ownership predicate exact and inline in workspace mode', async () => {
+ const statements = await captureScanSql('search-test-workspace');
+
+ for (const alias of SCAN_ALIASES) {
+ const where = whereClauseOf(scanOf(statements, alias));
+
+ // Workspace mode has no pushdown-able owner column, so over-fetching
+ // would silently drop rows. It keeps the exact predicate instead and
+ // stays on the slower plan until the column is indexed.
+ expect(where, `${alias}: workspace mode must not lift its own filter`).toContain(
+ 'workspace_id',
+ );
+ }
+ });
+ });
});
diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.ts
index 8b1ca99842b..351862a06d3 100644
--- a/packages/database/src/repositories/search/index.ts
+++ b/packages/database/src/repositories/search/index.ts
@@ -1,4 +1,5 @@
-import { and, eq, inArray, ne, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNull, ne, type SQL, sql, type SQLWrapper } from 'drizzle-orm';
+import type { AnyPgColumn } from 'drizzle-orm/pg-core';
import {
agents,
@@ -197,6 +198,66 @@ export interface SearchOptions {
*/
const RECENCY_CANDIDATE_MULTIPLIER = 4;
+/**
+ * Every query here is shaped as "inner single-table BM25 scan β†’ outer enrichment",
+ * because ParadeDB only picks its TopN custom scan (`TopNScanExecState`, which
+ * visits a handful of heap rows) when the scan node itself carries the whole
+ * `ORDER BY paradedb.score() LIMIT n`. Two things break that:
+ *
+ * 1. A qual over a column that is not in the BM25 index β€” `workspace_id` is the
+ * one that matters here. The plan degrades to a plain index scan that scores
+ * and sorts the *entire* match set β€” on an account with a long message
+ * history that turns a sub-second query into a multi-minute one, fetching
+ * tens of thousands of heap rows instead of 10.
+ * 2. A JOIN sitting between the scan and the `ORDER BY … LIMIT` β€” that alone
+ * downgrades messages/topics/files to `NormalScanExecState` even without any
+ * workspace qual.
+ *
+ * So joins always live outside the scan, and the ownership predicate is split by
+ * `liftsWorkspaceFilter` below.
+ *
+ * Known remaining gap: `agent_id` is not a BM25 field either, so the
+ * agent-scoped variants of `searchMessages` / `searchTopics` (the command menu
+ * passes the active agent) keep a non-indexed qual inside the scan and do not
+ * reach TopN. It is kept inline on purpose β€” `agent_id` is far more selective
+ * than the ownership predicate, so lifting it above the scan would drop most of
+ * the requested rows rather than merely risk a short result set. The fix is to
+ * index the column; tracked with the other missing fast fields in LOBE-12381.
+ *
+ * @see https://linear.app/lobehub/issue/LOBE-12379
+ */
+const WORKSPACE_FILTER_CANDIDATE_MULTIPLIER = 5;
+
+/**
+ * Floor for the personal-mode candidate pool. Rows dropped by the lifted
+ * `workspace_id IS NULL` check eat into the per-type limit, so an account with
+ * many workspace rows could otherwise come up short β€” with a pool of 60 an
+ * adversarial mix (5k high-scoring workspace rows vs 20 low-scoring personal
+ * ones) returned 0 of 12 rows.
+ *
+ * A generous pool is what makes that a non-issue, and it is measurably free:
+ * once the scan is TopN, the pool size barely registers (same dataset, full
+ * payload: 60 rows β†’ 0.53s, 1000 β†’ 0.46s, 2000 β†’ 0.46s). The tantivy scan
+ * dominates; the extra heap fetches do not.
+ */
+const WORKSPACE_FILTER_MIN_CANDIDATES = 500;
+
+/**
+ * Flip to `true` once every BM25 index used by this repo carries `workspace_id`
+ * as a fast keyword field (LOBE-12381). pg_search then pushes `workspace_id IS
+ * NULL` down as `must_not: exists(workspace_id)` and `workspace_id = ?` as a
+ * `term`, so the ownership predicate can stay inline and personal search becomes
+ * exact again (no candidate over-fetch, no dropped rows) while workspace-mode
+ * search gets TopN for free.
+ */
+const WORKSPACE_ID_IN_BM25_INDEX = false;
+
+interface WorkspaceScopedColumns {
+ userId: AnyPgColumn;
+ visibility?: AnyPgColumn;
+ workspaceId: AnyPgColumn;
+}
+
/**
* Search Repository - provides unified search across Agents, Topics, and Files
*/
@@ -215,6 +276,46 @@ export class SearchRepo {
return { userId: this.userId, workspaceId: this.workspaceId };
}
+ /**
+ * Whether the `workspace_id IS NULL` half of the personal-mode ownership
+ * predicate has to be evaluated above the BM25 scan.
+ *
+ * Only personal mode gets this treatment: it still keeps `user_id = ?` inside
+ * the scan (a fast field, so ParadeDB pushes it down), which bounds the
+ * candidate pool to the caller's own rows and makes over-fetching a sound
+ * approximation. Workspace mode has no such pushdown-able owner column β€” its
+ * rows are a tiny slice of a global TopN β€” so lifting the filter there would
+ * silently return nothing. It keeps the exact inline predicate and stays on
+ * the slow plan until LOBE-12381 lands.
+ */
+ private get liftsWorkspaceFilter() {
+ return !WORKSPACE_ID_IN_BM25_INDEX && !this.workspaceId;
+ }
+
+ /** Ownership predicate that is safe to keep inside the BM25 scan. */
+ private scanScopeWhere(cols: WorkspaceScopedColumns): SQL {
+ if (!this.liftsWorkspaceFilter) return buildWorkspaceWhere(this.scope, cols);
+
+ return eq(cols.userId, this.userId) as SQL;
+ }
+
+ /** Remainder of the ownership predicate, applied above the BM25 scan. */
+ private liftedScopeWhere(workspaceIdColumn: SQLWrapper): SQL | undefined {
+ return this.liftsWorkspaceFilter ? (isNull(workspaceIdColumn) as SQL) : undefined;
+ }
+
+ /**
+ * Candidate pool for the inner scan. When the workspace filter is lifted, rows
+ * dropped above the scan would otherwise shrink the result set, so over-fetch.
+ * Personal search stays exact unless more than `WORKSPACE_FILTER_MIN_CANDIDATES`
+ * of the account's workspace rows outscore its personal matches.
+ */
+ private scanCandidateLimit(limit: number) {
+ if (!this.liftsWorkspaceFilter) return limit;
+
+ return Math.max(limit * WORKSPACE_FILTER_CANDIDATE_MULTIPLIER, WORKSPACE_FILTER_MIN_CANDIDATES);
+ }
+
/**
* Search across agents, topics, files, and pages
*/
@@ -398,27 +499,47 @@ export class SearchRepo {
private async searchAgents(query: string, limit: number): Promise<AgentSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const hits = this.db
.select({
avatar: agents.avatar,
backgroundColor: agents.backgroundColor,
createdAt: agents.createdAt,
description: agents.description,
id: agents.id,
- score: sql<number>`paradedb.score(${agents.id})`,
+ score: sql<number>`paradedb.score(${agents.id})`.as('score'),
slug: agents.slug,
tags: agents.tags,
title: agents.title,
updatedAt: agents.updatedAt,
+ workspaceId: agents.workspaceId,
})
.from(agents)
.where(
and(
- buildWorkspaceWhere(this.scope, agents),
+ this.scanScopeWhere(agents),
sql`(${agents.title} @@@ ${bm25Query} OR ${agents.description} @@@ ${bm25Query} OR ${agents.slug} @@@ ${bm25Query} OR ${agents.tags} @@@ ${bm25Query} OR ${agents.systemRole} @@@ ${bm25Query})`,
),
)
.orderBy(sql`paradedb.score(${agents.id}) DESC`)
+ .limit(this.scanCandidateLimit(limit))
+ .as('agent_hits');
+
+ const rows = await this.db
+ .select({
+ avatar: hits.avatar,
+ backgroundColor: hits.backgroundColor,
+ createdAt: hits.createdAt,
+ description: hits.description,
+ id: hits.id,
+ score: hits.score,
+ slug: hits.slug,
+ tags: hits.tags,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
.limit(limit);
return this.mapScoresToRelevance(rows).map((row) => {
@@ -453,40 +574,64 @@ export class SearchRepo {
): Promise<TopicSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
+
+ const hits = this.db
.select({
- // agents.id is selected as a sentinel: non-null only when the JOIN
- // matched an agent owned by this user. Topics carrying an agentId
- // that points to another user's agent (possible via migrated/crafted
- // data) yield null here, so the renderer falls back to the
- // agent-less subtitle and never surfaces foreign metadata.
- agentAvatar: agents.avatar,
- agentBackgroundColor: agents.backgroundColor,
agentId: topics.agentId,
- agentMatchedId: agents.id,
- agentSlug: agents.slug,
- agentTitle: agents.title,
content: topics.content,
createdAt: topics.createdAt,
favorite: topics.favorite,
groupId: topics.groupId,
id: topics.id,
- score: sql<number>`paradedb.score(${topics.id})`,
+ score: sql<number>`paradedb.score(${topics.id})`.as('score'),
sessionId: topics.sessionId,
title: topics.title,
updatedAt: topics.updatedAt,
+ workspaceId: topics.workspaceId,
})
.from(topics)
- .leftJoin(agents, and(eq(topics.agentId, agents.id), buildWorkspaceWhere(this.scope, agents)))
.where(
and(
- buildWorkspaceWhere(this.scope, topics),
+ this.scanScopeWhere(topics),
+ // Not a BM25 field β€” costs TopN on the agent-scoped path. See the
+ // note on the scan-shape invariant above.
agentId ? eq(topics.agentId, agentId) : undefined,
sql`(${topics.title} @@@ ${bm25Query} OR ${topics.content} @@@ ${bm25Query} OR ${topics.description} @@@ ${bm25Query})`,
),
)
.orderBy(sql`paradedb.score(${topics.id}) DESC`)
- .limit(limit * RECENCY_CANDIDATE_MULTIPLIER);
+ .limit(this.scanCandidateLimit(candidateLimit))
+ .as('topic_hits');
+
+ const rows = await this.db
+ .select({
+ // agents.id is selected as a sentinel: non-null only when the JOIN
+ // matched an agent owned by this user. Topics carrying an agentId
+ // that points to another user's agent (possible via migrated/crafted
+ // data) yield null here, so the renderer falls back to the
+ // agent-less subtitle and never surfaces foreign metadata.
+ agentAvatar: agents.avatar,
+ agentBackgroundColor: agents.backgroundColor,
+ agentId: hits.agentId,
+ agentMatchedId: agents.id,
+ agentSlug: agents.slug,
+ agentTitle: agents.title,
+ content: hits.content,
+ createdAt: hits.createdAt,
+ favorite: hits.favorite,
+ groupId: hits.groupId,
+ id: hits.id,
+ score: hits.score,
+ sessionId: hits.sessionId,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .leftJoin(agents, and(eq(hits.agentId, agents.id), buildWorkspaceWhere(this.scope, agents)))
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
+ .limit(candidateLimit);
return this.mapScoresToRelevance(rows)
.map((row) => ({
@@ -528,33 +673,57 @@ export class SearchRepo {
): Promise<MessageSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;
+
+ const hits = this.db
.select({
agentId: messages.agentId,
- agentSlug: agents.slug,
- agentTitle: agents.title,
content: messages.content,
createdAt: messages.createdAt,
groupId: messages.groupId,
id: messages.id,
model: messages.model,
role: messages.role,
- score: sql<number>`paradedb.score(${messages.id})`,
+ score: sql<number>`paradedb.score(${messages.id})`.as('score'),
topicId: messages.topicId,
updatedAt: messages.updatedAt,
+ workspaceId: messages.workspaceId,
})
.from(messages)
- .leftJoin(agents, eq(messages.agentId, agents.id))
.where(
and(
- buildWorkspaceWhere(this.scope, messages),
+ this.scanScopeWhere(messages),
ne(messages.role, 'tool'),
+ // Not a BM25 field β€” costs TopN on the agent-scoped path. See the
+ // note on the scan-shape invariant above.
agentId ? eq(messages.agentId, agentId) : undefined,
sql`${messages.content} @@@ ${bm25Query}`,
),
)
.orderBy(sql`paradedb.score(${messages.id}) DESC`)
- .limit(limit * RECENCY_CANDIDATE_MULTIPLIER);
+ .limit(this.scanCandidateLimit(candidateLimit))
+ .as('message_hits');
+
+ const rows = await this.db
+ .select({
+ agentId: hits.agentId,
+ agentSlug: agents.slug,
+ agentTitle: agents.title,
+ content: hits.content,
+ createdAt: hits.createdAt,
+ groupId: hits.groupId,
+ id: hits.id,
+ model: hits.model,
+ role: hits.role,
+ score: hits.score,
+ topicId: hits.topicId,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .leftJoin(agents, eq(hits.agentId, agents.id))
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
+ .limit(candidateLimit);
return this.mapScoresToRelevance(rows)
.map((row) => ({
@@ -587,30 +756,48 @@ export class SearchRepo {
private async searchFiles(query: string, limit: number): Promise<FileSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const hits = this.db
.select({
- content: documents.content,
createdAt: files.createdAt,
fileType: files.fileType,
id: files.id,
- knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
name: files.name,
- score: sql<number>`paradedb.score(${files.id})`,
+ score: sql<number>`paradedb.score(${files.id})`.as('score'),
size: files.size,
updatedAt: files.updatedAt,
url: files.url,
+ workspaceId: files.workspaceId,
})
.from(files)
- .leftJoin(documents, eq(files.id, documents.fileId))
- .leftJoin(knowledgeBaseFiles, eq(files.id, knowledgeBaseFiles.fileId))
.where(
and(
- buildWorkspaceWhere(this.scope, files),
+ this.scanScopeWhere(files),
ne(files.fileType, 'custom/document'),
sql`${files.name} @@@ ${bm25Query}`,
),
)
.orderBy(sql`paradedb.score(${files.id}) DESC`)
+ .limit(this.scanCandidateLimit(limit))
+ .as('file_hits');
+
+ const rows = await this.db
+ .select({
+ content: documents.content,
+ createdAt: hits.createdAt,
+ fileType: hits.fileType,
+ id: hits.id,
+ knowledgeBaseId: knowledgeBaseFiles.knowledgeBaseId,
+ name: hits.name,
+ score: hits.score,
+ size: hits.size,
+ updatedAt: hits.updatedAt,
+ url: hits.url,
+ })
+ .from(hits)
+ .leftJoin(documents, eq(hits.id, documents.fileId))
+ .leftJoin(knowledgeBaseFiles, eq(hits.id, knowledgeBaseFiles.fileId))
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
.limit(limit);
return this.mapScoresToRelevance(rows).map((row) => ({
@@ -635,27 +822,46 @@ export class SearchRepo {
private async searchFolders(query: string, limit: number): Promise<FolderSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const hits = this.db
.select({
createdAt: documents.createdAt,
description: documents.description,
filename: documents.filename,
id: documents.id,
knowledgeBaseId: documents.knowledgeBaseId,
- score: sql<number>`paradedb.score(${documents.id})`,
+ score: sql<number>`paradedb.score(${documents.id})`.as('score'),
slug: documents.slug,
title: documents.title,
updatedAt: documents.updatedAt,
+ workspaceId: documents.workspaceId,
})
.from(documents)
.where(
and(
- buildWorkspaceWhere(this.scope, documents),
+ this.scanScopeWhere(documents),
eq(documents.fileType, DOCUMENT_FOLDER_TYPE),
sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.description} @@@ ${bm25Query})`,
),
)
.orderBy(sql`paradedb.score(${documents.id}) DESC`)
+ .limit(this.scanCandidateLimit(limit))
+ .as('folder_hits');
+
+ const rows = await this.db
+ .select({
+ createdAt: hits.createdAt,
+ description: hits.description,
+ filename: hits.filename,
+ id: hits.id,
+ knowledgeBaseId: hits.knowledgeBaseId,
+ score: hits.score,
+ slug: hits.slug,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
.limit(limit);
return this.mapScoresToRelevance(rows).map((row) => {
@@ -680,24 +886,40 @@ export class SearchRepo {
private async searchPages(query: string, limit: number): Promise<PageSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const hits = this.db
.select({
createdAt: documents.createdAt,
filename: documents.filename,
id: documents.id,
- score: sql<number>`paradedb.score(${documents.id})`,
+ score: sql<number>`paradedb.score(${documents.id})`.as('score'),
title: documents.title,
updatedAt: documents.updatedAt,
+ workspaceId: documents.workspaceId,
})
.from(documents)
.where(
and(
- buildWorkspaceWhere(this.scope, documents),
+ this.scanScopeWhere(documents),
eq(documents.fileType, 'custom/document'),
sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`,
),
)
.orderBy(sql`paradedb.score(${documents.id}) DESC`)
+ .limit(this.scanCandidateLimit(limit))
+ .as('page_hits');
+
+ const rows = await this.db
+ .select({
+ createdAt: hits.createdAt,
+ filename: hits.filename,
+ id: hits.id,
+ score: hits.score,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
.limit(limit);
return this.mapScoresToRelevance(rows).map((row) => {
@@ -728,6 +950,12 @@ export class SearchRepo {
* spanning bm25 and non-bm25 predicates ("Unsupported query shape").
*
* Folder rows (DOCUMENT_FOLDER_TYPE) are excluded β€” they carry no content.
+ *
+ * Unlike the command-palette searches above, this one is deliberately left on
+ * the plain index-scan plan: `knowledge_base_id` is not in the BM25 index
+ * either, so isolating the scan would not buy TopN. The KB filter does bound
+ * the match set to one knowledge base (via its btree index), which keeps it
+ * workable until LOBE-12381 adds the missing fast fields.
*/
async searchKnowledgeBaseDocuments(
query: string,
@@ -817,6 +1045,10 @@ export class SearchRepo {
/**
* Search memories by title, summary, details (BM25)
+ *
+ * Memories are user-scoped only (no workspace column) and this query joins
+ * nothing, so `user_id` is pushed into the tantivy query as-is and the scan
+ * already runs as TopN β€” no subquery isolation needed.
*/
private async searchMemories(query: string, limit: number): Promise<MemorySearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
@@ -859,25 +1091,43 @@ export class SearchRepo {
private async searchChatGroups(query: string, limit: number): Promise<ChatGroupSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const hits = this.db
.select({
avatar: chatGroups.avatar,
backgroundColor: chatGroups.backgroundColor,
createdAt: chatGroups.createdAt,
description: chatGroups.description,
id: chatGroups.id,
- score: sql<number>`paradedb.score(${chatGroups.id})`,
+ score: sql<number>`paradedb.score(${chatGroups.id})`.as('score'),
title: chatGroups.title,
updatedAt: chatGroups.updatedAt,
+ workspaceId: chatGroups.workspaceId,
})
.from(chatGroups)
.where(
and(
- buildWorkspaceWhere(this.scope, chatGroups),
+ this.scanScopeWhere(chatGroups),
sql`(${chatGroups.title} @@@ ${bm25Query} OR ${chatGroups.description} @@@ ${bm25Query})`,
),
)
.orderBy(sql`paradedb.score(${chatGroups.id}) DESC`)
+ .limit(this.scanCandidateLimit(limit))
+ .as('chat_group_hits');
+
+ const rows = await this.db
+ .select({
+ avatar: hits.avatar,
+ backgroundColor: hits.backgroundColor,
+ createdAt: hits.createdAt,
+ description: hits.description,
+ id: hits.id,
+ score: hits.score,
+ title: hits.title,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
.limit(limit);
return this.mapScoresToRelevance(rows).map((row) => ({
@@ -902,24 +1152,41 @@ export class SearchRepo {
): Promise<KnowledgeBaseSearchResult[]> {
const bm25Query = sanitizeBm25Query(query);
- const rows = await this.db
+ const hits = this.db
.select({
avatar: knowledgeBases.avatar,
createdAt: knowledgeBases.createdAt,
description: knowledgeBases.description,
id: knowledgeBases.id,
name: knowledgeBases.name,
- score: sql<number>`paradedb.score(${knowledgeBases.id})`,
+ score: sql<number>`paradedb.score(${knowledgeBases.id})`.as('score'),
updatedAt: knowledgeBases.updatedAt,
+ workspaceId: knowledgeBases.workspaceId,
})
.from(knowledgeBases)
.where(
and(
- buildWorkspaceWhere(this.scope, knowledgeBases),
+ this.scanScopeWhere(knowledgeBases),
sql`(${knowledgeBases.name} @@@ ${bm25Query} OR ${knowledgeBases.description} @@@ ${bm25Query})`,
),
)
.orderBy(sql`paradedb.score(${knowledgeBases.id}) DESC`)
+ .limit(this.scanCandidateLimit(limit))
+ .as('knowledge_base_hits');
+
+ const rows = await this.db
+ .select({
+ avatar: hits.avatar,
+ createdAt: hits.createdAt,
+ description: hits.description,
+ id: hits.id,
+ name: hits.name,
+ score: hits.score,
+ updatedAt: hits.updatedAt,
+ })
+ .from(hits)
+ .where(this.liftedScopeWhere(hits.workspaceId))
+ .orderBy(desc(hits.score))
.limit(limit);
return this.mapScoresToRelevance(rows).map((row) => ({