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(database): split OR in listMessagePluginsForOperation to restore topic index (#18457)

Arvin Xu1b128b8a525c
diff --git a/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts b/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
index 7bb3a22d0ea..64a0fa53861 100644
--- a/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.pluginsForOperation.test.ts
@@ -1,8 +1,11 @@
// @vitest-environment node
import { eq } from 'drizzle-orm';
+import { drizzle as nodeDrizzle } from 'drizzle-orm/node-postgres';
+import { drizzle as pgliteDrizzle } from 'drizzle-orm/pglite';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
+import * as schema from '../../../schemas';
import { messagePlugins, messages, threads, topics, users } from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
@@ -51,6 +54,51 @@ const seedToolCall = async (opts: {
});
};
+const isServerDB = process.env.TEST_SERVER_DB === '1';
+
+interface CapturedStatement {
+ params: unknown[];
+ sql: string;
+}
+
+/**
+ * Run `run` against a drizzle instance layered over the SAME underlying client as
+ * `serverDB` (so it sees the rows seeded through `serverDB`) but with a query
+ * logger attached, and return every SQL statement (with its bound params) it
+ * emitted. We re-`EXPLAIN` those exact statements to assert the *plan*, which is
+ * the only thing that reveals the degradation β€” row results are identical whether
+ * the predicates are OR-ed or split.
+ */
+const captureEmittedSql = async (
+ run: (db: LobeChatDatabase) => Promise<void>,
+): Promise<CapturedStatement[]> => {
+ const captured: CapturedStatement[] = [];
+ const logger = {
+ logQuery: (sql: string, params: unknown[]) => captured.push({ params, sql }),
+ };
+ const client = (serverDB as unknown as { $client: { waitReady?: unknown } }).$client;
+ const db = (
+ 'waitReady' in (client ?? {})
+ ? pgliteDrizzle({ client: client as any, logger, schema })
+ : nodeDrizzle(client as any, { logger, schema })
+ ) as unknown as LobeChatDatabase;
+ await run(db);
+ return captured;
+};
+
+/** Total rows the executor had to *examine* on the two base tables (output +
+ * filtered-out, times loops) β€” the signal a full-table scan leaks. */
+const rowsExaminedOnBaseTables = (node: any): number => {
+ let total = 0;
+ const rel = node?.['Relation Name'];
+ if (rel === 'messages' || rel === 'message_plugins') {
+ const loops = node['Actual Loops'] ?? 1;
+ total += ((node['Actual Rows'] ?? 0) + (node['Rows Removed by Filter'] ?? 0)) * loops;
+ }
+ for (const child of node?.Plans ?? []) total += rowsExaminedOnBaseTables(child);
+ return total;
+};
+
beforeEach(async () => {
await serverDB.delete(users).where(eq(users.id, userId));
await serverDB.delete(users).where(eq(users.id, otherUserId));
@@ -179,4 +227,102 @@ describe('MessageModel.listMessagePluginsForOperation', () => {
expect(asOther).toEqual([]);
});
+
+ // Query-plan regression β€” the accurate guard. It reproduces the actual
+ // degradation (a full scan of the user's whole plugin/message history) on a
+ // seeded skew and asserts the topic-scoped retrieval stays index-served.
+ //
+ // Gated to the server DB (real Postgres): PGlite's planner picks a *different*,
+ // already-fast plan for the OR predicate, so the regression is invisible there
+ // β€” a plan assertion on PGlite would be a false green. CI runs this suite
+ // against real Postgres via `vitest.config.server.mts` (TEST_SERVER_DB=1).
+ //
+ // Why the plan and not the SQL shape: the row results are identical for OR vs.
+ // split, and a "no OR() in the SQL" assertion breaks on innocent rewrites
+ // (UNION/CTE) that are equally fast. Rows-examined is what actually matters.
+ describe.skipIf(!isServerDB)('query-plan regression (real Postgres only)', () => {
+ const NOISE = 2000;
+
+ it('keeps the topic-scoped tool-call retrieval index-served instead of scanning the whole user history', async () => {
+ // Skew: NOISE plugin rows in a *different* topic (topic2) the query must
+ // never touch, plus a few in-window rows and one heterogeneous row far
+ // outside the window in the target topic (topic1).
+ const noiseMessages = Array.from({ length: NOISE }, (_, i) => ({
+ content: '',
+ createdAt: new Date(Date.UTC(2020, 0, 1) + i * 1000),
+ id: `noise-${i}`,
+ role: 'tool' as const,
+ topicId: 'topic2',
+ userId,
+ }));
+ await serverDB.insert(messages).values(noiseMessages);
+ await serverDB.insert(messagePlugins).values(
+ noiseMessages.map((m) => ({
+ apiName: 'writeFile',
+ id: m.id,
+ toolCallId: `tc-${m.id}`,
+ userId,
+ })),
+ );
+ await seedToolCall({ createdAt: T1, id: 'in-window', threadId: 'thread1', topicId: 'topic1' });
+ await seedToolCall({ createdAt: T2, id: 'in-window-2', threadId: 'thread1', topicId: 'topic1' });
+ await seedToolCall({
+ createdAt: new Date('2027-01-01T00:00:00.000Z'),
+ id: 'hetero',
+ metadata: { heterogeneousToolStateOperationId: 'op-1' },
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+
+ const pool = (
+ serverDB as unknown as {
+ $client: { query: (config: unknown) => Promise<{ rows: any[] }> };
+ }
+ ).$client;
+ await pool.query('ANALYZE messages');
+ await pool.query('ANALYZE message_plugins');
+
+ // Capture the exact statements the method issues, faithfully.
+ const statements = await captureEmittedSql(async (db) => {
+ const rows = await new MessageModel(db, userId).listMessagePluginsForOperation({
+ completedAt: T3,
+ operationId: 'op-1',
+ startedAt: T0,
+ threadId: 'thread1',
+ topicId: 'topic1',
+ });
+ // Correctness still holds across both branches under the skew.
+ expect(rows.map((r) => r.id).sort()).toEqual(['hetero', 'in-window', 'in-window-2']);
+ });
+
+ // Guard every plugin retrieval that constrains by `topic_id`. The
+ // heterogeneous-only branch carries no `topic_id`, so it is naturally
+ // exempt β€” it is knowingly an unindexed scan until the partial jsonb index
+ // lands (separate PR). Crucially, the OR regression *does* carry `topic_id`
+ // (alongside the metadata match), so it is caught here by its plan, not by
+ // any assumption about how the SQL is written.
+ const topicScopedPluginScans = statements.filter(
+ (s) =>
+ /"message_plugins"/i.test(s.sql) &&
+ /"messages"/i.test(s.sql) &&
+ /topic_id/i.test(s.sql),
+ );
+ expect(
+ topicScopedPluginScans.length,
+ 'no topic-scoped plugin retrieval was emitted β€” did the method stop querying by topic?',
+ ).toBeGreaterThan(0);
+
+ for (const statement of topicScopedPluginScans) {
+ const explained = await pool.query({
+ text: `EXPLAIN (ANALYZE, FORMAT JSON) ${statement.sql}`,
+ values: statement.params,
+ });
+ const examined = rowsExaminedOnBaseTables(explained.rows[0]['QUERY PLAN'][0].Plan);
+ expect(
+ examined,
+ `the topic-scoped plugin retrieval examined ${examined} rows β€” it scanned ~all of the user's ${NOISE}-row history instead of using the topic_id index. An unindexable predicate (e.g. an OR with the jsonb metadata match) was folded back into this query.`,
+ ).toBeLessThan(NOISE / 2);
+ }
+ });
+ });
});
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index a3dfd7b1ce7..626fc101511 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -2819,30 +2819,55 @@ export class MessageModel {
const heterogeneousMatch = sql`${messages.metadata}->>'heterogeneousToolStateOperationId' = ${params.operationId}`;
- const rows = await this.db
- .select({
- apiName: messagePlugins.apiName,
- arguments: messagePlugins.arguments,
- clientId: messagePlugins.clientId,
- // The tool message's text body. Heterogeneous CLI adapters (claude-code
- // Bash) persist the command's stdout here rather than in a structured
- // `state` field, and the completion-time github Work scan reads the gh
- // CLI's printed entity URL from it.
- content: messages.content,
- createdAt: messages.createdAt,
- error: messagePlugins.error,
- id: messagePlugins.id,
- identifier: messagePlugins.identifier,
- intervention: messagePlugins.intervention,
- state: messagePlugins.state,
- toolCallId: messagePlugins.toolCallId,
- type: messagePlugins.type,
- userId: messagePlugins.userId,
- })
- .from(messagePlugins)
- .innerJoin(messages, eq(messagePlugins.id, messages.id))
- .where(and(this.ownership(), this.pluginsOwnership(), or(withinWindow, heterogeneousMatch)))
- .orderBy(asc(messages.createdAt), asc(messages.id));
+ // Query the two conditions SEPARATELY instead of `OR`-ing them in one WHERE.
+ // A combined `... AND (withinWindow OR heterogeneousMatch)` is unindexable: the
+ // `metadata->>'heterogeneousToolStateOperationId'` branch has no index, so the
+ // planner abandons the `topic_id` index for the whole predicate and scans every
+ // plugin row the user owns (100k+ for heavy users), probing `messages` once per
+ // row β€” 25s+ per call in the worst case. Splitting lets each branch use its own
+ // index (topic-window range scan vs. the exact jsonb lookup). The branches can
+ // overlap (a heterogeneous row that also falls inside the window), so de-dup by
+ // message id before restoring the `createdAt asc, id asc` order the OR query
+ // produced in SQL.
+ const projection = {
+ apiName: messagePlugins.apiName,
+ arguments: messagePlugins.arguments,
+ clientId: messagePlugins.clientId,
+ // The tool message's text body. Heterogeneous CLI adapters (claude-code
+ // Bash) persist the command's stdout here rather than in a structured
+ // `state` field, and the completion-time github Work scan reads the gh
+ // CLI's printed entity URL from it.
+ content: messages.content,
+ createdAt: messages.createdAt,
+ error: messagePlugins.error,
+ id: messagePlugins.id,
+ identifier: messagePlugins.identifier,
+ intervention: messagePlugins.intervention,
+ state: messagePlugins.state,
+ toolCallId: messagePlugins.toolCallId,
+ type: messagePlugins.type,
+ userId: messagePlugins.userId,
+ };
+
+ const scan = (condition: SQL | undefined) =>
+ this.db
+ .select(projection)
+ .from(messagePlugins)
+ .innerJoin(messages, eq(messagePlugins.id, messages.id))
+ .where(and(this.ownership(), this.pluginsOwnership(), condition));
+
+ const [windowRows, heterogeneousRows] = await Promise.all([
+ scan(withinWindow),
+ scan(heterogeneousMatch),
+ ]);
+
+ const byId = new Map<string, (typeof windowRows)[number]>();
+ for (const row of windowRows) byId.set(row.id, row);
+ for (const row of heterogeneousRows) if (!byId.has(row.id)) byId.set(row.id, row);
+
+ const rows = [...byId.values()].sort(
+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id),
+ );
return rows.map((row) => ({
apiName: row.apiName ?? undefined,