π€― 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
β‘οΈ perf(hetero): read only the tool index columns on every event batch (#23142)
YuTengjing0e61691f9ecf
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/eventBranchesTestUtils.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/eventBranchesTestUtils.tsindex 2277feda50f..5c6a932c0ab 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/eventBranchesTestUtils.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/eventBranchesTestUtils.ts@@ -141,7 +141,7 @@ export const createHarness = (return match?.id;},),- listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),+ listToolCallIndexByTopic: vi.fn(async (_topicId: string) => []),updateMessagePlugin: vi.fn(async (id: string, patch: Record<string, unknown>) => {const existing = messages.get(id);if (existing) messages.set(id, { ...existing, plugin: { ...existing.plugin, ...patch } });diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.codexTurnProvenance.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.codexTurnProvenance.test.tsindex 48bbd05c67d..bb9b655dcd1 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.codexTurnProvenance.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.codexTurnProvenance.test.ts@@ -54,7 +54,7 @@ const createHarness = (params: {}),findById: vi.fn(async (id: string) => messages.get(id) ?? null),getLatestSpineMessageId: vi.fn(async () => undefined),- listMessagePluginsByTopic: vi.fn(async () => []),+ listToolCallIndexByTopic: vi.fn(async () => []),query: vi.fn(async () => [...messages.values()]),update: vi.fn(async (id: string, patch: Partial<FakeMessage>) => {const existing = messages.get(id);diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.tsindex c1a5f9beba9..ce4f714fcaa 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.coldReplicaChainAnchor.test.ts@@ -123,7 +123,7 @@ const createHarness = () => {return match?.id;},),- listMessagePluginsByTopic: vi.fn(async () =>+ listToolCallIndexByTopic: vi.fn(async () =>[...messages.values()].filter((m) => m.role === 'tool' && m.tool_call_id).map((m) => ({ id: m.id, toolCallId: m.tool_call_id! })),diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranches.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranches.test.tsindex d79401212fe..ce78d0e8664 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranches.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.eventBranches.test.ts@@ -313,7 +313,7 @@ describe('HeterogeneousPersistenceHandler β event branch coverage', () => {tool_call_id: 'todo-existing',topicId: h.topicId,});- h.messageModel.listMessagePluginsByTopic.mockResolvedValue([+ h.messageModel.listToolCallIndexByTopic.mockResolvedValue([{id: 'tool-existing',metadata: h.messages.get('tool-existing')?.metadata,diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.fixture.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.fixture.test.tsindex 8d6aba5e014..63a65aecfd2 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.fixture.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.fixture.test.ts@@ -195,7 +195,7 @@ const createHarness = () => {return match?.id;},),- listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),+ listToolCallIndexByTopic: vi.fn(async (_topicId: string) => []),};const threadModel = {diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.tsindex 240ff13f8af..01ab7be200b 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.interventionAck.test.ts@@ -50,7 +50,7 @@ describe('HeterogeneousPersistenceHandler β event branch coverage', () => {]);const toolRow = [...h.messages.values()].find((m) => m.tool_call_id === 'child-question')!;expect(toolRow.threadId).toBeTruthy();- h.messageModel.listMessagePluginsByTopic.mockImplementation(+ h.messageModel.listToolCallIndexByTopic.mockImplementation(async () =>[...h.messages.values()].filter((m) => m.role === 'tool')@@ -154,7 +154,7 @@ describe('HeterogeneousPersistenceHandler β event branch coverage', () => {intervention: { status: 'pending', operationId: 'other-op' },},});- h.messageModel.listMessagePluginsByTopic.mockImplementation(+ h.messageModel.listToolCallIndexByTopic.mockImplementation(async () =>[...h.messages.values()].filter((m) => m.role === 'tool')diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.mainTurnRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.mainTurnRehydration.test.tsindex 47771bd6002..5bf05e03748 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.mainTurnRehydration.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.mainTurnRehydration.test.ts@@ -138,7 +138,7 @@ const createHarness = () => {return match?.id;},),- listMessagePluginsByTopic: vi.fn(async () =>+ listToolCallIndexByTopic: vi.fn(async () =>[...messages.values()].filter((m) => m.role === 'tool' && m.tool_call_id).map((m) => ({ id: m.id, toolCallId: m.tool_call_id! })),diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.tsindex 0a9ef177026..4546fc24ffc 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.subagentRehydration.test.ts@@ -133,7 +133,7 @@ const createHarness = (params: {return match?.id;},),- listMessagePluginsByTopic: vi.fn(async (_topicId: string) => {+ listToolCallIndexByTopic: vi.fn(async (_topicId: string) => {// Mirror the real query: every persisted tool row's (toolCallId β id).return [...messages.values()].filter((m) => m.role === 'tool' && m.tool_call_id)diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.tsindex 5b27f1135ca..5c5513809b6 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/stateSync.ts@@ -262,7 +262,11 @@ export async function refreshToolMessageIndex(deps: HeterogeneousPersistenceHandlerDeps,state: OperationState,): Promise<void> {- const toolPlugins = await deps.messageModel.listMessagePluginsByTopic(state.topicId);+ // Runs once per event batch over the whole topic: read only the index+ // columns, not every tool's arguments and state.+ const toolPlugins = await deps.messageModel.listToolCallIndexByTopic(state.topicId, {+ interventionStateKey: HETEROGENEOUS_INTERVENTION_STATE_KEY,+ });for (const plugin of toolPlugins) {if (plugin.toolCallId) state.toolMsgIdByCallId.set(plugin.toolCallId, plugin.id);if (plugin.toolCallId && plugin.state && typeof plugin.state === 'object') {diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.tsindex 1114f2940dc..7854f87ea39 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/testUtils.ts@@ -142,7 +142,7 @@ export const createHarness = (params: {return match?.id;},),- listMessagePluginsByTopic: vi.fn(async (_topicId: string) => []),+ listToolCallIndexByTopic: vi.fn(async (_topicId: string) => []),};const threadModel = {diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.tsindex 6e80a5806eb..172d65f2df5 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/sessionResume.test.ts@@ -20,7 +20,7 @@ const createPersistenceHandler = (messageModel: {findById: vi.fn(async () => null),getLatestSpineMessageId: vi.fn(async () => null),- listMessagePluginsByTopic: vi.fn(async () => []),+ listToolCallIndexByTopic: vi.fn(async () => []),update: vi.fn(async () => ({ success: true })),} as any,threadModel: {} as any,diff --git a/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.tsindex 3ea32eb3520..6d08c9c4645 100644--- a/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts+++ b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts@@ -15,10 +15,12 @@ const otherUserId = 'plugin-lookup-other-user';const messageModel = new MessageModel(serverDB, userId);interface SeedArgs {+ arguments?: string;content?: string;createdAt?: Date;id: string;identifier?: string | null;+ intervention?: { status: 'pending' };metadata?: Record<string, unknown>;ownerId?: string;parentId?: string;@@ -59,8 +61,10 @@ const seedToolMessage = async (args: SeedArgs) => {await serverDB.insert(messagePlugins).values({apiName: args.id,+ arguments: args.arguments,id: args.id,identifier: args.identifier === undefined ? 'lobe-tool' : args.identifier,+ intervention: args.intervention,state: args.state,toolCallId: args.toolCallId === undefined ? `tc-${args.id}` : args.toolCallId,type: args.type === undefined ? undefined : args.type,@@ -233,6 +237,122 @@ describe('MessageModel.listMessagePluginsByTopic', () => {});});+describe('MessageModel.listToolCallIndexByTopic', () => {+ const interventionStateKey = 'heterogeneousIntervention';+ const pendingIntervention = { deadline: 1_700_000_000_000, transition: 'pending' };++ const seedIndexRows = async () => {+ await seedToolMessage({+ arguments: '{"question":"approve?"}',+ createdAt: new Date('2026-10-01T00:00:01Z'),+ id: 'plug-approval',+ intervention: { status: 'pending' },+ metadata: {+ heterogeneousToolStateOperationId: 'op-1',+ heterogeneousToolStateSeq: 3,+ operationId: 'op-1',+ usage: { totalTokens: 42 },+ },+ state: { [interventionStateKey]: pendingIntervention, todos: ['large payload'] },+ });+ await seedToolMessage({+ arguments: '{"command":"cat a-very-large-file"}',+ createdAt: new Date('2026-10-01T00:00:02Z'),+ id: 'plug-plain',+ metadata: { phase: 'second' },+ state: { todos: ['large payload'] },+ });+ };++ it('returns only the index columns, with arguments only for intervention rows', async () => {+ await seedIndexRows();++ const rows = await messageModel.listToolCallIndexByTopic('plugin-topic', {+ interventionStateKey,+ });++ expect(rows).toEqual([+ {+ apiName: 'plug-approval',+ arguments: '{"question":"approve?"}',+ id: 'plug-approval',+ identifier: 'lobe-tool',+ intervention: { status: 'pending' },+ metadata: {+ heterogeneousToolStateOperationId: 'op-1',+ heterogeneousToolStateSeq: 3,+ operationId: 'op-1',+ },+ state: { [interventionStateKey]: pendingIntervention },+ toolCallId: 'tc-plug-approval',+ },+ {+ apiName: 'plug-plain',+ id: 'plug-plain',+ identifier: 'lobe-tool',+ metadata: {},+ toolCallId: 'tc-plug-plain',+ },+ ]);+ });++ it('agrees with listMessagePluginsByTopic on every field the index reads', async () => {+ await seedIndexRows();++ const index = await messageModel.listToolCallIndexByTopic('plugin-topic', {+ interventionStateKey,+ });+ const full = await messageModel.listMessagePluginsByTopic('plugin-topic');++ expect(index.map((row) => row.id)).toEqual(full.map((row) => row.id));+ for (const [i, row] of full.entries()) {+ const stored = row.state?.[interventionStateKey];+ // `toEqual` treats an undefined field and a missing one alike.+ expect({+ apiName: index[i].apiName,+ identifier: index[i].identifier,+ intervention: index[i].intervention,+ metadata: index[i].metadata,+ toolCallId: index[i].toolCallId,+ }).toEqual({+ apiName: row.apiName,+ identifier: row.identifier,+ intervention: row.intervention,+ metadata: {+ heterogeneousToolStateOperationId: row.metadata?.heterogeneousToolStateOperationId,+ heterogeneousToolStateSeq: row.metadata?.heterogeneousToolStateSeq,+ operationId: row.metadata?.operationId,+ },+ toolCallId: row.toolCallId,+ });+ expect(index[i].state?.[interventionStateKey]).toEqual(stored);+ if (stored) expect(index[i].arguments).toBe(row.arguments);+ }+ });++ it('applies the topic and ownership scope of listMessagePluginsByTopic', async () => {+ await seedToolMessage({ id: 'plug-index-in-scope', topicId: 'plugin-topic' });+ await seedToolMessage({ id: 'plug-index-other-topic', topicId: 'plugin-topic-2' });+ await seedToolMessage({+ id: 'plug-index-other-message',+ ownerId: otherUserId,+ pluginOwnerId: userId,+ topicId: 'plugin-topic',+ });+ await seedToolMessage({+ id: 'plug-index-other-plugin',+ pluginOwnerId: otherUserId,+ topicId: 'plugin-topic',+ });++ const rows = await messageModel.listToolCallIndexByTopic('plugin-topic', {+ interventionStateKey,+ });++ expect(rows.map((row) => row.id)).toEqual(['plug-index-in-scope']);+ });+});+describe('MessageModel.listMessagePluginsByIds', () => {it('returns an empty list without querying when ids are empty', async () => {await expect(diff --git a/packages/database/src/models/__tests__/messages/message.publicApi.test.ts b/packages/database/src/models/__tests__/messages/message.publicApi.test.tsindex 4b6e55f7d9d..61ea4490b76 100644--- a/packages/database/src/models/__tests__/messages/message.publicApi.test.ts+++ b/packages/database/src/models/__tests__/messages/message.publicApi.test.ts@@ -69,6 +69,7 @@ const PUBLIC_INSTANCE_METHODS = ['listMessagePluginsByIds','listMessagePluginsByTopic','listMessagePluginsForOperation',+ 'listToolCallIndexByTopic','purgeMessages','query','queryAll',diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.tsindex c7d30c47b3b..ad0399cd223 100644--- a/packages/database/src/models/message/index.ts+++ b/packages/database/src/models/message/index.ts@@ -85,6 +85,7 @@ export class MessageModel {restoreHumanApproval: MessageApprovalRepo['restore'];findMessagePlugin: MessagePluginStore['findMessagePlugin'];listMessagePluginsByTopic: MessagePluginStore['listMessagePluginsByTopic'];+ listToolCallIndexByTopic: MessagePluginStore['listToolCallIndexByTopic'];findLatestPluginStateInTopic: MessagePluginStore['findLatestPluginStateInTopic'];listToolCallsInTopics: MessagePluginStore['listToolCallsInTopics'];listMessagePluginsForOperation: MessagePluginStore['listMessagePluginsForOperation'];@@ -204,6 +205,7 @@ export class MessageModel {this.restoreHumanApproval = approvals.restore;this.findMessagePlugin = plugins.findMessagePlugin;this.listMessagePluginsByTopic = plugins.listMessagePluginsByTopic;+ this.listToolCallIndexByTopic = plugins.listToolCallIndexByTopic;this.findLatestPluginStateInTopic = plugins.findLatestPluginStateInTopic;this.listToolCallsInTopics = plugins.listToolCallsInTopics;this.listMessagePluginsForOperation = plugins.listMessagePluginsForOperation;diff --git a/packages/database/src/models/message/plugin.ts b/packages/database/src/models/message/plugin.tsindex 2b2e4ff28c5..32fb0ef76d3 100644--- a/packages/database/src/models/message/plugin.ts+++ b/packages/database/src/models/message/plugin.ts@@ -17,6 +17,20 @@ export class HumanApprovalAlreadyResolvedError extends Error {}}+/** One row of `listToolCallIndexByTopic`. */+export interface ToolCallIndexItem extends Pick<+ MessagePluginItem,+ 'apiName' | 'arguments' | 'id' | 'identifier' | 'intervention' | 'toolCallId'+> {+ /** Only the operation and tool-state sequence keys of the tool message metadata. */+ metadata: Pick<+ MessageMetadata,+ 'heterogeneousToolStateOperationId' | 'heterogeneousToolStateSeq' | 'operationId'+ >;+ /** Only the requested intervention key of the plugin state. */+ state?: Record<string, unknown>;+}+export class MessagePluginStore extends MessageScope {private readonly lookups: MessageLookupQueries;@@ -164,6 +178,72 @@ export class MessagePluginStore extends MessageScope {}));};+ /**+ * A topic's tool-call index in the same first-seen order as+ * `listMessagePluginsByTopic`, without the payloads the index never reads.+ *+ * The heterogeneous persistence handler rebuilds its toolCallId β message id+ * map and pending-intervention state from this on every event batch, so it+ * runs once per batch over the whole topic. Full plugin rows there returned+ * every tool's arguments and state each time (β3.6 MB per call on busy+ * topics). This projection keeps only:+ * - `state`: just `interventionStateKey`, absent when the row has none;+ * - `arguments`: only on rows carrying that key, the only rows rebuilt into+ * intervention requests;+ * - `metadata`: just the operation and tool-state sequence keys.+ */+ listToolCallIndexByTopic = async (+ topicId: string,+ { interventionStateKey }: { interventionStateKey: string },+ ): Promise<ToolCallIndexItem[]> => {+ // `jsonb_exists` instead of `state -> key IS NOT NULL`: see the serverless+ // engine note in `spine.ts`.+ const hasInterventionState = sql`COALESCE(jsonb_exists(${messagePlugins.state}, ${interventionStateKey}::text), false)`;++ const rows = await this.db+ .select({+ apiName: messagePlugins.apiName,+ arguments: sql<+ string | null+ >`CASE WHEN ${hasInterventionState} THEN ${messagePlugins.arguments} END`,+ id: messagePlugins.id,+ identifier: messagePlugins.identifier,+ intervention: messagePlugins.intervention,+ interventionState: sql<unknown>`${messagePlugins.state} -> ${interventionStateKey}::text`,+ operationId: sql<unknown>`${messages.metadata} -> 'operationId'`,+ toolCallId: messagePlugins.toolCallId,+ toolStateOperationId: sql<unknown>`${messages.metadata} -> 'heterogeneousToolStateOperationId'`,+ toolStateSeq: sql<unknown>`${messages.metadata} -> 'heterogeneousToolStateSeq'`,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messagePlugins.id, messages.id))+ .where(and(eq(messages.topicId, topicId), this.ownership(), this.pluginsOwnership()))+ .orderBy(asc(messages.createdAt), asc(messages.id));++ return rows.map((row) => {+ const metadata: ToolCallIndexItem['metadata'] = {};+ if (typeof row.operationId === 'string') metadata.operationId = row.operationId;+ if (typeof row.toolStateOperationId === 'string')+ metadata.heterogeneousToolStateOperationId = row.toolStateOperationId;+ if (typeof row.toolStateSeq === 'number')+ metadata.heterogeneousToolStateSeq = row.toolStateSeq;++ return {+ apiName: row.apiName ?? undefined,+ arguments: row.arguments ?? undefined,+ id: row.id,+ identifier: row.identifier ?? undefined,+ intervention: row.intervention ?? undefined,+ metadata,+ state:+ row.interventionState === null || row.interventionState === undefined+ ? undefined+ : { [interventionStateKey]: row.interventionState },+ toolCallId: row.toolCallId ?? undefined,+ };+ });+ };+/*** The newest calls to one tool API across several topics, oldest first, with* the tool message's text β where a CLI adapter records the call's result.