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(agent-documents): skip unused document reads on later steps (#23169)

YuTengjing9072ebad6b13
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
index d41ea17bfe4..955f400dec4 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts
@@ -8,6 +8,7 @@ import {
agentDocumentChangesByMessage,
type AgentDocumentIndexSnapshot,
agentDocumentsFromSnapshot,
+ reusablePinnedAgentDocumentIndex,
} from '@lobechat/context-engine/agent-document';
import type { ContextFactProviders, ContextFactRequest } from '@lobechat/mecha';
import {
@@ -108,6 +109,15 @@ export const createServerContextFactProviders = ({
let pending = agentDocumentIndexes.get(agentId);
if (!pending) {
pending = (async () => {
+ // A later step of a run renders the index from the snapshot its first
+ // step pinned, so it needs no progressive document. Skip reading them:
+ // an agent can hold over 10k, and every step used to read them all.
+ const pinned = documentIndexTurn
+ ? reusablePinnedAgentDocumentIndex({
+ messages: documentIndexTurn.messages,
+ pinned: state.binding?.agentDocumentIndex,
+ })
+ : undefined;
const docs = toAgentContextDocuments(
await new AgentDocumentsService(
db,
@@ -115,8 +125,9 @@ export const createServerContextFactProviders = ({
workspaceId,
undefined,
documentAccessScope,
- ).getAgentContextDocuments(agentId),
+ ).getAgentContextDocuments(agentId, { excludeProgressive: !!pinned }),
);
+ if (pinned) return { docs, snapshot: pinned };
if (!documentIndexTurn) return { docs };
try {
const snapshot = await resolveServerAgentDocumentIndex({
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
index 1b1c9aad3e0..3666c1a09ff 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts
@@ -314,6 +314,16 @@ describe('createServerContextFactProviders', () => {
title: 'Report',
updatedAt: new Date(updatedAt),
});
+ const alwaysRow = {
+ content: 'Always follow the style guide.',
+ contentCharCount: 30,
+ documentId: 'doc-2',
+ filename: 'style.md',
+ id: 'agent-doc-2',
+ policyLoad: 'always',
+ title: 'Style',
+ updatedAt: new Date('2026-11-01T00:00:00.000Z'),
+ };
const turn = {
cacheTtlMs: 5 * 60 * 1000,
messages: [
@@ -370,6 +380,9 @@ describe('createServerContextFactProviders', () => {
],
});
expect(getAgentContextDocuments).toHaveBeenCalledTimes(1);
+ expect(getAgentContextDocuments).toHaveBeenCalledWith('agent-1', {
+ excludeProgressive: false,
+ });
expect(redisIndexGet).toHaveBeenCalledWith({
agentId: 'agent-1',
threadId: undefined,
@@ -380,21 +393,54 @@ describe('createServerContextFactProviders', () => {
});
it('renders later steps from the pinned snapshot without reading the stored one', async () => {
- getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-14T10:00:20.000Z')]);
+ // The database answers the narrowed read with the always-loaded documents only.
+ getAgentContextDocuments.mockResolvedValue([alwaysRow]);
const bindAgentDocumentIndex = vi.fn();
const providers = providersFor(
{ binding: { agentDocumentIndex: stored }, origin: { topicId: 'topic-1' } },
bindAgentDocumentIndex,
);
- const [doc] = (await providers.listAgentDocuments!('agent-1'))!;
+ const docs = (await providers.listAgentDocuments!('agent-1'))!;
- expect(doc).toMatchObject({ contentCharCount: 9400 });
+ expect(docs).toEqual([
+ expect.objectContaining({ content: 'Always follow the style guide.', id: 'agent-doc-2' }),
+ expect.objectContaining({ contentCharCount: 9400, id: 'agent-doc-1' }),
+ ]);
+ expect(getAgentContextDocuments).toHaveBeenCalledWith('agent-1', {
+ excludeProgressive: true,
+ });
expect(redisIndexGet).not.toHaveBeenCalled();
expect(redisIndexSet).not.toHaveBeenCalled();
expect(bindAgentDocumentIndex).not.toHaveBeenCalled();
});
+ it('reads every document again when a compression retires the pinned snapshot', async () => {
+ getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-14T10:00:20.000Z')]);
+ const bindAgentDocumentIndex = vi.fn();
+ const providers = createServerContextFactProviders({
+ ctx: { bindAgentDocumentIndex, serverDB: {}, userId: 'owner-1' } as never,
+ documentIndexTurn: {
+ ...turn,
+ messages: [...turn.messages, { id: 'cmp-1', role: 'compressedGroup' }],
+ },
+ state: {
+ binding: { agentDocumentIndex: stored },
+ origin: { topicId: 'topic-1' },
+ } as never,
+ });
+
+ const [doc] = (await providers.listAgentDocuments!('agent-1'))!;
+
+ expect(doc).toMatchObject({ contentCharCount: 14_100 });
+ expect(getAgentContextDocuments).toHaveBeenCalledWith('agent-1', {
+ excludeProgressive: false,
+ });
+ expect(bindAgentDocumentIndex).toHaveBeenCalledWith(
+ expect.objectContaining({ compressionId: 'cmp-1' }),
+ );
+ });
+
it('renders the live documents when the snapshot cannot be resolved', async () => {
getAgentContextDocuments.mockResolvedValue([reportRow(14_100, '2026-11-14T10:00:20.000Z')]);
redisIndexGet.mockRejectedValue(new Error('redis down'));
diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.ts
index 3535bab1600..81a39ef990b 100644
--- a/apps/server/src/services/agentDocuments/index.test.ts
+++ b/apps/server/src/services/agentDocuments/index.test.ts
@@ -1728,7 +1728,7 @@ lossless tool result
const service = new AgentDocumentsService(db, userId);
const result = await service.getAgentContextDocuments('agent-1');
- expect(mockModel.findContextByAgent).toHaveBeenCalledWith('agent-1');
+ expect(mockModel.findContextByAgent).toHaveBeenCalledWith('agent-1', undefined);
expect(result).toMatchObject([
{ content: 'raw content', id: 'always-doc' },
{ content: '', contentCharCount: 12_000, id: 'progressive-doc' },
diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.ts
index 1e12f14214c..9d9b0432408 100644
--- a/apps/server/src/services/agentDocuments/index.ts
+++ b/apps/server/src/services/agentDocuments/index.ts
@@ -391,9 +391,12 @@ export class AgentDocumentsService {
return this.projectDocuments(excludeArchivedToolResults(docs));
}
- async getAgentContextDocuments(agentId: string): Promise<AgentDocumentContextPayload[]> {
+ async getAgentContextDocuments(
+ agentId: string,
+ options?: Parameters<AgentDocumentModel['findContextByAgent']>[1],
+ ): Promise<AgentDocumentContextPayload[]> {
const docs = excludeArchivedToolResults(
- await this.agentDocumentModel.findContextByAgent(agentId),
+ await this.agentDocumentModel.findContextByAgent(agentId, options),
);
const projectedDocs = await Promise.all(
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
index ee61ef63c38..784d0a4a3da 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
@@ -32,6 +32,7 @@ export {
resolveAgentDocumentIndex,
type ResolveAgentDocumentIndexInput,
type ResolvedAgentDocumentIndex,
+ reusablePinnedAgentDocumentIndex,
sortByPriority,
takeAgentDocumentIndexSnapshot,
withRunStartedAt,
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/indexSnapshot.ts b/packages/context-engine/src/providers/AgentDocumentInjector/indexSnapshot.ts
index 56a18c58f2c..640c5a7de03 100644
--- a/packages/context-engine/src/providers/AgentDocumentInjector/indexSnapshot.ts
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/indexSnapshot.ts
@@ -321,7 +321,10 @@ export interface ResolveAgentDocumentIndexInput {
* refreshed for free. Same test as `StaleToolResultTrimProcessor`.
*/
cacheTtlMs: number;
- /** Live documents of the agent. */
+ /**
+ * Live documents of the agent. Unused when the pinned snapshot is reused
+ * (`reusablePinnedAgentDocumentIndex`).
+ */
docs: AgentContextDocument[];
/** The conversation the step runs on. */
messages: TurnMessage[];
@@ -347,6 +350,26 @@ export interface ResolvedAgentDocumentIndex {
store: boolean;
}
+const latestCompressionId = (messages: TurnMessage[]): string | undefined =>
+ messages.findLast((m) => m.role === 'compressedGroup')?.id;
+
+/**
+ * The snapshot the run already pinned, when this step keeps rendering from it.
+ *
+ * Such a step reads no progressive document: the index renders the pinned rows,
+ * so a caller can skip loading them (an agent can hold over 10k). A new history
+ * compression takes a fresh snapshot, which needs them again.
+ */
+export function reusablePinnedAgentDocumentIndex({
+ messages,
+ pinned,
+}: Pick<ResolveAgentDocumentIndexInput, 'messages' | 'pinned'>):
+ AgentDocumentIndexSnapshot | undefined {
+ return isSnapshot(pinned) && pinned.compressionId === latestCompressionId(messages)
+ ? pinned
+ : undefined;
+}
+
/**
* Pick the snapshot a step renders from.
*
@@ -366,11 +389,10 @@ export function resolveAgentDocumentIndex({
stored,
visibleMessages = messages,
}: ResolveAgentDocumentIndexInput): ResolvedAgentDocumentIndex {
- const compressionId = messages.findLast((m) => m.role === 'compressedGroup')?.id;
+ const reused = reusablePinnedAgentDocumentIndex({ messages, pinned });
+ if (reused) return { pin: false, snapshot: reused, store: false };
- if (isSnapshot(pinned) && pinned.compressionId === compressionId) {
- return { pin: false, snapshot: pinned, store: false };
- }
+ const compressionId = latestCompressionId(messages);
const lastUserIndex = messages.findLastIndex((m) => m.role === 'user');
const lastUser = messages[lastUserIndex];
diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentIndexSnapshot.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentIndexSnapshot.test.ts
index 1107f195622..1cd1d4244f6 100644
--- a/packages/context-engine/src/providers/__tests__/AgentDocumentIndexSnapshot.test.ts
+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentIndexSnapshot.test.ts
@@ -11,6 +11,7 @@ import {
formatAgentDocumentChanges,
noteAgentDocumentChanges,
resolveAgentDocumentIndex,
+ reusablePinnedAgentDocumentIndex,
takeAgentDocumentIndexSnapshot,
} from '../AgentDocumentInjector';
@@ -213,6 +214,25 @@ describe('agent-document index snapshot', () => {
expect(snapshot.rows).toHaveLength(1);
});
+ it('lets a later step skip the progressive documents only while its pin holds', () => {
+ const pinned = takeAgentDocumentIndexSnapshot([report()], { takenAt: new Date(at(0)) });
+ const laterStep = [...turn1, assistant('a1', at(0, 30))];
+ const compressed = [
+ ...laterStep,
+ { createdAt: at(1), id: 'compressed-1', role: 'compressedGroup' },
+ ];
+
+ expect(reusablePinnedAgentDocumentIndex({ messages: laterStep, pinned })).toBe(pinned);
+ expect(reusablePinnedAgentDocumentIndex({ messages: laterStep })).toBeUndefined();
+ expect(reusablePinnedAgentDocumentIndex({ messages: compressed, pinned })).toBeUndefined();
+ expect(
+ reusablePinnedAgentDocumentIndex({
+ messages: laterStep,
+ pinned: { [REPORT_ID]: { contentCharCount: 9_400 } },
+ }),
+ ).toBeUndefined();
+ });
+
it('renders deleted documents from their snapshot row and hides newer ones', () => {
const snapshot = takeAgentDocumentIndexSnapshot([report(), notes()], {
takenAt: new Date(at(0)),
diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.context.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.context.test.ts
new file mode 100644
index 00000000000..794fdf8d441
--- /dev/null
+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.context.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment node
+// `findContextByAgent` against a real database: the rows the agent runtime
+// reads to build the agent-document context of a step.
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agentDocuments, agents, documents, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { AgentDocumentModel, PolicyLoad } from '../agentDocument';
+
+const userId = 'agent-document-context-user';
+const agentId = 'agent-document-context-agent';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+let model: AgentDocumentModel;
+
+const cleanup = async () => {
+ // Users cascade to agents, documents and agent_documents.
+ await serverDB.delete(users).where(eq(users.id, userId));
+};
+
+beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ model = new AgentDocumentModel(serverDB, userId);
+});
+
+afterEach(cleanup);
+
+/** Binds a folder row the way the tool-result archive creates `.tool-results`. */
+const createFolder = async (filename: string, policyLoad: PolicyLoad) => {
+ const [folder] = await serverDB
+ .insert(documents)
+ .values({
+ fileType: 'custom/folder',
+ filename,
+ source: `test://${filename}`,
+ sourceType: 'agent',
+ title: filename,
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ })
+ .returning();
+ await serverDB
+ .insert(agentDocuments)
+ .values({ agentId, documentId: folder!.id, policyLoad, userId });
+ return folder!;
+};
+
+describe('AgentDocumentModel.findContextByAgent', () => {
+ beforeEach(async () => {
+ await model.create(agentId, 'notes.md', 'progressive notes');
+ await model.create(agentId, 'style.md', 'Always follow the style guide.', {
+ policyLoad: PolicyLoad.ALWAYS,
+ });
+ await model.create(agentId, 'paused.md', 'disabled for now', {
+ policyLoad: PolicyLoad.DISABLED,
+ });
+ await createFolder('.tool-results', PolicyLoad.PROGRESSIVE);
+ });
+
+ it('reads every live document by default', async () => {
+ const rows = await model.findContextByAgent(agentId);
+
+ expect(rows.map((row) => row.filename).sort()).toEqual([
+ '.tool-results',
+ 'notes.md',
+ 'paused.md',
+ 'style.md',
+ ]);
+ });
+
+ it('loads description only for always documents', async () => {
+ await serverDB
+ .update(documents)
+ .set({ description: 'summary' })
+ .where(eq(documents.userId, userId));
+
+ const rows = await model.findContextByAgent(agentId);
+
+ expect(rows.find((row) => row.filename === 'style.md')?.description).toBe('summary');
+ expect(rows.find((row) => row.filename === 'notes.md')?.description).toBeNull();
+ });
+
+ it('keeps only always documents and folders when asked', async () => {
+ const rows = await model.findContextByAgent(agentId, { excludeProgressive: true });
+
+ expect(rows.map((row) => row.filename).sort()).toEqual(['.tool-results', 'style.md']);
+ expect(rows.find((row) => row.filename === 'style.md')).toMatchObject({
+ content: 'Always follow the style guide.',
+ policyLoad: PolicyLoad.ALWAYS,
+ });
+ });
+});
diff --git a/packages/database/src/models/agentDocuments/agentDocument/index.ts b/packages/database/src/models/agentDocuments/agentDocument/index.ts
index d4d4a367c38..f5d89a46371 100644
--- a/packages/database/src/models/agentDocuments/agentDocument/index.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument/index.ts
@@ -5,6 +5,7 @@ import { AgentDocumentRepository } from '../../../repositories/agentDocument';
import type { LobeChatDatabase, Transaction } from '../../../type';
import type {
AgentDocument,
+ AgentDocumentContextQueryOptions,
AgentDocumentContextRow,
AgentDocumentListItem,
AgentDocumentListSourceType,
@@ -354,8 +355,11 @@ export class AgentDocumentModel {
return queries.findSkillDocsByAgent(this.ctx, agentId);
}
- async findContextByAgent(agentId: string): Promise<AgentDocumentContextRow[]> {
- return queries.findContextByAgent(this.ctx, agentId);
+ async findContextByAgent(
+ agentId: string,
+ options?: AgentDocumentContextQueryOptions,
+ ): Promise<AgentDocumentContextRow[]> {
+ return queries.findContextByAgent(this.ctx, agentId, options);
}
async findByDocumentIds(
diff --git a/packages/database/src/models/agentDocuments/agentDocument/queries.ts b/packages/database/src/models/agentDocuments/agentDocument/queries.ts
index 90f87c8037a..82555900114 100644
--- a/packages/database/src/models/agentDocuments/agentDocument/queries.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument/queries.ts
@@ -3,6 +3,7 @@ import { and, asc, desc, eq, inArray, isNotNull, isNull, like, ne, or, sql } fro
import {
AGENT_SKILL_TEMPLATE_ID,
agentDocuments,
+ DOCUMENT_FOLDER_TYPE,
documents,
knowledgeBaseFiles,
} from '../../../schemas';
@@ -11,6 +12,7 @@ import { deriveAgentDocumentFields } from '../deriveFields';
import { canReadDocument, parseLoadRules } from '../policy';
import {
type AgentDocument,
+ type AgentDocumentContextQueryOptions,
type AgentDocumentContextRow,
type AgentDocumentListItem,
type AgentDocumentListSourceType,
@@ -148,6 +150,7 @@ export async function findSkillDocsByAgent(
export async function findContextByAgent(
ctx: AgentDocumentContext,
agentId: string,
+ options?: AgentDocumentContextQueryOptions,
): Promise<AgentDocumentContextRow[]> {
const results = await ctx.db
.select({
@@ -159,7 +162,14 @@ export async function findContextByAgent(
ELSE ''
END
`.as('content'),
- description: documents.description,
+ // Context rendering never reads `description`, and across thousands of
+ // progressive rows it is a large share of the bytes; keep it on `always` rows.
+ description: sql<string | null>`
+ CASE
+ WHEN ${agentDocuments.policyLoad} = ${PolicyLoad.ALWAYS} THEN ${documents.description}
+ ELSE NULL
+ END
+ `.as('description'),
editorData: sql<Record<string, any> | null>`
CASE
WHEN ${agentDocuments.policyLoad} = ${PolicyLoad.ALWAYS} THEN ${documents.editorData}
@@ -194,6 +204,14 @@ export async function findContextByAgent(
agentDocOwnership(ctx),
eq(agentDocuments.agentId, agentId),
isNull(agentDocuments.deletedAt),
+ ...(options?.excludeProgressive
+ ? [
+ or(
+ eq(agentDocuments.policyLoad, PolicyLoad.ALWAYS),
+ eq(documents.fileType, DOCUMENT_FOLDER_TYPE),
+ ),
+ ]
+ : []),
),
)
.orderBy(desc(agentDocuments.updatedAt));
diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.ts
index 8dca1f04167..0382eee9535 100644
--- a/packages/database/src/models/agentDocuments/types.ts
+++ b/packages/database/src/models/agentDocuments/types.ts
@@ -130,6 +130,18 @@ export interface AgentDocumentContextRow extends AgentDocumentDerivedFields {
updatedAt: Date;
}
+export interface AgentDocumentContextQueryOptions {
+ /**
+ * Leave out progressive documents, for a step that renders the index from an
+ * already pinned snapshot: an agent can have over 10k of them, and reading
+ * them on every step was the bulk of agent-document reads. Disabled documents
+ * are left out too, since they are never injected. Only `always` documents and
+ * folder rows stay, so the archived tool results under `.tool-results` are
+ * still recognized.
+ */
+ excludeProgressive?: boolean;
+}
+
export interface AgentDocumentContextPayload {
content: string;
contentCharCount?: number;