From 2e11748bebc9c27c68130c37652495e475de6a07 Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 21 May 2026 12:45:26 +0800 Subject: [PATCH] perf(agent): optimize getPathToRoot to fetch all session entries in one query --- src/agent/database-session-storage.ts | 31 +++++++++++++++++++-------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/src/agent/database-session-storage.ts b/src/agent/database-session-storage.ts index 57f96232..23cbda9a 100644 --- a/src/agent/database-session-storage.ts +++ b/src/agent/database-session-storage.ts @@ -133,21 +133,34 @@ export class DatabaseSessionStorage implements SessionStorage { if (!leafId) return [] - const entries: SessionTreeEntry[] = [] + + // Fetch all entries for this session in a single query to avoid N+1 problem + const records = await prisma.agentSessionEntry.findMany({ + where: { sessionId: this.sessionId }, + }) + + // Build a map for fast lookup + const entryMap = new Map() + for (const record of records) { + entryMap.set(record.id, record.entry as unknown as SessionTreeEntry) + } + + const pathEntries: SessionTreeEntry[] = [] let currentId: string | null = leafId while (currentId) { - const record = await prisma.agentSessionEntry.findUnique({ - where: { id: currentId }, - }) - if (!record) break - const entry = record.entry as unknown as SessionTreeEntry - await this.reinjectImageDataAsync(entry) - entries.unshift(entry) + const entry = entryMap.get(currentId) + if (!entry) break + pathEntries.unshift(entry) currentId = (entry as SessionTreeEntryBase).parentId } - return entries + // Only reinject image data (which may involve S3 calls) for the entries in the path + for (const entry of pathEntries) { + await this.reinjectImageDataAsync(entry) + } + + return pathEntries } async getEntries(): Promise {