π€― 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
π fix(document): serialize the file parse cache write and order its lookup (#17919)
Lee Junhob639878df121
diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.tsindex 1c1ce3436e5..54b0da9b626 100644--- a/apps/server/src/services/document/__tests__/index.test.ts+++ b/apps/server/src/services/document/__tests__/index.test.ts@@ -1,5 +1,6 @@import { type LobeChatDatabase } from '@lobechat/database';import { TRPCError } from '@trpc/server';+import { PgDialect } from 'drizzle-orm/pg-core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DocumentModel } from '@/database/models/document';@@ -89,6 +90,7 @@ describe('DocumentService', () => {beforeEach(() => {mockDb = {+ execute: vi.fn().mockResolvedValue(undefined),query: {documents: {findMany: vi.fn().mockResolvedValue([]),@@ -1779,6 +1781,104 @@ describe('DocumentService', () => {expect(mockCleanup).toHaveBeenCalled();});+ it('should return the cached document without parsing it again', async () => {+ const cached = { content: 'Cached', id: 'doc-1' };+ mockDocumentModel.findByFileId.mockResolvedValueOnce(cached);++ const result = await service.parseFile('file-1');++ expect(result).toEqual(cached);+ expect(mockFileService.downloadFileToLocal).not.toHaveBeenCalled();+ expect(loadFile).not.toHaveBeenCalled();+ expect(mockDocumentModel.create).not.toHaveBeenCalled();+ });++ // The model bound to the locked transaction has to be a different object+ // from the one the service already holds, otherwise no assertion can tell+ // which connection the re-check and the insert actually ran on.+ const mountLockedTransaction = (transactionModel: any) => {+ const executeSpy = vi.fn().mockResolvedValue(undefined);+ const trx = { execute: executeSpy };+ mockDb.transaction = vi.fn(async (callback: any) => callback(trx));+ vi.mocked(DocumentModel).mockImplementation(+ (db: any) => (db === trx ? transactionModel : mockDocumentModel) as any,+ );++ return { executeSpy, trx };+ };++ it('should take a per-file advisory lock before writing the parse cache', async () => {+ vi.mocked(loadFile).mockResolvedValue({+ content: 'Content',+ fileType: 'markdown',+ metadata: {},+ pages: undefined,+ totalCharCount: 7,+ totalLineCount: 1,+ } as any);+ const transactionModel = {+ create: vi.fn().mockResolvedValue({ id: 'doc-1' }),+ findByFileId: vi.fn().mockResolvedValue(null),+ };+ const { executeSpy, trx } = mountLockedTransaction(transactionModel);+ const scopedService = new DocumentService(mockDb, userId, 'workspace-1', 'public');++ const result = await scopedService.parseFile('file-1');++ expect(executeSpy).toHaveBeenCalledTimes(1);+ // Render the statement the way the driver receives it, so the assertion+ // covers the real SQL and its bound parameter.+ const lockStatement = new PgDialect().sqlToQuery(executeSpy.mock.calls[0][0]);+ expect(lockStatement.sql).toContain('pg_advisory_xact_lock');+ // The key is derived from the file, so different files take different keys.+ expect(lockStatement.params).toEqual(['parseFile:file-1']);+ // The re-check and the insert run on the locked transaction and keep the+ // service's own scope β not on the connection the service already holds.+ expect(vi.mocked(DocumentModel)).toHaveBeenLastCalledWith(+ trx,+ userId,+ 'workspace-1',+ 'public',+ );+ expect(transactionModel.findByFileId).toHaveBeenCalledWith('file-1');+ expect(transactionModel.create).toHaveBeenCalledTimes(1);+ expect(mockDocumentModel.create).not.toHaveBeenCalled();+ // Both have to happen after the lock is held β re-checking before it would+ // leave the same window open.+ expect(executeSpy.mock.invocationCallOrder[0]).toBeLessThan(+ transactionModel.findByFileId.mock.invocationCallOrder[0],+ );+ expect(executeSpy.mock.invocationCallOrder[0]).toBeLessThan(+ transactionModel.create.mock.invocationCallOrder[0],+ );+ expect(result).toEqual({ id: 'doc-1' });+ });++ it('should return the document another request published while this parse ran', async () => {+ vi.mocked(loadFile).mockResolvedValue({+ content: 'Content',+ fileType: 'markdown',+ metadata: {},+ pages: undefined,+ totalCharCount: 7,+ totalLineCount: 1,+ } as any);+ const published = { content: 'Published by the other request', id: 'doc-raced' };+ const transactionModel = {+ create: vi.fn(),+ // The check before the parse missed it; the re-check under the lock hits.+ findByFileId: vi.fn().mockResolvedValue(published),+ };+ mountLockedTransaction(transactionModel);++ const result = await service.parseFile('file-1');++ expect(result).toEqual(published);+ expect(transactionModel.create).not.toHaveBeenCalled();+ expect(mockDocumentModel.create).not.toHaveBeenCalled();+ expect(mockCleanup).toHaveBeenCalled();+ });+it('should NOT strip page tags in parseFile (unlike parseDocument)', async () => {const contentWithPageTags ='<page number="1">First page</page><page number="2">Second page</page>';diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex b4841449961..bb6f491759f 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -7,7 +7,7 @@ import { documents, files } from '@lobechat/database/schemas';import { loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';import { TRPCError } from '@trpc/server';import debug from 'debug';-import { and, eq } from 'drizzle-orm';+import { and, eq, sql } from 'drizzle-orm';import isEqual from 'fast-deep-equal';import { DocumentModel } from '@/database/models/document';@@ -809,8 +809,14 @@ export class DocumentService {}/**- * Parse file content+ * Parse file content.*+ * Idempotent: returns the document already stored for the file, and serializes+ * the cache write per file so two concurrent calls cannot both insert one.+ *+ * The database handle must not be an open transaction β the advisory lock is+ * transaction scoped, so a nested call would hold it until the outer+ * transaction commits instead of releasing it after the insert.*/async parseFile(fileId: string): Promise<LobeDocument> {// Idempotent: return existing document if already parsed@@ -837,19 +843,48 @@ export class DocumentService {file.name.replace(/\.(pdf|docx?|md|markdown)$/i, '') ||'Untitled';- const document = await this.documentModel.create({- content: fileDocument.content,- fileId,- fileType: CUSTOM_DOCUMENT_FILE_TYPE, // Use custom/document for all parsed files- filename: title,- metadata: fileDocument.metadata,- pages: fileDocument.pages,- parentId: file.parentId,- source: file.url,- sourceType: 'file',- title,- totalCharCount: fileDocument.totalCharCount,- totalLineCount: fileDocument.totalLineCount,+ const document = await this.db.transaction(async (tx) => {+ // The existence check above ran before the download and the parse, so+ // another request can have published its own row for this file in the+ // meantime. Serialize the write per file so two concurrent `parseFile`+ // calls cannot both insert one. `hashtext` returns int4 while+ // `pg_advisory_xact_lock` takes bigint, so cast. Under the default READ+ // COMMITTED isolation the re-check below takes a fresh snapshot once the+ // lock is granted, so it sees whatever the holder committed. The parse+ // itself stays outside the transaction: it downloads and reads the whole+ // file, and holding a connection that long would turn every large upload+ // into pool pressure.+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(hashtext(${`parseFile:${fileId}`})::bigint)`,+ );++ const transactionDb = tx as unknown as LobeChatDatabase;+ const transactionDocumentModel = new DocumentModel(+ transactionDb,+ this.userId,+ this.workspaceId,+ this.callerAgentVisibility,+ );++ // Whoever inserted first wins; discard this parse rather than adding a+ // second document for the same file.+ const raced = await transactionDocumentModel.findByFileId(fileId);+ if (raced) return raced;++ return transactionDocumentModel.create({+ content: fileDocument.content,+ fileId,+ fileType: CUSTOM_DOCUMENT_FILE_TYPE, // Use custom/document for all parsed files+ filename: title,+ metadata: fileDocument.metadata,+ pages: fileDocument.pages,+ parentId: file.parentId,+ source: file.url,+ sourceType: 'file',+ title,+ totalCharCount: fileDocument.totalCharCount,+ totalLineCount: fileDocument.totalLineCount,+ });});return document as LobeDocument;diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.tsindex 8b958d75831..9a1c9ecdab3 100644--- a/packages/database/src/models/__tests__/document.test.ts+++ b/packages/database/src/models/__tests__/document.test.ts@@ -590,6 +590,89 @@ describe('DocumentModel', () => {expect(found?.id).toBe(firstId);});+ it('should return the oldest document when rows are inserted out of order', async () => {+ const { id: fileId } = await fileModel.create({+ fileType: 'text/plain',+ name: 'test.txt',+ size: 100,+ url: 'https://example.com/test.txt',+ });++ const file = await fileModel.findById(fileId);+ if (!file) throw new Error('File not found after creation');++ // Insert the newer row first, so physical row order disagrees with+ // creation order and an unordered lookup would return the wrong one.+ await documentModel.create({+ content: 'Newer document',+ createdAt: new Date('2026-02-02T00:00:00.000Z'),+ fileId: file.id,+ fileType: 'text/plain',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 14,+ totalLineCount: 1,+ });++ const { id: olderId } = await documentModel.create({+ content: 'Older document',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ fileId: file.id,+ fileType: 'text/plain',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 14,+ totalLineCount: 1,+ });++ const found = await documentModel.findByFileId(file.id);+ expect(found?.id).toBe(olderId);+ expect(found?.content).toBe('Older document');+ });++ it('should break created-at ties on id so the lookup stays stable', async () => {+ const { id: fileId } = await fileModel.create({+ fileType: 'text/plain',+ name: 'test.txt',+ size: 100,+ url: 'https://example.com/test.txt',+ });++ const file = await fileModel.findById(fileId);+ if (!file) throw new Error('File not found after creation');++ const sameInstant = new Date('2026-03-03T00:00:00.000Z');++ // Identical timestamps, inserted highest id first: without a tiebreaker+ // the row that comes back is whichever one the scan reaches first.+ await documentModel.create({+ content: 'Tie b',+ createdAt: sameInstant,+ fileId: file.id,+ fileType: 'text/plain',+ id: 'document-tie-b',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 5,+ totalLineCount: 1,+ });++ await documentModel.create({+ content: 'Tie a',+ createdAt: sameInstant,+ fileId: file.id,+ fileType: 'text/plain',+ id: 'document-tie-a',+ source: file.url,+ sourceType: 'file',+ totalCharCount: 5,+ totalLineCount: 1,+ });++ const found = await documentModel.findByFileId(file.id);+ expect(found?.id).toBe('document-tie-a');+ });+it('should handle different file types', async () => {const { id: pdfFileId } = await fileModel.create({fileType: 'application/pdf',diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex b1219562ad6..4dabac42685 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -1,4 +1,4 @@-import { and, count, desc, eq, inArray, isNull, ne, notInArray, sum } from 'drizzle-orm';+import { and, asc, count, desc, eq, inArray, isNull, ne, notInArray, sum } from 'drizzle-orm';import type { DocumentItem, NewDocument } from '../schemas';import { DOCUMENT_FOLDER_TYPE, documents, files, works } from '../schemas';@@ -206,6 +206,12 @@ export class DocumentModel {findByFileId = async (fileId: string) => {return this.db.query.documents.findFirst({+ // A file can legitimately own more than one document: `parseDocument`+ // writes a page-editor copy next to the parse cache `parseFile` writes.+ // Pick the oldest one explicitly instead of leaving the choice to the+ // query plan, so repeated lookups keep returning the same content.+ // `created_at` carries no uniqueness guarantee, so `id` breaks ties.+ orderBy: [asc(documents.createdAt), asc(documents.id)],where: and(this.ownership(), eq(documents.fileId, fileId)),});};