π€― 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(kb): preserve files on NoSuchKey and clean orphan documents/tasks (#14501)
Innei79cf5febedf3
diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.tsindex 8ec343be477..27c1684d850 100644--- a/packages/database/src/models/__tests__/file.test.ts+++ b/packages/database/src/models/__tests__/file.test.ts@@ -5,7 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';import {+ asyncTasks,chunks,+ documents,embeddings,fileChunks,files,@@ -196,6 +198,91 @@ describe('FileModel', () => {expect(file).toBeUndefined();expect(globalFile).toBeDefined();});++ it('should delete mirror documents (sourceType=file) tied to the file', async () => {+ const { id: fileId } = await fileModel.create({+ name: 'mirror.pdf',+ url: 'https://example.com/mirror.pdf',+ size: 100,+ fileType: 'application/pdf',+ });++ await serverDB.insert(documents).values({+ userId,+ fileId,+ sourceType: 'file',+ source: 'mirror.pdf',+ fileType: 'application/pdf',+ totalCharCount: 0,+ totalLineCount: 0,+ });++ await fileModel.delete(fileId);++ const remainingDocs = await serverDB.query.documents.findMany({+ where: eq(documents.userId, userId),+ });+ expect(remainingDocs).toHaveLength(0);+ });++ it('should NOT delete non-mirror documents, only null out their fileId', async () => {+ const { id: fileId } = await fileModel.create({+ name: 'shared.pdf',+ url: 'https://example.com/shared.pdf',+ size: 100,+ fileType: 'application/pdf',+ });++ const inserted = await serverDB+ .insert(documents)+ .values({+ userId,+ fileId,+ // not a mirror β created from a topic, just happens to reference this file+ sourceType: 'topic',+ source: 'topic-source',+ fileType: 'application/pdf',+ totalCharCount: 0,+ totalLineCount: 0,+ })+ .returning();+ const docId = inserted[0]!.id;++ await fileModel.delete(fileId);++ const doc = await serverDB.query.documents.findFirst({+ where: eq(documents.id, docId),+ });+ expect(doc).toBeDefined();+ expect(doc?.fileId).toBeNull();+ });++ it('should delete asyncTasks attached to the file', async () => {+ const [chunkTask] = await serverDB+ .insert(asyncTasks)+ .values({ userId, type: 'chunk', status: 'success' })+ .returning();+ const [embeddingTask] = await serverDB+ .insert(asyncTasks)+ .values({ userId, type: 'embedding', status: 'success' })+ .returning();++ const { id: fileId } = await fileModel.create({+ name: 'tasked.pdf',+ url: 'https://example.com/tasked.pdf',+ size: 100,+ fileType: 'application/pdf',+ chunkTaskId: chunkTask!.id,+ embeddingTaskId: embeddingTask!.id,+ });++ await fileModel.delete(fileId);++ const remainingTasks = await serverDB.query.asyncTasks.findMany({+ where: inArray(asyncTasks.id, [chunkTask!.id, embeddingTask!.id]),+ });+ expect(remainingTasks).toHaveLength(0);+ });});describe('deleteMany', () => {@@ -234,7 +321,7 @@ describe('FileModel', () => {});expect(globalFilesResult).toHaveLength(2);- await fileModel.deleteMany([file1.id, file2.id]);+ const deletedFiles = await fileModel.deleteMany([file1.id, file2.id]);const remainingFiles = await serverDB.query.files.findMany({where: eq(files.userId, userId),@@ -248,6 +335,7 @@ describe('FileModel', () => {expect(remainingFiles).toHaveLength(0);expect(globalFilesResult2).toHaveLength(0);+ expect(deletedFiles.map((file) => file.id).sort()).toEqual([file1.id, file2.id].sort());});it('should delete multiple files but not remove global files if DISABLE_REMOVE_GLOBAL_FILE=true', async () => {await fileModel.createGlobalFile({@@ -286,7 +374,7 @@ describe('FileModel', () => {expect(globalFilesResult).toHaveLength(2);- await fileModel.deleteMany([file1.id, file2.id], false);+ const deletedFiles = await fileModel.deleteMany([file1.id, file2.id], false);const remainingFiles = await serverDB.query.files.findMany({where: eq(files.userId, userId),@@ -297,6 +385,117 @@ describe('FileModel', () => {expect(remainingFiles).toHaveLength(0);expect(globalFilesResult2).toHaveLength(2);+ expect(deletedFiles).toEqual([]);+ });++ it('should return only files whose backing global file is no longer referenced', async () => {+ await fileModel.createGlobalFile({+ hashId: 'shared-hash',+ url: 'https://example.com/shared.txt',+ size: 100,+ fileType: 'text/plain',+ creator: userId,+ });+ await fileModel.createGlobalFile({+ hashId: 'exclusive-hash',+ url: 'https://example.com/exclusive.txt',+ size: 100,+ fileType: 'text/plain',+ creator: userId,+ });++ const sharedFileA = await fileModel.create({+ name: 'shared-a.txt',+ url: 'https://example.com/shared.txt',+ size: 100,+ fileHash: 'shared-hash',+ fileType: 'text/plain',+ });+ await fileModel.create({+ name: 'shared-b.txt',+ url: 'https://example.com/shared.txt',+ size: 100,+ fileHash: 'shared-hash',+ fileType: 'text/plain',+ });+ const exclusiveFile = await fileModel.create({+ name: 'exclusive.txt',+ url: 'https://example.com/exclusive.txt',+ size: 100,+ fileHash: 'exclusive-hash',+ fileType: 'text/plain',+ });++ const deletedFiles = await fileModel.deleteMany([sharedFileA.id, exclusiveFile.id]);++ expect(deletedFiles.map((file) => file.id)).toEqual([exclusiveFile.id]);++ const sharedGlobalFile = await serverDB.query.globalFiles.findFirst({+ where: eq(globalFiles.hashId, 'shared-hash'),+ });+ const exclusiveGlobalFile = await serverDB.query.globalFiles.findFirst({+ where: eq(globalFiles.hashId, 'exclusive-hash'),+ });+ expect(sharedGlobalFile).toBeDefined();+ expect(exclusiveGlobalFile).toBeUndefined();+ });++ it('should delete mirror documents and asyncTasks for all files in batch', async () => {+ const [chunkTask1] = await serverDB+ .insert(asyncTasks)+ .values({ userId, type: 'chunk', status: 'success' })+ .returning();+ const [chunkTask2] = await serverDB+ .insert(asyncTasks)+ .values({ userId, type: 'chunk', status: 'success' })+ .returning();++ const file1 = await fileModel.create({+ name: 'a.pdf',+ url: 'https://example.com/a.pdf',+ size: 100,+ fileType: 'application/pdf',+ chunkTaskId: chunkTask1!.id,+ });+ const file2 = await fileModel.create({+ name: 'b.pdf',+ url: 'https://example.com/b.pdf',+ size: 100,+ fileType: 'application/pdf',+ chunkTaskId: chunkTask2!.id,+ });++ await serverDB.insert(documents).values([+ {+ userId,+ fileId: file1.id,+ sourceType: 'file',+ source: 'a.pdf',+ fileType: 'application/pdf',+ totalCharCount: 0,+ totalLineCount: 0,+ },+ {+ userId,+ fileId: file2.id,+ sourceType: 'file',+ source: 'b.pdf',+ fileType: 'application/pdf',+ totalCharCount: 0,+ totalLineCount: 0,+ },+ ]);++ await fileModel.deleteMany([file1.id, file2.id]);++ const remainingDocs = await serverDB.query.documents.findMany({+ where: eq(documents.userId, userId),+ });+ const remainingTasks = await serverDB.query.asyncTasks.findMany({+ where: inArray(asyncTasks.id, [chunkTask1!.id, chunkTask2!.id]),+ });+ expect(remainingDocs).toHaveLength(0);+ expect(remainingTasks).toHaveLength(0);});});diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.tsindex 2dc848001d9..2752793deec 100644--- a/packages/database/src/models/file.ts+++ b/packages/database/src/models/file.ts@@ -5,8 +5,10 @@ import type { PgTransaction } from 'drizzle-orm/pg-core';import type { FileItem, NewFile, NewGlobalFile } from '../schemas';import {+ asyncTasks,chunks,documentChunks,+ documents,embeddings,fileChunks,files,@@ -118,18 +120,43 @@ export class FileModel {const file = await this.findById(id, tx);if (!file) return;- const fileHash = file.fileHash!;+ const fileHash = file.fileHash;- // 2. Delete related chunks+ // 1. Delete related chunksawait this.deleteFileChunks(tx as any, [id]);- // 3. Delete file record+ // 2. Delete mirror documents whose source is this file. Without this,+ // documents.fileId would be set null by FK and leave orphan rows behind+ // (still indexed by BM25, still occupying KB slots).+ await tx+ .delete(documents)+ .where(+ and(+ eq(documents.fileId, id),+ eq(documents.userId, this.userId),+ eq(documents.sourceType, 'file'),+ ),+ );++ // 3. Delete the chunk/embedding asyncTasks tied to this file. files.chunkTaskId+ // and embeddingTaskId are `set null` on the asyncTasks side, so without this+ // the task rows would dangle in the DB forever.+ const taskIds = [file.chunkTaskId, file.embeddingTaskId].filter((taskId): taskId is string =>+ Boolean(taskId),+ );+ if (taskIds.length > 0) {+ await tx.delete(asyncTasks).where(inArray(asyncTasks.id, taskIds));+ }++ // 4. Delete file recordawait tx.delete(files).where(and(eq(files.id, id), eq(files.userId, this.userId)));+ if (!fileHash) return;+const result = await tx.select({ count: count() }).from(files)- .where(and(eq(files.fileHash, fileHash)));+ .where(eq(files.fileHash, fileHash));const fileCount = result[0].count;@@ -177,11 +204,31 @@ export class FileModel {// 2. Delete related chunksawait this.deleteFileChunks(trx as any, ids);- // 3. Delete file records+ // 3. Delete mirror documents (sourceType='file') so they don't linger as+ // orphans with fileId set to null after the file row is removed.+ await trx+ .delete(documents)+ .where(+ and(+ inArray(documents.fileId, ids),+ eq(documents.userId, this.userId),+ eq(documents.sourceType, 'file'),+ ),+ );++ // 4. Delete chunk/embedding asyncTasks attached to these files.+ const taskIds = fileList+ .flatMap((file) => [file.chunkTaskId, file.embeddingTaskId])+ .filter((taskId): taskId is string => Boolean(taskId));+ if (taskIds.length > 0) {+ await trx.delete(asyncTasks).where(inArray(asyncTasks.id, taskIds));+ }++ // 5. Delete file recordsawait trx.delete(files).where(and(inArray(files.id, ids), eq(files.userId, this.userId)));- // If global files don't need to be deleted, return directly- if (!removeGlobalFile || hashList.length === 0) return fileList;+ // If global files don't need to be deleted, no storage object should be removed.+ if (!removeGlobalFile || hashList.length === 0) return [];// 4. Find hashes that are no longer referencedconst remainingFiles = await trx@@ -197,13 +244,15 @@ export class FileModel {// Find hashes to delete (those no longer used by any file)const hashesToDelete = hashList.filter((hash) => !usedHashes.has(hash));- if (hashesToDelete.length === 0) return fileList;+ if (hashesToDelete.length === 0) return [];// 5. Delete global files that are no longer referencedawait trx.delete(globalFiles).where(inArray(globalFiles.hashId, hashesToDelete));- // Return the list of deleted files- return fileList;+ const hashesToDeleteSet = new Set(hashesToDelete);++ // Return only files whose backing global object became unreferenced.+ return fileList.filter((file) => file.fileHash && hashesToDeleteSet.has(file.fileHash));});};diff --git a/src/server/routers/async/__tests__/file.test.ts b/src/server/routers/async/__tests__/file.test.tsnew file mode 100644index 00000000000..1eb58bea71e--- /dev/null+++ b/src/server/routers/async/__tests__/file.test.ts@@ -0,0 +1,143 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { ChunkModel } from '@/database/models/chunk';+import { EmbeddingModel } from '@/database/models/embedding';+import { FileModel } from '@/database/models/file';+import { ChunkService } from '@/server/services/chunk';+import { DocumentService } from '@/server/services/document';+import { FileService } from '@/server/services/file';+import { AsyncTaskStatus } from '@/types/asyncTask';++import { fileRouter } from '../file';++vi.mock('@/database/models/asyncTask', () => ({ AsyncTaskModel: vi.fn() }));+vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));+vi.mock('@/database/models/embedding', () => ({ EmbeddingModel: vi.fn() }));+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));+vi.mock('@/server/services/chunk', () => ({ ChunkService: vi.fn() }));+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));+vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));+vi.mock('@/business/server/trpc-middlewares/async', () => ({+ checkEmbeddingUsage: async (opts: any) => opts.next({ ctx: opts.ctx }),+}));++vi.mock('@/libs/trpc/async', async () => {+ const init = await vi.importActual<{ asyncTrpc: any }>('@/libs/trpc/async/init');+ const { asyncTrpc } = init;+ return {+ asyncAuthedProcedure: asyncTrpc.procedure,+ asyncRouter: asyncTrpc.router,+ createAsyncCallerFactory: asyncTrpc.createCallerFactory,+ publicProcedure: asyncTrpc.procedure,+ };+});++describe('fileRouter.parseFileToChunks β NoSuchKey + internal:// branches', () => {+ const userId = 'user_test';+ let mockCtx: any;+ let asyncTaskModelMock: any;+ let fileModelMock: any;+ let fileServiceMock: any;+ let chunkServiceMock: any;+ let documentServiceMock: any;+ let chunkModelMock: any;++ beforeEach(() => {+ vi.clearAllMocks();++ asyncTaskModelMock = { findById: vi.fn(), update: vi.fn() };+ fileModelMock = { findById: vi.fn(), delete: vi.fn() };+ fileServiceMock = { getFileByteArray: vi.fn() };+ chunkServiceMock = {+ asyncEmbeddingFileChunks: vi.fn(),+ chunkContent: vi.fn(),+ };+ documentServiceMock = { parseFile: vi.fn() };+ chunkModelMock = { bulkCreate: vi.fn(), bulkCreateUnstructuredChunks: vi.fn() };++ vi.mocked(AsyncTaskModel).mockImplementation(() => asyncTaskModelMock);+ vi.mocked(FileModel).mockImplementation(() => fileModelMock);+ vi.mocked(FileService).mockImplementation(() => fileServiceMock);+ vi.mocked(ChunkService).mockImplementation(() => chunkServiceMock);+ vi.mocked(DocumentService).mockImplementation(() => documentServiceMock);+ vi.mocked(ChunkModel).mockImplementation(() => chunkModelMock);+ vi.mocked(EmbeddingModel).mockImplementation(() => ({}) as any);++ mockCtx = { serverDB: {}, userId };+ });++ it('does NOT delete the file row when storage returns NoSuchKey; marks task Error and throws', async () => {+ fileModelMock.findById.mockResolvedValue({+ id: 'file_xyz',+ name: 'doc.pdf',+ url: 'https://example.com/doc.pdf',+ });+ fileServiceMock.getFileByteArray.mockRejectedValue({ Code: 'NoSuchKey' });++ const caller = fileRouter.createCaller(mockCtx);++ await expect(+ caller.parseFileToChunks({ fileId: 'file_xyz', taskId: 'task_1' }),+ ).rejects.toThrow(TRPCError);++ expect(fileModelMock.delete).not.toHaveBeenCalled();+ expect(asyncTaskModelMock.update).toHaveBeenCalledWith(+ 'task_1',+ expect.objectContaining({+ status: AsyncTaskStatus.Error,+ error: expect.objectContaining({+ name: expect.any(String),+ }),+ }),+ );+ });++ it('skips storage fetch and returns gracefully when url is internal://', async () => {+ fileModelMock.findById.mockResolvedValue({+ id: 'file_inline',+ name: 'note',+ url: 'internal://document/placeholder',+ });++ const caller = fileRouter.createCaller(mockCtx);+ const result = await caller.parseFileToChunks({+ fileId: 'file_inline',+ taskId: 'task_2',+ });++ expect(fileServiceMock.getFileByteArray).not.toHaveBeenCalled();+ expect(fileModelMock.delete).not.toHaveBeenCalled();+ expect(asyncTaskModelMock.update).toHaveBeenCalledWith(+ 'task_2',+ expect.objectContaining({ status: AsyncTaskStatus.Error }),+ );+ expect(result).toMatchObject({ success: false });+ });++ it('marks task Error and propagates for non-NoSuchKey storage errors (does not delete)', async () => {+ fileModelMock.findById.mockResolvedValue({+ id: 'file_other',+ name: 'doc.pdf',+ url: 'https://example.com/doc.pdf',+ });+ fileServiceMock.getFileByteArray.mockRejectedValue({+ Code: 'AccessDenied',+ message: 'forbidden',+ });++ const caller = fileRouter.createCaller(mockCtx);++ await expect(+ caller.parseFileToChunks({ fileId: 'file_other', taskId: 'task_3' }),+ ).rejects.toThrow();++ expect(fileModelMock.delete).not.toHaveBeenCalled();+ expect(asyncTaskModelMock.update).toHaveBeenCalledWith(+ 'task_3',+ expect.objectContaining({ status: AsyncTaskStatus.Error }),+ );+ });+});diff --git a/src/server/routers/async/file.ts b/src/server/routers/async/file.tsindex 65992ec93e2..365c68c43eb 100644--- a/src/server/routers/async/file.ts+++ b/src/server/routers/async/file.ts@@ -6,7 +6,6 @@ import pMap from 'p-map';import { z } from 'zod';import { checkEmbeddingUsage } from '@/business/server/trpc-middlewares/async';-import { serverDBEnv } from '@/config/db';import { DEFAULT_FILE_EMBEDDING_MODEL_ITEM } from '@/const/settings/knowledge';import { AsyncTaskModel } from '@/database/models/asyncTask';import { ChunkModel } from '@/database/models/chunk';@@ -168,16 +167,56 @@ export const fileRouter = router({throw new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' });}+ // Inline documents (custom/document) keep a mirror file row whose url is the+ // `internal://document/placeholder` marker. Their content lives on documents.content+ // and is intentionally not chunked β searching is handled by BM25 instead.+ if (file.url.startsWith('internal://')) {+ await ctx.asyncTaskModel.update(input.taskId, {+ error: new AsyncTaskError(+ AsyncTaskErrorType.TaskTriggerError,+ 'Inline documents (custom/document) do not require chunking; content is searched via BM25.',+ ),+ status: AsyncTaskStatus.Error,+ });+ return {+ message: `File ${file.name}(${input.taskId}) is an inline document and was skipped`,+ success: false,+ };+ }+let content: Uint8Array | undefined;try {content = await ctx.fileService.getFileByteArray(file.url);} catch (e) {console.error(e);- // if file not found, delete it from db- if ((e as any).Code === 'NoSuchKey') {- await ctx.fileModel.delete(input.fileId, serverDBEnv.REMOVE_GLOBAL_FILE);- throw new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' });+ const errorCode = (e as any).Code;+ // Storage returned NoSuchKey. Do NOT delete the file row β transient S3+ // outages, IAM misconfig, or already-orphaned DB rows must not cascade+ // into destroying chunks/embeddings/documents. Mark the task as Error+ // so users see a clear message and can re-upload or retry.+ if (errorCode === 'NoSuchKey') {+ await ctx.asyncTaskModel.update(input.taskId, {+ error: new AsyncTaskError(+ AsyncTaskErrorType.TaskTriggerError,+ 'File content unavailable in storage. Verify storage access or re-upload.',+ ),+ status: AsyncTaskStatus.Error,+ });+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'File content unavailable in storage.',+ });}+ // Other fetch errors (network, IAM, etc.) β mark the task as Error so+ // the user surface stays consistent, then propagate.+ await ctx.asyncTaskModel.update(input.taskId, {+ error: new AsyncTaskError(+ AsyncTaskErrorType.TaskTriggerError,+ `Failed to fetch file content: ${(e as Error)?.message ?? errorCode ?? 'unknown error'}`,+ ),+ status: AsyncTaskStatus.Error,+ });+ throw e;}if (!content) return;diff --git a/src/server/services/document/__tests__/index.test.ts b/src/server/services/document/__tests__/index.test.tsindex 08a66f09141..fa10c357549 100644--- a/src/server/services/document/__tests__/index.test.ts+++ b/src/server/services/document/__tests__/index.test.ts@@ -105,6 +105,7 @@ describe('DocumentService', () => {};mockFileService = {+ deleteFile: vi.fn(),downloadFileToLocal: vi.fn(),};@@ -474,11 +475,27 @@ describe('DocumentService', () => {fileId: 'file-1',});mockDocumentModel.delete.mockResolvedValue(undefined);- mockFileModel.delete.mockResolvedValue(undefined);+ mockFileModel.delete.mockResolvedValue({ url: 'files/doc-1.md' });await service.deleteDocument('doc-1');expect(mockFileModel.delete).toHaveBeenCalledWith('file-1');+ expect(mockFileService.deleteFile).toHaveBeenCalledWith('files/doc-1.md');+ expect(mockDocumentModel.delete).toHaveBeenCalledWith('doc-1');+ });++ it('should not delete storage for internal document placeholder files', async () => {+ mockDocumentModel.findById.mockResolvedValue({+ id: 'doc-1',+ fileType: 'custom/document',+ fileId: 'file-1',+ });+ mockFileModel.delete.mockResolvedValue({ url: 'internal://document/placeholder' });++ await service.deleteDocument('doc-1');++ expect(mockFileModel.delete).toHaveBeenCalledWith('file-1');+ expect(mockFileService.deleteFile).not.toHaveBeenCalled();expect(mockDocumentModel.delete).toHaveBeenCalledWith('doc-1');});@@ -525,11 +542,16 @@ describe('DocumentService', () => {{ id: 'file-in-folder-1' },{ id: 'file-in-folder-2' },]);+ mockFileModel.delete+ .mockResolvedValueOnce({ url: 'files/file-in-folder-1.pdf' })+ .mockResolvedValueOnce({ url: 'files/file-in-folder-2.pdf' });await service.deleteDocument('folder-1');expect(mockFileModel.delete).toHaveBeenCalledWith('file-in-folder-1');expect(mockFileModel.delete).toHaveBeenCalledWith('file-in-folder-2');+ expect(mockFileService.deleteFile).toHaveBeenCalledWith('files/file-in-folder-1.pdf');+ expect(mockFileService.deleteFile).toHaveBeenCalledWith('files/file-in-folder-2.pdf');expect(mockDocumentModel.delete).toHaveBeenCalledWith('folder-1');});});diff --git a/src/server/services/document/index.ts b/src/server/services/document/index.tsindex 34ea5f4fb3a..b6ff385e037 100644--- a/src/server/services/document/index.ts+++ b/src/server/services/document/index.ts@@ -56,6 +56,13 @@ export class DocumentService {return this.documentHistoryServiceInstance;}+ private async deleteFileRecordAndStorage(fileId: string) {+ const file = await this.fileModel.delete(fileId);+ if (!file?.url || file.url.startsWith('internal://')) return;++ await this.fileService.deleteFile(file.url);+ }+/*** Create a document*/@@ -269,13 +276,13 @@ export class DocumentService {});for (const file of childFiles) {- await this.fileModel.delete(file.id);+ await this.deleteFileRecordAndStorage(file.id);}}// Delete the associated file record if it existsif (document.fileId) {- await this.fileModel.delete(document.fileId);+ await this.deleteFileRecordAndStorage(document.fileId);}// Finally delete the document itself