🤯 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(file-parse): isolate uploaded-file parsing and chunking (#23117)
Mochaed5faa0d62b8
diff --git a/AGENTS.md b/AGENTS.mdindex 48b75c3b31f..00c4cdeba37 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -49,6 +49,8 @@ bun run devpnpm --filter @lobechat/server dev```+The file-parse worker is a prebuilt file the server starts by absolute path. `bun run dev`, `dev:next` and `dev:bun` build it before starting (`bun run build:file-parse-worker`). The standalone Hono `pnpm --filter @lobechat/server dev` does not build it and runs with `apps/server` as the working directory, so build it from the repo root first and point `FILE_PARSE_WORKER_PATH` at the absolute path of `<repo root>/dist/file-parse-worker/fileParseWorker.mjs` (for example `FILE_PARSE_WORKER_PATH="$(git rev-parse --show-toplevel)/dist/file-parse-worker/fileParseWorker.mjs"`). Known baseline limitation: that Hono `dev` script calls `vite-node`, which is not declared as a dependency, and it was not verified against a real server.+After `dev:spa` starts, the terminal prints a **Debug Proxy** URL:```plaintextdiff --git a/apps/server/src/modules/ContentChunk/index.test.ts b/apps/server/src/modules/ContentChunk/index.test.tsindex de3a195348f..ae31198bfd8 100644--- a/apps/server/src/modules/ContentChunk/index.test.ts+++ b/apps/server/src/modules/ContentChunk/index.test.ts@@ -1,14 +1,18 @@import { readFile } from 'node:fs/promises';+import { FileParseBudgetError } from '@lobechat/file-loaders';import { beforeEach, describe, expect, it, vi } from 'vitest';import { knowledgeEnv } from '@/envs/knowledge';-import { ChunkingLoader } from '@/libs/document-loaders';+import type { ChunkingLoader } from '@/libs/document-loaders';+import { chunkContentInWorker } from '@/server/services/fileParse';+import { FileParseError } from '@/server/services/fileParse/errors';import { ContentChunk } from './index';// Mock the dependencies-vi.mock('@/libs/document-loaders');+// The splitter runs on the shared parse worker; its own tests cover the real thread.+vi.mock('@/server/services/fileParse', () => ({ chunkContentInWorker: vi.fn() }));vi.mock('@/envs/knowledge', () => ({knowledgeEnv: {FILE_TYPE_CHUNKING_RULES: '',@@ -24,23 +28,11 @@ describe('ContentChunk', () => {beforeEach(() => {vi.clearAllMocks();- // Setup LangChain mock- mockLangChainPartition = vi.fn();- (ChunkingLoader as unknown as ReturnType<typeof vi.fn>).mockImplementation(function () {- return {- partitionContent: mockLangChainPartition,- };- });+ mockLangChainPartition = vi.mocked(chunkContentInWorker) as unknown as ReturnType<typeof vi.fn>;contentChunk = new ContentChunk();});- describe('constructor', () => {- it('should initialize with LangChain client', () => {- expect(ChunkingLoader).toHaveBeenCalledTimes(1);- });- });-describe('chunkContent', () => {const mockFileContent = new Uint8Array([1, 2, 3, 4, 5]);const mockFilename = 'test-document.pdf';@@ -191,6 +183,53 @@ describe('ContentChunk', () => {).rejects.toThrow('LangChain error');});+ it.each([+ ['the input size cap', new FileParseError('INPUT_TOO_LARGE', 'too big')],+ ['the xlsx ZIP structure budget', new FileParseBudgetError('zip-expansion', 1, 2)],+ ])('does not run the next chunking service after %s refused the file', async (_, refusal) => {+ vi.mocked(knowledgeEnv).FILE_TYPE_CHUNKING_RULES = 'pdf=unstructured,default';+ try {+ const chunker = new ContentChunk();+ mockLangChainPartition.mockRejectedValue(refusal);++ await expect(+ chunker.chunkContent({+ content: mockFileContent,+ fileType: 'application/pdf',+ filename: mockFilename,+ }),+ ).rejects.toBe(refusal);++ // the next service reads the same bytes under the same limit+ expect(mockLangChainPartition).toHaveBeenCalledTimes(1);+ } finally {+ vi.mocked(knowledgeEnv).FILE_TYPE_CHUNKING_RULES = '';+ }+ });++ it('lets the next chunking service try after one service failed on its own', async () => {+ vi.mocked(knowledgeEnv).FILE_TYPE_CHUNKING_RULES = 'pdf=unstructured,default';+ try {+ const chunker = new ContentChunk();+ mockLangChainPartition+ .mockRejectedValueOnce(new FileParseError('PARSE_FAILED', 'first service cannot read it'))+ .mockResolvedValueOnce([+ { id: 'c1', metadata: { loc: { lines: { from: 1, to: 1 } } }, pageContent: 'ok' },+ ]);++ const result = await chunker.chunkContent({+ content: mockFileContent,+ fileType: 'application/pdf',+ filename: mockFilename,+ });++ expect(mockLangChainPartition).toHaveBeenCalledTimes(2);+ expect(result.chunks).toEqual([expect.objectContaining({ text: 'ok' })]);+ } finally {+ vi.mocked(knowledgeEnv).FILE_TYPE_CHUNKING_RULES = '';+ }+ });+it('should handle empty langchain results', async () => {mockLangChainPartition.mockResolvedValue([]);diff --git a/apps/server/src/modules/ContentChunk/index.ts b/apps/server/src/modules/ContentChunk/index.tsindex d9c3cb21969..55ac108741e 100644--- a/apps/server/src/modules/ContentChunk/index.ts+++ b/apps/server/src/modules/ContentChunk/index.ts@@ -1,6 +1,7 @@import { type NewChunkItem, type NewUnstructuredChunkItem } from '@/database/schemas';import { knowledgeEnv } from '@/envs/knowledge';-import { ChunkingLoader } from '@/libs/document-loaders';+import { chunkContentInWorker } from '@/server/services/fileParse';+import { isSharedLimitFailure } from '@/server/services/fileParse/failure';import { type ChunkingService } from './rules';import { ChunkingRuleParser } from './rules';@@ -18,11 +19,9 @@ interface ChunkResult {}export class ContentChunk {- private chunkingClient: ChunkingLoader;private chunkingRules: Record<string, ChunkingService[]>;constructor() {- this.chunkingClient = new ChunkingLoader();this.chunkingRules = ChunkingRuleParser.parse(knowledgeEnv.FILE_TYPE_CHUNKING_RULES || '');}@@ -47,6 +46,9 @@ export class ContentChunk {}}} catch (error) {+ // A limit every service meets on the same bytes (input size, xlsx ZIP structure) would+ // refuse the next one too. One service's own failure leaves the next one its turn.+ if (isSharedLimitFailure(error)) throw error;// If this is the last service, throw the errorif (service === services.at(-1)) throw error;// Otherwise continue to next service@@ -63,7 +65,9 @@ export class ContentChunk {}private chunkByDefault = async (filename: string, content: Uint8Array): Promise<ChunkResult> => {- const res = await this.chunkingClient.partitionContent(filename, content);+ // Parsing and splitting run on the shared worker; this thread keeps the routing and the+ // result mapping (and, in ChunkService, every database write).+ const res = await chunkContentInWorker(filename, content);const documents = res.map((item, index) => ({id: item.id,diff --git a/apps/server/src/routers/async/__tests__/file.test.ts b/apps/server/src/routers/async/__tests__/file.test.tsindex ff9bd1332a5..aad4020c202 100644--- a/apps/server/src/routers/async/__tests__/file.test.ts+++ b/apps/server/src/routers/async/__tests__/file.test.ts@@ -1,5 +1,6 @@// @vitest-environment nodeimport { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';+import { FileParseBudgetError } from '@lobechat/file-loaders';import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -10,6 +11,8 @@ 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 { FileParseError } from '@/server/services/fileParse/errors';+import { normalizeParseFileError } from '@/server/services/fileParse/normalizeError';import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';import { fileRouter } from '../file';@@ -437,3 +440,208 @@ describe('fileRouter.parseFileToChunks — NoSuchKey + internal:// branches', ()});});});++describe('fileRouter.parseFileToChunks — document parse fallback and late persistence', () => {+ const userId = 'user_test';+ let asyncTaskModelMock: any;+ let chunkModelMock: any;+ let chunkServiceMock: any;+ let documentServiceMock: any;+ let caller: ReturnType<typeof fileRouter.createCaller>;++ beforeEach(() => {+ vi.clearAllMocks();+ asyncTaskModelMock = { findById: vi.fn().mockResolvedValue({ id: 'task' }), update: vi.fn() };+ chunkModelMock = { bulkCreate: vi.fn(), bulkCreateUnstructuredChunks: vi.fn() };+ chunkServiceMock = {+ asyncEmbeddingFileChunks: vi.fn(),+ chunkContent: vi.fn().mockResolvedValue({+ chunks: [{ index: 0, text: 'hello', type: 'DocumentChunk' }],+ }),+ };+ documentServiceMock = { parseFile: vi.fn() };+ const fileModelMock = {+ findById: vi.fn().mockResolvedValue({+ fileType: 'application/vnd.ms-excel',+ id: 'file',+ name: 'book.xlsx',+ size: 10,+ url: 'https://example.com/book.xlsx',+ }),+ };++ vi.mocked(AsyncTaskModel).mockImplementation(function () {+ return asyncTaskModelMock;+ });+ vi.mocked(FileModel).mockImplementation(function () {+ return fileModelMock as any;+ });+ vi.mocked(FileService).mockImplementation(function () {+ return { getFileByteArray: vi.fn().mockResolvedValue(new Uint8Array([1])) } as any;+ });+ vi.mocked(ChunkService).mockImplementation(function () {+ return chunkServiceMock;+ });+ vi.mocked(DocumentService).mockImplementation(function () {+ return documentServiceMock;+ });+ vi.mocked(ChunkModel).mockImplementation(function () {+ return chunkModelMock;+ });+ vi.mocked(EmbeddingModel).mockImplementation(function () {+ return {} as any;+ });+ Reflect.set(FileModel, 'getFileById', undefined);+ caller = fileRouter.createCaller({ serverDB: {}, userId } as any);+ });++ const run = () => caller.parseFileToChunks({ fileId: 'file', taskId: 'task_v' });++ it.each([+ [+ 'the input size cap',+ () => normalizeParseFileError(new FileParseError('INPUT_TOO_LARGE', 'too big')),+ ],+ [+ 'the xlsx ZIP structure budget',+ () => normalizeParseFileError(new FileParseBudgetError('zip-expansion', 1, 2)),+ ],+ ])('does not run the chunk parse a second time after %s refused the file', async (_, failure) => {+ documentServiceMock.parseFile.mockRejectedValue(failure());++ await expect(run()).resolves.toMatchObject({ success: false });++ // the chunk job reads the same bytes under the same limit: it would be refused too+ expect(chunkServiceMock.chunkContent).not.toHaveBeenCalled();+ expect(chunkModelMock.bulkCreate).not.toHaveBeenCalled();+ expect(asyncTaskModelMock.update).toHaveBeenLastCalledWith(+ 'task_v',+ expect.objectContaining({+ error: expect.objectContaining({ name: AsyncTaskErrorType.FileTooLargeToParse }),+ status: AsyncTaskStatus.Error,+ }),+ );+ expect(asyncTaskModelMock.update).not.toHaveBeenCalledWith(+ 'task_v',+ expect.objectContaining({ status: AsyncTaskStatus.Success }),+ );+ });++ it.each([+ [+ 'a document parser that cannot read the file',+ () => normalizeParseFileError(new FileParseError('LOAD_FAILED', 'no usable pages')),+ ],+ [+ 'a corrupt file for the document parser',+ () => normalizeParseFileError(new FileParseError('PARSE_FAILED', 'bad pdf')),+ ],+ [+ 'the document parser sheet-cells budget, which the chunk loader does not apply',+ () => normalizeParseFileError(new FileParseBudgetError('sheet-cells', 5_000_000, 6_000_000)),+ ],+ [+ 'a document parse timeout',+ () => normalizeParseFileError(new FileParseError('TIMEOUT', 'too slow')),+ ],+ [+ 'a document parse out of memory',+ () => normalizeParseFileError(new FileParseError('OUT_OF_MEMORY', 'heap limit')),+ ],+ ['a busy parse queue', () => normalizeParseFileError(new FileParseError('QUEUE_FULL', 'busy'))],+ ['an unrelated error', () => new Error('document db unavailable')],+ ])('still chunks after %s, and the task succeeds with those chunks', async (_, failure) => {+ documentServiceMock.parseFile.mockRejectedValue(failure());++ await expect(run()).resolves.toEqual({ success: true });++ expect(chunkServiceMock.chunkContent).toHaveBeenCalledTimes(1);+ expect(chunkModelMock.bulkCreate).toHaveBeenCalledWith(+ [expect.objectContaining({ index: 0 })],+ 'file',+ );+ expect(asyncTaskModelMock.update).toHaveBeenLastCalledWith(+ 'task_v',+ expect.objectContaining({ status: AsyncTaskStatus.Success }),+ );+ expect(asyncTaskModelMock.update).not.toHaveBeenCalledWith(+ 'task_v',+ expect.objectContaining({ status: AsyncTaskStatus.Error }),+ );+ });++ it('records an error when the document parser and the chunk parser both fail', async () => {+ documentServiceMock.parseFile.mockRejectedValue(+ normalizeParseFileError(new FileParseError('LOAD_FAILED', 'no usable pages')),+ );+ chunkServiceMock.chunkContent.mockRejectedValue(+ new FileParseError('PARSE_FAILED', 'cannot split'),+ );++ await expect(run()).resolves.toMatchObject({ success: false });++ expect(chunkServiceMock.chunkContent).toHaveBeenCalledTimes(1);+ expect(chunkModelMock.bulkCreate).not.toHaveBeenCalled();+ expect(asyncTaskModelMock.update).toHaveBeenLastCalledWith(+ 'task_v',+ expect.objectContaining({ status: AsyncTaskStatus.Error }),+ );+ expect(asyncTaskModelMock.update).not.toHaveBeenCalledWith(+ 'task_v',+ expect.objectContaining({ status: AsyncTaskStatus.Success }),+ );+ });++ it('records a deterministic chunking failure as the task error and never as a success', async () => {+ chunkServiceMock.chunkContent.mockRejectedValue(+ new FileParseError('OUTPUT_TOO_LARGE', 'too many chunks'),+ );++ await expect(run()).resolves.toMatchObject({ success: false });++ expect(chunkModelMock.bulkCreate).not.toHaveBeenCalled();+ expect(asyncTaskModelMock.update).toHaveBeenLastCalledWith(+ 'task_v',+ expect.objectContaining({+ error: expect.objectContaining({ name: AsyncTaskErrorType.FileTooLargeToParse }),+ status: AsyncTaskStatus.Error,+ }),+ );+ });++ it('writes nothing once the task has timed out, however late the chunking finishes', async () => {+ vi.useFakeTimers();+ try {+ let finish!: () => void;+ chunkServiceMock.chunkContent.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = () => resolve({ chunks: [{ index: 0, text: 'late', type: 'DocumentChunk' }] });+ }),+ );++ const running = run();+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);+ await expect(running).resolves.toMatchObject({ success: false });+ expect(asyncTaskModelMock.update).toHaveBeenLastCalledWith(+ 'task_v',+ expect.objectContaining({+ error: expect.objectContaining({ name: AsyncTaskErrorType.Timeout }),+ status: AsyncTaskStatus.Error,+ }),+ );++ finish();+ await vi.advanceTimersByTimeAsync(0);++ expect(chunkModelMock.bulkCreate).not.toHaveBeenCalled();+ expect(asyncTaskModelMock.update).not.toHaveBeenCalledWith(+ 'task_v',+ expect.objectContaining({ status: AsyncTaskStatus.Success }),+ );+ expect(chunkServiceMock.asyncEmbeddingFileChunks).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/apps/server/src/routers/async/file.ts b/apps/server/src/routers/async/file.tsindex e4f1e2d6ad6..74ddae92e32 100644--- a/apps/server/src/routers/async/file.ts+++ b/apps/server/src/routers/async/file.ts@@ -21,6 +21,7 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { ChunkService } from '@/server/services/chunk';import { DocumentService } from '@/server/services/document';import { FileService } from '@/server/services/file';+import { isSharedLimitFailure, toAsyncTaskErrorType } from '@/server/services/fileParse/failure';import { type IAsyncTaskError } from '@/types/asyncTask';import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';import { safeParseJSON } from '@/utils/safeParseJSON';@@ -49,10 +50,10 @@ const fileProcedure = asyncAuthedProcedure.use(async (opts) => {});/**- * Parsing and splitting a file is synchronous CPU work on this process' event loop, and every- * running task keeps a whole file (up to MAX_FILE_PARSE_SIZE) in memory. A folder upload fires- * one task per file at once, so they queue here instead of all running together and starving- * every other request served by this process.+ * Parsing and splitting run on the file-parse worker thread (one at a time per process), but every+ * running task still keeps a whole file (up to MAX_FILE_PARSE_SIZE) in memory here. A folder+ * upload fires one task per file at once, so they queue here instead of all running together and+ * starving every other request served by this process.*/const PARSE_CONCURRENCY = 2;let activeParses = 0;@@ -372,8 +373,13 @@ export const fileRouter = router({try {const startAt = Date.now();+ // Once the wait has given up the task is recorded as failed: the work behind it must not+ // write chunks or a success status over that afterwards.+ let expired = false;+ let timeoutTimer: NodeJS.Timeout | undefined;const timeoutPromise = new Promise((_, reject) => {- setTimeout(() => {+ timeoutTimer = setTimeout(() => {+ expired = true;reject(new AsyncTaskError(AsyncTaskErrorType.Timeout,@@ -382,6 +388,14 @@ export const fileRouter = router({);}, ASYNC_TASK_TIMEOUT);});+ const assertNotExpired = () => {+ if (expired) {+ throw new AsyncTaskError(+ AsyncTaskErrorType.Timeout,+ 'chunking task is timeout, please try again',+ );+ }+ };const chunkingPromise = async () => {// The task was created before it queued for a slot, and the stale-task watchdog@@ -397,6 +411,11 @@ export const fileRouter = router({try {await documentService.parseFile(input.fileId);} catch (e) {+ // A limit the chunking applies to the same bytes (input size, xlsx ZIP structure)+ // would refuse it again: stop here. Any other failure is this parser's own (the+ // document view reads with other libraries than the chunk loader), so chunking+ // still gets its chance and a failure there is what the task records.+ if (isSharedLimitFailure(e)) throw e;// document parsing failure should not block chunkingconsole.warn('[parseFileToChunks] document parsing failed, continuing with chunking:',@@ -411,6 +430,8 @@ export const fileRouter = router({filename: file.name,});+ assertNotExpired();+// after finish partition, we need to filter out some elementsconst chunks = chunkResult.chunks.map(({ text, ...item }): NewChunkItem => ({...item,@@ -430,6 +451,7 @@ export const fileRouter = router({};}+ assertNotExpired();await chunkModel.bulkCreate(chunks, input.fileId);if (chunkResult.unstructuredChunks) {@@ -445,6 +467,7 @@ export const fileRouter = router({}// update the task status to success+ assertNotExpired();await asyncTaskModel.update(input.taskId, {duration,status: AsyncTaskStatus.Success,@@ -465,7 +488,11 @@ export const fileRouter = router({// so the slot stays taken until it is really done.const chunking = chunkingPromise();slot.holdUntil(chunking);- return await Promise.race([chunking, timeoutPromise]);+ try {+ return await Promise.race([chunking, timeoutPromise]);+ } finally {+ clearTimeout(timeoutTimer);+ }} catch (e) {const error = e as any;@@ -474,7 +501,7 @@ export const fileRouter = router({body: safeParseJSON(error.body) ?? error.body,name: error.name,} as IAsyncTaskError)- : new AsyncTaskError((error as Error).name, error.message);+ : new AsyncTaskError(toAsyncTaskErrorType(e) ?? (error as Error).name, error.message);console.error('[Chunking Error]', asyncTaskError);await asyncTaskModel.update(input.taskId, {diff --git a/apps/server/src/routers/lambda/agentEval/datasets.parseLimit.test.ts b/apps/server/src/routers/lambda/agentEval/datasets.parseLimit.test.tsnew file mode 100644index 00000000000..e5d58161936--- /dev/null+++ b/apps/server/src/routers/lambda/agentEval/datasets.parseLimit.test.ts@@ -0,0 +1,90 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import { MAX_FILE_PARSE_SIZE } from '@/const/file';++import { datasetRouter } from './datasets';++const parseDatasetInWorker = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/fileParse', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ parseDatasetInWorker,+}));+vi.mock('./procedures', async () => {+ // Pass-through procedures: the auth chain is not what is under test.+ const { initTRPC } = await import('@trpc/server');+ const t = initTRPC.context<object>().create();+ return { agentEvalProcedure: t.procedure, agentEvalProcedureWrite: t.procedure };+});+vi.mock('@/libs/trpc/lambda', async () => {+ const { initTRPC } = await import('@trpc/server');+ return { router: initTRPC.context<object>().create().router };+});++const makeCtx = (contentLength: number) => ({+ fileService: {+ getFileByteArray: vi.fn().mockResolvedValue(new Uint8Array([1])),+ getFileContent: vi.fn().mockResolvedValue('a,b\n1,2'),+ getFileMetadata: vi.fn().mockResolvedValue({ contentLength }),+ },+ fileUploadService: {+ assertActiveOrLegacy: vi.fn().mockResolvedValue(undefined),+ releaseBestEffort: vi.fn(),+ },+});++describe('dataset parse routes and the parse size cap', () => {+ const caller = (ctx: object) => datasetRouter.createCaller(ctx as never);++ it.each([+ [+ 'parseDatasetFile',+ (c: ReturnType<typeof caller>) => c.parseDatasetFile({ pathname: 'p.xlsx', format: 'xlsx' }),+ ],+ [+ 'importDataset',+ (c: ReturnType<typeof caller>) =>+ c.importDataset({+ datasetId: 'd',+ fieldMapping: { input: 'a' },+ filename: 'big.xlsx',+ pathname: 'p.xlsx',+ }),+ ],+ ])('%s refuses an oversized upload before reading or cloning its bytes', async (_, call) => {+ const ctx = makeCtx(MAX_FILE_PARSE_SIZE + 1);++ const error = await call(caller(ctx)).catch((e: unknown) => e);++ expect(error).toMatchObject({ code: 'BAD_REQUEST' });+ expect((error as Error).message).toContain('cannot be parsed in memory');+ expect(ctx.fileService.getFileByteArray).not.toHaveBeenCalled();+ expect(ctx.fileService.getFileContent).not.toHaveBeenCalled();+ expect(parseDatasetInWorker).not.toHaveBeenCalled();+ });++ it('releases the claimed upload when parseDatasetFile refuses an oversized file', async () => {+ const ctx = makeCtx(MAX_FILE_PARSE_SIZE + 1);+ ctx.fileUploadService.assertActiveOrLegacy.mockResolvedValue({ id: 'upload' });++ await expect(+ caller(ctx).parseDatasetFile({ pathname: 'p.csv', format: 'csv' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ expect(ctx.fileUploadService.releaseBestEffort).toHaveBeenCalledWith('p.csv');+ });++ it('reads and parses a dataset within the cap on the worker', async () => {+ const ctx = makeCtx(MAX_FILE_PARSE_SIZE);+ parseDatasetInWorker.mockResolvedValue({+ format: 'csv',+ headers: ['a'],+ rows: [],+ totalCount: 0,+ });++ await caller(ctx).parseDatasetFile({ pathname: 'p.csv', format: 'csv' });++ expect(parseDatasetInWorker).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/routers/lambda/agentEval/datasets.parseRetry.test.ts b/apps/server/src/routers/lambda/agentEval/datasets.parseRetry.test.tsnew file mode 100644index 00000000000..1973e670a55--- /dev/null+++ b/apps/server/src/routers/lambda/agentEval/datasets.parseRetry.test.ts@@ -0,0 +1,147 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { FileParseError } from '@/server/services/fileParse';++import { datasetRouter } from './datasets';++const parseDatasetInWorker = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/fileParse', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ parseDatasetInWorker,+}));+vi.mock('./procedures', async () => {+ // Pass-through procedures: the auth chain is not what is under test.+ const { initTRPC } = await import('@trpc/server');+ const t = initTRPC.context<object>().create();+ return { agentEvalProcedure: t.procedure, agentEvalProcedureWrite: t.procedure };+});+vi.mock('@/libs/trpc/lambda', async () => {+ const { initTRPC } = await import('@trpc/server');+ return { router: initTRPC.context<object>().create().router };+});++const PATHNAME = 'eval/upload.csv';+const PARSED = { format: 'csv', headers: ['q'], rows: [{ q: 'hi' }], totalCount: 1 };++/** An upload session that behaves like the real one: once released, the same pathname is gone. */+const makeCtx = () => {+ let active = true;+ const ctx = {+ fileService: {+ deleteFile: vi.fn(),+ getFileByteArray: vi.fn().mockResolvedValue(new Uint8Array([1])),+ getFileContent: vi.fn().mockResolvedValue('q\nhi'),+ getFileMetadata: vi.fn().mockResolvedValue({ contentLength: 4 }),+ },+ fileUploadService: {+ assertActiveOrLegacy: vi.fn(async () => {+ if (!active) throw new TRPCError({ code: 'CONFLICT', message: 'no longer active' });+ return { id: 'upload' };+ }),+ releaseBestEffort: vi.fn(async () => {+ active = false;+ }),+ },+ testCaseModel: {+ batchCreate: vi.fn(async (rows: unknown[]) => rows),+ countByDatasetId: vi.fn().mockResolvedValue(0),+ },+ };+ return { ctx, isActive: () => active };+};++type Caller = ReturnType<typeof datasetRouter.createCaller>;+const entries: Array<[string, (c: Caller) => Promise<unknown>]> = [+ ['parseDatasetFile', (c) => c.parseDatasetFile({ format: 'csv', pathname: PATHNAME })],+ [+ 'importDataset',+ (c) => c.importDataset({ datasetId: 'd', fieldMapping: { input: 'q' }, pathname: PATHNAME }),+ ],+];++/** Same name and code, different class: what another bundle copy of FileParseError looks like. */+const otherCopyError = (code: string) =>+ Object.assign(new Error(`${code} from another copy`), { code, name: 'FileParseError' });++describe.each(entries)('%s with the shared parse worker', (_, call) => {+ const caller = (ctx: object) => datasetRouter.createCaller(ctx as never);++ beforeEach(() => parseDatasetInWorker.mockReset());++ it.each([+ ['QUEUE_FULL', 'TOO_MANY_REQUESTS'],+ ['QUEUE_TIMEOUT', 'TOO_MANY_REQUESTS'],+ ['UNAVAILABLE', 'SERVICE_UNAVAILABLE'],+ ['START_FAILED', 'SERVICE_UNAVAILABLE'],+ ['WORKER_FAILED', 'SERVICE_UNAVAILABLE'],+ ] as const)(+ 'keeps the upload and answers a retryable %s as %s, then the same pathname succeeds',+ async (fileParseCode, trpcCode) => {+ const { ctx, isActive } = makeCtx();+ parseDatasetInWorker.mockRejectedValueOnce(new FileParseError(fileParseCode, 'busy'));++ const error = await call(caller(ctx)).catch((e: unknown) => e);++ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({ code: trpcCode });+ expect(ctx.fileUploadService.releaseBestEffort).not.toHaveBeenCalled();+ expect(ctx.fileService.deleteFile).not.toHaveBeenCalled();+ expect(ctx.testCaseModel.batchCreate).not.toHaveBeenCalled();+ expect(isActive()).toBe(true);++ parseDatasetInWorker.mockResolvedValueOnce(PARSED);+ await expect(call(caller(ctx))).resolves.toBeTruthy();+ expect(parseDatasetInWorker).toHaveBeenCalledTimes(2);+ },+ );++ it('recognises a retryable error from another module copy by name and code', async () => {+ const { ctx, isActive } = makeCtx();+ parseDatasetInWorker.mockRejectedValueOnce(otherCopyError('QUEUE_TIMEOUT'));++ const error = await call(caller(ctx)).catch((e: unknown) => e);++ expect(error).toMatchObject({ code: 'TOO_MANY_REQUESTS' });+ expect(ctx.fileUploadService.releaseBestEffort).not.toHaveBeenCalled();+ expect(isActive()).toBe(true);+ });++ it.each([+ new FileParseError('PARSE_FAILED', 'bad csv'),+ new FileParseError('LOAD_FAILED', 'nothing usable'),+ new FileParseError('OUTPUT_TOO_LARGE', 'too big'),+ new FileParseError('TIMEOUT', 'too slow'),+ new FileParseError('OUT_OF_MEMORY', 'heap'),+ otherCopyError('PARSE_FAILED'),+ new Error('plain parser failure'),+ ])('still releases the upload and rejects a deterministic failure (%s)', async (failure) => {+ const { ctx, isActive } = makeCtx();+ parseDatasetInWorker.mockRejectedValueOnce(failure);++ const error = await call(caller(ctx)).catch((e: unknown) => e);++ expect(error).toMatchObject({ code: 'BAD_REQUEST' });+ expect((error as Error).message).toContain('Failed to parse file');+ expect(ctx.fileUploadService.releaseBestEffort).toHaveBeenCalledWith(PATHNAME);+ expect(ctx.testCaseModel.batchCreate).not.toHaveBeenCalled();+ expect(isActive()).toBe(false);+ });+});++describe('importDataset consumes the upload only on success', () => {+ it('imports the rows and releases the upload once', async () => {+ const { ctx, isActive } = makeCtx();+ parseDatasetInWorker.mockReset().mockResolvedValue(PARSED);++ const result = await datasetRouter+ .createCaller(ctx as never)+ .importDataset({ datasetId: 'd', fieldMapping: { input: 'q' }, pathname: PATHNAME });++ expect(result.count).toBe(1);+ expect(ctx.testCaseModel.batchCreate).toHaveBeenCalledTimes(1);+ expect(ctx.fileUploadService.releaseBestEffort).toHaveBeenCalledTimes(1);+ expect(isActive()).toBe(false);+ });+});diff --git a/apps/server/src/routers/lambda/agentEval/datasets.ts b/apps/server/src/routers/lambda/agentEval/datasets.tsindex 9daf3bbf451..3933890660b 100644--- a/apps/server/src/routers/lambda/agentEval/datasets.ts+++ b/apps/server/src/routers/lambda/agentEval/datasets.ts@@ -1,9 +1,15 @@-import { parseDataset } from '@lobechat/eval-dataset-parser';+import type { ParseResult } from '@lobechat/eval-dataset-parser';import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE, MAX_FILE_PARSE_SIZE } from '@/const/file';import { AgentEvalDatasetWriteError } from '@/database/models/agentEval/datasetAccess';import { router } from '@/libs/trpc/lambda';+import type { FileService } from '@/server/services/file';+import { FileParseError, parseDatasetInWorker } from '@/server/services/fileParse';+import { isFileParseError } from '@/server/services/fileParse/errors';+import { isDeterministicParseFailure } from '@/server/services/fileParse/failure';+import { normalizeParseFileError } from '@/server/services/fileParse/normalizeError';import {importDatasetPackageProcedure,@@ -14,6 +20,38 @@ import { assertDatasetDeletable, assertDatasetMove } from './lobeBenchMembershipimport { agentEvalProcedure, agentEvalProcedureWrite } from './procedures';import { evalConfigSchema, evalTestCaseContentSchema, rubricTypeSchema } from './schemas';+/**+ * Refuses a stored upload larger than the in-memory parse cap by its stored size, before the+ * bytes are fetched: a few hundred MiB would otherwise be read, then cloned into the parse thread.+ */+const assertWithinParseLimit = async (fileService: FileService, pathname: string) => {+ const { contentLength } = await fileService.getFileMetadata(pathname);+ if (contentLength > MAX_FILE_PARSE_SIZE) {+ throw new FileParseError('INPUT_TOO_LARGE', FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE);+ }+};++/**+ * A parse failure that is the worker's state, not the file's (queue full or timed out, artifact+ * missing, thread could not start or died): the same upload can parse later, so it is kept.+ */+const isRetryableParseFailure = (error: unknown) =>+ isFileParseError(error) && !isDeterministicParseFailure(error);++/** Retryable: 429 when busy, 503 otherwise. Anything else is a bad file, as before. */+const toParseRequestError = (error: any) => {+ if (!isRetryableParseFailure(error)) {+ return new TRPCError({+ code: 'BAD_REQUEST',+ message: `Failed to parse file: ${error.message}`,+ });+ }+ const mapped = normalizeParseFileError(error) as TRPCError;+ return mapped.code === 'INTERNAL_SERVER_ERROR'+ ? new TRPCError({ cause: error, code: 'SERVICE_UNAVAILABLE', message: error.message })+ : mapped;+};+export const datasetRouter = router({importDatasetPackage: importDatasetPackageProcedure,// ============================================@@ -174,6 +212,19 @@ export const datasetRouter = router({const archive = isZip? await readDatasetPackageUpload(ctx.fileService, input.pathname): undefined;+ if (!archive) {+ try {+ await assertWithinParseLimit(ctx.fileService, input.pathname);+ } catch (error) {+ // A storage failure is not a user validation error; only the size refusal is.+ if (!(error instanceof FileParseError)) throw error;+ if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Failed to parse file: ${error.message}`,+ });+ }+ }const content =archive ??(isXlsx@@ -184,7 +235,7 @@ export const datasetRouter = router({if (archive) {return previewDatasetPackage(archive);}- const result = parseDataset(content, {+ const result = await parseDatasetInWorker<ParseResult>(content, {filename: resolvedFilename,format: format === 'auto' || format === 'zip' ? undefined : format,preview: 50,@@ -198,11 +249,11 @@ export const datasetRouter = router({datasetPackage: undefined,};} catch (error: any) {- if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Failed to parse file: ${error.message}`,- });+ // A busy or unavailable worker keeps the upload so the same pathname can be retried.+ if (upload && !isRetryableParseFailure(error)) {+ await ctx.fileUploadService.releaseBestEffort(input.pathname);+ }+ throw toParseRequestError(error);}}),importDataset: agentEvalProcedureWrite@@ -226,6 +277,7 @@ export const datasetRouter = router({.mutation(async ({ input, ctx }) => {const upload = await ctx.fileUploadService.assertActiveOrLegacy(input.pathname);let imported = false;+ let keepUpload = false;try {const format = input.format || 'auto';@@ -234,18 +286,17 @@ export const datasetRouter = router({let parsed;try {+ await assertWithinParseLimit(ctx.fileService, input.pathname);const content = isXlsx? await ctx.fileService.getFileByteArray(input.pathname): await ctx.fileService.getFileContent(input.pathname);- parsed = parseDataset(content, {+ parsed = await parseDatasetInWorker<ParseResult>(content, {filename: resolvedFilename,format: format === 'auto' ? undefined : format,});} catch (error: any) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Failed to parse file: ${error.message}`,- });+ keepUpload = isRetryableParseFailure(error);+ throw toParseRequestError(error);}const { fieldMapping } = input;@@ -327,8 +378,9 @@ export const datasetRouter = router({}throw error;} finally {- if (upload) await ctx.fileUploadService.releaseBestEffort(input.pathname);- else if (imported) await ctx.fileService.deleteFile(input.pathname);+ if (upload) {+ if (!keepUpload) await ctx.fileUploadService.releaseBestEffort(input.pathname);+ } else if (imported) await ctx.fileService.deleteFile(input.pathname);}}),});diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.tsindex df984f6102b..8e6113f3ba4 100644--- a/apps/server/src/services/document/__tests__/index.test.ts+++ b/apps/server/src/services/document/__tests__/index.test.ts@@ -12,7 +12,8 @@ import { EditLockService } from '../../editLock';import { FileService } from '../../file';import { publishResourceEvent } from '../../resourceEvents';import { DocumentHistoryService } from '../history';-import { capParsedFileDocument, DocumentService, PARSED_FILE_CONTENT_MAX_CHARS } from '../index';+import { DocumentService } from '../index';+import { PARSED_FILE_CONTENT_MAX_CHARS } from '../parsedFileCap';vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));vi.mock('@/database/models/document');@@ -26,6 +27,8 @@ vi.mock('../../resourceEvents', () => ({ publishResourceEvent: vi.fn() }));const publishResourceEventMock = vi.mocked(publishResourceEvent);vi.mock('@lobechat/file-loaders', () => ({+ isFileParseBudgetError: (error: unknown) =>+ error instanceof Error && error.name === 'FileParseBudgetError',loadFile: vi.fn(),UnsupportedFileTypeError: class UnsupportedFileTypeError extends Error {fileType: string;@@ -37,6 +40,18 @@ vi.mock('@lobechat/file-loaders', () => ({}},}));+// The worker-thread boundary. Real threads are covered by `fileParse/*.test.ts`; here the same+// pure steps run in-process so these cases keep asserting how the service uses the result.+vi.mock('../../fileParse', async () => {+ const { loadFile } = await import('@lobechat/file-loaders');+ const { capParsedFileDocument, stripPageWrappers } = await import('../parsedFileCap');+ return {+ parseFileInWorker: vi.fn(async (filePath: string, { mode }: { mode: 'document' | 'file' }) => {+ const loaded = await loadFile(filePath);+ return capParsedFileDocument(mode === 'document' ? stripPageWrappers(loaded) : loaded);+ }),+ };+});vi.mock('debug', () => ({default: () => vi.fn(),}));@@ -2050,7 +2065,13 @@ describe('DocumentService', () => {await service.parseFile('file-visitor', accessScope);expect(mockDocumentModel.findByFileId).toHaveBeenCalledWith('file-visitor', accessScope);- expect(mockFileService.downloadFileToLocal).toHaveBeenCalledWith('file-visitor', accessScope);+ expect(mockFileService.downloadFileToLocal).toHaveBeenCalledWith(+ 'file-visitor',+ accessScope,+ {+ maxBytes: 64 * 1024 * 1024,+ },+ );});it('should use file name as title (stripping extension) when metadata has no title', async () => {@@ -2226,72 +2247,3 @@ describe('DocumentService', () => {});});});--describe('capParsedFileDocument', () => {- const fileDocument = (content: string, fileType = 'txt') =>- ({- content,- fileType,- filename: 'big.txt',- metadata: { source: 'big.txt' },- pages: [{ charCount: content.length, lineCount: 1, metadata: {}, pageContent: content }],- totalCharCount: content.length,- totalLineCount: 1,- }) as unknown as Parameters<typeof capParsedFileDocument>[0];-- it('keeps parsed text within the limit untouched', () => {- const input = fileDocument('hello');-- expect(capParsedFileDocument(input)).toBe(input);- });-- it('does not split a surrogate pair at the cap', () => {- const content = `${'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 1)}🐛`;- const result = capParsedFileDocument(fileDocument(content));-- expect(result.content).toBe('a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 1));- });-- it('closes a PDF page cut by the cap without exceeding it', () => {- const page = (n: number, body: string) => `<page pageNumber="${n}">\n${body}\n</page>\n`;- const content = page(1, 'first') + page(2, 'b'.repeat(PARSED_FILE_CONTENT_MAX_CHARS));- const result = capParsedFileDocument(fileDocument(content, 'pdf'));-- expect(result.content.startsWith(page(1, 'first'))).toBe(true);- expect(result.content.endsWith('b\n</page>')).toBe(true);- expect(result.content.length).toBeLessThanOrEqual(PARSED_FILE_CONTENT_MAX_CHARS);- expect(result.content.match(/<page /g)).toHaveLength(2);- expect(result.content.match(/<\/page>/g)).toHaveLength(2);- });-- it('drops a page opening tag cut by the cap', () => {- const first = `<page pageNumber="1">\n${'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 40)}\n</page>\n`;- const result = capParsedFileDocument(- fileDocument(`${first}<page pageNumber="2">\nsecond\n</page>`, 'pdf'),- );-- expect(result.content).toBe(first.trimEnd());- });-- it('leaves a literal page tag in non-PDF text untouched', () => {- const content = `<page title="example">\n${'c'.repeat(PARSED_FILE_CONTENT_MAX_CHARS)}`;- const result = capParsedFileDocument(fileDocument(content));-- expect(result.content).toBe(content.slice(0, PARSED_FILE_CONTENT_MAX_CHARS));- });-- it('truncates oversized parsed text and drops the duplicated pages', () => {- const originalLength = PARSED_FILE_CONTENT_MAX_CHARS + 10;- const result = capParsedFileDocument(fileDocument(`${'a\n'.repeat(originalLength / 2)}`));-- expect(result.content).toHaveLength(PARSED_FILE_CONTENT_MAX_CHARS);- expect(result.pages).toBeUndefined();- expect(result.totalCharCount).toBe(PARSED_FILE_CONTENT_MAX_CHARS);- expect(result.totalLineCount).toBe(PARSED_FILE_CONTENT_MAX_CHARS / 2 + 1);- expect(result.metadata).toMatchObject({- originalCharCount: originalLength,- source: 'big.txt',- truncated: true,- });- });-});diff --git a/apps/server/src/services/document/__tests__/parseWorker.test.ts b/apps/server/src/services/document/__tests__/parseWorker.test.tsnew file mode 100644index 00000000000..77ef5d2d21d--- /dev/null+++ b/apps/server/src/services/document/__tests__/parseWorker.test.ts@@ -0,0 +1,179 @@+import { type LobeChatDatabase } from '@lobechat/database';+import { FileParseBudgetError } from '@lobechat/file-loaders';+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { DocumentModel } from '@/database/models/document';+import { FileModel } from '@/database/models/file';+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';++import { FileService } from '../../file';+import { FileParseError, parseFileInWorker } from '../../fileParse';+import { DocumentService } from '../index';++vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));+vi.mock('@/database/models/document');+vi.mock('@/database/models/file');+vi.mock('@/database/models/knowledgeBase');+vi.mock('../../file');+vi.mock('../history');+vi.mock('../../resourceEvents', () => ({ publishResourceEvent: vi.fn() }));+vi.mock('../../fileParse', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ parseFileInWorker: vi.fn(),+}));++describe('DocumentService parsing through the worker boundary', () => {+ const createdDocument = vi.fn();+ const downloadFileToLocal = vi.fn();+ let cleanupFinished: boolean;+ let service: DocumentService;++ beforeEach(() => {+ vi.resetAllMocks();+ cleanupFinished = false;+ createdDocument.mockResolvedValue({ id: 'doc-1' });++ vi.mocked(DocumentModel).mockImplementation(function () {+ return { create: createdDocument, findByFileId: vi.fn().mockResolvedValue(null) } as never;+ });+ vi.mocked(FileModel).mockImplementation(function () {+ return {} as never;+ });+ vi.mocked(KnowledgeBaseModel).mockImplementation(function () {+ return {} as never;+ });+ vi.mocked(FileService).mockImplementation(function () {+ return { downloadFileToLocal } as never;+ });++ downloadFileToLocal.mockResolvedValue({+ // The temp directory is removed asynchronously: the service must wait for it.+ cleanup: async () => {+ await new Promise((resolve) => setTimeout(resolve, 20));+ cleanupFinished = true;+ },+ file: { name: 'report.xlsx', parentId: null, url: 's3://bucket/report.xlsx' },+ filePath: '/tmp/x/report.xlsx',+ });++ const db = {+ transaction: vi.fn(async (callback: (tx: LobeChatDatabase) => Promise<unknown>) =>+ callback({ execute: vi.fn() } as never),+ ),+ } as never;+ service = new DocumentService(db, 'user-1');+ });++ it.each([+ ['QUEUE_FULL', 'TOO_MANY_REQUESTS'],+ ['QUEUE_TIMEOUT', 'TOO_MANY_REQUESTS'],+ ['TIMEOUT', 'TIMEOUT'],+ ['UNAVAILABLE', 'SERVICE_UNAVAILABLE'],+ ['LOAD_FAILED', 'UNPROCESSABLE_CONTENT'],+ ['INPUT_TOO_LARGE', 'PAYLOAD_TOO_LARGE'],+ ['WORKER_FAILED', 'INTERNAL_SERVER_ERROR'],+ ])(+ 'maps %s to %s, stores nothing, and finishes cleanup before rejecting',+ async (code, trpcCode) => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(parseFileInWorker).mockRejectedValue(+ new FileParseError(code as never, 'parse failed'),+ );++ for (const parse of [+ () => service.parseFile('file-1'),+ () => service.parseDocument('file-1'),+ ]) {+ cleanupFinished = false;+ const error = await parse().catch((e) => e);++ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({ code: trpcCode });+ expect(cleanupFinished).toBe(true);+ }+ expect(createdDocument).not.toHaveBeenCalled();+ },+ );++ it('parses both entries on the worker with the file id and the matching mode', async () => {+ vi.mocked(parseFileInWorker).mockResolvedValue({+ content: 'text',+ metadata: {},+ totalCharCount: 4,+ totalLineCount: 1,+ } as never);++ await service.parseFile('file-1');+ await service.parseDocument('file-1');++ expect(parseFileInWorker).toHaveBeenNthCalledWith(1, '/tmp/x/report.xlsx', {+ fileId: 'file-1',+ mode: 'file',+ });+ expect(parseFileInWorker).toHaveBeenNthCalledWith(2, '/tmp/x/report.xlsx', {+ fileId: 'file-1',+ mode: 'document',+ });+ expect(cleanupFinished).toBe(true);+ });++ it('maps a budget refusal to a non-500 error that keeps reason, limit and actual as its cause', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const budget = new FileParseBudgetError('sheet-cells', 5_000_000, 52_428_800);+ vi.mocked(parseFileInWorker).mockRejectedValue(budget);++ for (const parse of [+ () => service.parseFile('file-1'),+ () => service.parseDocument('file-1'),+ ]) {+ cleanupFinished = false;+ const error = await parse().catch((e) => e);++ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({ code: 'PAYLOAD_TOO_LARGE' });+ expect(error.cause).toBe(budget);+ expect(error.cause).toMatchObject({+ actual: 52_428_800,+ limit: 5_000_000,+ reason: 'sheet-cells',+ });+ expect(cleanupFinished).toBe(true);+ }+ expect(createdDocument).not.toHaveBeenCalled();+ });++ it('asks the download for the 64 MiB parse cap on both entries and keeps the access scope', async () => {+ vi.mocked(parseFileInWorker).mockResolvedValue({+ content: 'text',+ metadata: {},+ totalCharCount: 4,+ totalLineCount: 1,+ } as never);+ const scope = { kind: 'custom' } as never;++ await service.parseFile('file-1', scope);+ await service.parseDocument('file-2');++ expect(downloadFileToLocal).toHaveBeenNthCalledWith(1, 'file-1', scope, {+ maxBytes: 64 * 1024 * 1024,+ });+ expect(downloadFileToLocal).toHaveBeenNthCalledWith(2, 'file-2', undefined, {+ maxBytes: 64 * 1024 * 1024,+ });+ });++ it('stores nothing and parses nothing when the download refuses an oversized file', async () => {+ downloadFileToLocal.mockRejectedValue(+ new TRPCError({ code: 'PAYLOAD_TOO_LARGE', message: 'too large' }),+ );++ await expect(service.parseFile('file-1')).rejects.toMatchObject({ code: 'PAYLOAD_TOO_LARGE' });+ await expect(service.parseDocument('file-1')).rejects.toMatchObject({+ code: 'PAYLOAD_TOO_LARGE',+ });++ expect(parseFileInWorker).not.toHaveBeenCalled();+ expect(createdDocument).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/document/__tests__/parsedFileCap.test.ts b/apps/server/src/services/document/__tests__/parsedFileCap.test.tsnew file mode 100644index 00000000000..0c1d74b15b9--- /dev/null+++ b/apps/server/src/services/document/__tests__/parsedFileCap.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';++import { capParsedFileDocument, PARSED_FILE_CONTENT_MAX_CHARS } from '../parsedFileCap';++describe('capParsedFileDocument', () => {+ const fileDocument = (content: string, fileType = 'txt') =>+ ({+ content,+ fileType,+ filename: 'big.txt',+ metadata: { source: 'big.txt' },+ pages: [{ charCount: content.length, lineCount: 1, metadata: {}, pageContent: content }],+ totalCharCount: content.length,+ totalLineCount: 1,+ }) as unknown as Parameters<typeof capParsedFileDocument>[0];++ it('keeps parsed text within the limit untouched', () => {+ const input = fileDocument('hello');++ expect(capParsedFileDocument(input)).toBe(input);+ });++ it('does not split a surrogate pair at the cap', () => {+ const content = `${'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 1)}🐛`;+ const result = capParsedFileDocument(fileDocument(content));++ expect(result.content).toBe('a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 1));+ });++ it('closes a PDF page cut by the cap without exceeding it', () => {+ const page = (n: number, body: string) => `<page pageNumber="${n}">\n${body}\n</page>\n`;+ const content = page(1, 'first') + page(2, 'b'.repeat(PARSED_FILE_CONTENT_MAX_CHARS));+ const result = capParsedFileDocument(fileDocument(content, 'pdf'));++ expect(result.content.startsWith(page(1, 'first'))).toBe(true);+ expect(result.content.endsWith('b\n</page>')).toBe(true);+ expect(result.content.length).toBeLessThanOrEqual(PARSED_FILE_CONTENT_MAX_CHARS);+ expect(result.content.match(/<page /g)).toHaveLength(2);+ expect(result.content.match(/<\/page>/g)).toHaveLength(2);+ });++ it('drops a page opening tag cut by the cap', () => {+ const first = `<page pageNumber="1">\n${'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS - 40)}\n</page>\n`;+ const result = capParsedFileDocument(+ fileDocument(`${first}<page pageNumber="2">\nsecond\n</page>`, 'pdf'),+ );++ expect(result.content).toBe(first.trimEnd());+ });++ it('leaves a literal page tag in non-PDF text untouched', () => {+ const content = `<page title="example">\n${'c'.repeat(PARSED_FILE_CONTENT_MAX_CHARS)}`;+ const result = capParsedFileDocument(fileDocument(content));++ expect(result.content).toBe(content.slice(0, PARSED_FILE_CONTENT_MAX_CHARS));+ });++ it('truncates oversized parsed text and drops the duplicated pages', () => {+ const originalLength = PARSED_FILE_CONTENT_MAX_CHARS + 10;+ const result = capParsedFileDocument(fileDocument(`${'a\n'.repeat(originalLength / 2)}`));++ expect(result.content).toHaveLength(PARSED_FILE_CONTENT_MAX_CHARS);+ expect(result.pages).toBeUndefined();+ expect(result.totalCharCount).toBe(PARSED_FILE_CONTENT_MAX_CHARS);+ expect(result.totalLineCount).toBe(PARSED_FILE_CONTENT_MAX_CHARS / 2 + 1);+ expect(result.metadata).toMatchObject({+ originalCharCount: originalLength,+ source: 'big.txt',+ truncated: true,+ });+ });+});diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex 5cd223190fc..2d4ad8ba080 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -8,8 +8,6 @@ import {import { type LobeChatDatabase } from '@lobechat/database';import { type DocumentItem } from '@lobechat/database/schemas';import { documents, files } from '@lobechat/database/schemas';-import { loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';-import { sliceHead } from '@lobechat/prompts/textWindow';import type { DocumentAccessScope, DocumentWriteSource, FileAccessScope } from '@lobechat/types';import {ordinaryDocumentAccessScope,@@ -21,6 +19,7 @@ import debug from 'debug';import { and, eq, sql } from 'drizzle-orm';import isEqual from 'fast-deep-equal';+import { MAX_FILE_PARSE_SIZE } from '@/const/file';import { DocumentModel, type DocumentQuerySortBy } from '@/database/models/document';import { FileModel } from '@/database/models/file';import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';@@ -32,6 +31,8 @@ import { type LobeDocument } from '@/types/document';import { EditLockService } from '../editLock';import { FileService } from '../file';+import { parseFileInWorker } from '../fileParse';+import { normalizeParseFileError } from '../fileParse/normalizeError';import { dropPageRooms } from '../pageCollab/notify';import { publishResourceEvent } from '../resourceEvents';import { countEditorDataText } from './editorData';@@ -53,73 +54,6 @@ import { assertDocumentWriteWithinLimit } from './writeLimit';const log = debug('lobe-chat:service:document');-/**- * Upper bound, in characters, of parsed file text stored in `documents.content`.- *- * Parsing raw CSV exports, logs, or sparse spreadsheets can yield 100+ MiB of text. Rows that large- * slow every read of the document, overflow the model context when attached, and cannot be synced- * to full-text search. The original file stays in storage for tools that process it directly.- */-export const PARSED_FILE_CONTENT_MAX_CHARS = 5_000_000;--type ParsedFileDocument = Awaited<ReturnType<typeof loadFile>>;--const PAGE_CLOSE_TAG = '\n</page>';--/**- * PDF loaders wrap each page in `<page ...>...</page>`. A cut inside a page leaves an opening tag- * with no closing tag (or a half-written tag at the tail), which previews and `readAttachment`- * would expose as malformed markup. Close the cut page, or drop a half-written opening tag, while- * staying within the cap. Page tags are kept rather than stripped so page numbers survive.- */-const closeCutPage = (content: string): string => {- const open = content.lastIndexOf('<page');- if (open === -1 || open < content.lastIndexOf('</page>')) return content;-- const openEnd = content.indexOf('>', open);- if (openEnd === -1) return content.slice(0, open).trimEnd();-- const bodyEnd = Math.max(openEnd + 1, content.length - PAGE_CLOSE_TAG.length);- const body = content.slice(0, bodyEnd).replace(/<\/?(?:p(?:a(?:ge?)?)?)?$/, '');- return `${body}${PAGE_CLOSE_TAG}`;-};--/**- * Truncates oversized parsed text before it is stored. `pages` repeats the full text, so it is- * dropped for truncated documents; `metadata` records the original length.- */-export const capParsedFileDocument = (fileDocument: ParsedFileDocument): ParsedFileDocument => {- if (fileDocument.content.length <= PARSED_FILE_CONTENT_MAX_CHARS) return fileDocument;-- const head = sliceHead(fileDocument.content, PARSED_FILE_CONTENT_MAX_CHARS);- // Only the PDF loader emits page wrappers; other text may contain a literal `<page` to keep.- const content = fileDocument.fileType === 'pdf' ? closeCutPage(head) : head;- return {- ...fileDocument,- content,- metadata: {- ...fileDocument.metadata,- originalCharCount: fileDocument.content.length,- truncated: true,- },- pages: undefined,- totalCharCount: content.length,- totalLineCount: content.split('\n').length,- };-};--const normalizeParseFileError = (error: unknown) => {- if (error instanceof UnsupportedFileTypeError) {- return new TRPCError({- cause: error,- code: 'BAD_REQUEST',- message: error.message,- });- }-- return error;-};-export class DocumentService {userId: string;private fileModel: FileModel;@@ -943,23 +877,18 @@ export class DocumentService {* Parse file and create a document for page editor (without page tags)*/async parseDocument(fileId: string): Promise<LobeDocument> {- const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(fileId);+ const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(+ fileId,+ undefined,+ { maxBytes: MAX_FILE_PARSE_SIZE },+ );const logPrefix = `[${file.name}]`;log(`${logPrefix} Starting to parse file as document, path: ${filePath}`);try {- const loaded = await loadFile(filePath);- // Strip <page> wrappers before capping: a cut inside a page would leave an opening tag with- // no closing tag, which the strip regex can no longer match.- const fileDocument = capParsedFileDocument(- loaded.content.includes('<page')- ? {- ...loaded,- content: loaded.content.replaceAll(/<page[^>]*>([\S\s]*?)<\/page>/g, '$1').trim(),- }- : loaded,- );+ // Strips the <page> wrappers and applies the stored-content cap inside the worker thread.+ const fileDocument = await parseFileInWorker(filePath, { fileId, mode: 'document' });log(`${logPrefix} File parsed successfully %O`, {fileType: fileDocument.fileType,@@ -994,7 +923,7 @@ export class DocumentService {console.error(`${logPrefix} File parsing failed:`, parseError);throw parseError;} finally {- cleanup();+ await cleanup();}}@@ -1019,14 +948,15 @@ export class DocumentService {const { filePath, file, cleanup } = await this.fileService.downloadFileToLocal(fileId,accessScope,+ { maxBytes: MAX_FILE_PARSE_SIZE },);const logPrefix = `[${file.name}]`;log(`${logPrefix} Starting to parse file, path: ${filePath}`);try {- // Use loadFile to load file content- const fileDocument = capParsedFileDocument(await loadFile(filePath));+ // Parsed and capped on a worker thread: a heavy file must not hold this one.+ const fileDocument = await parseFileInWorker(filePath, { fileId, mode: 'file' });log(`${logPrefix} File parsed successfully %O`, {fileType: fileDocument.fileType,@@ -1090,7 +1020,7 @@ export class DocumentService {console.error(`${logPrefix} File parsing failed:`, parseError);throw parseError;} finally {- cleanup();+ await cleanup();}}}diff --git a/apps/server/src/services/document/parsedFileCap.ts b/apps/server/src/services/document/parsedFileCap.tsnew file mode 100644index 00000000000..856e0f3ffdd--- /dev/null+++ b/apps/server/src/services/document/parsedFileCap.ts@@ -0,0 +1,71 @@+// Pure module: the parse worker bundles it, so it must not import the document service, the+// database, or anything that reads the environment.+import type { FileDocument } from '@lobechat/file-loaders';+import { sliceHead } from '@lobechat/prompts/textWindow';++/**+ * Upper bound, in characters, of parsed file text stored in `documents.content`.+ *+ * Parsing raw CSV exports, logs, or sparse spreadsheets can yield 100+ MiB of text. Rows that large+ * slow every read of the document, overflow the model context when attached, and cannot be synced+ * to full-text search. The original file stays in storage for tools that process it directly.+ */+export const PARSED_FILE_CONTENT_MAX_CHARS = 5_000_000;++export type ParsedFileDocument = FileDocument;++const PAGE_CLOSE_TAG = '\n</page>';++/**+ * PDF loaders wrap each page in `<page ...>...</page>`. A cut inside a page leaves an opening tag+ * with no closing tag (or a half-written tag at the tail), which previews and `readAttachment`+ * would expose as malformed markup. Close the cut page, or drop a half-written opening tag, while+ * staying within the cap. Page tags are kept rather than stripped so page numbers survive.+ */+const closeCutPage = (content: string): string => {+ const open = content.lastIndexOf('<page');+ if (open === -1 || open < content.lastIndexOf('</page>')) return content;++ const openEnd = content.indexOf('>', open);+ if (openEnd === -1) return content.slice(0, open).trimEnd();++ const bodyEnd = Math.max(openEnd + 1, content.length - PAGE_CLOSE_TAG.length);+ const body = content.slice(0, bodyEnd).replace(/<\/?(?:p(?:a(?:ge?)?)?)?$/, '');+ return `${body}${PAGE_CLOSE_TAG}`;+};++/**+ * Truncates oversized parsed text before it is stored. `pages` repeats the full text, so it is+ * dropped for truncated documents; `metadata` records the original length.+ */+export const capParsedFileDocument = (fileDocument: ParsedFileDocument): ParsedFileDocument => {+ if (fileDocument.content.length <= PARSED_FILE_CONTENT_MAX_CHARS) return fileDocument;++ const head = sliceHead(fileDocument.content, PARSED_FILE_CONTENT_MAX_CHARS);+ // Only the PDF loader emits page wrappers; other text may contain a literal `<page` to keep.+ const content = fileDocument.fileType === 'pdf' ? closeCutPage(head) : head;+ return {+ ...fileDocument,+ content,+ metadata: {+ ...fileDocument.metadata,+ originalCharCount: fileDocument.content.length,+ truncated: true,+ },+ pages: undefined,+ totalCharCount: content.length,+ totalLineCount: content.split('\n').length,+ };+};++/**+ * Page editor text carries no `<page>` wrappers. Strip them before capping: a cut inside a page+ * would leave an opening tag with no closing tag, which the strip regex can no longer match.+ */+export const stripPageWrappers = (fileDocument: ParsedFileDocument): ParsedFileDocument =>+ fileDocument.content.includes('<page')+ ? {+ ...fileDocument,+ content: fileDocument.content.replaceAll(/<page[^>]*>([\S\s]*?)<\/page>/g, '$1').trim(),+ }+ : fileDocument;diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.tsindex 40b206f0185..9f4c91e792b 100644--- a/apps/server/src/services/file/__tests__/index.test.ts+++ b/apps/server/src/services/file/__tests__/index.test.ts@@ -192,6 +192,53 @@ describe('FileService', () => {expect(mockTempManager.writeTempFile).toHaveBeenCalledWith(mockContent, mockFile.name);});+ describe('maxBytes', () => {+ it('refuses by the stored size before any bytes are read', async () => {+ mockFileModel.findById.mockResolvedValue({ ...mockFile, size: 65 });++ await expect(+ service.downloadFileToLocal('test-file-id', undefined, { maxBytes: 64 }),+ ).rejects.toMatchObject({ code: 'PAYLOAD_TOO_LARGE' });++ expect(service['impl'].getFileByteArray).not.toHaveBeenCalled();+ expect(mockTempManager.writeTempFile).not.toHaveBeenCalled();+ });++ it('refuses by the received bytes when the stored size understates them', async () => {+ mockFileModel.findById.mockResolvedValue({ ...mockFile, size: 3 });+ vi.mocked(service['impl'].getFileByteArray).mockResolvedValue(new Uint8Array(65));++ await expect(+ service.downloadFileToLocal('test-file-id', undefined, { maxBytes: 64 }),+ ).rejects.toMatchObject({ code: 'PAYLOAD_TOO_LARGE' });++ expect(mockTempManager.writeTempFile).not.toHaveBeenCalled();+ });++ it('keeps the access scope and downloads a file within the limit', async () => {+ const accessScope = agentShareFileAccessScope({+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ });+ mockFileModel.findById.mockResolvedValue({ ...mockFile, size: 3 });+ vi.mocked(service['impl'].getFileByteArray).mockResolvedValue(new Uint8Array(3));+ mockTempManager.writeTempFile.mockResolvedValue('/tmp/test.txt');++ await service.downloadFileToLocal('test-file-id', accessScope, { maxBytes: 64 });++ expect(mockFileModel.findById).toHaveBeenCalledWith('test-file-id', { accessScope });+ expect(mockTempManager.writeTempFile).toHaveBeenCalled();+ });++ it('applies no limit unless one is passed (skill ZIP import keeps its own contract)', async () => {+ mockFileModel.findById.mockResolvedValue({ ...mockFile, size: 10 ** 9 });+ vi.mocked(service['impl'].getFileByteArray).mockResolvedValue(new Uint8Array(3));+ mockTempManager.writeTempFile.mockResolvedValue('/tmp/test.txt');++ await expect(service.downloadFileToLocal('test-file-id')).resolves.toBeDefined();+ });+ });+it('should resolve an agent-share file only through its provenance scope', async () => {const accessScope = agentShareFileAccessScope({shareId: 'share-1',diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex d48c606b34e..1bfdeec2a2f 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -562,15 +562,29 @@ export class FileService {return { fileId: createdId, key, url };}+ /**+ * Downloads a stored file to a temp path. `maxBytes` (optional) refuses a file larger than the+ * limit before any bytes are read, by the stored size, and again by the bytes actually received.+ * Callers that do not pass it (skill ZIP import) keep their own limits.+ */async downloadFileToLocal(fileId: string,accessScope: FileAccessScope = ordinaryFileAccessScope,- ): Promise<{ cleanup: () => void; file: FileItem; filePath: string }> {+ options: { maxBytes?: number } = {},+ ): Promise<{ cleanup: () => Promise<void>; file: FileItem; filePath: string }> {const file = await this.fileModel.findById(fileId, { accessScope });if (!file) {throw new TRPCError({ code: 'BAD_REQUEST', message: 'File not found' });}+ const { maxBytes } = options;+ const tooLarge = () =>+ new TRPCError({+ code: 'PAYLOAD_TOO_LARGE',+ message: `Files larger than ${maxBytes} bytes cannot be parsed in memory`,+ });+ if (maxBytes !== undefined && file.size > maxBytes) throw tooLarge();+let content: Uint8Array | undefined;try {content = await this.getFileByteArray(file.url);@@ -587,6 +601,7 @@ export class FileService {}if (!content) throw new TRPCError({ code: 'BAD_REQUEST', message: 'File content is empty' });+ if (maxBytes !== undefined && content.byteLength > maxBytes) throw tooLarge();const dir = nanoid();const tempManager = new TempFileManager(dir);diff --git a/apps/server/src/services/fileParse/artifact.ts b/apps/server/src/services/fileParse/artifact.tsnew file mode 100644index 00000000000..031a9205be1--- /dev/null+++ b/apps/server/src/services/fileParse/artifact.ts@@ -0,0 +1,17 @@+import path from 'node:path';++/** Where `bun run build:file-parse-worker` writes the worker, relative to the app root. */+const FILE_PARSE_WORKER_RELATIVE_PATH = 'dist/file-parse-worker/fileParseWorker.mjs';++/** Deployments whose working directory is not the app root set this to the artifact path. */+export const FILE_PARSE_WORKER_PATH_ENV = 'FILE_PARSE_WORKER_PATH';++/**+ * The worker is a prebuilt file, started by absolute path: `new Worker(new URL(...))` would make+ * the bundler emit a virtual asset, and a path derived from the module location changes with how+ * the server is bundled. Next standalone keeps the app root as the working directory and carries+ * the file through `outputFileTracingIncludes`.+ */+export const resolveFileParseWorkerPath = (): string =>+ process.env[FILE_PARSE_WORKER_PATH_ENV] ||+ path.join(/* turbopackIgnore: true */ process.cwd(), FILE_PARSE_WORKER_RELATIVE_PATH);diff --git a/apps/server/src/services/fileParse/chunkLimits.test.ts b/apps/server/src/services/fileParse/chunkLimits.test.tsnew file mode 100644index 00000000000..67a1c25474a--- /dev/null+++ b/apps/server/src/services/fileParse/chunkLimits.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { MAX_FILE_PARSE_SIZE } from '@/const/file';++import {+ assertChunkResultWithinLimits,+ ChunkOutputTooLargeError,+ DEFAULT_CHUNK_RESULT_LIMITS,+} from './chunkLimits';++const chunk = (text: string) => ({ metadata: {}, pageContent: text });++describe('assertChunkResultWithinLimits', () => {+ it('sizes the text bound so a file at the parse cap still fits after overlap', () => {+ // 800-character chunks every 400 characters: about 2x the input+ expect(DEFAULT_CHUNK_RESULT_LIMITS.maxChars).toBeGreaterThan(2 * MAX_FILE_PARSE_SIZE);+ expect(DEFAULT_CHUNK_RESULT_LIMITS.maxChunks).toBeGreaterThan(MAX_FILE_PARSE_SIZE / 400);+ });++ it('returns the very same chunks when they are within bounds', () => {+ const chunks = [chunk('ab'), chunk('cd')];++ expect(assertChunkResultWithinLimits(chunks, { maxChars: 4, maxChunks: 2 })).toBe(chunks);+ });++ it('rejects too many chunks instead of cutting the list', () => {+ const error = (() => {+ try {+ assertChunkResultWithinLimits([chunk('a'), chunk('b'), chunk('c')], {+ maxChars: 99,+ maxChunks: 2,+ });+ } catch (e) {+ return e;+ }+ })();++ expect(error).toBeInstanceOf(ChunkOutputTooLargeError);+ expect(error).toMatchObject({ actual: 3, limit: 2, unit: 'chunks' });+ });++ it('rejects too much text instead of cutting a chunk', () => {+ expect(() =>+ assertChunkResultWithinLimits([chunk('abc'), chunk('de')], { maxChars: 4, maxChunks: 9 }),+ ).toThrow(ChunkOutputTooLargeError);+ });+});diff --git a/apps/server/src/services/fileParse/chunkLimits.ts b/apps/server/src/services/fileParse/chunkLimits.tsnew file mode 100644index 00000000000..6a59d2da6bc--- /dev/null+++ b/apps/server/src/services/fileParse/chunkLimits.ts@@ -0,0 +1,56 @@+// Pure module bundled into the parse worker: no document service, DB or environment.+import { MAX_FILE_PARSE_SIZE } from '@/const/file';+import type { DocumentChunk } from '@/libs/document-loaders/types';++/**+ * Bounds of what one chunk job may copy back to the request thread. The worker only measures the+ * result, it never truncates: a file that exceeds a bound fails, so the caller cannot index half a+ * document and call it complete.+ *+ * The text bound is sized from the input cap: the splitter overlaps neighbouring chunks (800+ * characters every 400), so a file at `MAX_FILE_PARSE_SIZE` yields about twice its size, and a+ * spreadsheet repeats the header on every row, hence the factor 3. The count bound is a quarter of+ * a million rows more than a full-size text file needs.+ */+export interface ChunkResultLimits {+ maxChars: number;+ maxChunks: number;+}++export const DEFAULT_CHUNK_RESULT_LIMITS: ChunkResultLimits = {+ maxChars: 3 * MAX_FILE_PARSE_SIZE,+ maxChunks: 500_000,+};++export class ChunkOutputTooLargeError extends Error {+ readonly actual: number;+ readonly limit: number;+ readonly unit: 'chars' | 'chunks';++ constructor(unit: 'chars' | 'chunks', limit: number, actual: number) {+ super(`File produced too many chunk ${unit} to index: ${actual} > ${limit}`);+ this.name = 'FileParseOutputTooLargeError';+ this.unit = unit;+ this.limit = limit;+ this.actual = actual;+ }+}++/** Returns the chunks untouched, or throws; a result over the bound is never cut down. */+export const assertChunkResultWithinLimits = (+ chunks: DocumentChunk[],+ limits: ChunkResultLimits = DEFAULT_CHUNK_RESULT_LIMITS,+): DocumentChunk[] => {+ if (chunks.length > limits.maxChunks) {+ throw new ChunkOutputTooLargeError('chunks', limits.maxChunks, chunks.length);+ }++ let chars = 0;+ for (const chunk of chunks) {+ chars += chunk.pageContent.length;+ if (chars > limits.maxChars) {+ throw new ChunkOutputTooLargeError('chars', limits.maxChars, chars);+ }+ }+ return chunks;+};diff --git a/apps/server/src/services/fileParse/errors.ts b/apps/server/src/services/fileParse/errors.tsnew file mode 100644index 00000000000..8a5b25707a6--- /dev/null+++ b/apps/server/src/services/fileParse/errors.ts@@ -0,0 +1,53 @@+export type FileParseErrorCode =+ /** The input is larger than the in-memory parse cap; refused before any worker starts. */+ | 'INPUT_TOO_LARGE'+ /** The loader read the file but produced no usable content (all pages failed). */+ | 'LOAD_FAILED'+ /** The worker ran out of its heap limit. */+ | 'OUT_OF_MEMORY'+ /** The parse succeeded but its result is too big to copy back; never truncated silently. */+ | 'OUTPUT_TOO_LARGE'+ /** Waiting list is full: rejected at once, no worker started. */+ | 'QUEUE_FULL'+ /** Waited too long for a free slot. */+ | 'QUEUE_TIMEOUT'+ /** The thread could not be created. */+ | 'START_FAILED'+ /** The parse exceeded its time budget and the worker was terminated. */+ | 'TIMEOUT'+ /** The worker artifact is missing: never falls back to parsing on the main thread. */+ | 'UNAVAILABLE'+ /** The worker threw outside the parse, or exited without reporting a result. */+ | 'WORKER_FAILED'+ /** The parse itself raised an error (corrupt file, loader exception). */+ | 'PARSE_FAILED';++export class FileParseError extends Error {+ readonly code: FileParseErrorCode;++ constructor(code: FileParseErrorCode, message: string, options?: { cause?: unknown }) {+ super(message, options);+ this.name = 'FileParseError';+ this.code = code;+ }++ /** Saturation, not a bad file: the same request can succeed later. */+ get retryable() {+ return this.code === 'QUEUE_FULL' || this.code === 'QUEUE_TIMEOUT';+ }+}++/**+ * Name/code based, not `instanceof`: the shared runner lives on `globalThis` and may have been+ * created by another bundle copy (a different Next route bundle, an HMR reload), whose+ * `FileParseError` class is not the one the caller imports.+ */+export const isFileParseError = (error: unknown): error is FileParseError =>+ error instanceof FileParseError ||+ (error instanceof Error &&+ error.name === 'FileParseError' &&+ typeof (error as { code?: unknown }).code === 'string');++/** Name based for the same cross-copy reason as {@link isFileParseError}. */+export const isUnsupportedFileTypeError = (error: unknown): error is Error =>+ error instanceof Error && error.name === 'UnsupportedFileTypeError';diff --git a/apps/server/src/services/fileParse/failure.test.ts b/apps/server/src/services/fileParse/failure.test.tsnew file mode 100644index 00000000000..8e765ef769d--- /dev/null+++ b/apps/server/src/services/fileParse/failure.test.ts@@ -0,0 +1,118 @@+import { FileParseBudgetError } from '@lobechat/file-loaders';+import { TRPCError } from '@trpc/server';+import { describe, expect, it } from 'vitest';++import { AsyncTaskErrorType } from '@/types/asyncTask';++import { FileParseError } from './errors';+import { isDeterministicParseFailure, isSharedLimitFailure, toAsyncTaskErrorType } from './failure';+import { normalizeParseFileError } from './normalizeError';++describe('isDeterministicParseFailure', () => {+ it.each([+ 'INPUT_TOO_LARGE',+ 'LOAD_FAILED',+ 'OUT_OF_MEMORY',+ 'OUTPUT_TOO_LARGE',+ 'PARSE_FAILED',+ 'TIMEOUT',+ ] as const)('treats %s as a verdict on the file, also behind a TRPCError', (code) => {+ const error = new FileParseError(code, 'x');++ expect(isDeterministicParseFailure(error)).toBe(true);+ expect(isDeterministicParseFailure(normalizeParseFileError(error))).toBe(true);+ });++ it('treats a budget refusal as deterministic', () => {+ const budget = new FileParseBudgetError('sheet-xml', 10, 20);++ expect(isDeterministicParseFailure(budget)).toBe(true);+ expect(isDeterministicParseFailure(normalizeParseFileError(budget))).toBe(true);+ });++ it.each(['QUEUE_FULL', 'QUEUE_TIMEOUT', 'START_FAILED', 'UNAVAILABLE', 'WORKER_FAILED'] as const)(+ 'does not treat %s as a verdict: a later attempt may succeed',+ (code) => {+ expect(+ isDeterministicParseFailure(normalizeParseFileError(new FileParseError(code, 'x'))),+ ).toBe(false);+ },+ );++ it('does not treat unrelated errors as parse verdicts', () => {+ expect(isDeterministicParseFailure(new Error('db down'))).toBe(false);+ expect(isDeterministicParseFailure(new TRPCError({ code: 'BAD_REQUEST', message: 'x' }))).toBe(+ false,+ );+ expect(isDeterministicParseFailure(undefined)).toBe(false);+ });++ it('recognizes errors made by another copy of the classes, by name and code', () => {+ const foreign = Object.assign(new Error('x'), { code: 'TIMEOUT', name: 'FileParseError' });++ expect(isDeterministicParseFailure(foreign)).toBe(true);+ });+});++describe('isSharedLimitFailure', () => {+ it.each(['sheet-xml', 'zip-entries', 'zip-expansion', 'zip-input'] as const)(+ 'treats the shared ZIP preflight reason %s as refused for every parser, also behind a TRPCError',+ (reason) => {+ const budget = new FileParseBudgetError(reason, 1, 2);++ expect(isSharedLimitFailure(budget)).toBe(true);+ expect(isSharedLimitFailure(normalizeParseFileError(budget))).toBe(true);+ },+ );++ it('treats the input size cap as shared, behind a TRPCError and from another bundle copy', () => {+ const tooLarge = new FileParseError('INPUT_TOO_LARGE', 'x');++ expect(isSharedLimitFailure(tooLarge)).toBe(true);+ expect(isSharedLimitFailure(normalizeParseFileError(tooLarge))).toBe(true);+ expect(+ isSharedLimitFailure(+ Object.assign(new Error('x'), { code: 'INPUT_TOO_LARGE', name: 'FileParseError' }),+ ),+ ).toBe(true);+ });++ it('leaves the limits only one parser enforces, and one parser own failures, to the next parser', () => {+ expect(isSharedLimitFailure(new FileParseBudgetError('sheet-cells', 1, 2))).toBe(false);+ for (const code of [+ 'LOAD_FAILED',+ 'OUT_OF_MEMORY',+ 'OUTPUT_TOO_LARGE',+ 'PARSE_FAILED',+ 'QUEUE_FULL',+ 'TIMEOUT',+ 'WORKER_FAILED',+ ] as const) {+ expect(isSharedLimitFailure(normalizeParseFileError(new FileParseError(code, 'x')))).toBe(+ false,+ );+ }+ expect(isSharedLimitFailure(new Error('db down'))).toBe(false);+ });+});++describe('toAsyncTaskErrorType', () => {+ it('reuses the existing too-large and timeout task errors', () => {+ expect(toAsyncTaskErrorType(new FileParseBudgetError('zip-input', 1, 2))).toBe(+ AsyncTaskErrorType.FileTooLargeToParse,+ );+ for (const code of ['INPUT_TOO_LARGE', 'OUT_OF_MEMORY', 'OUTPUT_TOO_LARGE'] as const) {+ expect(toAsyncTaskErrorType(normalizeParseFileError(new FileParseError(code, 'x')))).toBe(+ AsyncTaskErrorType.FileTooLargeToParse,+ );+ }+ expect(toAsyncTaskErrorType(new FileParseError('TIMEOUT', 'x'))).toBe(+ AsyncTaskErrorType.Timeout,+ );+ });++ it('leaves everything else to the error own name', () => {+ expect(toAsyncTaskErrorType(new FileParseError('PARSE_FAILED', 'x'))).toBeUndefined();+ expect(toAsyncTaskErrorType(new Error('x'))).toBeUndefined();+ });+});diff --git a/apps/server/src/services/fileParse/failure.ts b/apps/server/src/services/fileParse/failure.tsnew file mode 100644index 00000000000..ce44799b689--- /dev/null+++ b/apps/server/src/services/fileParse/failure.ts@@ -0,0 +1,82 @@+import { isFileParseBudgetError } from '@lobechat/file-loaders';++import { AsyncTaskErrorType } from '@/types/asyncTask';++import { isFileParseError } from './errors';++/** Follows `cause` (a TRPCError wraps the original parse error) to the parse error underneath. */+const findParseFailure = (error: unknown) => {+ for (let current = error, depth = 0; current && depth < 5; depth++) {+ if (isFileParseBudgetError(current) || isFileParseError(current)) return current;+ current = (current as { cause?: unknown }).cause;+ }+ return undefined;+};++const DETERMINISTIC_CODES = new Set([+ 'INPUT_TOO_LARGE',+ 'LOAD_FAILED',+ 'OUT_OF_MEMORY',+ 'OUTPUT_TOO_LARGE',+ 'PARSE_FAILED',+ 'TIMEOUT',+]);+const TOO_LARGE_CODES = new Set(['INPUT_TOO_LARGE', 'OUT_OF_MEMORY', 'OUTPUT_TOO_LARGE']);++/**+ * The same file would fail the same way again: a structural budget, a file that does not parse,+ * a result too large, a heap or time limit. Saturation (`QUEUE_FULL`, `QUEUE_TIMEOUT`) and a+ * missing artifact are not: a later or different attempt may succeed, and a type error from+ * outside the parse worker is not a parse verdict at all.+ *+ * It says nothing about whether another parser would fail too (see {@link isSharedLimitFailure}):+ * callers use it to tell a bad file from a busy server, not to skip the next parser.+ */+export const isDeterministicParseFailure = (error: unknown): boolean => {+ const failure = findParseFailure(error);+ if (!failure) return false;+ return (+ isFileParseBudgetError(failure) || DETERMINISTIC_CODES.has((failure as { code: string }).code)+ );+};++/**+ * Budget reasons raised by `preflightXlsxZip`, which the document-view parse, the chunk job and+ * the dataset parse all run before any loader. `sheet-cells` is not here: only the SheetJS loader+ * enforces it, the chunk loader (ExcelJS) never does.+ */+const SHARED_ZIP_BUDGET_REASONS = new Set([+ 'sheet-xml',+ 'zip-entries',+ 'zip-expansion',+ 'zip-input',+]);++/**+ * The refusal comes from a limit every parse path applies to the same bytes (the input size cap+ * before any worker starts, the xlsx ZIP structure preflight), so another path would be refused+ * the same way. Any other failure is one parser's verdict (it could not read the file, ran out of+ * time or heap, or hit a limit only it enforces): a different parser, such as the chunk loader+ * after the document-view parse, may still succeed, within the same worker, heap and timeout.+ */+export const isSharedLimitFailure = (error: unknown): boolean => {+ const failure = findParseFailure(error);+ if (!failure) return false;+ if (isFileParseBudgetError(failure)) return SHARED_ZIP_BUDGET_REASONS.has(failure.reason);+ return (failure as { code: string }).code === 'INPUT_TOO_LARGE';+};++/**+ * The existing task error type that describes a deterministic failure to the member: too large+ * (budget, input, output, heap) or timed out. Everything else keeps the error's own name.+ */+export const toAsyncTaskErrorType = (error: unknown): AsyncTaskErrorType | undefined => {+ const failure = findParseFailure(error);+ if (!failure) return undefined;+ if (isFileParseBudgetError(failure)) return AsyncTaskErrorType.FileTooLargeToParse;++ const code = (failure as { code: string }).code;+ if (TOO_LARGE_CODES.has(code)) return AsyncTaskErrorType.FileTooLargeToParse;+ if (code === 'TIMEOUT') return AsyncTaskErrorType.Timeout;+ return undefined;+};diff --git a/apps/server/src/services/fileParse/index.shared.test.ts b/apps/server/src/services/fileParse/index.shared.test.tsnew file mode 100644index 00000000000..44c9b7f08ec--- /dev/null+++ b/apps/server/src/services/fileParse/index.shared.test.ts@@ -0,0 +1,105 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';++import { FILE_PARSE_WORKER_PATH_ENV } from './artifact';+import { DEFAULT_FILE_PARSE_LIMITS } from './runner';++// The process-wide runner and the structured log line, with real threads running a scenario+// script: `content` of the dataset job selects the behaviour ("busy:<ms>" or "fail").+const SCENARIOS = `+import { parentPort, workerData as job } from 'node:worker_threads';+const [kind, arg] = String(job.content).split(':');+if (kind === 'busy') { const end = Date.now() + Number(arg); while (Date.now() < end); }+parentPort.postMessage(kind === 'fail'+ ? { type: 'error', error: { name: 'Error', message: 'corrupt' } }+ : { type: 'result', value: 'done' });+`;++let dir: string;+const previousEnv = process.env[FILE_PARSE_WORKER_PATH_ENV];++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-shared-'));+ const workerPath = path.join(dir, 'scenarios.mjs');+ await writeFile(workerPath, SCENARIOS);+ process.env[FILE_PARSE_WORKER_PATH_ENV] = workerPath;+});++afterAll(async () => {+ if (previousEnv === undefined) delete process.env[FILE_PARSE_WORKER_PATH_ENV];+ else process.env[FILE_PARSE_WORKER_PATH_ENV] = previousEnv;+ await rm(dir, { force: true, recursive: true });+});++afterEach(() => vi.restoreAllMocks());++const loadCopy = async () => {+ vi.resetModules();+ return import('./index');+};++describe('shared file parse runner', () => {+ it('is one runner for every module copy, so slot and queue limits hold per process', async () => {+ // Two copies, like two Next route bundles or a dev HMR reload.+ const copyA = await loadCopy();+ const copyB = await loadCopy();+ expect(copyA).not.toBe(copyB);+ expect(copyA.getSharedFileParseRunner()).toBe(copyB.getSharedFileParseRunner());++ const first = copyA.parseDatasetInWorker('busy:300');+ // The default limit is one running parse: a parse submitted through the other copy waits.+ const second = copyB.parseDatasetInWorker('busy:1');+ await vi.waitFor(() =>+ expect(copyB.getSharedFileParseRunner().stats()).toEqual({ active: 1, queued: 1 }),+ );+ expect(copyA.getSharedFileParseRunner().stats()).toEqual({ active: 1, queued: 1 });++ await Promise.all([first, second]);+ expect(copyA.getSharedFileParseRunner().stats()).toEqual({ active: 0, queued: 0 });+ });++ it('logs a refused task as waiting time only, not as a long parse', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const { parseDatasetInWorker } = await loadCopy();++ // One running plus a full queue fill the runner; the next task is refused at once.+ const accepted = Array.from({ length: 1 + DEFAULT_FILE_PARSE_LIMITS.maxQueue }, () =>+ parseDatasetInWorker('busy:30'),+ );+ const refused = await parseDatasetInWorker('busy:1').catch((error) => error);+ await Promise.all(accepted);++ expect(refused).toMatchObject({ code: 'QUEUE_FULL' });+ const line = JSON.parse(warn.mock.calls.at(-1)![0] as string);+ expect(line).toMatchObject({ code: 'QUEUE_FULL', event: 'file_parse.failed', parseMs: 0 });+ });++ it('separates the queue wait from the parse time of a task that started late and failed', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const { parseDatasetInWorker } = await loadCopy();++ const running = parseDatasetInWorker('busy:400');+ const failing = await parseDatasetInWorker('fail').catch((error) => error);+ await running;++ expect(failing).toMatchObject({ code: 'PARSE_FAILED' });+ const line = JSON.parse(warn.mock.calls.at(-1)![0] as string);+ expect(line).toMatchObject({ code: 'PARSE_FAILED', event: 'file_parse.failed' });+ expect(line.queuedMs).toBeGreaterThanOrEqual(0);+ expect(line.parseMs).toBeGreaterThanOrEqual(0);+ });++ it('refuses an input over the parse cap before it reaches a thread', async () => {+ const { parseDatasetInWorker, getSharedFileParseRunner } = await loadCopy();+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const tooBig = new Uint8Array(64 * 1024 * 1024 + 1);++ const error = await parseDatasetInWorker(tooBig, { format: 'xlsx' }).catch((e) => e);++ expect(error).toMatchObject({ code: 'INPUT_TOO_LARGE' });+ expect(getSharedFileParseRunner().stats()).toEqual({ active: 0, queued: 0 });+ });+});diff --git a/apps/server/src/services/fileParse/index.sharedQueueLimits.test.ts b/apps/server/src/services/fileParse/index.sharedQueueLimits.test.tsnew file mode 100644index 00000000000..5120f5665de--- /dev/null+++ b/apps/server/src/services/fileParse/index.sharedQueueLimits.test.ts@@ -0,0 +1,94 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { MAX_UPLOAD_FILE_COUNT } from '@lobechat/const';+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';++import { FILE_PARSE_WORKER_PATH_ENV } from './artifact';+import { createFileParseRunner } from './runner';++// `content` of the dataset job is "busy:<ms>"; real threads run it.+const SCENARIOS = `+import { parentPort, workerData as job } from 'node:worker_threads';+const end = Date.now() + Number(String(job.content).split(':')[1] ?? 0);+while (Date.now() < end);+parentPort.postMessage({ type: 'result', value: 'done' });+`;++const SHARED_RUNNER_KEY = Symbol.for('lobehub.fileParse.sharedRunner');++let dir: string;+let workerPath: string;+const previousEnv = process.env[FILE_PARSE_WORKER_PATH_ENV];++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-shared-limits-'));+ workerPath = path.join(dir, 'scenarios.mjs');+ await writeFile(workerPath, SCENARIOS);+ process.env[FILE_PARSE_WORKER_PATH_ENV] = workerPath;+});++afterEach(() => {+ delete (globalThis as Record<symbol, unknown>)[SHARED_RUNNER_KEY];+});++afterAll(async () => {+ if (previousEnv === undefined) delete process.env[FILE_PARSE_WORKER_PATH_ENV];+ else process.env[FILE_PARSE_WORKER_PATH_ENV] = previousEnv;+ await rm(dir, { force: true, recursive: true });+});++const loadCopy = async () => {+ vi.resetModules();+ return import('./index');+};++describe('queue limits across module copies', () => {+ it('share the waiting-task count: copies together hold one upload, the next is refused', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const copyA = await loadCopy();+ const copyB = await loadCopy();++ const parses = [copyA.parseDatasetInWorker('busy:200')];+ // The rest of the upload arrives alternately through the two copies.+ for (let i = 1; i < MAX_UPLOAD_FILE_COUNT; i += 1) {+ parses.push((i % 2 ? copyA : copyB).parseDatasetInWorker('busy:0'));+ }+ expect(copyA.getSharedFileParseRunner().stats()).toEqual({+ active: 1,+ queued: MAX_UPLOAD_FILE_COUNT - 1,+ });++ for (const copy of [copyA, copyB]) {+ expect(await copy.parseDatasetInWorker('busy:0').catch((e) => e)).toMatchObject({+ code: 'QUEUE_FULL',+ });+ }+ await expect(Promise.all(parses)).resolves.toHaveLength(MAX_UPLOAD_FILE_COUNT);+ });++ it('share the queued byte budget: bytes waiting in one copy count against the other', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ // The route copies find the runner on globalThis; this one has a small byte budget.+ (globalThis as Record<symbol, unknown>)[SHARED_RUNNER_KEY] = createFileParseRunner({+ maxQueuedBytes: 20,+ workerPath: () => workerPath,+ });+ const copyA = await loadCopy();+ const copyB = await loadCopy();++ const running = copyA.parseDatasetInWorker('busy:200'); // 8 bytes, runs at once+ const fromA = copyA.parseDatasetInWorker('busy:0'); // 6 bytes queued+ const fromB = copyB.parseDatasetInWorker('busy:0'); // 6 bytes queued, 12 of 20+ const tooMuch = await copyB.parseDatasetInWorker('busy:0:padding!!').catch((e) => e); // 16 bytes+ expect(tooMuch).toMatchObject({ code: 'QUEUE_FULL' });++ await Promise.all([running, fromA, fromB]);+ // Everything left the queue, so the budget is whole again: a 16-byte task fits behind a runner.+ const next = copyA.parseDatasetInWorker('busy:150');+ const fits = copyB.parseDatasetInWorker('busy:0:padding!!');+ expect(copyA.getSharedFileParseRunner().stats()).toEqual({ active: 1, queued: 1 });+ await Promise.all([next, fits]);+ });+});diff --git a/apps/server/src/services/fileParse/index.ts b/apps/server/src/services/fileParse/index.tsnew file mode 100644index 00000000000..8cc93e9e493--- /dev/null+++ b/apps/server/src/services/fileParse/index.ts@@ -0,0 +1,149 @@+import { stat } from 'node:fs/promises';+import path from 'node:path';+import { performance } from 'node:perf_hooks';++import type { FileDocument } from '@lobechat/file-loaders';+import debug from 'debug';++import { FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE, MAX_FILE_PARSE_SIZE } from '@/const/file';+import type { DocumentChunk } from '@/libs/document-loaders/types';++import { resolveFileParseWorkerPath } from './artifact';+import { FileParseError } from './errors';+import type { DatasetParseOptions, FileParseJob, FileParseMode } from './protocol';+import type { FileParseRunner } from './runner';+import { createFileParseRunner } from './runner';++export { FileParseError } from './errors';++const log = debug('lobe-chat:service:file-parse');++/** A parse slower than this is worth a log line; faster ones stay at debug level. */+const SLOW_PARSE_LOG_MS = 5000;++const SHARED_RUNNER_KEY = Symbol.for('lobehub.fileParse.sharedRunner');++/**+ * One runner per OS process, kept on `globalThis`: Next bundles each route separately and dev HMR+ * reloads modules, so a module-level variable would give every copy its own slot and queue and the+ * process would run several parses at once. The runner holds only counters and queued jobs for the+ * lifetime of single parses; nothing user- or request-scoped outlives a task.+ */+export const getSharedFileParseRunner = (): FileParseRunner => {+ const holder = globalThis as { [SHARED_RUNNER_KEY]?: FileParseRunner };+ return (holder[SHARED_RUNNER_KEY] ??= createFileParseRunner({+ workerPath: resolveFileParseWorkerPath,+ }));+};++interface TrackedParse {+ bytes?: number;+ fileId?: string;+ format?: string;+ job: FileParseJob;+}++/**+ * One structured line records the outcome of every parse (file id, format, size, timings and the+ * error code, never the content or the temp path). Only failures and slow parses are logged above+ * debug level.+ */+const track = async <T>({ bytes, fileId, format, job }: TrackedParse): Promise<T> => {+ const startedAt = performance.now();+ let parseStartedAt: number | undefined;+ const onStart = () => {+ parseStartedAt = performance.now();+ };++ const report = (outcome: string, error?: unknown) => {+ const now = performance.now();+ // A task that never started (queue full, queue timeout) only has waiting time: its whole+ // life is `queuedMs` and `parseMs` is 0, so a long queue wait is not read as a long parse.+ const parseStarted = parseStartedAt ?? now;+ const line = {+ bytes,+ code: (error as { code?: string } | undefined)?.code,+ event: `file_parse.${outcome}`,+ fileId,+ format,+ kind: job.kind === 'file' ? job.mode : job.kind,+ parseMs: Math.round(now - parseStarted),+ queuedMs: Math.round(parseStarted - startedAt),+ };+ if (outcome === 'failed') console.warn(JSON.stringify(line));+ else if (line.parseMs >= SLOW_PARSE_LOG_MS) console.info(JSON.stringify(line));+ else log('%O', line);+ };++ try {+ // Authoritative or measured size, checked before anything is cloned into a thread.+ if (bytes !== undefined && bytes > MAX_FILE_PARSE_SIZE) {+ throw new FileParseError('INPUT_TOO_LARGE', FILE_PARSE_SIZE_LIMIT_ERROR_MESSAGE);+ }+ const value = await getSharedFileParseRunner().run<T>(job, { onStart });+ report('completed');+ return value;+ } catch (error) {+ report('failed', error);+ throw error;+ }+};++const statBytes = async (filePath: string) => {+ try {+ return (await stat(filePath)).size;+ } catch {+ return undefined;+ }+};++/**+ * Parses a downloaded file on a worker thread. `mode: 'document'` drops the `<page>` wrappers+ * (page editor text); both modes apply the stored-content cap inside the worker.+ * Rejects with `UnsupportedFileTypeError` for unsupported types and `FileParseError` otherwise.+ */+export const parseFileInWorker = async (+ filePath: string,+ options: { fileId?: string; mode: FileParseMode },+): Promise<FileDocument> =>+ track<FileDocument>({+ bytes: await statBytes(filePath),+ fileId: options.fileId,+ format: path.extname(filePath).slice(1).toLowerCase() || undefined,+ job: { filePath, kind: 'file', mode: options.mode },+ });++/** Parses an eval dataset (CSV/JSON/JSONL/XLSX) on a worker thread, under the same limits. */+export const parseDatasetInWorker = <T>(+ content: Uint8Array | string,+ options?: DatasetParseOptions,+): Promise<T> =>+ track<T>({+ bytes: typeof content === 'string' ? Buffer.byteLength(content) : content.byteLength,+ format:+ options?.format && options.format !== 'auto'+ ? options.format+ : path+ .extname(options?.filename ?? '')+ .slice(1)+ .toLowerCase() || undefined,+ job: { content, kind: 'dataset', options },+ });++/**+ * Splits a knowledge-base file into chunks on a worker thread, under the same slot, queue and+ * limits as every other parse. Only bytes and a file name cross the boundary, and only+ * `DocumentChunk[]` comes back: the database and the knowledge routing stay on the caller's thread.+ * A result over the chunk bounds is rejected (`OUTPUT_TOO_LARGE`), never truncated.+ */+export const chunkContentInWorker = (+ filename: string,+ content: Uint8Array,+ options?: { fileId?: string },+): Promise<DocumentChunk[]> =>+ track<DocumentChunk[]>({+ bytes: content.byteLength,+ fileId: options?.fileId,+ format: path.extname(filename).slice(1).toLowerCase() || undefined,+ job: { content, filename, kind: 'chunk' },+ });diff --git a/apps/server/src/services/fileParse/loadedFile.ts b/apps/server/src/services/fileParse/loadedFile.tsnew file mode 100644index 00000000000..e6e8c7080ea--- /dev/null+++ b/apps/server/src/services/fileParse/loadedFile.ts@@ -0,0 +1,26 @@+import type { FileDocument } from '@lobechat/file-loaders';++import { LOAD_FAILED_ERROR_NAME } from './protocol';++export class FileLoadFailedError extends Error {+ constructor(message: string) {+ super(message);+ this.name = LOAD_FAILED_ERROR_NAME;+ }+}++/**+ * `loadFile` reports a whole-file failure as error pages plus `metadata.error` instead of throwing.+ * Storing that as a document would cache an empty "successful" parse, so the failure is refused+ * here. A load with usable content and a secondary error (e.g. metadata attach) is still accepted.+ */+export const assertFileLoaded = (loaded: FileDocument): FileDocument => {+ const error = loaded.metadata?.error;+ if (!error) return loaded;++ const allPagesFailed =+ !!loaded.pages?.length && loaded.pages.every((page) => page.metadata?.error);+ if (allPagesFailed || loaded.content.trim() === '') throw new FileLoadFailedError(error);++ return loaded;+};diff --git a/apps/server/src/services/fileParse/normalizeError.crossCopy.test.ts b/apps/server/src/services/fileParse/normalizeError.crossCopy.test.tsnew file mode 100644index 00000000000..7360905f8e7--- /dev/null+++ b/apps/server/src/services/fileParse/normalizeError.crossCopy.test.ts@@ -0,0 +1,153 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { TRPCError } from '@trpc/server';+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { FILE_PARSE_WORKER_PATH_ENV } from './artifact';+import { DEFAULT_FILE_PARSE_LIMITS } from './runner';++vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));+vi.mock('@/database/models/document');+vi.mock('@/database/models/file');+vi.mock('@/database/models/knowledgeBase');+vi.mock('../file');+vi.mock('../document/history');+vi.mock('../resourceEvents', () => ({ publishResourceEvent: vi.fn() }));++// A real thread whose behaviour follows the file name of the job.+const SCENARIOS = `+import path from 'node:path';+import { parentPort, workerData as job } from 'node:worker_threads';+const name = path.basename(job.filePath ?? '');+if (name === 'busy.bin') { const end = Date.now() + 300; while (Date.now() < end); }+parentPort.postMessage(name === 'unsupported.zip'+ ? { type: 'error', error: { name: 'UnsupportedFileTypeError', message: 'unsupported', fileType: 'zip' } }+ : { type: 'result', value: { content: 'ok', metadata: {}, totalCharCount: 2, totalLineCount: 1 } });+`;++const SHARED_RUNNER_KEY = Symbol.for('lobehub.fileParse.sharedRunner');++let dir: string;+let workerPath: string;+const previousEnv = process.env[FILE_PARSE_WORKER_PATH_ENV];++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-copies-'));+ workerPath = path.join(dir, 'scenarios.mjs');+ await writeFile(workerPath, SCENARIOS);+});++afterAll(async () => {+ if (previousEnv === undefined) delete process.env[FILE_PARSE_WORKER_PATH_ENV];+ else process.env[FILE_PARSE_WORKER_PATH_ENV] = previousEnv;+ await rm(dir, { force: true, recursive: true });+});++beforeEach(() => {+ delete (globalThis as Record<symbol, unknown>)[SHARED_RUNNER_KEY];+ process.env[FILE_PARSE_WORKER_PATH_ENV] = workerPath;+});++/**+ * Copy A creates the process-wide runner (and so throws copy A's error classes); copy B is the+ * DocumentService a different bundle or an HMR reload keeps using, with its own classes.+ */+const loadCopies = async () => {+ vi.resetModules();+ const copyA = await import('./index');+ const errorsA = await import('./errors');+ const loadersA = await import('@lobechat/file-loaders');+ copyA.getSharedFileParseRunner();++ vi.resetModules();+ const { DocumentService } = await import('../document');+ const errorsB = await import('./errors');+ const loadersB = await import('@lobechat/file-loaders');+ const { DocumentModel } = await import('@/database/models/document');+ const { FileModel } = await import('@/database/models/file');+ const { KnowledgeBaseModel } = await import('@/database/models/knowledgeBase');+ const { FileService } = await import('../file');++ // The premise of every case below: two copies of the classes that `instanceof` would compare.+ expect(errorsA.FileParseError).not.toBe(errorsB.FileParseError);+ expect(loadersA.UnsupportedFileTypeError).not.toBe(loadersB.UnsupportedFileTypeError);++ const downloadFileToLocal = vi.fn();+ vi.mocked(DocumentModel).mockImplementation(function () {+ return { create: vi.fn(), findByFileId: vi.fn().mockResolvedValue(null) } as never;+ });+ vi.mocked(FileModel).mockImplementation(function () {+ return {} as never;+ });+ vi.mocked(KnowledgeBaseModel).mockImplementation(function () {+ return {} as never;+ });+ vi.mocked(FileService).mockImplementation(function () {+ return { downloadFileToLocal } as never;+ });+ const db = {+ transaction: vi.fn(async (callback: (tx: unknown) => Promise<unknown>) =>+ callback({ execute: vi.fn() }),+ ),+ } as never;++ const parseAs = (fileName: string) => {+ downloadFileToLocal.mockResolvedValue({+ cleanup: async () => {},+ file: { name: fileName, parentId: null, url: `s3://bucket/${fileName}` },+ filePath: path.join(dir, fileName),+ });+ return [+ () => new DocumentService(db, 'user-1').parseFile('file-1'),+ () => new DocumentService(db, 'user-1').parseDocument('file-1'),+ ];+ };++ return { copyA, parseAs };+};++// Each case reloads the document service twice; under a loaded full run that outlasts 5s.+describe('parse errors thrown by another module copy', { timeout: 30_000 }, () => {+ beforeEach(() => vi.spyOn(console, 'error').mockImplementation(() => {}));++ it('maps a full queue to TOO_MANY_REQUESTS', async () => {+ const { copyA, parseAs } = await loadCopies();+ const runner = copyA.getSharedFileParseRunner();+ const job = { filePath: path.join(dir, 'busy.bin'), kind: 'file', mode: 'file' } as const;+ // One running parse and a full waiting list.+ const { maxQueue } = DEFAULT_FILE_PARSE_LIMITS;+ const fillers = Array.from({ length: 1 + maxQueue }, () => runner.run(job));+ expect(runner.stats()).toEqual({ active: 1, queued: maxQueue });++ for (const parse of parseAs('report.bin')) {+ const error = await parse().catch((e) => e);+ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({ code: 'TOO_MANY_REQUESTS' });+ }+ await Promise.all(fillers);+ });++ it('maps a missing worker artifact to SERVICE_UNAVAILABLE', async () => {+ const { parseAs } = await loadCopies();+ process.env[FILE_PARSE_WORKER_PATH_ENV] = path.join(dir, 'missing.mjs');++ for (const parse of parseAs('report.bin')) {+ const error = await parse().catch((e) => e);+ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({ code: 'SERVICE_UNAVAILABLE' });+ }+ });++ it('keeps an unsupported file type a BAD_REQUEST', async () => {+ const { parseAs } = await loadCopies();++ for (const parse of parseAs('unsupported.zip')) {+ const error = await parse().catch((e) => e);+ expect(error).toBeInstanceOf(TRPCError);+ expect(error).toMatchObject({ code: 'BAD_REQUEST' });+ expect(error.cause).toMatchObject({ name: 'UnsupportedFileTypeError' });+ }+ });+});diff --git a/apps/server/src/services/fileParse/normalizeError.ts b/apps/server/src/services/fileParse/normalizeError.tsnew file mode 100644index 00000000000..f97dd93054e--- /dev/null+++ b/apps/server/src/services/fileParse/normalizeError.ts@@ -0,0 +1,43 @@+import { isFileParseBudgetError } from '@lobechat/file-loaders';+import { TRPCError } from '@trpc/server';++import { isFileParseError, isUnsupportedFileTypeError } from './errors';++const FILE_PARSE_TRPC_CODES = {+ INPUT_TOO_LARGE: 'PAYLOAD_TOO_LARGE',+ LOAD_FAILED: 'UNPROCESSABLE_CONTENT',+ OUT_OF_MEMORY: 'PAYLOAD_TOO_LARGE',+ QUEUE_FULL: 'TOO_MANY_REQUESTS',+ QUEUE_TIMEOUT: 'TOO_MANY_REQUESTS',+ START_FAILED: 'SERVICE_UNAVAILABLE',+ TIMEOUT: 'TIMEOUT',+ UNAVAILABLE: 'SERVICE_UNAVAILABLE',+} as const;++/**+ * Maps a parse failure to a TRPCError; anything else is returned untouched. Every check is by+ * name/code so the mapping survives errors created by another copy of the error classes.+ */+export const normalizeParseFileError = (error: unknown) => {+ if (isUnsupportedFileTypeError(error)) {+ return new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });+ }++ // A structural refusal (zip size, entries, cell area) is a client-side "file too large", not a+ // 500. The budget error stays as `cause` so callers can read reason / limit / actual.+ if (isFileParseBudgetError(error)) {+ return new TRPCError({ cause: error, code: 'PAYLOAD_TOO_LARGE', message: error.message });+ }++ if (isFileParseError(error)) {+ return new TRPCError({+ cause: error,+ code:+ FILE_PARSE_TRPC_CODES[error.code as keyof typeof FILE_PARSE_TRPC_CODES] ??+ 'INTERNAL_SERVER_ERROR',+ message: error.message,+ });+ }++ return error;+};diff --git a/apps/server/src/services/fileParse/protocol.ts b/apps/server/src/services/fileParse/protocol.tsnew file mode 100644index 00000000000..d2b2a4b5fd7--- /dev/null+++ b/apps/server/src/services/fileParse/protocol.ts@@ -0,0 +1,41 @@+// Shared by the main-thread runner and the worker entry. Types and constants only: the worker+// bundle imports this file, so it must stay free of runtime dependencies.+import type { FileDocument, FileParseBudgetReason } from '@lobechat/file-loaders';++import type { DocumentChunk } from '@/libs/document-loaders/types';++export type FileParseMode = 'document' | 'file';++export interface DatasetParseOptions {+ csvDelimiter?: string;+ filename?: string;+ format?: 'auto' | 'csv' | 'json' | 'jsonl' | 'xlsx';+ headerRow?: number;+ preview?: number;+ sheet?: number | string;+}++/** What a worker thread is asked to do. Local path or content plus options: no credentials, no DB. */+export type FileParseJob =+ /** Knowledge-base chunking: file name and bytes in, `DocumentChunk[]` out. No DB, no env routing. */+ | { content: Uint8Array; filename: string; kind: 'chunk' }+ | { content: Uint8Array | string; kind: 'dataset'; options?: DatasetParseOptions }+ | { filePath: string; kind: 'file'; mode: FileParseMode };++export interface SerializedWorkerError {+ /** Set for a budget refusal: structure only, no file content. */+ budget?: { actual: number; limit: number; reason: FileParseBudgetReason };+ fileType?: string;+ message: string;+ name: string;+}++export type FileParseWorkerMessage =+ | { error: SerializedWorkerError; type: 'error' }+ | { type: 'result'; value: DocumentChunk[] | FileDocument | unknown };++/** Error names the worker may report; the runner maps them back to typed errors. */+export const UNSUPPORTED_FILE_TYPE_ERROR_NAME = 'UnsupportedFileTypeError';+export const LOAD_FAILED_ERROR_NAME = 'FileLoadFailedError';+export const BUDGET_ERROR_NAME = 'FileParseBudgetError';+export const OUTPUT_TOO_LARGE_ERROR_NAME = 'FileParseOutputTooLargeError';diff --git a/apps/server/src/services/fileParse/runner.exitOrder.test.ts b/apps/server/src/services/fileParse/runner.exitOrder.test.tsnew file mode 100644index 00000000000..dc4a7f688ef--- /dev/null+++ b/apps/server/src/services/fileParse/runner.exitOrder.test.ts@@ -0,0 +1,144 @@+import { EventEmitter } from 'node:events';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { FileParseJob } from './protocol';++// The event order "deadline passed, terminate() called, a message still arrives, then exit" cannot+// be produced deterministically with a real thread (terminate() usually drops the pending+// message). The real-thread behaviour is covered in runner.test.ts; this pins the ordering rule.+class FakeWorker extends EventEmitter {+ static instances: FakeWorker[] = [];+ /** Heap probe threads; `autoProbe = false` leaves them to the test to answer. */+ static probes: FakeWorker[] = [];+ static autoProbe = true;+ terminate = vi.fn(async () => 0);+ constructor(_source?: unknown, options?: { eval?: boolean; resourceLimits?: any }) {+ super();+ if (options?.eval) {+ // The runner's heap probe, not a parse worker: reports the limit its resourceLimits give.+ const { maxOldGenerationSizeMb, maxYoungGenerationSizeMb } = options.resourceLimits;+ FakeWorker.probes.push(this);+ if (FakeWorker.autoProbe) {+ queueMicrotask(() => {+ this.emit('message', (maxOldGenerationSizeMb + maxYoungGenerationSizeMb) * 1024 * 1024);+ this.emit('exit', 0);+ });+ }+ return;+ }+ FakeWorker.instances.push(this);+ }+}++vi.mock('node:worker_threads', () => ({ Worker: FakeWorker }));+vi.mock('node:fs/promises', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ access: async () => {},+}));+// The worker is created once the (async) artifact check has passed.+const nextWorker = async () => {+ await vi.advanceTimersByTimeAsync(0);+ return FakeWorker.instances[0];+};++const job = { filePath: '/tmp/a.txt', kind: 'file', mode: 'file' } as FileParseJob;++describe('createFileParseRunner exit ordering', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ FakeWorker.instances = [];+ FakeWorker.probes = [];+ FakeWorker.autoProbe = true;+ });+ afterEach(() => vi.useRealTimers());++ it('rejects with TIMEOUT when a result message arrives after the deadline, before the exit', async () => {+ const { createFileParseRunner } = await import('./runner');+ const runner = createFileParseRunner({+ parseTimeoutMs: 100,+ workerPath: () => '/x/worker.mjs',+ });++ const outcome = runner.run(job).then(+ (value) => ({ value }),+ (error: unknown) => ({ error }),+ );+ const worker = await nextWorker();++ await vi.advanceTimersByTimeAsync(150);+ expect(worker.terminate).toHaveBeenCalledTimes(1);+ // Late message from the dying thread, then the exit.+ worker.emit('message', { type: 'result', value: { content: 'late' } });+ expect(runner.stats().active).toBe(1);+ worker.emit('exit', 1);++ expect(await outcome).toMatchObject({ error: { code: 'TIMEOUT' } });+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });++ it('settles nothing before the exit even when the result message is already in', async () => {+ const { createFileParseRunner } = await import('./runner');+ const runner = createFileParseRunner({ workerPath: () => '/x/worker.mjs' });+ let settled = false;+ const outcome = runner.run(job).finally(() => (settled = true));+ const worker = await nextWorker();++ worker.emit('message', { type: 'result', value: 'ok' });+ await vi.advanceTimersByTimeAsync(1000);+ expect(settled).toBe(false);++ worker.emit('exit', 0);+ await expect(outcome).resolves.toBe('ok');+ });++ it('keeps the slot of a failed heap probe until the probe thread has really exited', async () => {+ FakeWorker.autoProbe = false;+ const { createFileParseRunner } = await import('./runner');+ const runner = createFileParseRunner({ workerPath: () => '/x/worker.mjs' });+ const outcome = runner.run(job).then(+ (value) => ({ value }),+ (error: unknown) => ({ error }),+ );+ await vi.advanceTimersByTimeAsync(0);+ const [probe] = FakeWorker.probes;++ probe.emit('error', new Error('probe crashed'));+ await vi.advanceTimersByTimeAsync(0);+ expect(runner.stats().active).toBe(1);++ probe.emit('exit', 1);+ expect(await outcome).toMatchObject({ error: { code: 'START_FAILED' } });+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ // No parse worker was ever created.+ expect(FakeWorker.instances).toHaveLength(0);+ });++ it('terminates a heap probe that never answers and rejects only after it has exited', async () => {+ FakeWorker.autoProbe = false;+ const { createFileParseRunner } = await import('./runner');+ // A short parse budget must not become the cold-start deadline of the probe thread.+ const runner = createFileParseRunner({+ parseTimeoutMs: 100,+ workerPath: () => '/x/worker.mjs',+ });+ const outcome = runner.run(job).then(+ (value) => ({ value }),+ (error: unknown) => ({ error }),+ );+ await vi.advanceTimersByTimeAsync(0);+ const [probe] = FakeWorker.probes;++ await vi.advanceTimersByTimeAsync(1000);+ expect(probe.terminate).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(60_000);+ expect(probe.terminate).toHaveBeenCalledTimes(1);+ expect(runner.stats().active).toBe(1);++ probe.emit('exit', 1);+ expect(await outcome).toMatchObject({ error: { code: 'START_FAILED' } });+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ expect(FakeWorker.instances).toHaveLength(0);+ });+});diff --git a/apps/server/src/services/fileParse/runner.heapCap.test.ts b/apps/server/src/services/fileParse/runner.heapCap.test.tsnew file mode 100644index 00000000000..ae35f0ba646--- /dev/null+++ b/apps/server/src/services/fileParse/runner.heapCap.test.ts@@ -0,0 +1,192 @@+import { execFile } from 'node:child_process';+import { existsSync } from 'node:fs';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++import { build } from 'esbuild';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++const run = promisify(execFile);++// A V8 heap flag of the PARENT process (CLI or NODE_OPTIONS) overrides `resourceLimits` of every+// worker (Node docs, `new Worker` > `resourceLimits`). It has to be a real parent process: the+// flag is read at process start, so setting `process.env` inside this test would prove nothing.+// The runner is bundled once and driven in a child `node`, started with the flags under test.+const RUNNER = fileURLToPath(new URL('./runner.ts', import.meta.url));+const BUDGET_MB = 768;++const DRIVER = `+import { createFileParseRunner } from ${JSON.stringify(RUNNER)};+const [workerPath, marker, oomLimitMb] = process.argv.slice(2);+const outcome = async (promise) => {+ try { return { value: await promise }; } catch (e) { return { code: e.code, message: e.message }; }+};+(async () => {+ const runner = createFileParseRunner({ workerPath: () => workerPath });+ const results = [];+ results.push(await outcome(runner.run({ marker, scenario: 'heap' })));+ results.push(await outcome(runner.run({ marker, scenario: 'heap' })));+ if (oomLimitMb) {+ const small = createFileParseRunner({+ maxOldGenerationSizeMb: Number(oomLimitMb),+ workerPath: () => workerPath,+ });+ results.push(await outcome(small.run({ marker, scenario: 'oom' })));+ results.push(await outcome(small.run({ marker, scenario: 'heap' })));+ results.push(small.stats());+ }+ results.push(runner.stats());+ console.log(JSON.stringify(results));+})();+`;++// What a parser would see: the heap limit of its thread, reported after the marker is written.+const SCENARIOS = `+import { appendFileSync } from 'node:fs';+import v8 from 'node:v8';+import { parentPort, workerData as job } from 'node:worker_threads';++appendFileSync(job.marker, 'x');+if (job.scenario === 'oom') { const hold = []; for (;;) hold.push(new Array(100000).fill('x'.repeat(16))); }+parentPort.postMessage({ type: 'result', value: v8.getHeapStatistics().heap_size_limit / 1048576 });+`;++let dir: string;+let driverPath: string;+let workerPath: string;+let markerCounter = 0;++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-heapcap-'));+ workerPath = path.join(dir, 'scenarios.mjs');+ driverPath = path.join(dir, 'driver.cjs');+ const entry = path.join(dir, 'driver.mjs');+ await writeFile(workerPath, SCENARIOS);+ await writeFile(entry, DRIVER);+ await build({+ bundle: true,+ entryPoints: [entry],+ format: 'cjs',+ logLevel: 'silent',+ outfile: driverPath,+ platform: 'node',+ });+}, 60_000);++afterAll(() => rm(dir, { force: true, recursive: true }));++const spawnDriver = async (flags: { args?: string[]; nodeOptions?: string }, oomLimitMb = '') => {+ const marker = path.join(dir, `started-${markerCounter++}`);+ const env = { ...process.env };+ delete env.NODE_OPTIONS;+ if (flags.nodeOptions !== undefined) env.NODE_OPTIONS = flags.nodeOptions;+ const { stdout } = await run(+ process.execPath,+ [...(flags.args ?? []), driverPath, workerPath, marker, oomLimitMb],+ { env, timeout: 60_000 },+ );+ return { marker, results: JSON.parse(stdout.trim().split('\n').pop()!) as any[] };+};++describe('parent V8 heap flags vs the worker memory budget', () => {+ it('runs with the configured heap when the parent sets no heap flag, and recovers from OOM', async () => {+ const { marker, results } = await spawnDriver({}, '64');++ // Young generation is on top of the old generation budget; both runs are the same bounded thread.+ expect(results[0].value).toBeGreaterThan(BUDGET_MB);+ expect(results[0].value).toBeLessThan(BUDGET_MB + 400);+ expect(results[1].value).toBe(results[0].value);+ // A real heap exhaustion is typed, frees the slot, and the next job still runs.+ expect(results[2]).toMatchObject({ code: 'OUT_OF_MEMORY' });+ expect(results[3].value).toBeGreaterThan(64);+ expect(results[4]).toEqual({ active: 0, queued: 0 });+ expect(results[5]).toEqual({ active: 0, queued: 0 });+ expect(existsSync(marker)).toBe(true);+ }, 60_000);++ // Every form that gives the parent a larger old-space limit: CLI or NODE_OPTIONS, `-` or `_`.+ it.each([+ ['CLI --max-old-space-size', { args: ['--max-old-space-size=4096'] }],+ ['CLI --max_old_space_size', { args: ['--max_old_space_size=4096'] }],+ ['NODE_OPTIONS --max-old-space-size', { nodeOptions: '--max-old-space-size=4096' }],+ ['NODE_OPTIONS --max_old_space_size', { nodeOptions: '--max_old_space_size=4096' }],+ ['CLI --max-heap-size', { args: ['--max-heap-size=4096'] }],+ ])(+ 'refuses before loading any parser when the parent has %s above the budget',+ async (_, flags) => {+ const { marker, results } = await spawnDriver(flags);++ for (const result of results.slice(0, 2)) {+ expect(result).toMatchObject({ code: 'START_FAILED' });+ expect(result.message).toMatch(/--max-old-space-size/);+ }+ // The scenario (the parser entry) never ran, the slot is free and the queue still moves.+ expect(existsSync(marker)).toBe(false);+ expect(results[2]).toEqual({ active: 0, queued: 0 });+ },+ 60_000,+ );++ it.each([+ ['equal to the budget', { nodeOptions: `--max-old-space-size=${BUDGET_MB}` }, 768],+ ['smaller than the budget', { nodeOptions: '--max-old-space-size=256' }, 256],+ ['smaller, as CLI', { args: ['--max_old_space_size=256'] }, 256],+ ])(+ 'keeps working when the parent flag is %s (the heap is not larger)',+ async (_, flags, mb) => {+ const { marker, results } = await spawnDriver(flags);++ expect(results[0].value).toBeGreaterThanOrEqual(mb);+ expect(results[0].value).toBeLessThan(mb + 400);+ expect(results[1].value).toBe(results[0].value);+ expect(existsSync(marker)).toBe(true);+ },+ 60_000,+ );++ // Node versions differ in which heap option forms they accept. An accepted form must fail+ // closed in the runner (START_FAILED, parser never started); otherwise Node must reject the+ // specific option at startup, rather than crash or time out.+ it.each([+ [+ 'CLI --max-old-space-size (space-separated)',+ { args: ['--max-old-space-size', '4096'] },+ /bad option: --max-old-space-size(?:\s|$)/,+ ],+ [+ 'NODE_OPTIONS --max-old-space-size (space-separated)',+ { nodeOptions: '--max-old-space-size 4096' },+ /bad option: --max-old-space-size(?:\s|$)/,+ ],+ [+ 'NODE_OPTIONS --max-heap-size',+ { nodeOptions: '--max-heap-size=4096' },+ /--max-heap-size=? is not allowed in NODE_OPTIONS/,+ ],+ ])(+ 'never starts a parser with a larger heap for version-dependent option forms (%s)',+ async (_, flags, rejection) => {+ const outcome = await spawnDriver(flags).then(+ (value) => ({ value }),+ (error: { code?: number; signal?: string | null; stderr?: string }) => ({ error }),+ );++ if ('error' in outcome) {+ // Node rejected the flag itself: an actual option error, not a crash from something else.+ expect(outcome.error.code).toBe(9);+ expect(outcome.error.signal).toBeNull();+ expect(outcome.error.stderr).toMatch(rejection);+ return;+ }+ for (const result of outcome.value.results.slice(0, 2)) {+ expect(result).toMatchObject({ code: 'START_FAILED' });+ expect(result.message).toMatch(/--max-old-space-size/);+ }+ expect(existsSync(outcome.value.marker)).toBe(false);+ },+ 60_000,+ );+});diff --git a/apps/server/src/services/fileParse/runner.queueLimits.test.ts b/apps/server/src/services/fileParse/runner.queueLimits.test.tsnew file mode 100644index 00000000000..51a0d94ec8c--- /dev/null+++ b/apps/server/src/services/fileParse/runner.queueLimits.test.ts@@ -0,0 +1,247 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { MAX_UPLOAD_FILE_COUNT } from '@lobechat/const';+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';++import type { FileParseJob } from './protocol';+import { createFileParseRunner, DEFAULT_FILE_PARSE_LIMITS } from './runner';++// Real worker threads: the budget must be released when a task leaves the queue, whichever way.+// `ms` is how long the thread keeps the slot busy.+const SCENARIOS = `+import { parentPort, workerData as job } from 'node:worker_threads';+import { spawnSync } from 'node:child_process';+// A native sleep keeps the thread where terminate() cannot interrupt it.+if (job.sleep) spawnSync('sleep', [String(job.sleep)]);+const end = Date.now() + (job.ms ?? 0);+while (Date.now() < end);+parentPort.postMessage({ type: 'result', value: 'done' });+`;++let dir: string;+let workerPath: string;++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-queue-limits-'));+ workerPath = path.join(dir, 'scenarios.mjs');+ await writeFile(workerPath, SCENARIOS);+});++afterAll(() => rm(dir, { force: true, recursive: true }));+afterEach(() => vi.restoreAllMocks());++/** A file job waits as a path: it holds no bytes. */+const fileJob = (ms = 0) =>+ ({ filePath: '/unused/report.pdf', kind: 'file', mode: 'file', ms }) as unknown as FileParseJob;+/** A dataset job waits with its content in memory. */+const datasetJob = (bytes: number, ms = 0) =>+ ({ content: new Uint8Array(bytes), kind: 'dataset', ms }) as unknown as FileParseJob;++/** A chunk job also waits with the whole file in memory. */+const chunkJob = (bytes: number, ms = 0) =>+ ({+ content: new Uint8Array(bytes),+ filename: 'a.xlsx',+ kind: 'chunk',+ ms,+ }) as unknown as FileParseJob;++const rejection = (promise: Promise<unknown>) =>+ promise.then(+ () => undefined,+ (error) => error,+ );++describe('default queue limits', () => {+ it('keeps one slot and a queue that holds the rest of one upload', () => {+ expect(DEFAULT_FILE_PARSE_LIMITS.maxConcurrent).toBe(1);+ expect(DEFAULT_FILE_PARSE_LIMITS.maxOldGenerationSizeMb).toBe(768);+ expect(DEFAULT_FILE_PARSE_LIMITS.maxQueue).toBeGreaterThanOrEqual(MAX_UPLOAD_FILE_COUNT - 1);+ });++ it('parses a whole upload of ordinary attachments at once, and refuses the one after', async () => {+ const runner = createFileParseRunner({ workerPath: () => workerPath });++ // resolveAttachments starts every attachment together (Promise.all).+ const upload = Array.from({ length: MAX_UPLOAD_FILE_COUNT }, (_, i) =>+ runner.run(fileJob(i === 0 ? 150 : 0)),+ );+ expect(runner.stats()).toEqual({ active: 1, queued: MAX_UPLOAD_FILE_COUNT - 1 });++ const eleventh = await rejection(runner.run(fileJob()));+ expect(eleventh).toMatchObject({ code: 'QUEUE_FULL' });+ expect(runner.stats()).toEqual({ active: 1, queued: MAX_UPLOAD_FILE_COUNT - 1 });++ await expect(Promise.all(upload)).resolves.toEqual(+ Array.from({ length: MAX_UPLOAD_FILE_COUNT }, () => 'done'),+ );+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });+});++describe('queue wait budget', () => {+ it('is the bounded serial time of one normal upload: parse timeout x upload file count', () => {+ expect(DEFAULT_FILE_PARSE_LIMITS.maxConcurrent).toBe(1);+ expect(DEFAULT_FILE_PARSE_LIMITS.parseTimeoutMs).toBe(60_000);+ expect(DEFAULT_FILE_PARSE_LIMITS.queueTimeoutMs).toBe(+ DEFAULT_FILE_PARSE_LIMITS.parseTimeoutMs * MAX_UPLOAD_FILE_COUNT,+ );+ // the last queued task waits behind at most maxQueue tasks that each run a full timeout+ expect(DEFAULT_FILE_PARSE_LIMITS.queueTimeoutMs).toBeGreaterThan(+ DEFAULT_FILE_PARSE_LIMITS.parseTimeoutMs * DEFAULT_FILE_PARSE_LIMITS.maxQueue,+ );+ });++ it('lets a whole upload of slow files finish one after another', async () => {+ // Observe the scheduled budgets without advancing a fake clock alongside real workers.+ // Ten serial parse budgets must fit; the old fixed 30s queue budget would expire too early.+ const timers = vi.spyOn(globalThis, 'setTimeout');+ const runner = createFileParseRunner({ parseTimeoutMs: 5000, workerPath: () => workerPath });+ const starts: number[] = [];+ const upload = Array.from({ length: MAX_UPLOAD_FILE_COUNT }, (_, i) =>+ runner.run(fileJob(), { onStart: () => starts.push(i) }),+ );+ expect(runner.stats()).toEqual({ active: 1, queued: MAX_UPLOAD_FILE_COUNT - 1 });++ await expect(Promise.all(upload)).resolves.toEqual(+ Array.from({ length: MAX_UPLOAD_FILE_COUNT }, () => 'done'),+ );+ expect(starts).toEqual(Array.from({ length: MAX_UPLOAD_FILE_COUNT }, (_, i) => i));+ const budgets = timers.mock.calls.map(([, delay]) => delay);+ expect(budgets.filter((delay) => delay === 5000)).toHaveLength(MAX_UPLOAD_FILE_COUNT);+ expect(budgets.filter((delay) => delay === 5000 * MAX_UPLOAD_FILE_COUNT)).toHaveLength(+ MAX_UPLOAD_FILE_COUNT - 1,+ );+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ }, 20_000);++ it('still bounds the wait: a queued task behind a thread that will not die gives up at the derived budget', async () => {+ // parse timeout 200ms, queue of 2 => 600ms. The thread sits in native code for 2s.+ const timers = vi.spyOn(globalThis, 'setTimeout');+ const runner = createFileParseRunner({+ maxQueue: 2,+ parseTimeoutMs: 200,+ workerPath: () => workerPath,+ });+ const stuck = rejection(runner.run({ ...fileJob(), sleep: 2 } as unknown as FileParseJob));+ const queued = await rejection(runner.run(fileJob()));++ expect(queued).toMatchObject({ code: 'QUEUE_TIMEOUT' });+ expect(timers.mock.calls.map(([, delay]) => delay)).toContain(600);+ expect(runner.stats()).toEqual({ active: 1, queued: 0 });+ expect(await stuck).toMatchObject({ code: 'TIMEOUT' });+ }, 20_000);++ it('an explicit queueTimeoutMs still wins', async () => {+ const runner = createFileParseRunner({+ parseTimeoutMs: 5000,+ queueTimeoutMs: 100,+ workerPath: () => workerPath,+ });+ const running = runner.run(fileJob(400));+ expect(await rejection(runner.run(fileJob()))).toMatchObject({ code: 'QUEUE_TIMEOUT' });+ await running;+ });+});++describe('queued input byte budget', () => {+ const makeRunner = (+ extra: Parameters<typeof createFileParseRunner>[0] extends infer T ? Partial<T> : never = {},+ ) => createFileParseRunner({ maxQueuedBytes: 100, workerPath: () => workerPath, ...extra });++ it('has a default that keeps queued content well inside the process memory', () => {+ expect(DEFAULT_FILE_PARSE_LIMITS.maxQueuedBytes).toBe(128 * 1024 * 1024);+ });++ it('refuses at once a task whose content would push the waiting bytes over the budget', async () => {+ const runner = makeRunner();+ const running = runner.run(fileJob(200));+ const waiting = [runner.run(datasetJob(60)), runner.run(datasetJob(40))];+ expect(runner.stats()).toEqual({ active: 1, queued: 2 });++ // 100 of 100 bytes are queued: even one more byte is refused, count is far from the limit.+ const error = await rejection(runner.run(datasetJob(1)));+ expect(error).toMatchObject({ code: 'QUEUE_FULL' });+ expect(runner.stats()).toEqual({ active: 1, queued: 2 });++ await Promise.all([running, ...waiting]);+ });++ it('counts string content by its UTF-8 bytes', async () => {+ const runner = makeRunner();+ const running = runner.run(fileJob(150));+ // 40 CJK characters are 120 bytes, over the 100-byte budget although only 40 characters long.+ const text = { content: '数'.repeat(40), kind: 'dataset', ms: 0 } as unknown as FileParseJob;+ const error = await rejection(runner.run(text));+ expect(error).toMatchObject({ code: 'QUEUE_FULL' });+ await running;+ });++ it('does not count a file job, which waits as a path', async () => {+ const runner = makeRunner();+ const running = runner.run(fileJob(150));+ const waiting = [runner.run(datasetJob(100)), runner.run(fileJob()), runner.run(fileJob())];+ expect(runner.stats()).toEqual({ active: 1, queued: 3 });+ await Promise.all([running, ...waiting]);+ });++ it('gives the budget back when a queued task starts', async () => {+ const runner = makeRunner();+ const running = runner.run(fileJob(100));+ const queued = runner.run(datasetJob(100, 200));+ expect(await rejection(runner.run(datasetJob(10)))).toMatchObject({ code: 'QUEUE_FULL' });++ await running; // the queued dataset job now holds the slot, no longer the queue+ expect(runner.stats()).toMatchObject({ active: 1, queued: 0 });+ const next = runner.run(datasetJob(100));+ expect(runner.stats()).toEqual({ active: 1, queued: 1 });++ await Promise.all([queued, next]);+ });++ it('gives the budget back when a queued task times out', async () => {+ const runner = makeRunner({ queueTimeoutMs: 100 });+ const running = runner.run(fileJob(400));+ const timedOut = await rejection(runner.run(datasetJob(100)));+ expect(timedOut).toMatchObject({ code: 'QUEUE_TIMEOUT' });+ expect(runner.stats()).toEqual({ active: 1, queued: 0 });++ // The whole budget is free again: a 100-byte task is accepted (and later times out as well).+ const next = rejection(runner.run(datasetJob(100)));+ expect(runner.stats()).toEqual({ active: 1, queued: 1 });+ expect(await next).toMatchObject({ code: 'QUEUE_TIMEOUT' });+ await running;+ });++ it('does not charge a refused task', async () => {+ const runner = makeRunner();+ const running = runner.run(fileJob(150));+ expect(await rejection(runner.run(datasetJob(101)))).toMatchObject({ code: 'QUEUE_FULL' });+ const fits = runner.run(datasetJob(100));+ expect(runner.stats()).toEqual({ active: 1, queued: 1 });+ await Promise.all([running, fits]);+ });+});++describe('chunk jobs share the queue byte budget', () => {+ it('counts the content of waiting chunk jobs and refuses what would not fit', async () => {+ const runner = createFileParseRunner({+ maxQueuedBytes: 1000,+ queueTimeoutMs: 5000,+ workerPath: () => workerPath,+ });+ const running = runner.run(fileJob(150));+ const waiting = runner.run(chunkJob(600));++ const refused = await rejection(runner.run(chunkJob(401)));+ expect(refused).toMatchObject({ code: 'QUEUE_FULL' });+ // a rejected job holds nothing, and a dataset job competes for the very same budget+ const fits = runner.run(datasetJob(400));+ expect(runner.stats().queued).toBe(2);+ expect(await rejection(runner.run(datasetJob(1)))).toMatchObject({ code: 'QUEUE_FULL' });++ await Promise.all([running, waiting, fits]);+ });+});diff --git a/apps/server/src/services/fileParse/runner.scratch.test.ts b/apps/server/src/services/fileParse/runner.scratch.test.tsnew file mode 100644index 00000000000..3c0b30e72f1--- /dev/null+++ b/apps/server/src/services/fileParse/runner.scratch.test.ts@@ -0,0 +1,232 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import type * as FsPromises from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import type { FileParseJob } from './protocol';+import { createFileParseRunner } from './runner';++// The runner prepares its scratch directory and checks the artifact with async fs only, and says+// so (a structured event, no path) when the scratch directory cannot be removed. The hooks let a+// test hold or fail one fs call while the worker thread stays real.+const hooks = vi.hoisted(() => ({+ access: undefined as undefined | ((...args: unknown[]) => Promise<unknown>),+ mkdtemp: undefined as undefined | ((...args: unknown[]) => Promise<unknown>),+ rm: undefined as undefined | ((...args: unknown[]) => Promise<unknown>),+}));++vi.mock('node:fs/promises', async (importOriginal) => {+ const actual = await importOriginal<typeof FsPromises>();+ return {+ ...actual,+ access: (...args: unknown[]) =>+ hooks.access ? hooks.access(...args) : (actual.access as any)(...args),+ mkdtemp: (...args: unknown[]) =>+ hooks.mkdtemp ? hooks.mkdtemp(...args) : (actual.mkdtemp as any)(...args),+ rm: (...args: unknown[]) => (hooks.rm ? hooks.rm(...args) : (actual.rm as any)(...args)),+ };+});++// The request thread must not touch the filesystem synchronously for a task.+vi.mock('node:fs', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ existsSync: () => {+ throw new Error('existsSync on the request thread');+ },+ mkdtempSync: () => {+ throw new Error('mkdtempSync on the request thread');+ },+}));++// The module is mocked below; the test itself talks to the real one.+const {+ mkdtemp: realMkdtemp,+ readdir,+ rm: realRm,+ writeFile,+} = await vi.importActual<typeof FsPromises>('node:fs/promises');++const SCENARIOS = `+import { parentPort, workerData as job } from 'node:worker_threads';+const end = Date.now() + (job.ms ?? 0);+while (Date.now() < end);+if (job.scenario === 'error') parentPort.postMessage({ type: 'error', error: { name: 'Error', message: 'corrupt zip' } });+else parentPort.postMessage({ type: 'result', value: process.env.TMPDIR });+`;++let dir: string;+let workerPath: string;++beforeAll(async () => {+ dir = await realMkdtemp(path.join(tmpdir(), 'file-parse-scratch-'));+ workerPath = path.join(dir, 'scenarios.mjs');+ await writeFile(workerPath, SCENARIOS);+});+afterAll(() => realRm(dir, { force: true, recursive: true }));++let scratchRoot: string;+let previousTmp: string | undefined;+beforeEach(async () => {+ scratchRoot = await realMkdtemp(path.join(tmpdir(), 'file-parse-scratch-root-'));+ previousTmp = process.env.TMPDIR;+ process.env.TMPDIR = scratchRoot;+});+afterEach(async () => {+ hooks.access = hooks.mkdtemp = hooks.rm = undefined;+ vi.restoreAllMocks();+ if (previousTmp === undefined) delete process.env.TMPDIR;+ else process.env.TMPDIR = previousTmp;+ await realRm(scratchRoot, { force: true, recursive: true });+});++const chunkJob = (extra: Record<string, unknown> = {}) =>+ ({+ content: new Uint8Array(4),+ filename: 'secret-name.epub',+ kind: 'chunk',+ ...extra,+ }) as unknown as FileParseJob;+const fileJob = () =>+ ({ filePath: '/unused/report.pdf', kind: 'file', mode: 'file' }) as unknown as FileParseJob;+const make = (+ limits: Parameters<typeof createFileParseRunner>[0] extends infer T ? Partial<T> : never = {},+) => createFileParseRunner({ workerPath: () => workerPath, ...limits });+const rejection = (promise: Promise<unknown>) =>+ promise.then(+ () => undefined,+ (e) => e,+ );+const deferred = <T = void>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => ((resolve = res), (reject = rej)));+ return { promise, reject, resolve };+};+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++describe('async preparation on the request thread', () => {+ it('runs file and chunk jobs without sync fs (existsSync / mkdtempSync would throw)', async () => {+ const runner = make();+ await expect(runner.run(fileJob())).resolves.toBeDefined();+ const scratch = await runner.run<string>(chunkJob());+ expect(path.dirname(scratch)).toBe(scratchRoot);+ expect(await readdir(scratchRoot)).toEqual([]);+ });++ it('takes the slot at once, so a task arriving while the scratch directory is being made queues', async () => {+ const made = deferred<string>();+ hooks.mkdtemp = () => made.promise;+ const runner = make();+ const started: string[] = [];++ const first = runner.run<string>(chunkJob(), { onStart: () => started.push('first') });+ expect(runner.stats()).toEqual({ active: 1, queued: 0 });+ const second = runner.run<string>(fileJob(), { onStart: () => started.push('second') });+ expect(runner.stats()).toEqual({ active: 1, queued: 1 });+ await sleep(50);+ expect(started).toEqual([]); // nothing runs before the directory exists++ made.resolve(await realMkdtemp(path.join(scratchRoot, 'file-parse-')));+ await Promise.all([first, second]);+ expect(started).toEqual(['first', 'second']);+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });++ it('gives the slot back and runs the next task when the scratch directory cannot be made', async () => {+ hooks.mkdtemp = () => Promise.reject(Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' }));+ const runner = make();+ const failing = rejection(runner.run(chunkJob()));+ const next = runner.run(fileJob());+ expect(await failing).toMatchObject({ code: 'START_FAILED' });+ await expect(next).resolves.toBeDefined();+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });++ it('fails closed with UNAVAILABLE when the artifact is missing, and moves on', async () => {+ let missing = true;+ const runner = createFileParseRunner({+ workerPath: () => (missing ? path.join(dir, 'nope.mjs') : workerPath),+ });+ const first = rejection(runner.run(fileJob()));+ const second = runner.run(fileJob());+ expect(await first).toMatchObject({ code: 'UNAVAILABLE' });+ // `second` was queued behind the first; it saw the same missing file.+ expect(await rejection(second)).toMatchObject({ code: 'UNAVAILABLE' });+ missing = false;+ await expect(runner.run(fileJob())).resolves.toBeDefined();+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });++ it('keeps each task activity: a bound onStart sees the context of its own caller', async () => {+ const { AsyncResource } = await import('node:async_hooks');+ const als = new AsyncLocalStorage<string>();+ const seen: Array<[string, string | undefined]> = [];+ const runner = make();+ const run = (name: string) =>+ als.run(name, () =>+ runner.run(chunkJob(), {+ onStart: AsyncResource.bind(() => seen.push([name, als.getStore()])),+ }),+ );+ await Promise.all([run('a'), run('b'), run('c')]);+ expect(seen).toEqual([+ ['a', 'a'],+ ['b', 'b'],+ ['c', 'c'],+ ]);+ });+});++describe('scratch directory cleanup', () => {+ it('settles only after the removal, and frees the slot only then', async () => {+ const removal = deferred();+ hooks.rm = (...args) => removal.promise.then(() => (realRm as any)(...args));+ const runner = make();+ let settled = false;+ const run = runner.run<string>(chunkJob()).finally(() => (settled = true));+ await sleep(300); // the thread has long exited+ expect(settled).toBe(false);+ expect(runner.stats().active).toBe(1);+ // a new task cannot jump the queue in the gap+ const waiting = runner.run(fileJob());+ expect(runner.stats()).toEqual({ active: 1, queued: 1 });++ removal.resolve();+ await Promise.all([run, waiting]);+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });++ it('reports a failed removal as its own event and keeps the parse result', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ hooks.rm = () =>+ Promise.reject(Object.assign(new Error(`EIO at ${scratchRoot}/x`), { code: 'EIO' }));+ const runner = make();++ const value = await runner.run<string>(chunkJob());+ expect(path.dirname(value)).toBe(scratchRoot); // the original result, untouched+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });++ const lines = warn.mock.calls.map(([line]) => String(line));+ expect(lines).toHaveLength(1);+ expect(JSON.parse(lines[0])).toEqual({+ code: 'EIO',+ event: 'file_parse.cleanup_failed',+ jobKind: 'chunk',+ });+ expect(lines[0]).not.toContain(scratchRoot);+ expect(lines[0]).not.toContain('secret-name');+ });++ it('keeps the original error when the parse failed and the removal failed too', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ hooks.rm = () => Promise.reject(Object.assign(new Error('EPERM'), { code: 'EPERM' }));+ const runner = make();++ const error = await rejection(runner.run(chunkJob({ scenario: 'error' })));+ expect(error).toMatchObject({ code: 'PARSE_FAILED', message: 'corrupt zip' });+ expect(warn).toHaveBeenCalledTimes(1);+ expect(JSON.parse(String(warn.mock.calls[0][0]))).toMatchObject({ code: 'EPERM' });+ });+});diff --git a/apps/server/src/services/fileParse/runner.test.ts b/apps/server/src/services/fileParse/runner.test.tsnew file mode 100644index 00000000000..bfb623091eb--- /dev/null+++ b/apps/server/src/services/fileParse/runner.test.ts@@ -0,0 +1,252 @@+import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { UnsupportedFileTypeError } from '@lobechat/file-loaders';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { FileParseError } from './errors';+import type { FileParseJob } from './protocol';+import { createFileParseRunner } from './runner';++// Real worker threads running a scenario script: the runner's contract is about thread exit, which+// no mock can stand in for. A scenario spins on the CPU like a heavy parser does.+const SCENARIOS = `+import { spawnSync } from 'node:child_process';+import { appendFileSync } from 'node:fs';+import { parentPort, workerData as job } from 'node:worker_threads';++const busy = (ms) => { const end = Date.now() + ms; while (Date.now() < end); };+// Keeps writing while alive, so a test can tell when the thread is really gone.+const beat = (file) => { for (;;) { appendFileSync(file, 'x'); busy(10); } };+const post = (message) => parentPort.postMessage(message);++switch (job.scenario) {+ case 'busy': busy(job.ms); post({ type: 'result', value: job.value ?? 'done' }); break;+ case 'forever': beat(job.beatFile); break;+ case 'result-then-spin': post({ type: 'result', value: 'ok' }); beat(job.beatFile); break;+ case 'throw': throw new Error('boom at top level');+ case 'exit': process.exit(3);+ case 'unsupported': post({ type: 'error', error: { name: 'UnsupportedFileTypeError', fileType: 'xyz', message: 'x' } }); break;+ case 'load-failed': post({ type: 'error', error: { name: 'FileLoadFailedError', message: 'all pages failed' } }); break;+ case 'plain-error': post({ type: 'error', error: { name: 'Error', message: 'corrupt zip' } }); break;+ case 'native-block': spawnSync('sleep', [String(job.seconds)]); beat(job.beatFile); break;+ case 'oom': { const hold = []; for (;;) hold.push(new Array(100000).fill('x'.repeat(16))); }+ case 'env': post({ type: 'result', value: Object.keys(process.env) }); break;+}+`;++let dir: string;+let workerPath: string;+let beatCounter = 0;++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-runner-'));+ workerPath = path.join(dir, 'scenarios.mjs');+ await writeFile(workerPath, SCENARIOS);+});++afterAll(() => rm(dir, { force: true, recursive: true }));++const job = (data: Record<string, unknown>) => data as unknown as FileParseJob;+const newBeatFile = () => path.join(dir, `beat-${beatCounter++}`);+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+const sizeOf = async (file: string) => (await stat(file).catch(() => ({ size: 0 }))).size;++const makeRunner = (+ limits: Parameters<typeof createFileParseRunner>[0] extends infer T ? Partial<T> : never = {},+) => createFileParseRunner({ workerPath: () => workerPath, ...limits });++const rejection = async (promise: Promise<unknown>) => {+ try {+ await promise;+ } catch (error) {+ return error;+ }+ throw new Error('expected the task to reject');+};++describe('createFileParseRunner', () => {+ it('keeps the main thread timers running while a worker holds the CPU', async () => {+ const runner = makeRunner();+ let ticks = 0;+ const interval = setInterval(() => {+ ticks += 1;+ }, 20);++ let value;+ try {+ value = await runner.run(job({ ms: 700, scenario: 'busy' }));+ } finally {+ clearInterval(interval);+ }++ expect(value).toBe('done');+ expect(ticks).toBeGreaterThan(0);+ });++ it('terminates a worker that outlives its budget and settles only after it exited', async () => {+ const runner = makeRunner({ parseTimeoutMs: 200 });+ const beatFile = newBeatFile();++ const error = await rejection(runner.run(job({ beatFile, scenario: 'forever' })));++ expect(error).toMatchObject({ code: 'TIMEOUT', name: 'FileParseError' });+ // The slot is free and the thread no longer writes: the exit had happened before the rejection.+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ const afterReject = await sizeOf(beatFile);+ await sleep(150);+ expect(await sizeOf(beatFile)).toBe(afterReject);+ });++ it('resolves a finished task only once its thread is gone', async () => {+ const runner = makeRunner();+ const beatFile = newBeatFile();++ await expect(runner.run(job({ beatFile, scenario: 'result-then-spin' }))).resolves.toBe('ok');++ expect(runner.stats().active).toBe(0);+ const afterResolve = await sizeOf(beatFile);+ await sleep(150);+ expect(await sizeOf(beatFile)).toBe(afterResolve);+ });++ it('refuses work beyond slots plus queue at once, and runs queued work in order', async () => {+ const runner = makeRunner({ maxConcurrent: 1, maxQueue: 1 });+ const order: string[] = [];+ const first = runner+ .run(job({ ms: 300, scenario: 'busy', value: 'first' }))+ .then((v) => order.push(String(v)));+ const second = runner+ .run(job({ ms: 10, scenario: 'busy', value: 'second' }))+ .then((v) => order.push(String(v)));+ expect(runner.stats()).toEqual({ active: 1, queued: 1 });++ const error = await rejection(runner.run(job({ ms: 10, scenario: 'busy', value: 'third' })));+ expect(error).toMatchObject({ code: 'QUEUE_FULL' });+ expect(order).toEqual([]);++ await Promise.all([first, second]);+ expect(order).toEqual(['first', 'second']);+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });++ it('fails a task that waits too long for a slot without disturbing the running one', async () => {+ const runner = makeRunner({ queueTimeoutMs: 100 });+ const running = runner.run(job({ ms: 500, scenario: 'busy' }));+ const waiting = runner.run(job({ ms: 10, scenario: 'busy' }));++ const error = await rejection(waiting);++ expect(error).toMatchObject({ code: 'QUEUE_TIMEOUT' });+ expect((error as FileParseError).retryable).toBe(true);+ expect(runner.stats()).toEqual({ active: 1, queued: 0 });+ await expect(running).resolves.toBe('done');+ });++ it.each([+ ['throws outside the parse', 'throw', 'WORKER_FAILED'],+ ['exits without a message', 'exit', 'WORKER_FAILED'],+ ['reports a parse error', 'plain-error', 'PARSE_FAILED'],+ ['reports a failed load', 'load-failed', 'LOAD_FAILED'],+ ])(+ 'rejects with a typed error when a worker %s, and the next task still runs',+ async (_, scenario, code) => {+ const runner = makeRunner();++ const error = await rejection(runner.run(job({ scenario })));+ expect(error).toBeInstanceOf(FileParseError);+ expect(error).toMatchObject({ code });++ expect(runner.stats().active).toBe(0);+ await expect(runner.run(job({ ms: 1, scenario: 'busy' }))).resolves.toBe('done');+ },+ );++ it('turns running out of the heap limit into a typed error and survives it', async () => {+ const runner = makeRunner({ maxOldGenerationSizeMb: 64 });++ const error = await rejection(runner.run(job({ scenario: 'oom' })));++ expect(error).toMatchObject({ code: 'OUT_OF_MEMORY' });+ await expect(runner.run(job({ ms: 1, scenario: 'busy' }))).resolves.toBe('done');+ });++ it('keeps UnsupportedFileTypeError semantics across the thread boundary', async () => {+ const runner = makeRunner();++ const error = await rejection(+ runner.run(+ job({+ filePath: '/tmp/some/archive.xyz',+ kind: 'file',+ mode: 'file',+ scenario: 'unsupported',+ }),+ ),+ );++ expect(error).toBeInstanceOf(UnsupportedFileTypeError);+ expect((error as UnsupportedFileTypeError).message).toBe(+ "Unsupported file type 'xyz' for file 'archive.xyz'.",+ );+ });++ it('never falls back to parsing in-process when the artifact is missing', async () => {+ const runner = createFileParseRunner({ workerPath: () => path.join(dir, 'missing.mjs') });++ const error = await rejection(runner.run(job({ scenario: 'busy' })));++ expect(error).toMatchObject({ code: 'UNAVAILABLE' });+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ });++ it('gives the worker no process credentials', async () => {+ process.env.FILE_PARSE_TEST_SECRET = 'secret';+ try {+ const keys = await makeRunner().run<string[]>(job({ scenario: 'env' }));+ expect(keys).not.toContain('FILE_PARSE_TEST_SECRET');+ expect(keys).not.toContain('DATABASE_URL');+ } finally {+ delete process.env.FILE_PARSE_TEST_SECRET;+ }+ });++ it('keeps a task pending, its temp file and the queue untouched until a stuck thread has exited', async () => {+ // The queue wait is fixed: the default follows the parse timeout, which is 100ms here.+ const runner = makeRunner({ parseTimeoutMs: 100, queueTimeoutMs: 10_000 });+ const beatFile = newBeatFile();+ const tempFile = path.join(dir, `temp-${beatCounter++}`);+ await writeFile(tempFile, 'payload');++ // Like DocumentService: the temp file goes in `finally`, i.e. as soon as the task settles.+ let settled = false;+ // `sleep` blocks the thread in native code for 1.2s: terminate() cannot interrupt it.+ const stuck = runner+ .run(job({ beatFile, scenario: 'native-block', seconds: 1.2 }))+ .finally(() => {+ settled = true;+ return rm(tempFile, { force: true });+ });+ const stuckResult = rejection(stuck);+ let nextStarted = false;+ const next = runner.run(job({ ms: 1, scenario: 'busy', value: 'after' }), {+ onStart: () => (nextStarted = true),+ });++ // Well past the 100ms deadline (terminate() was called), long before the sleep returns.+ await sleep(600);+ expect(settled).toBe(false);+ expect(await sizeOf(tempFile)).toBeGreaterThan(0);+ expect(nextStarted).toBe(false);+ expect(runner.stats()).toEqual({ active: 1, queued: 1 });++ const error = await stuckResult;+ expect(error).toMatchObject({ code: 'TIMEOUT' });+ expect(settled).toBe(true);+ expect(await sizeOf(tempFile)).toBe(0);+ await expect(next).resolves.toBe('after');+ expect(nextStarted).toBe(true);+ expect(runner.stats().active).toBe(0);+ });+});diff --git a/apps/server/src/services/fileParse/runner.ts b/apps/server/src/services/fileParse/runner.tsnew file mode 100644index 00000000000..660e7b62886--- /dev/null+++ b/apps/server/src/services/fileParse/runner.ts@@ -0,0 +1,424 @@+import { access, mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { Worker } from 'node:worker_threads';++import { MAX_UPLOAD_FILE_COUNT } from '@lobechat/const';+import { FileParseBudgetError, UnsupportedFileTypeError } from '@lobechat/file-loaders';++import { FileParseError, isFileParseError } from './errors';+import type { FileParseJob, FileParseWorkerMessage, SerializedWorkerError } from './protocol';+import {+ BUDGET_ERROR_NAME,+ LOAD_FAILED_ERROR_NAME,+ OUTPUT_TOO_LARGE_ERROR_NAME,+ UNSUPPORTED_FILE_TYPE_ERROR_NAME,+} from './protocol';++/** Limits of one runner. Tests construct their own; production uses these. */+export interface FileParseRunnerOptions {+ /** Tasks running at the same time; each one is a thread that may hold up to its heap limit. */+ maxConcurrent: number;+ /** Heap limit of one worker; it shares the process memory with the request threads. */+ maxOldGenerationSizeMb: number;+ /** Waiting tasks beyond this are refused at once. */+ maxQueue: number;+ /**+ * Input bytes the waiting tasks may hold in memory together. Datasets and chunk jobs carry their+ * content and count; a file job waits as a path and holds no bytes. Beyond this a task is+ * refused at once.+ */+ maxQueuedBytes: number;+ /** Wall time of one parse; the worker is terminated when it runs out. */+ parseTimeoutMs: number;+ /**+ * How long a task may wait for a free slot. Defaults to the longest the tasks ahead can hold it:+ * `parseTimeoutMs` for each of the `maxQueue + 1` tasks, so a full normal upload never times out+ * only because of its own earlier files.+ */+ queueTimeoutMs: number;+ /** Absolute path of the built worker file; read on every task so a missing file fails closed. */+ workerPath: () => string;+}++export const DEFAULT_FILE_PARSE_LIMITS = {+ maxConcurrent: 1,+ maxOldGenerationSizeMb: 768,+ // One upload may carry MAX_UPLOAD_FILE_COUNT files and the attachments are parsed together:+ // with one slot running, the rest of a normal upload must fit in the queue.+ maxQueue: MAX_UPLOAD_FILE_COUNT - 1,+ maxQueuedBytes: 128 * 1024 * 1024,+ parseTimeoutMs: 60_000,+ // The queue holds the rest of one upload (maxQueue), the running task included that is+ // MAX_UPLOAD_FILE_COUNT tasks in series, each bounded by parseTimeoutMs: 10 x 60s = 10 min.+ // Waiting longer than that is a saturated server, not a slow queue.+ queueTimeoutMs: 60_000 * MAX_UPLOAD_FILE_COUNT,+} as const;++/** Environment a worker is given: parsing needs none of the process credentials. */+const WORKER_ENV_KEYS = ['DEBUG', 'LANG', 'NODE_ENV', 'TEMP', 'TMP', 'TMPDIR', 'TZ'] as const;++/**+ * A V8 heap flag on the parent process (`--max-old-space-size` and friends, from the command line+ * or `NODE_OPTIONS`) overrides the `resourceLimits` of every worker thread (Node docs, `Worker`+ * options), and neither the worker `env` nor `execArgv` can undo it. So the budget is verified,+ * not assumed: a probe thread, never a parser, reports the heap limit it really got.+ */+const HEAP_PROBE_YOUNG_MB = 48;+const HEAP_PROBE_SOURCE = `+const { parentPort } = require('node:worker_threads');+parentPort.postMessage(require('node:v8').getHeapStatistics().heap_size_limit);+`;++/**+ * Heap limit (bytes) a thread gets with the given old generation size, as the parent flags leave it.+ * Settles only after the probe thread has exited; a probe that errors or never answers within+ * `timeoutMs` is terminated and rejected, so a stuck probe cannot hold a task forever.+ */+const probeHeapLimitBytes = (maxOldGenerationSizeMb: number, timeoutMs: number) =>+ new Promise<number>((resolve, reject) => {+ let limit: number | undefined;+ let failure: Error | undefined;+ const probe = new Worker(HEAP_PROBE_SOURCE, {+ env: {},+ eval: true,+ execArgv: [],+ resourceLimits: {+ // Explicit, so the expected limit is exactly old + young instead of a V8 default.+ maxOldGenerationSizeMb,+ maxYoungGenerationSizeMb: HEAP_PROBE_YOUNG_MB,+ },+ });+ const timer = setTimeout(() => {+ failure ??= new Error(`heap probe did not answer within ${timeoutMs}ms`);+ void probe.terminate();+ }, timeoutMs);+ probe.on('message', (value: number) => (limit = value));+ probe.on('error', (error) => (failure ??= error));+ probe.on('exit', () => {+ clearTimeout(timer);+ if (failure) reject(failure);+ else if (limit === undefined) reject(new Error('heap probe exited without a result'));+ else resolve(limit);+ });+ });++const buildWorkerEnv = () => {+ const env: Record<string, string> = {};+ for (const key of WORKER_ENV_KEYS) {+ const value = process.env[key];+ if (value !== undefined) env[key] = value;+ }+ return env;+};++export interface FileParseRunOptions {+ /** Called when a slot is taken and the worker starts (the task has stopped waiting). */+ onStart?: () => void;+}++export interface FileParseRunner {+ run: <T>(job: FileParseJob, options?: FileParseRunOptions) => Promise<T>;+ stats: () => { active: number; queued: number };+}++interface Task {+ job: FileParseJob;+ /** Input bytes this task holds while it waits; 0 for a file job, which waits as a path. */+ memoryBytes: number;+ onStart?: () => void;+ reject: (error: Error) => void;+ resolve: (value: never) => void;+}++const heldBytes = (job: FileParseJob) => {+ // Datasets and chunk jobs carry their content; a file job waits as a path and holds nothing.+ const content = 'content' in job ? job.content : undefined;+ if (content === undefined) return 0;+ return typeof content === 'string' ? Buffer.byteLength(content) : content.byteLength;+};++const toTypedError = (error: SerializedWorkerError, job: FileParseJob): Error => {+ // Semantics callers branch on survive the thread boundary.+ if (error.name === UNSUPPORTED_FILE_TYPE_ERROR_NAME && job.kind === 'file') {+ return new UnsupportedFileTypeError(error.fileType ?? '', path.basename(job.filePath));+ }+ // A structural refusal keeps its reason and numbers: callers tell the user the file is too large.+ if (error.name === BUDGET_ERROR_NAME && error.budget) {+ return new FileParseBudgetError(error.budget.reason, error.budget.limit, error.budget.actual);+ }+ if (error.name === LOAD_FAILED_ERROR_NAME)+ return new FileParseError('LOAD_FAILED', error.message);+ if (error.name === OUTPUT_TOO_LARGE_ERROR_NAME)+ return new FileParseError('OUTPUT_TOO_LARGE', error.message);+ return new FileParseError('PARSE_FAILED', error.message);+};++/**+ * Runs each parse on its own `worker_threads` thread, so a parser that blocks for seconds blocks+ * only that thread and never the request thread or any timer-driven background work on it.+ *+ * A task settles only after the thread has really exited, so the slot, the temp file and the+ * memory are free by the time the caller continues. There is no main-thread fallback anywhere.+ */+export const createFileParseRunner = (+ limits: Partial<Omit<FileParseRunnerOptions, 'workerPath'>> &+ Pick<FileParseRunnerOptions, 'workerPath'>,+): FileParseRunner => {+ const merged = { ...DEFAULT_FILE_PARSE_LIMITS, ...limits };+ const options: FileParseRunnerOptions = {+ ...merged,+ // Follows a custom parse timeout / queue size unless the caller fixed the wait itself.+ queueTimeoutMs: limits.queueTimeoutMs ?? merged.parseTimeoutMs * (merged.maxQueue + 1),+ };+ const queue: Array<Task & { timer: NodeJS.Timeout }> = [];+ let active = 0;+ /** The process flags never change, so one successful probe holds for the runner's life. */+ let heapProbe: Promise<number> | undefined;++ /**+ * Fails closed when the parent's V8 flags give a worker more heap than `maxOldGenerationSizeMb`+ * allows. A smaller limit is kept: it is inside the budget (a parse may then run out of memory+ * earlier, as a typed `OUT_OF_MEMORY`).+ */+ const assertHeapBudgetHolds = async () => {+ heapProbe ??= probeHeapLimitBytes(+ options.maxOldGenerationSizeMb,+ // The default parse budget, not the caller's: a thread cold start must not depend on a tight one.+ DEFAULT_FILE_PARSE_LIMITS.parseTimeoutMs,+ );+ let actualBytes: number;+ try {+ actualBytes = await heapProbe;+ } catch (error) {+ heapProbe = undefined;+ throw error;+ }+ const allowedBytes = (options.maxOldGenerationSizeMb + HEAP_PROBE_YOUNG_MB) * 1024 * 1024;+ if (actualBytes > allowedBytes) {+ throw new FileParseError(+ 'START_FAILED',+ `File parse workers get ${Math.round(actualBytes / 1024 / 1024)}MB of heap instead of the ` ++ `${options.maxOldGenerationSizeMb}MB old generation budget: the Node process was started ` ++ 'with a larger V8 heap flag (--max-old-space-size / --max-heap-size, on the command line ' ++ 'or in NODE_OPTIONS), which overrides the worker limit. Remove it or lower it to at most ' ++ 'the budget.',+ );+ }+ };++ /**+ * Removes a scratch directory. A failure never changes the outcome of the task (the parse result+ * or error stays as it is) but is not silent: one event with the job kind and the filesystem+ * error code, never the path or the file name.+ */+ const removeScratch = async (scratchDir: string, kind: FileParseJob['kind']) => {+ try {+ await rm(scratchDir, { force: true, recursive: true });+ } catch (error) {+ console.warn(+ JSON.stringify({+ code: (error as { code?: unknown } | undefined)?.code,+ event: 'file_parse.cleanup_failed',+ jobKind: kind,+ }),+ );+ }+ };++ /** Gives the slot back after everything the task held is gone, then lets the queue move on. */+ const release = () => {+ active -= 1;+ pump();+ };++ /**+ * Runs a task that already owns a slot (`active` was raised by the caller before this first+ * await, so no other task can slip in while the filesystem is being asked). Everything the+ * request thread does here is async: a stalled temp volume delays this task only.+ */+ const start = async (task: Task) => {+ // The artifact is resolved when the task actually starts: a deploy fixing it takes effect at once.+ let workerPath: string;+ try {+ workerPath = options.workerPath();+ await access(workerPath);+ } catch (error) {+ task.reject(+ new FileParseError(+ 'UNAVAILABLE',+ 'File parse worker artifact is missing; build it with `bun run build:file-parse-worker`',+ { cause: error },+ ),+ );+ return release();+ }++ // Before any parser is loaded: a worker that would outgrow its budget never starts.+ try {+ await assertHeapBudgetHolds();+ } catch (error) {+ task.reject(+ isFileParseError(error)+ ? error+ : new FileParseError(+ 'START_FAILED',+ 'Could not verify the file parse worker heap limit',+ {+ cause: error,+ },+ ),+ );+ return release();+ }++ // A chunk job (epub writes a temp file) gets a scratch directory of its own as `TMPDIR`. A+ // thread killed at the deadline cannot run its `finally`, so the runner removes the directory+ // once the thread has exited and before the task settles.+ let scratchDir: string | undefined;+ let worker: Worker;+ try {+ const env = buildWorkerEnv();+ if (task.job.kind === 'chunk') {+ scratchDir = await mkdtemp(path.join(tmpdir(), 'file-parse-'));+ env.TMPDIR = scratchDir;+ }+ task.onStart?.();+ worker = new Worker(workerPath, {+ env,+ // Keep the parent's loaders (tsx, Sentry preloads…) out of the thread.+ execArgv: [],+ resourceLimits: { maxOldGenerationSizeMb: options.maxOldGenerationSizeMb },+ workerData: task.job,+ });+ } catch (error) {+ if (scratchDir) await removeScratch(scratchDir, task.job.kind);+ task.reject(+ new FileParseError('START_FAILED', 'Could not start the file parse worker', {+ cause: error,+ }),+ );+ return release();+ }++ let message: FileParseWorkerMessage | undefined;+ let workerError: (Error & { code?: string }) | undefined;+ let timedOut = false;++ // Only the exit event settles a task. A thread stuck in native code keeps its slot, its temp+ // file and the caller waiting: releasing any of them early would let a second parse start+ // while the first still holds the memory.+ const timeoutTimer = setTimeout(() => {+ timedOut = true;+ void worker.terminate();+ }, options.parseTimeoutMs);++ worker.on('message', (value: FileParseWorkerMessage) => {+ message ??= value;+ clearTimeout(timeoutTimer);+ // The result is in; end the thread and wait for the exit event to settle.+ void worker.terminate();+ });+ worker.on('error', (error: Error) => {+ workerError ??= error;+ });+ const settleAfterExit = (code: number) => {+ // Timeout first: a result that arrived after the deadline must not be accepted (and stored).+ if (timedOut) {+ return task.reject(+ new FileParseError('TIMEOUT', `File parsing exceeded ${options.parseTimeoutMs}ms`),+ );+ }+ if (message?.type === 'result') return task.resolve(message.value as never);+ if (message?.type === 'error') return task.reject(toTypedError(message.error, task.job));+ if (workerError?.code === 'ERR_WORKER_OUT_OF_MEMORY') {+ return task.reject(+ new FileParseError(+ 'OUT_OF_MEMORY',+ `File parsing exceeded the ${options.maxOldGenerationSizeMb}MB worker memory limit`,+ { cause: workerError },+ ),+ );+ }+ if (workerError) {+ return task.reject(+ new FileParseError('WORKER_FAILED', `File parse worker failed: ${workerError.message}`, {+ cause: workerError,+ }),+ );+ }+ task.reject(+ new FileParseError(+ 'WORKER_FAILED',+ `File parse worker exited with code ${code} without a result`,+ ),+ );+ };+ worker.on('exit', (code) => {+ clearTimeout(timeoutTimer);+ void (async () => {+ // The scratch directory is gone, and the slot free, before the caller hears the outcome.+ if (scratchDir) await removeScratch(scratchDir, task.job.kind);+ active -= 1;+ settleAfterExit(code);+ pump();+ })();+ });+ };++ function pump() {+ while (active < options.maxConcurrent && queue.length > 0) {+ const next = queue.shift()!;+ clearTimeout(next.timer);+ active += 1;+ void start(next);+ }+ }++ return {+ run<T>(job: FileParseJob, runOptions: FileParseRunOptions = {}) {+ return new Promise<T>((resolve, reject) => {+ const task: Task = {+ job,+ memoryBytes: heldBytes(job),+ onStart: runOptions.onStart,+ reject,+ resolve: resolve as never,+ };++ if (active < options.maxConcurrent) {+ active += 1;+ return void start(task);+ }++ const queuedBytes = queue.reduce((sum, waiting) => sum + waiting.memoryBytes, 0);+ if (+ queue.length >= options.maxQueue ||+ queuedBytes + task.memoryBytes > options.maxQueuedBytes+ ) {+ return reject(+ new FileParseError(+ 'QUEUE_FULL',+ `File parsing is busy: ${queue.length} tasks (${queuedBytes} bytes) already waiting`,+ ),+ );+ }++ const entry = {+ ...task,+ timer: setTimeout(() => {+ queue.splice(queue.indexOf(entry), 1);+ reject(+ new FileParseError(+ 'QUEUE_TIMEOUT',+ `File parsing waited ${options.queueTimeoutMs}ms for a free worker`,+ ),+ );+ }, options.queueTimeoutMs),+ };+ queue.push(entry);+ });+ },+ stats: () => ({ active, queued: queue.length }),+ };+};diff --git a/apps/server/src/services/fileParse/worker.budget.test.ts b/apps/server/src/services/fileParse/worker.budget.test.tsnew file mode 100644index 00000000000..e171610d348--- /dev/null+++ b/apps/server/src/services/fileParse/worker.budget.test.ts@@ -0,0 +1,107 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { FileParseBudgetError, isFileParseBudgetError } from '@lobechat/file-loaders';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { buildTestZip } from '../../../../../packages/file-loaders/src/loaders/excel/testUtils';+import { buildFileParseWorker } from '../../../../../scripts/buildFileParseWorker.mjs';+import { FILE_PARSE_WORKER_PATH_ENV } from './artifact';+import { parseDatasetInWorker, parseFileInWorker } from './index';++// Real built artifact, real threads: the Excel budget refusals must survive the thread boundary+// with reason / limit / actual, and a dataset xlsx must not reach SheetJS without the zip preflight+// however its format is named or detected.+const here = (relative: string) => fileURLToPath(new URL(relative, import.meta.url));++const WORKSHEET_LIMIT = 256 * 1024 * 1024;+const OVERSIZED_SHEET_DECLARATION = 300 * 1024 * 1024;++let dir: string;+let oversizedSheetZip: Buffer;+let smallXlsx: Buffer;+const previousEnv = process.env[FILE_PARSE_WORKER_PATH_ENV];++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-budget-'));+ process.env[FILE_PARSE_WORKER_PATH_ENV] = await buildFileParseWorker({+ outdir: path.join(dir, 'artifact'),+ });++ // A tiny archive whose central directory declares a 300 MiB worksheet: refused by the preflight+ // from the declaration alone, before anything is inflated.+ oversizedSheetZip = buildTestZip([+ {+ data: '<x/>',+ declaredSize: OVERSIZED_SHEET_DECLARATION,+ deflate: true,+ name: 'xl/worksheets/sheet1.xml',+ },+ ]);++ const XLSX = createRequire(here('../../../../../packages/file-loaders/package.json'))('xlsx');+ smallXlsx = XLSX.write(+ {+ SheetNames: ['S'],+ Sheets: { S: { '!ref': 'A1:A2', 'A1': { t: 's', v: 'q' }, 'A2': { t: 's', v: 'a' } } },+ },+ { bookType: 'xlsx', type: 'buffer' },+ );+}, 60_000);++afterAll(async () => {+ if (previousEnv === undefined) delete process.env[FILE_PARSE_WORKER_PATH_ENV];+ else process.env[FILE_PARSE_WORKER_PATH_ENV] = previousEnv;+ await rm(dir, { force: true, recursive: true });+});++const rejection = async (promise: Promise<unknown>) => {+ try {+ await promise;+ } catch (error) {+ return error;+ }+ throw new Error('expected the parse to reject');+};++const expectSheetBudget = (error: unknown) => {+ expect(isFileParseBudgetError(error)).toBe(true);+ expect(error).toBeInstanceOf(FileParseBudgetError);+ expect(error).toMatchObject({+ actual: OVERSIZED_SHEET_DECLARATION,+ limit: WORKSHEET_LIMIT,+ reason: 'sheet-xml',+ });+};++describe('file parse worker budget refusals', () => {+ it('restores the budget error of a file parse with reason, limit and actual', async () => {+ const file = path.join(dir, 'huge-sheet.xlsx');+ await writeFile(file, oversizedSheetZip);++ expectSheetBudget(await rejection(parseFileInWorker(file, { mode: 'file' })));+ expectSheetBudget(await rejection(parseFileInWorker(file, { mode: 'document' })));+ });++ it.each([+ ['an explicit xlsx format', { format: 'xlsx' as const }],+ ['the .xlsx file name with format auto', { filename: 'data.xlsx', format: 'auto' as const }],+ ['the legacy .xls file name', { filename: 'data.xls' }],+ ['byte detection with no name and no format', {}],+ ])('runs the zip preflight on a dataset chosen by %s', async (_, options) => {+ const error = await rejection(parseDatasetInWorker(oversizedSheetZip, options));++ expectSheetBudget(error);+ });++ it('still parses an ordinary xlsx dataset', async () => {+ const result = await parseDatasetInWorker<{ totalCount: number }>(smallXlsx, {+ format: 'auto',+ });++ expect(result.totalCount).toBe(1);+ });+});diff --git a/apps/server/src/services/fileParse/worker.chunk.test.ts b/apps/server/src/services/fileParse/worker.chunk.test.tsnew file mode 100644index 00000000000..997bbfecd07--- /dev/null+++ b/apps/server/src/services/fileParse/worker.chunk.test.ts@@ -0,0 +1,266 @@+import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { isFileParseBudgetError } from '@lobechat/file-loaders';+import { buildTestZip } from '@lobechat/file-loaders/src/loaders/excel/testUtils';+import { Workbook } from 'exceljs';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { ChunkingLoader } from '@/libs/document-loaders';++import { buildFileParseWorker } from '../../../../../scripts/buildFileParseWorker.mjs';+import { FILE_PARSE_WORKER_PATH_ENV } from './artifact';+import { FileParseError } from './errors';+import { chunkContentInWorker, getSharedFileParseRunner } from './index';+import { createFileParseRunner, DEFAULT_FILE_PARSE_LIMITS } from './runner';++// The real build artifact in real threads, on the chunking path of the knowledge base.+const here = (relative: string) => fileURLToPath(new URL(relative, import.meta.url));++let dir: string;+let workerPath: string;+const previousEnv = process.env[FILE_PARSE_WORKER_PATH_ENV];++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-chunk-'));+ workerPath = await buildFileParseWorker({ outdir: path.join(dir, 'artifact') });+ process.env[FILE_PARSE_WORKER_PATH_ENV] = workerPath;+}, 60_000);++afterAll(async () => {+ if (previousEnv === undefined) delete process.env[FILE_PARSE_WORKER_PATH_ENV];+ else process.env[FILE_PARSE_WORKER_PATH_ENV] = previousEnv;+ await rm(dir, { force: true, recursive: true });+});++const trackTimerProgress = () => {+ let ticks = 0;+ const interval = setInterval(() => {+ ticks += 1;+ }, 20);+ return () => {+ clearInterval(interval);+ return ticks;+ };+};++const buildDenseWorkbook = async (rows: number) => {+ const workbook = new Workbook();+ const sheet = workbook.addWorksheet('Dense');+ sheet.addRow(['id', 'name', 'note', 'a', 'b', 'c', 'd', 'e']);+ for (let i = 0; i < rows; i++) {+ sheet.addRow([i, `name-${i}`, `note ${i} `.repeat(4), 1, 2, 3, 4, 5]);+ }+ return new Uint8Array(await workbook.xlsx.writeBuffer());+};++describe('chunking in the parse worker', () => {+ it('keeps chunk content, row metadata and cell semantics identical to the in-process loader', async () => {+ const workbook = new Workbook();+ const pricing = workbook.addWorksheet('Pricing');+ pricing.addRow(['Plan', 'Discount']);+ pricing.addRow(['Basic', '10%']);+ pricing.addRow([]);+ pricing.addRow(['Pro', '20%']);+ const values = workbook.addWorksheet('Values');+ values.addRow(['Rich text', 'Formula', 'Date', 'Error']);+ values.addRow([+ { richText: [{ text: 'Hello ' }, { text: 'world' }] },+ { formula: '1+1', result: 2 },+ new Date('2026-10-07T00:00:00Z'),+ { error: '#DIV/0!' },+ ]);+ const content = new Uint8Array(await workbook.xlsx.writeBuffer());++ const inProcess = await new ChunkingLoader().partitionContent('book.xlsx', content);+ const inWorker = await chunkContentInWorker('book.xlsx', content);++ expect(inWorker).toEqual(inProcess);+ expect(inWorker.map((chunk) => chunk.metadata)).toEqual([+ { row: 2, sheetName: 'Pricing', source: 'blob' },+ { row: 4, sheetName: 'Pricing', source: 'blob' },+ { row: 2, sheetName: 'Values', source: 'blob' },+ ]);+ expect(inWorker[2].pageContent).toBe(+ 'Rich text: Hello world\nFormula: 2\nDate: 2026-10-07\nError: #DIV/0!',+ );+ });++ it('chunks markdown and text through the same worker with the same output', async () => {+ const markdown = new TextEncoder().encode(`# Title\n\n${'paragraph text. '.repeat(400)}\n`);++ const inProcess = await new ChunkingLoader().partitionContent('doc.md', markdown);+ const inWorker = await chunkContentInWorker('doc.md', markdown);++ expect(inWorker.length).toBeGreaterThan(1);+ expect(inWorker).toEqual(inProcess);+ });++ it('keeps the request thread timers running while the splitter is busy', async () => {+ // One 16MB paragraph with no separator: the recursive splitter works through it+ // synchronously for about a second, which on the request thread stops every timer.+ const content = new TextEncoder().encode('abcdefghij'.repeat(1_600_000));+ const stop = trackTimerProgress();+ let ticks = 0;++ const chunks = await chunkContentInWorker('wall-of-text.md', content).finally(() => {+ ticks = stop();+ });++ expect(chunks.length).toBeGreaterThan(30_000);+ expect(ticks).toBeGreaterThan(0);+ }, 60_000);++ it('refuses a spreadsheet archive over the zip budget before exceljs sees it', async () => {+ // Declares a 300MiB worksheet but holds a few bytes: refused on the declaration alone.+ const bomb = buildTestZip([+ {+ data: '<worksheet/>',+ declaredSize: 300 * 1024 * 1024,+ deflate: true,+ name: 'xl/worksheets/sheet1.xml',+ },+ ]);++ const error = await chunkContentInWorker('bomb.xlsx', new Uint8Array(bomb)).catch((e) => e);++ expect(isFileParseBudgetError(error)).toBe(true);+ expect(error).toMatchObject({ reason: 'sheet-xml' });+ });++ it('stops an empty-styled-rows spreadsheet inside the worker and keeps the request thread alive', async () => {+ const part = (name: string, data: string) => ({ data, name });+ const rows = Array.from(+ { length: 800_000 },+ (_, i) => `<row r="${i + 1}" s="1" customFormat="1"><c r="A${i + 1}" s="1"/></row>`,+ ).join('');+ // Rows with a style and no value: a few bytes each in the file, an object each in exceljs.+ const content = new Uint8Array(+ buildTestZip([+ part(+ '[Content_Types].xml',+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>',+ ),+ part(+ '_rels/.rels',+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>',+ ),+ part(+ 'xl/workbook.xml',+ '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="S" sheetId="1" r:id="rId1"/></sheets></workbook>',+ ),+ part(+ 'xl/_rels/workbook.xml.rels',+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>',+ ),+ // exceljs resolves `s="1"` against the stylesheet: without one the parse fails on the first row+ // instead of building the row objects this test is about.+ part(+ 'xl/styles.xml',+ '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts><fills count="1"><fill><patternFill patternType="none"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"/></cellXfs></styleSheet>',+ ),+ {+ data: `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${rows}</sheetData></worksheet>`,+ deflate: true,+ name: 'xl/worksheets/sheet1.xml',+ },+ ]),+ );+ // The production heap limit: a heap this far below it (160MB) aborts the whole process on Node+ // 24.11.1 ("Reached heap limit" fatal error) instead of ending the thread with a typed error.+ const runner = createFileParseRunner({+ maxOldGenerationSizeMb: DEFAULT_FILE_PARSE_LIMITS.maxOldGenerationSizeMb,+ parseTimeoutMs: 20_000,+ workerPath: () => workerPath,+ });+ const stop = trackTimerProgress();+ let ticks = 0;++ const error = await runner+ .run({ content, filename: 'styled.xlsx', kind: 'chunk' })+ .finally(() => {+ ticks = stop();+ })+ .catch((e) => e);++ expect(ticks).toBeGreaterThan(0);+ expect(error).toBeInstanceOf(FileParseError);+ expect(['OUT_OF_MEMORY', 'TIMEOUT']).toContain(error.code);+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ // the next job runs normally on a fresh thread+ await expect(+ runner.run({ content: new TextEncoder().encode('fine'), filename: 'a.txt', kind: 'chunk' }),+ ).resolves.toHaveLength(1);+ }, 60_000);++ it('reports a malformed spreadsheet as a failure and leaves the runner usable', async () => {+ const error = await chunkContentInWorker(+ 'broken.xlsx',+ new TextEncoder().encode('not a zip'),+ ).catch((e) => e);++ expect(error).toBeInstanceOf(FileParseError);+ expect(error).toMatchObject({ code: 'PARSE_FAILED' });+ expect(getSharedFileParseRunner().stats()).toEqual({ active: 0, queued: 0 });+ await expect(+ chunkContentInWorker('ok.txt', new TextEncoder().encode('still works')),+ ).resolves.toHaveLength(1);+ });++ it('reports a file no chunking loader handles as a failure, never as an empty success', async () => {+ const error = await chunkContentInWorker('x.qzx', new Uint8Array([1])).catch((e) => e);++ expect(error).toBeInstanceOf(FileParseError);+ expect(error.message).toContain('Unsupported file type');+ });++ it('terminates a worker that runs out of time, frees the slot and writes no result', async () => {+ const runner = createFileParseRunner({ parseTimeoutMs: 500, workerPath: () => workerPath });+ const content = await buildDenseWorkbook(40_000);++ const error = await runner+ .run({ content, filename: 'slow.xlsx', kind: 'chunk' })+ .catch((e) => e);++ expect(error).toMatchObject({ code: 'TIMEOUT', name: 'FileParseError' });+ // The promise only settled after the thread really exited: the slot is back already.+ expect(runner.stats()).toEqual({ active: 0, queued: 0 });+ await expect(+ runner.run({ content: new TextEncoder().encode('after'), filename: 'a.txt', kind: 'chunk' }),+ ).resolves.toHaveLength(1);+ }, 60_000);++ it('gives a chunk job its own scratch directory and removes it once the thread has exited', async () => {+ const scratchRoot = await mkdtemp(path.join(tmpdir(), 'file-parse-scratch-root-'));+ const previousTmp = process.env.TMPDIR;+ process.env.TMPDIR = scratchRoot;+ try {+ const epub = new Uint8Array(+ await readFile(here('../../../../../packages/file-loaders/test/fixtures/test.epub')),+ );++ const done = createFileParseRunner({ workerPath: () => workerPath });+ const chunks = await done.run<unknown[]>({+ content: epub,+ filename: 'book.epub',+ kind: 'chunk',+ });+ expect(chunks.length).toBeGreaterThan(0);+ expect(await readdir(scratchRoot)).toEqual([]);++ // Killed in the middle of the epub: whatever the thread had written is gone with it.+ const killed = createFileParseRunner({ parseTimeoutMs: 1, workerPath: () => workerPath });+ const error = await killed+ .run({ content: epub, filename: 'book.epub', kind: 'chunk' })+ .catch((e) => e);+ expect(error).toMatchObject({ code: 'TIMEOUT' });+ expect(await readdir(scratchRoot)).toEqual([]);+ } finally {+ if (previousTmp === undefined) delete process.env.TMPDIR;+ else process.env.TMPDIR = previousTmp;+ await rm(scratchRoot, { force: true, recursive: true });+ }+ }, 60_000);+});diff --git a/apps/server/src/services/fileParse/worker.test.ts b/apps/server/src/services/fileParse/worker.test.tsnew file mode 100644index 00000000000..3630af0173c--- /dev/null+++ b/apps/server/src/services/fileParse/worker.test.ts@@ -0,0 +1,174 @@+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { UnsupportedFileTypeError } from '@lobechat/file-loaders';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { buildFileParseWorker } from '../../../../../scripts/buildFileParseWorker.mjs';+import { PARSED_FILE_CONTENT_MAX_CHARS } from '../document/parsedFileCap';+import { FILE_PARSE_WORKER_PATH_ENV } from './artifact';+import { FileParseError, parseDatasetInWorker, parseFileInWorker } from './index';++// The real build artifact in real threads: this is what a deployment runs. A 100k-row sparse range keeps+// a worker busy for ~1.5s, which on the request thread would stall every timer for as long.+const here = (relative: string) => fileURLToPath(new URL(relative, import.meta.url));+const SPARSE_ROWS = 100_000;+const CORRUPTED_PPTX = here(+ '../../../../../packages/file-loaders/src/loaders/pptx/fixtures/corrupted-slides.pptx',+);++let dir: string;+let SPARSE_XLSX: string;+const previousEnv = process.env[FILE_PARSE_WORKER_PATH_ENV];++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-worker-'));+ process.env[FILE_PARSE_WORKER_PATH_ENV] = await buildFileParseWorker({+ outdir: path.join(dir, 'artifact'),+ });++ // Two cells, but a declared range of 100k x 50: `sheet_to_json` walks every empty cell of it.+ const XLSX = createRequire(here('../../../../../packages/file-loaders/package.json'))('xlsx');+ SPARSE_XLSX = path.join(dir, 'sparse-range.xlsx');+ await writeFile(+ SPARSE_XLSX,+ XLSX.write(+ {+ SheetNames: ['S'],+ Sheets: {+ S: {+ '!ref': `A1:AX${SPARSE_ROWS}`,+ 'A1': { t: 's', v: 'head' },+ [`AX${SPARSE_ROWS}`]: { t: 's', v: 'tail' },+ },+ },+ },+ { bookType: 'xlsx', type: 'buffer' },+ ),+ );+}, 60_000);++afterAll(async () => {+ if (previousEnv === undefined) delete process.env[FILE_PARSE_WORKER_PATH_ENV];+ else process.env[FILE_PARSE_WORKER_PATH_ENV] = previousEnv;+ await rm(dir, { force: true, recursive: true });+});++const write = async (name: string, content: string | Uint8Array) => {+ const file = path.join(dir, name);+ await writeFile(file, content);+ return file;+};++const trackTimerProgress = () => {+ let ticks = 0;+ const interval = setInterval(() => {+ ticks += 1;+ }, 20);+ return () => {+ clearInterval(interval);+ return ticks;+ };+};++describe('file parse worker artifact', () => {+ it('parses a spreadsheet with a huge declared range without stalling the main thread', async () => {+ const stop = trackTimerProgress();+ let ticks = 0;++ const document = await parseFileInWorker(SPARSE_XLSX, {+ fileId: 'file-sparse',+ mode: 'file',+ }).finally(() => {+ ticks = stop();+ });++ expect(document.content).toContain('tail');+ // A callback ran while the parse was pending on its worker thread.+ expect(ticks).toBeGreaterThan(0);+ });++ it('parses an eval dataset spreadsheet in the same bounded worker', async () => {+ const content = new Uint8Array(await readFile(SPARSE_XLSX));+ const stop = trackTimerProgress();+ let ticks = 0;++ const result = await parseDatasetInWorker<{ totalCount: number }>(content, {+ filename: 'sparse.xlsx',+ preview: 50,+ }).finally(() => {+ ticks = stop();+ });++ expect(ticks).toBeGreaterThan(0);+ expect(result.totalCount).toBeGreaterThan(0);+ });++ it('parses CSV datasets and reports a broken JSON dataset as a parse failure', async () => {+ await expect(+ parseDatasetInWorker<{ totalCount: number }>('a,b\n1,2\n3,4\n', { format: 'csv' }),+ ).resolves.toMatchObject({ totalCount: 2 });++ const error = await parseDatasetInWorker('{not json', { format: 'json' }).catch((e) => e);+ expect(error).toBeInstanceOf(FileParseError);+ expect(error).toMatchObject({ code: 'PARSE_FAILED' });+ });++ it('strips page wrappers for the page editor but keeps them for parseFile', async () => {+ const file = await write(+ 'pages.txt',+ '<page number="1">alpha</page><page number="2">beta</page>',+ );++ const asDocument = await parseFileInWorker(file, { mode: 'document' });+ const asFile = await parseFileInWorker(file, { mode: 'file' });++ expect(asDocument.content).toBe('alphabeta');+ expect(asFile.content).toContain('<page number="1">');+ });++ it('caps oversized text inside the worker, so the main thread never receives the whole of it', async () => {+ const file = await write('huge.txt', 'a'.repeat(PARSED_FILE_CONTENT_MAX_CHARS + 100));++ const document = await parseFileInWorker(file, { mode: 'file' });++ expect(document.content).toHaveLength(PARSED_FILE_CONTENT_MAX_CHARS);+ expect(document.metadata).toMatchObject({+ originalCharCount: PARSED_FILE_CONTENT_MAX_CHARS + 100,+ truncated: true,+ });+ });++ it('keeps UnsupportedFileTypeError for files no loader handles', async () => {+ const file = await write('payload.qzx', 'binary-ish');++ const error = await parseFileInWorker(file, { mode: 'file' }).catch((e) => e);++ expect(error).toBeInstanceOf(UnsupportedFileTypeError);+ expect(error.message).toBe("Unsupported file type 'qzx' for file 'payload.qzx'.");+ });++ it('rejects a file whose pages all failed instead of returning an empty successful document', async () => {+ const error = await parseFileInWorker(CORRUPTED_PPTX, { mode: 'file' }).catch((e) => e);++ expect(error).toBeInstanceOf(FileParseError);+ expect(error).toMatchObject({ code: 'LOAD_FAILED' });+ });++ it('fails closed, without parsing on the main thread, when the artifact is missing', async () => {+ const file = await write('fine.txt', 'perfectly parseable');+ const present = process.env[FILE_PARSE_WORKER_PATH_ENV];+ process.env[FILE_PARSE_WORKER_PATH_ENV] = path.join(dir, 'nowhere/fileParseWorker.mjs');+ try {+ const error = await parseFileInWorker(file, { mode: 'file' }).catch((e) => e);++ expect(error).toBeInstanceOf(FileParseError);+ expect(error).toMatchObject({ code: 'UNAVAILABLE' });+ } finally {+ process.env[FILE_PARSE_WORKER_PATH_ENV] = present;+ }+ });+});diff --git a/apps/server/src/services/fileParse/worker.ts b/apps/server/src/services/fileParse/worker.tsnew file mode 100644index 00000000000..6dea0d8ff2a--- /dev/null+++ b/apps/server/src/services/fileParse/worker.ts@@ -0,0 +1,88 @@+// Entry of the parse worker thread (bundled by scripts/buildFileParseWorker.mts). One thread per+// task: the job arrives in `workerData`, the outcome goes back as one message. It runs parsers+// that can hold the CPU for tens of seconds, which is why it is not on the request thread.+// Keep the imports to parsing libraries: no document service, database or auth code.+import { parentPort, workerData } from 'node:worker_threads';++import { detectFormat, parseDataset } from '@lobechat/eval-dataset-parser';+import { isFileParseBudgetError, loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';+import { preflightXlsxZip } from '@lobechat/file-loaders/src/xlsxBudget';++import { ChunkingLoader } from '@/libs/document-loaders';++import { capParsedFileDocument, stripPageWrappers } from '../document/parsedFileCap';+import { assertChunkResultWithinLimits, ChunkOutputTooLargeError } from './chunkLimits';+import { assertFileLoaded } from './loadedFile';+import type { FileParseJob, FileParseWorkerMessage, SerializedWorkerError } from './protocol';+import {+ BUDGET_ERROR_NAME,+ OUTPUT_TOO_LARGE_ERROR_NAME,+ UNSUPPORTED_FILE_TYPE_ERROR_NAME,+} from './protocol';++/**+ * Same format decision `parseDataset` makes (explicit format, else file name, else the bytes),+ * so an xlsx cannot reach SheetJS without the zip preflight by naming or auto-detecting around it.+ */+const runDataset = async (job: Extract<FileParseJob, { kind: 'dataset' }>) => {+ const { content, options } = job;+ const format =+ options?.format && options.format !== 'auto'+ ? options.format+ : detectFormat(content, options?.filename);+ if (format === 'xlsx' && typeof content !== 'string') await preflightXlsxZip(content);+ return parseDataset(content, options);+};++/**+ * The knowledge-base splitter, on the raw loader: never the wrapper that sends the job here (that+ * would queue the job behind itself). An xlsx passes the zip preflight inside `ExcelLoader`, before+ * exceljs inflates anything. The result is measured, not cut: it is copied back to the request+ * thread whole or the job fails.+ */+const runChunk = async (job: Extract<FileParseJob, { kind: 'chunk' }>) =>+ assertChunkResultWithinLimits(+ await new ChunkingLoader().partitionContent(job.filename, job.content),+ );++const runJob = async (job: FileParseJob) => {+ if (job.kind === 'dataset') return runDataset(job);+ if (job.kind === 'chunk') return runChunk(job);++ const loaded = assertFileLoaded(await loadFile(job.filePath));+ return capParsedFileDocument(job.mode === 'document' ? stripPageWrappers(loaded) : loaded);+};++const serializeError = (error: unknown): SerializedWorkerError => {+ if (error instanceof ChunkOutputTooLargeError) {+ return { message: error.message, name: OUTPUT_TOO_LARGE_ERROR_NAME };+ }+ if (error instanceof UnsupportedFileTypeError) {+ return {+ fileType: error.fileType,+ message: error.message,+ name: UNSUPPORTED_FILE_TYPE_ERROR_NAME,+ };+ }+ if (isFileParseBudgetError(error)) {+ return {+ budget: { actual: error.actual, limit: error.limit, reason: error.reason },+ message: error.message,+ name: BUDGET_ERROR_NAME,+ };+ }+ const { message, name } = error instanceof Error ? error : new Error(String(error));+ return { message, name };+};++const port = parentPort;+if (!port) throw new Error('fileParseWorker must run inside a worker thread');++runJob(workerData as FileParseJob).then(+ (value) => port.postMessage({ type: 'result', value } satisfies FileParseWorkerMessage),+ (error) =>+ port.postMessage({+ error: serializeError(error),+ type: 'error',+ } satisfies FileParseWorkerMessage),+);diff --git a/apps/server/src/services/skill/importer.cleanup.test.ts b/apps/server/src/services/skill/importer.cleanup.test.tsnew file mode 100644index 00000000000..23de64b8aa4--- /dev/null+++ b/apps/server/src/services/skill/importer.cleanup.test.ts@@ -0,0 +1,114 @@+// @vitest-environment node+import { mkdtemp, readdir, rm, stat } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { setImmediate } from 'node:timers/promises';++import type { LobeChatDatabase } from '@lobechat/database';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TempFileManager } from '@/server/utils/tempFileManager';++import { SkillImporter } from './importer';++const mocks = vi.hoisted(() => ({+ create: vi.fn(),+ downloadFileToLocal: vi.fn(),+ parseZipPackage: vi.fn(),+}));+vi.mock('@/database/models/agentSkill', () => ({+ AgentSkillModel: class {+ create = mocks.create;+ findByName = vi.fn().mockResolvedValue(undefined);+ },+}));+vi.mock('@/server/modules/GitHub', () => ({+ GitHub: class {},+ GitHubNotFoundError: class extends Error {},+ GitHubParseError: class extends Error {},+}));+vi.mock('@/server/services/file', () => ({+ FileService: class {+ downloadFileToLocal = mocks.downloadFileToLocal;+ },+}));+vi.mock('./resource', () => ({ SkillResourceService: class {} }));+vi.mock('./parser', () => ({+ SkillParser: class {+ parseZipPackage = mocks.parseZipPackage;+ },+}));++let root: string;+let manager: TempFileManager;+beforeEach(async () => {+ vi.resetAllMocks();+ root = await mkdtemp(path.join(tmpdir(), 'skill-import-cleanup-'));+ manager = new TempFileManager(path.join(path.relative(tmpdir(), root), 'zip-'));+});+afterEach(async () => {+ await manager.cleanup();+ await rm(root, { force: true, recursive: true });+});++describe('SkillImporter ZIP temp file cleanup', () => {+ it.each([false, true])(+ 'waits for the actual cleanup before the import settles (parse fails = %s)',+ async (fails) => {+ const bytes = Buffer.from('downloaded ZIP bytes');+ const filePath = await manager.writeTempFile(bytes, 'skill.zip');+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let entered!: () => void;+ const cleaning = new Promise<void>((resolve) => {+ entered = resolve;+ });+ mocks.downloadFileToLocal.mockResolvedValue({+ cleanup: async () => {+ entered();+ await gate;+ await manager.cleanup();+ },+ filePath,+ });+ const failure = new Error('invalid ZIP');+ if (fails) mocks.parseZipPackage.mockRejectedValue(failure);+ else {+ mocks.parseZipPackage.mockResolvedValue({+ content: 'skill content',+ manifest: { name: 'Imported skill' },+ resources: new Map(),+ });+ mocks.create.mockResolvedValue({ id: 'created' });+ }++ let settled = false;+ const result = new SkillImporter({} as LobeChatDatabase, 'owner')+ .importFromZip({ zipFileId: 'zip-id' })+ .then(+ (value) => ({ value }),+ (error: unknown) => ({ error }),+ )+ .finally(() => {+ settled = true;+ });+ try {+ await cleaning;+ await setImmediate();+ expect(mocks.parseZipPackage).toHaveBeenCalledWith(bytes);+ expect(settled).toBe(false);+ expect((await stat(filePath)).isFile()).toBe(true);+ } finally {+ release();+ await result;+ await manager.cleanup();+ }++ if (fails) expect(await result).toEqual({ error: failure });+ else expect(await result).toMatchObject({ value: { status: 'created' } });+ expect(await readdir(root)).toEqual([]);+ },+ );+});diff --git a/apps/server/src/services/skill/importer.test.ts b/apps/server/src/services/skill/importer.test.tsindex e57f58976b4..cdbfab18eb6 100644--- a/apps/server/src/services/skill/importer.test.ts+++ b/apps/server/src/services/skill/importer.test.ts@@ -91,8 +91,8 @@ vi.mock('@/server/services/file/impls', () => ({})),}));-// Mock fs/promises readFile-vi.mock('node:fs/promises', () => ({+vi.mock(import('node:fs/promises'), async (importOriginal) => ({+ ...(await importOriginal()),readFile: vi.fn().mockResolvedValue(Buffer.from('mock-zip-content')),}));diff --git a/apps/server/src/services/skill/importer.ts b/apps/server/src/services/skill/importer.tsindex 8cd2cdf8793..615322c7e45 100644--- a/apps/server/src/services/skill/importer.ts+++ b/apps/server/src/services/skill/importer.ts@@ -155,7 +155,7 @@ export class SkillImporter {log('importFromZip: created skill id=%s', skill.id);return { skill, status: 'created' };} finally {- cleanup();+ await cleanup();log('importFromZip: cleaned up temp file');}}diff --git a/apps/server/src/utils/__tests__/tempFileManager.test.ts b/apps/server/src/utils/__tests__/tempFileManager.test.tsdeleted file mode 100644index 5ad6f63dc77..00000000000--- a/apps/server/src/utils/__tests__/tempFileManager.test.ts+++ /dev/null@@ -1,139 +0,0 @@-import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';--import { describe, expect, it, vi } from 'vitest';--import { TempFileManager } from '../tempFileManager';--// Mock node modules-vi.mock('node:fs', () => ({- existsSync: vi.fn(),- mkdtempSync: vi.fn(),- rmSync: vi.fn(),- writeFileSync: vi.fn(),-}));-vi.mock('node:os', () => ({ tmpdir: vi.fn() }));-vi.mock('node:path', () => ({- join: (...args: string[]) => args.join('/'),- basename: (p: string) => p.split('/').pop()!.split('\\').pop()!,- resolve: (...args: string[]) => args.join('/'),- default: {- join: (...args: string[]) => args.join('/'),- basename: (p: string) => p.split('/').pop()!.split('\\').pop()!,- resolve: (...args: string[]) => args.join('/'),- },-}));--describe('TempFileManager', () => {- const mockTmpDir = '/tmp';- const mockDirname = 'test-';- const mockFullTmpDir = '/tmp/test-xyz';-- beforeEach(() => {- vi.clearAllMocks();- vi.mocked(tmpdir).mockReturnValue(mockTmpDir);- vi.mocked(mkdtempSync).mockReturnValue(mockFullTmpDir);- vi.mocked(existsSync).mockReturnValue(true);- });-- it('should create temp directory on initialization', () => {- new TempFileManager(mockDirname);-- expect(tmpdir).toHaveBeenCalled();- expect(mkdtempSync).toHaveBeenCalledWith(`${mockTmpDir}/${mockDirname}`);- });-- it('should write temp file successfully', async () => {- const manager = new TempFileManager(mockDirname);- const testData = new Uint8Array([1, 2, 3]);- const fileName = 'test.txt';-- const filePath = await manager.writeTempFile(testData, fileName);-- expect(writeFileSync).toHaveBeenCalledWith(`${mockFullTmpDir}/${fileName}`, testData);- expect(filePath).toBe(`${mockFullTmpDir}/${fileName}`);- });-- it('should cleanup on write failure', async () => {- const manager = new TempFileManager(mockDirname);- const testData = new Uint8Array([1, 2, 3]);- const fileName = 'test.txt';-- vi.mocked(writeFileSync).mockImplementation(function () {- throw new Error('Write failed');- });-- await expect(manager.writeTempFile(testData, fileName)).rejects.toThrow(- 'Failed to write temp file: Write failed',- );-- expect(existsSync).toHaveBeenCalledWith(mockFullTmpDir);- expect(rmSync).toHaveBeenCalledWith(mockFullTmpDir, { force: true, recursive: true });- });-- it('should cleanup temp directory', () => {- const manager = new TempFileManager(mockDirname);- vi.mocked(existsSync).mockReturnValue(true);-- manager.cleanup();-- expect(existsSync).toHaveBeenCalledWith(mockFullTmpDir);- expect(rmSync).toHaveBeenCalledWith(mockFullTmpDir, { force: true, recursive: true });- });-- it('should skip cleanup if directory does not exist', () => {- const manager = new TempFileManager(mockDirname);- vi.mocked(existsSync).mockReturnValue(false);-- manager.cleanup();-- expect(existsSync).toHaveBeenCalledWith(mockFullTmpDir);- expect(rmSync).not.toHaveBeenCalled();- });-});--// Path traversal regression tests-// These tests use the mocked path module (same as above) but verify that-// basename() is called to strip traversal components before constructing the file path.-describe('TempFileManager - path traversal prevention', () => {- const traversalPayloads = [- { input: '../../etc/passwd', expected: 'passwd' },- { input: '../../../tmp/evil.txt', expected: 'evil.txt' },- { input: '..\\..\\..\\windows\\system32\\evil.dll', expected: 'evil.dll' },- { input: 'foo/../../bar/evil.txt', expected: 'evil.txt' },- { input: '../startServer.js', expected: 'startServer.js' },- ];-- beforeEach(() => {- vi.resetAllMocks();- vi.mocked(tmpdir).mockReturnValue('/tmp');- vi.mocked(mkdtempSync).mockReturnValue('/tmp/test-xyz');- vi.mocked(existsSync).mockReturnValue(true);- });-- it.each(traversalPayloads)(- 'should sanitize path traversal filename: $input → $expected',- async ({ input, expected }) => {- const manager = new TempFileManager('test-');- const testData = new Uint8Array([0x41, 0x42, 0x43]);-- const resultPath = await manager.writeTempFile(testData, input);-- // writeFileSync should be called with the safe basename, not the traversal path- expect(writeFileSync).toHaveBeenCalledWith(`/tmp/test-xyz/${expected}`, testData);- expect(resultPath).toBe(`/tmp/test-xyz/${expected}`);- },- );-- it('should not write to traversed path', async () => {- const manager = new TempFileManager('test-');- const testData = new Uint8Array([0x41, 0x42, 0x43]);-- const resultPath = await manager.writeTempFile(testData, '../../evil.txt');-- // Should write to /tmp/test-xyz/evil.txt, NOT /tmp/test-xyz/../../evil.txt- expect(resultPath).toBe('/tmp/test-xyz/evil.txt');- expect(resultPath).not.toContain('..');- expect(writeFileSync).toHaveBeenCalledWith('/tmp/test-xyz/evil.txt', testData);- });-});diff --git a/apps/server/src/utils/tempFileManager.test.ts b/apps/server/src/utils/tempFileManager.test.tsnew file mode 100644index 00000000000..0a25a522aa1--- /dev/null+++ b/apps/server/src/utils/tempFileManager.test.ts@@ -0,0 +1,125 @@+import * as fs from 'node:fs/promises';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TempFileManager } from './tempFileManager';++const state = vi.hoisted(() => ({ root: '' }));+vi.mock('node:os', () => ({ tmpdir: () => state.root }));+vi.mock('node:fs/promises', async (importOriginal) => ({+ ...(await importOriginal<typeof fs>()),+}));++const managers: TempFileManager[] = [];+const createManager = () => {+ const manager = new TempFileManager('parse-');+ managers.push(manager);+ return manager;+};++beforeEach(async () => {+ const { tmpdir } = await vi.importActual<{ tmpdir: () => string }>('node:os');+ state.root = await fs.mkdtemp(path.join(tmpdir(), 'temp-file-manager-'));+});+afterEach(async () => {+ vi.restoreAllMocks();+ await Promise.allSettled(managers.splice(0).map((manager) => manager.cleanup()));+ await fs.rm(state.root, { force: true, recursive: true });+});++describe('TempFileManager', () => {+ it.each(['../../escape.txt', '/absolute.txt', 'nested/file.txt', '..\\windows\\file.txt'])(+ 'keeps %s inside its own temp directory',+ async (name) => {+ const manager = createManager();+ const data = new Uint8Array([0, 128, 255]);+ const filePath = await manager.writeTempFile(data, name);+ expect(path.dirname(path.dirname(filePath))).toBe(state.root);+ expect(path.basename(filePath)).toBe(path.basename(name));+ expect(await fs.readFile(filePath)).toEqual(Buffer.from(data));+ await manager.cleanup();+ await expect(fs.stat(path.dirname(filePath))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await fs.readdir(state.root)).toEqual([]);+ },+ );++ it('a failed write waits for cleanup and keeps the original cause', async () => {+ const manager = createManager();+ await expect(manager.writeTempFile(new Uint8Array([1]), '.')).rejects.toMatchObject({+ cause: { code: 'EISDIR' },+ message: expect.stringContaining('Failed to write temp file:'),+ });+ expect(await fs.readdir(state.root)).toEqual([]);+ });++ it('a failed directory creation also surfaces the original cause', async () => {+ await fs.rm(state.root, { recursive: true });+ const manager = createManager();+ await expect(manager.writeTempFile(new Uint8Array([1]), 'file.txt')).rejects.toMatchObject({+ cause: { code: 'ENOENT' },+ });+ await manager.cleanup();+ });++ it('a failed cleanup does not mask the original write error', async () => {+ const manager = createManager();+ vi.spyOn(fs, 'rm').mockRejectedValueOnce(new Error('cleanup failed'));+ await expect(manager.writeTempFile(new Uint8Array([1]), '.')).rejects.toMatchObject({+ cause: { code: 'EISDIR' },+ });+ });++ it('repeated cleanup is safe and later writes are refused', async () => {+ const manager = createManager();+ await manager.writeTempFile(new Uint8Array([1]), 'first.txt');+ await Promise.all([manager.cleanup(), manager.cleanup()]);+ await manager.cleanup();+ await expect(manager.writeTempFile(new Uint8Array([2]), 'late.txt')).rejects.toThrow();+ expect(await fs.readdir(state.root)).toEqual([]);+ });++ it('cleanup before any write also closes the manager', async () => {+ const manager = createManager();+ await manager.cleanup();+ await expect(manager.writeTempFile(new Uint8Array([1]), 'late.txt')).rejects.toThrow();+ expect(await fs.readdir(state.root)).toEqual([]);+ });++ it('cleanup waits for a started real write, leaves no file and admits no later write', async () => {+ const manager = createManager();+ const realWrite = fs.writeFile;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let entered!: () => void;+ const started = new Promise<void>((resolve) => {+ entered = resolve;+ });+ vi.spyOn(fs, 'writeFile').mockImplementationOnce(async (...args) => {+ entered();+ await gate;+ return realWrite(...args);+ });+ const writing = manager.writeTempFile(new Uint8Array([1, 2]), 'pending.txt');+ try {+ await Promise.race([+ started,+ writing.then(() => {+ throw new Error('the write must go through the async filesystem boundary');+ }),+ ]);+ const cleaning = manager.cleanup();+ await expect(manager.writeTempFile(new Uint8Array([3]), 'late.txt')).rejects.toThrow();+ release();+ const filePath = await writing;+ await cleaning;+ await expect(fs.stat(filePath)).rejects.toMatchObject({ code: 'ENOENT' });+ expect(await fs.readdir(state.root)).toEqual([]);+ } finally {+ release();+ await writing;+ }+ });+});diff --git a/apps/server/src/utils/tempFileManager.ts b/apps/server/src/utils/tempFileManager.tsindex 05fbcf6e600..caa0e315ee7 100644--- a/apps/server/src/utils/tempFileManager.ts+++ b/apps/server/src/utils/tempFileManager.ts@@ -1,6 +1,6 @@-import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';-import { basename, join, resolve } from 'node:path';+import path from 'node:path';/*** Utility class for safely storing temporary files. Callers clean up in `finally`.@@ -10,41 +10,47 @@ import { basename, join, resolve } from 'node:path';* any later stray error into a crash. Callers own cleanup; the host owns termination.*/export class TempFileManager {- private readonly tempDir: string;- private filePaths: Set<string> = new Set();+ private tempDir?: Promise<string>;+ private readonly writes = new Set<Promise<string>>();+ private cleanupPromise?: Promise<void>;- constructor(dirname: string) {- // Create unique temporary directory (cross-platform safe)- this.tempDir = mkdtempSync(join(tmpdir(), dirname));- }-- /**- * Write Uint8Array data to a temporary file+ constructor(private readonly dirname: string) {}- */+ /** Creates the directory asynchronously on first write; no new write is accepted once cleanup has started. */async writeTempFile(data: Uint8Array, name: string): Promise<string> {- // Sanitize filename to prevent path traversal (GHSA-2g9j-v25c-4j97)- const safeName = basename(name);- const filePath = resolve(this.tempDir, safeName);+ if (this.cleanupPromise) throw new Error('Temp file manager is already closed');- try {- writeFileSync(filePath, data);- this.filePaths.add(filePath);+ const directory = (this.tempDir ??= mkdtemp(path.join(tmpdir(), this.dirname)));+ const writing = (async () => {+ // Sanitize filename to prevent path traversal (GHSA-2g9j-v25c-4j97)+ const filePath = path.resolve(await directory, path.basename(name));+ await writeFile(filePath, data);return filePath;+ })();+ this.writes.add(writing);++ try {+ return await writing;} catch (error) {- this.cleanup(); // Immediately cleanup on write failure+ // Remove itself first so the cleanup on the failure path does not wait for this write.+ this.writes.delete(writing);+ // A cleanup error must not mask the original write failure.+ await this.cleanup().catch(() => {});throw new Error(`Failed to write temp file: ${(error as Error).message}`, { cause: error });+ } finally {+ this.writes.delete(writing);}}- /**- * Safely cleanup temporary resources- */- cleanup(): void {- if (existsSync(this.tempDir)) {- // Recursively delete directory and its contents- rmSync(this.tempDir, { force: true, recursive: true });- this.filePaths.clear();- }+ /** Callers `await` it in `finally`; concurrent and repeated calls share one cleanup. */+ cleanup(): Promise<void> {+ this.cleanupPromise ??= (async () => {+ // Wait for admitted writes to settle before deleting, so a delete never interleaves with a+ // write and leaves a file behind.+ await Promise.allSettled(this.writes);+ const directory = await this.tempDir?.catch(() => undefined);+ if (directory) await rm(directory, { force: true, recursive: true });+ })();+ return this.cleanupPromise;}}diff --git a/docs/self-hosting/platform/vercel.mdx b/docs/self-hosting/platform/vercel.mdxindex f675131986b..1536694903d 100644--- a/docs/self-hosting/platform/vercel.mdx+++ b/docs/self-hosting/platform/vercel.mdx@@ -386,7 +386,7 @@ To sync manually: Actions → Upstream Sync → Run workflow.## Troubleshooting-**Deployment fails** — Check build logs in Vercel Dashboard → Deployments → click the failed deployment → Build Logs. Common causes: missing environment variables, TypeScript errors, or out of memory (fix with `NODE_OPTIONS=--max-old-space-size=4096`).+**Deployment fails** — Check build logs in Vercel Dashboard → Deployments → click the failed deployment → Build Logs. Common causes: missing environment variables, TypeScript errors, or out of memory (fix with `NODE_OPTIONS=--max-old-space-size=4096`, set for the build step only: if it also applies at runtime, file parsing is refused with `START_FAILED`, because the larger heap flag overrides the parse worker's memory limit).**Function timeout** — If requests timeout on Hobby plan: upgrade to Pro (60s timeout), use faster AI models (e.g., GPT-4o-mini instead of GPT-4o), reduce max tokens, or ensure streaming is enabled.diff --git a/docs/self-hosting/platform/vercel.zh-CN.mdx b/docs/self-hosting/platform/vercel.zh-CN.mdxindex 159e35c1c1c..ffd7fc6b165 100644--- a/docs/self-hosting/platform/vercel.zh-CN.mdx+++ b/docs/self-hosting/platform/vercel.zh-CN.mdx@@ -381,7 +381,7 @@ tags:## 故障排查-**部署失败** — 在 Vercel 控制台 → 部署记录 → 点击失败的部署 → 构建日志中查看详情。常见原因:环境变量缺失、TypeScript 报错、内存不足(通过 `NODE_OPTIONS=--max-old-space-size=4096` 修复)。+**部署失败** — 在 Vercel 控制台 → 部署记录 → 点击失败的部署 → 构建日志中查看详情。常见原因:环境变量缺失、TypeScript 报错、内存不足(通过 `NODE_OPTIONS=--max-old-space-size=4096` 修复,仅在构建步骤设置:若运行时也生效,文件解析会因更大的堆参数覆盖解析 worker 的内存上限而被拒绝,返回 `START_FAILED`)。**函数超时** — 在 Hobby 套餐遇到超时时:升级到 Pro(60 秒超时)、使用更快的模型(如 GPT-4o-mini 代替 GPT-4o)、减少最大 token 数,或确认已启用流式响应。diff --git a/package.json b/package.jsonindex f1a7c845cdd..b32b087e6c2 100644--- a/package.json+++ b/package.json@@ -48,9 +48,10 @@"build": "bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next","build:analyze": "cross-env NODE_OPTIONS=--max-old-space-size=81920 next experimental-analyze","build:canvas-runtime": "pnpm --filter @lobechat/canvas-runtime build",- "build:docker": "pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build",+ "build:docker": "pnpm run build:file-parse-worker && pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build",+ "build:file-parse-worker": "tsx scripts/buildFileParseWorker.mts","build:next": "cross-env NODE_OPTIONS=--max-old-space-size=7168 bun run build:next:raw",- "build:next:raw": "next build",+ "build:next:raw": "pnpm run build:file-parse-worker && next build","build:raw": "bun run build:spa:raw && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next:raw","build:spa": "cross-env NODE_OPTIONS=--max-old-space-size=8192 pnpm run build:spa:raw","build:spa:auth": "rm -rf public/_spa public/_spa-auth && cross-env NODE_OPTIONS=--max-old-space-size=8192 AUTH=true vite build",@@ -77,12 +78,12 @@"desktop:package:local": "npm run package:local --prefix=./apps/desktop","desktop:package:local:reuse": "npm run package:local:reuse --prefix=./apps/desktop","dev": "tsx scripts/devStartupSequence.mts",- "dev:bun": "bun --bun next dev -p 3010",+ "dev:bun": "bun run build:file-parse-worker && bun --bun next dev -p 3010","dev:desktop": "cd apps/desktop && pnpm run dev","dev:docker": "docker compose -f docker-compose/dev/docker-compose.yml up -d --wait postgresql redis rustfs searxng","dev:docker:down": "docker compose -f docker-compose/dev/docker-compose.yml down","dev:docker:reset": "docker compose -f docker-compose/dev/docker-compose.yml down -v && rm -rf docker-compose/dev/data && npm run dev:docker && pnpm db:migrate",- "dev:next": "next dev -p 3010",+ "dev:next": "bun run build:file-parse-worker && next dev -p 3010","dev:spa": "vite","dev:spa:auth": "cross-env AUTH=true vite","dev:spa:mobile": "cross-env MOBILE=true vite",diff --git a/packages/database/src/models/__tests__/chunk.test.ts b/packages/database/src/models/__tests__/chunk.test.tsindex 5021d1c31d3..ad93e50fc23 100644--- a/packages/database/src/models/__tests__/chunk.test.ts+++ b/packages/database/src/models/__tests__/chunk.test.ts@@ -15,6 +15,7 @@ import {workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { INSERT_BATCH_SIZE } from '../../utils/batchInsert';import { ChunkModel } from '../chunk';import { codeEmbedding, designThinkingQuery, designThinkingQuery2 } from './fixtures/embedding';@@ -104,6 +105,54 @@ describe('ChunkModel', () => {});expect(createdChunks).toHaveLength(0);});++ it('should insert past one statement batch, keeping order and file links', async () => {+ const total = INSERT_BATCH_SIZE * 2 + 7;+ const params = Array.from({ length: total }, (_, i) => ({+ index: i,+ text: `Chunk ${i}`,+ userId,+ }));++ const result = await chunkModel.bulkCreate(params, '1');++ expect(result.map((c) => c.index)).toEqual(params.map((p) => p.index));+ const links = await serverDB.query.fileChunks.findMany({ where: eq(fileChunks.fileId, '1') });+ expect(new Set(links.map((l) => l.chunkId))).toEqual(new Set(result.map((c) => c.id)));+ });++ // 50,000 rows is a real spreadsheet (one chunk per row); a single INSERT of that many rows+ // overflows the call stack inside Drizzle's query builder.+ it('should insert a 50,000-row file in one transaction', async () => {+ const params = Array.from({ length: 50_000 }, (_, i) => ({+ index: i,+ text: `Chunk ${i}`,+ userId,+ }));++ const result = await chunkModel.bulkCreate(params, '1');++ expect(result).toHaveLength(50_000);+ expect(result.at(-1)?.index).toBe(49_999);+ }, 60_000);++ it('should roll back every batch when a later batch fails', async () => {+ const params = Array.from({ length: INSERT_BATCH_SIZE + 2 }, (_, i) => ({+ index: i,+ text: `Chunk ${i}`,+ userId,+ })) as any[];+ params[INSERT_BATCH_SIZE + 1] = { index: 'abc', userId };++ await expect(chunkModel.bulkCreate(params, '1')).rejects.toThrow();++ expect(+ await serverDB.query.chunks.findMany({ where: eq(chunks.userId, userId) }),+ ).toHaveLength(0);+ expect(+ await serverDB.query.fileChunks.findMany({ where: eq(fileChunks.fileId, '1') }),+ ).toHaveLength(0);+ });});describe('delete', () => {diff --git a/packages/database/src/models/chunk.ts b/packages/database/src/models/chunk.tsindex e78b94087c1..b6c5e18d85f 100644--- a/packages/database/src/models/chunk.ts+++ b/packages/database/src/models/chunk.ts@@ -5,6 +5,7 @@ import { chunk } from 'es-toolkit/compat';import type { NewChunkItem, NewUnstructuredChunkItem } from '../schemas';import { chunks, embeddings, fileChunks, files, unstructuredChunks } from '../schemas';import type { LobeChatDatabase } from '../type';+import { insertInBatches } from '../utils/batchInsert';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';export class ChunkModel {@@ -29,14 +30,21 @@ export class ChunkModel {return this.db.transaction(async (trx) => {if (params.length === 0) return [];- const result = await trx- .insert(chunks)- .values(- params.map((p) =>- buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, p),- ),- )- .returning();+ // One statement per INSERT_BATCH_SIZE rows, all inside this transaction: a spreadsheet of+ // tens of thousands of rows would otherwise exceed PG's 65,535 bind parameters, and+ // Drizzle's query builder overflows the call stack on that many rows before it gets there.+ const result: (typeof chunks.$inferSelect)[] = [];+ await insertInBatches(params, async (batch) => {+ const created = await trx+ .insert(chunks)+ .values(+ batch.map((p) =>+ buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, p),+ ),+ )+ .returning();+ result.push(...created);+ });const fileChunksData = result.map((chunk) => ({chunkId: chunk.id,@@ -45,8 +53,7 @@ export class ChunkModel {workspaceId: this.workspaceId ?? null,}));- // `params` is non-empty here and INSERT … RETURNING yields one row per value.- await trx.insert(fileChunks).values(fileChunksData);+ await insertInBatches(fileChunksData, (batch) => trx.insert(fileChunks).values(batch));return result;});diff --git a/packages/eval-dataset-parser/package.json b/packages/eval-dataset-parser/package.jsonindex 35d9634b713..2c00c38215f 100644--- a/packages/eval-dataset-parser/package.json+++ b/packages/eval-dataset-parser/package.json@@ -27,6 +27,7 @@"test:coverage": "vitest --coverage --silent='passed-only'"},"dependencies": {+ "@lobechat/file-loaders": "workspace:*","papaparse": "^5.5.4","xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"},diff --git a/packages/eval-dataset-parser/src/parsers/xlsx.test.ts b/packages/eval-dataset-parser/src/parsers/xlsx.test.tsnew file mode 100644index 00000000000..dc00285866c--- /dev/null+++ b/packages/eval-dataset-parser/src/parsers/xlsx.test.ts@@ -0,0 +1,59 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import * as XLSX from 'xlsx';++import { parseXLSX } from './xlsx';++const toBuffer = (sheets: Record<string, XLSX.WorkSheet>) => {+ const workbook = XLSX.utils.book_new();+ for (const [name, sheet] of Object.entries(sheets))+ XLSX.utils.book_append_sheet(workbook, sheet, name);+ return new Uint8Array(XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' }));+};++afterEach(() => {+ vi.restoreAllMocks();+});++describe('parseXLSX data bounds', () => {+ it('parses a sheet with a stretched declared range to the same rows', () => {+ const sheet = XLSX.utils.aoa_to_sheet([+ ['q', 'a'],+ ['one', 0],+ ['two', false],+ ]);+ sheet['!ref'] = 'A1:Z20000';+ const toJson = vi.spyOn(XLSX.utils, 'sheet_to_json');++ const result = parseXLSX(toBuffer({ Data: sheet }));++ expect(result.headers).toEqual(['q', 'a']);+ expect(result.rows).toEqual([+ { a: '0', q: 'one' },+ { a: 'FALSE', q: 'two' },+ ]);+ expect(result.totalCount).toBe(2);+ const received = toJson.mock.calls[0][0] as XLSX.WorkSheet;+ expect(XLSX.utils.decode_range(received['!ref']!).e.r).toBeLessThan(10);+ });++ it('still selects the sheet by name and by index', () => {+ const first = XLSX.utils.aoa_to_sheet([['a'], ['1']]);+ const second = XLSX.utils.aoa_to_sheet([['b'], ['2']]);+ const buffer = toBuffer({ First: first, Second: second });++ expect(parseXLSX(buffer, { sheet: 'Second' }).rows).toEqual([{ b: '2' }]);+ expect(parseXLSX(buffer, { sheet: 1 }).rows).toEqual([{ b: '2' }]);+ });++ it('throws a budget error when real values span an over-budget rectangle', () => {+ const sheet: XLSX.WorkSheet = {+ '!ref': 'A1:CCC3000',+ 'A1': { t: 's', v: 'head' },+ 'CCC3000': { t: 's', v: 'tail' },+ };++ expect(() => parseXLSX(toBuffer({ Data: sheet }))).toThrow(+ expect.objectContaining({ name: 'FileParseBudgetError', reason: 'sheet-cells' }),+ );+ });+});diff --git a/packages/eval-dataset-parser/src/parsers/xlsx.ts b/packages/eval-dataset-parser/src/parsers/xlsx.tsindex 65bd9dcefd9..7e4acd23c33 100644--- a/packages/eval-dataset-parser/src/parsers/xlsx.ts+++ b/packages/eval-dataset-parser/src/parsers/xlsx.ts@@ -1,11 +1,9 @@+import { clampSheetRefToData } from '@lobechat/file-loaders/src/xlsxBudget';import * as XLSX from 'xlsx';import type { ParseOptions, ParseResult } from '../types';-export function parseXLSX(- data: Buffer | Uint8Array,- options?: ParseOptions,-): ParseResult {+export function parseXLSX(data: Buffer | Uint8Array, options?: ParseOptions): ParseResult {const workbook = XLSX.read(data, { type: 'array' });// Select sheet@@ -23,6 +21,9 @@ export function parseXLSX(return { format: 'xlsx', headers: [], metadata: { sheetName }, rows: [], totalCount: 0 };}+ // A declared used range can span a million styled-but-empty rows: clamp it to the real data+ clampSheetRefToData(worksheet);+const allRows = XLSX.utils.sheet_to_json<Record<string, any>>(worksheet, {defval: '',raw: false,diff --git a/packages/file-loaders/src/fileParseBudget.ts b/packages/file-loaders/src/fileParseBudget.tsnew file mode 100644index 00000000000..7bc048b9d19--- /dev/null+++ b/packages/file-loaders/src/fileParseBudget.ts@@ -0,0 +1,39 @@+/**+ * Why a file was refused before or during parsing. The values describe structure only,+ * never file content:+ * - `zip-input`: the compressed archive itself is too large+ * - `zip-entries`: the archive declares too many entries+ * - `zip-expansion`: the entries inflate to too much data in total+ * - `sheet-xml`: one worksheet part inflates to too much data+ * - `sheet-cells`: the rectangle that spans the real cells of a sheet is too large+ */+export type FileParseBudgetReason =+ 'sheet-cells' | 'sheet-xml' | 'zip-entries' | 'zip-expansion' | 'zip-input';++/**+ * A file exceeds a fixed structural budget (input size, entry count, inflated size, cell area). It is a+ * deliberate refusal, not a corrupt file, so loaders rethrow it instead of returning an error+ * page and callers can tell the user the file is too large.+ *+ * `limit` and `actual` use the unit of the reason: entries, bytes or cells.+ */+export class FileParseBudgetError extends Error {+ actual: number;+ limit: number;+ reason: FileParseBudgetReason;++ constructor(reason: FileParseBudgetReason, limit: number, actual: number) {+ super(`File exceeds the parse budget (${reason}): ${actual} > ${limit}`);+ this.name = 'FileParseBudgetError';+ this.reason = reason;+ this.limit = limit;+ this.actual = actual;+ }+}++/**+ * Name based so it still matches after the error crossed a module-copy or worker boundary.+ */+export const isFileParseBudgetError = (error: unknown): error is FileParseBudgetError =>+ error instanceof FileParseBudgetError ||+ (error instanceof Error && error.name === 'FileParseBudgetError');diff --git a/packages/file-loaders/src/index.ts b/packages/file-loaders/src/index.tsindex 9be76115281..b82eb72022d 100644--- a/packages/file-loaders/src/index.ts+++ b/packages/file-loaders/src/index.ts@@ -1,6 +1,7 @@export * from './blackList';-export * from './loadFile';+export * from './fileParseBudget';export { convertIpynbToMarkdown, scrubIpynbFallbackText } from './loaders/ipynb';+export * from './loadFile';export * from './types';export * from './utils/isBinaryContent';export * from './utils/isTextReadableFile';diff --git a/packages/file-loaders/src/loadFile.ts b/packages/file-loaders/src/loadFile.tsindex f375c79b1dd..dfbdba09e0a 100644--- a/packages/file-loaders/src/loadFile.ts+++ b/packages/file-loaders/src/loadFile.ts@@ -3,6 +3,7 @@ import path from 'node:path';import debug from 'debug';+import { isFileParseBudgetError } from './fileParseBudget';import { getFileLoader } from './loaders';import type { DocumentPage, FileDocument, FileMetadata, SupportedFileType } from './types';import { isTextReadableFile } from './utils/isTextReadableFile';@@ -198,6 +199,8 @@ export const loadFile = async (log('Loader does not support attachDocumentMetadata.');}} catch (loadErr) {+ // A budget refusal must reach the caller instead of becoming a cached error page+ if (isFileParseBudgetError(loadErr)) throw loadErr;const error = loadErr as Error;console.error(`Error loading pages for ${filePath} using ${LoaderClass.name}: ${error.message}`,diff --git a/packages/file-loaders/src/loaders/excel/index.budget.test.ts b/packages/file-loaders/src/loaders/excel/index.budget.test.tsnew file mode 100644index 00000000000..9564f86f598--- /dev/null+++ b/packages/file-loaders/src/loaders/excel/index.budget.test.ts@@ -0,0 +1,181 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as xlsx from 'xlsx';++import { loadFile } from '../../loadFile';+import { ExcelLoader } from './index';+import { buildTestZip } from './testUtils';++let dir: string;+let loader: ExcelLoader;++beforeEach(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'excel-budget-'));+ loader = new ExcelLoader();+});++afterEach(async () => {+ vi.restoreAllMocks();+ await rm(dir, { force: true, recursive: true });+});++const writeBook = async (name: string, sheets: Record<string, xlsx.WorkSheet>): Promise<string> => {+ const workbook = xlsx.utils.book_new();+ for (const [sheetName, sheet] of Object.entries(sheets)) {+ xlsx.utils.book_append_sheet(workbook, sheet, sheetName);+ }+ const filePath = path.join(dir, name);+ await writeFile(filePath, xlsx.write(workbook, { bookType: 'xlsx', type: 'buffer' }));+ return filePath;+};++const refArea = (ref: string) => {+ const range = xlsx.utils.decode_range(ref);+ return (range.e.r - range.s.r + 1) * (range.e.c - range.s.c + 1);+};++describe('ExcelLoader data bounds', () => {+ it('hands sheet_to_json a range shrunk to the real data when a huge range is declared', async () => {+ const sheet = xlsx.utils.aoa_to_sheet([+ ['name', 'value'],+ ['a', 0],+ ['b', false],+ ]);+ sheet['!ref'] = 'A1:Z50000';+ const filePath = await writeBook('declared.xlsx', { Declared: sheet });+ const toJson = vi.spyOn(xlsx.utils, 'sheet_to_json').mockReturnValue([]);++ await loader.loadPages(filePath);++ const received = toJson.mock.calls[0][0] as xlsx.WorkSheet;+ expect(refArea(received['!ref']!)).toBeLessThanOrEqual(6);+ }, 30_000);++ it('keeps the markdown for values 0 / false and drops declared blank rows', async () => {+ const sheet = xlsx.utils.aoa_to_sheet([+ ['name', 'value'],+ ['a', 0],+ ['b', false],+ ]);+ sheet['!ref'] = 'A1:Z3000';++ const pages = await loader.loadPages(await writeBook('zero.xlsx', { Zero: sheet }));++ expect(pages[0].pageContent).toBe('| name | value |\n| --- | --- |\n| a | 0 |\n| b | FALSE |');+ });++ it('turns a sheet with no real cells into the empty placeholder', async () => {+ const sheet: xlsx.WorkSheet = { '!ref': 'A1:Z3000' };+ const filePath = await writeBook('blank.xlsx', { Blank: sheet });+ const toJson = vi.spyOn(xlsx.utils, 'sheet_to_json');++ const pages = await loader.loadPages(filePath);++ expect(pages[0].pageContent).toBe('*Sheet is empty or contains no data.*');+ expect(refArea((toJson.mock.calls[0][0] as xlsx.WorkSheet)['!ref']!)).toBe(1);+ });++ it('loads an large declared range with a real 3150 x 8 sheet completely', async () => {+ const rows = [+ Array.from({ length: 8 }, (_, c) => `h${c}`),+ ...Array.from({ length: 3149 }, (_, r) => Array.from({ length: 8 }, (_, c) => `${r}-${c}`)),+ ];+ const sheet = xlsx.utils.aoa_to_sheet(rows);+ sheet['!ref'] = 'A1:AX30000';++ const pages = await loader.loadPages(await writeBook('big.xlsx', { Big: sheet }));++ expect(pages[0].metadata.error).toBeUndefined();+ expect(pages[0].lineCount).toBe(3150 + 1);+ expect(pages[0].pageContent).toContain('| 3148-0 |');+ expect(pages[0].pageContent).toContain('3148-7 |');+ });++ it('processes every sheet of a multi-sheet workbook independently', async () => {+ const sparse = xlsx.utils.aoa_to_sheet([+ ['k', 'v'],+ ['x', 1],+ ]);+ sparse['!ref'] = 'A1:Z5000';+ const normal = xlsx.utils.aoa_to_sheet([+ ['p', 'q'],+ ['y', 2],+ ]);++ const pages = await loader.loadPages(+ await writeBook('multi.xlsx', { Normal: normal, Sparse: sparse }),+ );++ expect(pages.map((page) => page.metadata.sheetName)).toEqual(['Normal', 'Sparse']);+ expect(pages[1].pageContent).toBe('| k | v |\n| --- | --- |\n| x | 1 |');+ expect(pages[0].pageContent).toBe('| p | q |\n| --- | --- |\n| y | 2 |');+ });++ it('rejects with a budget error when real values span an over-budget rectangle', async () => {+ const sheet: xlsx.WorkSheet = {+ '!ref': 'A1:CCC3000',+ 'A1': { t: 's', v: 'head' },+ 'CCC3000': { t: 's', v: 'tail' },+ };+ const filePath = await writeBook('diagonal.xlsx', { Diagonal: sheet });++ await expect(loader.loadPages(filePath)).rejects.toMatchObject({+ name: 'FileParseBudgetError',+ reason: 'sheet-cells',+ });+ });+});++describe('ExcelLoader zip budget', () => {+ it('rejects an archive with too many entries before parsing it', async () => {+ const filePath = path.join(dir, 'many.xlsx');+ await writeFile(+ filePath,+ buildTestZip(Array.from({ length: 5001 }, (_, i) => ({ name: `xl/media/${i}.bin` }))),+ );++ await expect(loader.loadPages(filePath)).rejects.toMatchObject({+ actual: 5001,+ limit: 5000,+ name: 'FileParseBudgetError',+ reason: 'zip-entries',+ });+ });++ it('still reports a corrupt archive through the usual error page', async () => {+ const filePath = path.join(dir, 'corrupt.xlsx');+ await writeFile(filePath, Buffer.concat([Buffer.from('PK\u0003\u0004'), Buffer.alloc(40)]));++ const pages = await loader.loadPages(filePath);++ expect(pages).toHaveLength(1);+ expect(pages[0].metadata.error).toContain('Failed to load Excel file');+ });+});++describe('loadFile with budget errors', () => {+ it('rethrows the budget error instead of turning it into an error page', async () => {+ const filePath = path.join(dir, 'many.xlsx');+ await writeFile(+ filePath,+ buildTestZip(Array.from({ length: 5001 }, (_, i) => ({ name: `xl/media/${i}.bin` }))),+ );++ await expect(loadFile(filePath)).rejects.toMatchObject({+ name: 'FileParseBudgetError',+ reason: 'zip-entries',+ });+ });++ it('keeps ordinary excel failures as an error page', async () => {+ const filePath = path.join(dir, 'corrupt.xlsx');+ await writeFile(filePath, Buffer.concat([Buffer.from('PK\u0003\u0004'), Buffer.alloc(40)]));++ const doc = await loadFile(filePath);++ expect(doc.metadata.error).toContain('Failed to load Excel file');+ });+});diff --git a/packages/file-loaders/src/loaders/excel/index.ts b/packages/file-loaders/src/loaders/excel/index.tsindex 820d469875b..16f178e4150 100644--- a/packages/file-loaders/src/loaders/excel/index.ts+++ b/packages/file-loaders/src/loaders/excel/index.ts@@ -3,8 +3,11 @@ import { readFile } from 'node:fs/promises';import debug from 'debug';import * as xlsx from 'xlsx';+import { isFileParseBudgetError } from '../../fileParseBudget';import type { DocumentPage, FileLoaderInterface } from '../../types';import { promptTemplate } from './prompt';+import { clampSheetRefToData } from './sheetBounds';+import { preflightXlsxZip } from './zipBudget';const log = debug('file-loaders:excel');@@ -67,6 +70,9 @@ export class ExcelLoader implements FileLoaderInterface {const dataBuffer = await readFile(filePath);log('Excel file read successfully, size:', dataBuffer.length, 'bytes');+ // Refuse oversized ZIP structures before SheetJS inflates them+ await preflightXlsxZip(dataBuffer);+log('Parsing Excel workbook');const workbook = xlsx.read(dataBuffer, { type: 'buffer' });log('Excel workbook parsed successfully, sheets:', workbook.SheetNames.length);@@ -74,6 +80,8 @@ export class ExcelLoader implements FileLoaderInterface {for (const sheetName of workbook.SheetNames) {log(`Processing sheet: ${sheetName}`);const worksheet = workbook.Sheets[sheetName];+ // A declared used range can span a million styled-but-empty rows: clamp it to the real data+ clampSheetRefToData(worksheet);// Use sheet_to_json to get array of objects for our custom markdown functionconst jsonData = xlsx.utils.sheet_to_json<Record<string, any>>(worksheet, {// Get formatted strings, not raw values@@ -117,6 +125,8 @@ export class ExcelLoader implements FileLoaderInterface {log('Excel loading completed, total pages:', pages.length);return pages;} catch (e) {+ // A budget refusal is not a corrupt file: let callers tell the user the file is too large+ if (isFileParseBudgetError(e)) throw e;const error = e as Error;log('Error encountered while loading Excel file');console.error(`Error loading Excel file ${filePath}: ${error.message}`);diff --git a/packages/file-loaders/src/loaders/excel/sheetBounds.test.ts b/packages/file-loaders/src/loaders/excel/sheetBounds.test.tsnew file mode 100644index 00000000000..17caf34ace7--- /dev/null+++ b/packages/file-loaders/src/loaders/excel/sheetBounds.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from 'vitest';+import * as xlsx from 'xlsx';++import { clampSheetRefToData, MAX_SHEET_CELLS } from './sheetBounds';++const sheetWith = (ref: string, cells: Record<string, xlsx.CellObject>): xlsx.WorkSheet => ({+ '!ref': ref,+ ...cells,+});++describe('clampSheetRefToData', () => {+ it('shrinks the end of a stretched range to the last real cell and keeps the start', () => {+ const ws = sheetWith('B2:ZZ99999', {+ C5: { t: 's', v: 'x' },+ D7: { t: 'n', v: 1 },+ });++ clampSheetRefToData(ws);++ expect(ws['!ref']).toBe('B2:D7');+ });++ it('does not walk the declared rectangle (a declared XFD1048576 range with two cells)', () => {+ const ws = sheetWith('A1:XFD1048576', {+ A1: { t: 's', v: 'head' },+ C3: { t: 's', v: 'tail' },+ });++ clampSheetRefToData(ws);++ expect(ws['!ref']).toBe('A1:C3');+ });++ it.each([+ ['zero', { t: 'n', v: 0 } as xlsx.CellObject],+ ['false', { t: 'b', v: false } as xlsx.CellObject],+ ['date', { t: 'd', v: new Date(0) } as xlsx.CellObject],+ ['error', { t: 'e', v: 0x07, w: '#DIV/0!' } as xlsx.CellObject],+ ['formula cached value', { f: 'A1+1', t: 'n', v: 2 } as xlsx.CellObject],+ ['formula without cache', { f: 'A1+1', t: 'n' } as xlsx.CellObject],+ ['empty string', { t: 's', v: '' } as xlsx.CellObject],+ ])('treats a far %s cell as real data', (_name, cell) => {+ const ws = sheetWith('A1:Z5000', { A1: { t: 's', v: 'head' }, E40: cell });++ clampSheetRefToData(ws);++ expect(ws['!ref']).toBe('A1:E40');+ });++ it('ignores style-only stub cells', () => {+ const ws = sheetWith('A1:Z5000', {+ A1: { t: 's', v: 'head' },+ D100: { t: 'z' },+ E200: { t: 'z', s: { bold: true } } as xlsx.CellObject,+ });++ clampSheetRefToData(ws);++ expect(ws['!ref']).toBe('A1');+ });++ it('collapses a sheet without any real cell to its start cell', () => {+ const ws = sheetWith('C4:Z5000', { '!margins': {} as any, 'D9': { t: 'z' } });++ clampSheetRefToData(ws);++ expect(ws['!ref']).toBe('C4');+ expect(xlsx.utils.sheet_to_json(ws)).toEqual([]);+ });++ it('never extends the range to cells outside the declared one', () => {+ const ws = sheetWith('A1:C3', { A1: { t: 's', v: 'h' }, Z99: { t: 's', v: 'outside' } });++ clampSheetRefToData(ws);++ expect(ws['!ref']).toBe('A1');+ });++ it('leaves a sheet without !ref untouched', () => {+ const ws: xlsx.WorkSheet = { A1: { t: 's', v: 'x' } };++ expect(() => clampSheetRefToData(ws)).not.toThrow();+ expect(ws['!ref']).toBeUndefined();+ });++ it('keeps sheet_to_json output identical for a normal dense sheet', () => {+ const ws = xlsx.utils.aoa_to_sheet([+ ['name', 'value'],+ ['a', 0],+ ['b', false],+ ]);+ const before = xlsx.utils.sheet_to_json(ws, { defval: '', raw: false });++ clampSheetRefToData(ws);++ expect(xlsx.utils.sheet_to_json(ws, { defval: '', raw: false })).toEqual(before);+ });++ it('accepts a 3150 x 8 data area declared as a million-row range', () => {+ const rows = Array.from({ length: 3150 }, (_, r) => Array.from({ length: 8 }, (_, c) => r + c));+ const ws = xlsx.utils.aoa_to_sheet(rows);+ ws['!ref'] = 'A1:AX1046048';++ clampSheetRefToData(ws);++ expect(ws['!ref']).toBe('A1:H3150');+ });++ it('rejects a real-data rectangle above the cell budget without leaking cell content', () => {+ const ws = sheetWith('A1:ZZ9999', {+ A1: { t: 's', v: 'SECRET-HEAD' },+ J20: { t: 's', v: 'SECRET-TAIL' },+ });++ let caught: any;+ try {+ clampSheetRefToData(ws, { maxCells: 100 });+ } catch (error) {+ caught = error;+ }++ expect(caught).toMatchObject({+ actual: 200,+ limit: 100,+ name: 'FileParseBudgetError',+ reason: 'sheet-cells',+ });+ expect(caught.message).not.toContain('SECRET');+ });++ it('allows a rectangle exactly at the budget', () => {+ const ws = sheetWith('A1:Z100', { A1: { t: 's', v: 'h' }, J10: { t: 's', v: 't' } });++ expect(() => clampSheetRefToData(ws, { maxCells: 100 })).not.toThrow();+ });++ it('defaults to a 5,000,000 cell budget', () => {+ expect(MAX_SHEET_CELLS).toBe(5_000_000);+ });+});diff --git a/packages/file-loaders/src/loaders/excel/sheetBounds.ts b/packages/file-loaders/src/loaders/excel/sheetBounds.tsnew file mode 100644index 00000000000..90d9b018c11--- /dev/null+++ b/packages/file-loaders/src/loaders/excel/sheetBounds.ts@@ -0,0 +1,58 @@+import * as xlsx from 'xlsx';++import { FileParseBudgetError } from '../../fileParseBudget';++/** Largest rectangle (rows x columns) spanning the real cells of one sheet. */+export const MAX_SHEET_CELLS = 5_000_000;++export interface SheetBoundsOptions {+ maxCells?: number;+}++/** A stub (`t: 'z'`) or a cell with neither value, formula nor text carries only style. */+const isRealCell = (cell: xlsx.CellObject | undefined): boolean =>+ !!cell &&+ typeof cell === 'object' &&+ cell.t !== 'z' &&+ (cell.v !== undefined && cell.v !== null ? true : cell.f !== undefined || cell.w !== undefined);++/**+ * Shrinks the end of `!ref` to the last row/column holding a real cell, keeping the declared+ * start so header semantics stay as they were. Spreadsheets routinely declare a used range of+ * a million styled-but-empty rows; `sheet_to_json` walks the whole declared rectangle, so+ * the range is clamped first.+ *+ * Only the cells that exist in the sheet object are visited, never the declared rectangle.+ * Cells outside the declared range are ignored (as `sheet_to_json` would). A sheet with no+ * real cell collapses to its start cell. Throws `FileParseBudgetError('sheet-cells')` when the+ * clamped rectangle is still above the budget. Mutates `worksheet`.+ */+export const clampSheetRefToData = (+ worksheet: xlsx.WorkSheet | undefined,+ { maxCells = MAX_SHEET_CELLS }: SheetBoundsOptions = {},+): void => {+ const ref = worksheet?.['!ref'];+ if (!worksheet || !ref) return;++ const range = xlsx.utils.decode_range(ref);+ let lastRow = range.s.r;+ let lastCol = range.s.c;++ for (const key in worksheet) {+ if (key.charCodeAt(0) === 33 /* "!" */) continue;+ if (!isRealCell(worksheet[key] as xlsx.CellObject)) continue;++ const { c, r } = xlsx.utils.decode_cell(key);+ if (r < range.s.r || r > range.e.r || c < range.s.c || c > range.e.c) continue;+ if (r > lastRow) lastRow = r;+ if (c > lastCol) lastCol = c;+ }++ const area = (lastRow - range.s.r + 1) * (lastCol - range.s.c + 1);+ if (area > maxCells) throw new FileParseBudgetError('sheet-cells', maxCells, area);++ worksheet['!ref'] = xlsx.utils.encode_range({+ e: { c: lastCol, r: lastRow },+ s: range.s,+ });+};diff --git a/packages/file-loaders/src/loaders/excel/testUtils.ts b/packages/file-loaders/src/loaders/excel/testUtils.tsnew file mode 100644index 00000000000..f01b211e5da--- /dev/null+++ b/packages/file-loaders/src/loaders/excel/testUtils.ts@@ -0,0 +1,65 @@+import { crc32, deflateRawSync } from 'node:zlib';++export interface TestZipEntry {+ /** Real uncompressed bytes. */+ data?: Buffer | string;+ /** Central-directory declared uncompressed size; defaults to the real data length. */+ declaredSize?: number;+ /** Store the data deflated (method 8) instead of stored (method 0). */+ deflate?: boolean;+ name: string;+}++/**+ * Builds a minimal ZIP in memory (stored, or deflated per entry). The declared size in the central+ * directory can differ from the real data, so size budgets are testable with tiny fixtures.+ */+export const buildTestZip = (entries: TestZipEntry[]): Buffer => {+ const locals: Buffer[] = [];+ const centrals: Buffer[] = [];+ let offset = 0;++ for (const entry of entries) {+ const name = Buffer.from(entry.name, 'utf8');+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data ?? '', 'utf8');+ const crc = crc32(data);+ const payload = entry.deflate ? deflateRawSync(data) : data;+ const method = entry.deflate ? 8 : 0;++ const local = Buffer.alloc(30 + name.length);+ local.writeUInt32LE(0x04_03_4b_50, 0);+ local.writeUInt16LE(20, 4);+ local.writeUInt16LE(method, 8);+ local.writeUInt32LE(crc, 14);+ local.writeUInt32LE(payload.length, 18);+ local.writeUInt32LE(data.length, 22);+ local.writeUInt16LE(name.length, 26);+ name.copy(local, 30);+ locals.push(local, payload);++ const central = Buffer.alloc(46 + name.length);+ central.writeUInt32LE(0x02_01_4b_50, 0);+ central.writeUInt16LE(20, 4);+ central.writeUInt16LE(20, 6);+ central.writeUInt16LE(method, 10);+ central.writeUInt32LE(crc, 16);+ central.writeUInt32LE(payload.length, 20);+ central.writeUInt32LE(entry.declaredSize ?? data.length, 24);+ central.writeUInt16LE(name.length, 28);+ central.writeUInt32LE(offset, 42);+ name.copy(central, 46);+ centrals.push(central);++ offset += local.length + payload.length;+ }++ const centralSize = centrals.reduce((sum, item) => sum + item.length, 0);+ const end = Buffer.alloc(22);+ end.writeUInt32LE(0x06_05_4b_50, 0);+ end.writeUInt16LE(entries.length, 8);+ end.writeUInt16LE(entries.length, 10);+ end.writeUInt32LE(centralSize, 12);+ end.writeUInt32LE(offset, 16);++ return Buffer.concat([...locals, ...centrals, end]);+};diff --git a/packages/file-loaders/src/loaders/excel/zipBudget.test.ts b/packages/file-loaders/src/loaders/excel/zipBudget.test.tsnew file mode 100644index 00000000000..562e4a3f187--- /dev/null+++ b/packages/file-loaders/src/loaders/excel/zipBudget.test.ts@@ -0,0 +1,293 @@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';++import { afterEach, describe, expect, it, vi } from 'vitest';+import yauzl from 'yauzl';++import { buildTestZip } from './testUtils';+import { DEFAULT_XLSX_ZIP_LIMITS, preflightXlsxZip } from './zipBudget';++const limits = {+ maxEntries: 10,+ maxInputBytes: 100_000,+ maxTotalBytes: 1000,+ maxWorksheetBytes: 400,+};++const big = (n: number) => 'x'.repeat(n);++afterEach(() => {+ vi.restoreAllMocks();+});++describe('preflightXlsxZip', () => {+ it('defaults to 64 MiB input, 5000 entries, 512 MiB total and 256 MiB per worksheet', () => {+ expect(DEFAULT_XLSX_ZIP_LIMITS).toEqual({+ maxEntries: 5000,+ maxInputBytes: 64 * 1024 * 1024,+ maxTotalBytes: 512 * 1024 * 1024,+ maxWorksheetBytes: 256 * 1024 * 1024,+ });+ });++ it('accepts a small normal archive (stored and deflated, with a directory)', async () => {+ const zip = buildTestZip([+ { data: '<a/>', name: 'xl/workbook.xml' },+ { data: big(300), deflate: true, name: 'xl/worksheets/sheet1.xml' },+ { name: 'xl/media/' },+ ]);++ await expect(preflightXlsxZip(zip, limits)).resolves.toBeUndefined();+ });++ it('is a no-op for data that is not a ZIP (legacy .xls / unknown)', async () => {+ await expect(+ preflightXlsxZip(Buffer.from('not a zip at all'), limits),+ ).resolves.toBeUndefined();+ await expect(preflightXlsxZip(Buffer.alloc(0), limits)).resolves.toBeUndefined();+ // Not a ZIP: the input budget is the caller's concern+ await expect(+ preflightXlsxZip(Buffer.alloc(200_000, 1), { ...limits, maxInputBytes: 10 }),+ ).resolves.toBeUndefined();+ });++ it('rejects a ZIP whose compressed input is over the input budget', async () => {+ const zip = buildTestZip([{ data: big(50), name: 'a.xml' }]);++ await expect(preflightXlsxZip(zip, { ...limits, maxInputBytes: 50 })).rejects.toMatchObject({+ actual: zip.length,+ limit: 50,+ name: 'FileParseBudgetError',+ reason: 'zip-input',+ });+ });++ it('rejects too many entries', async () => {+ const zip = buildTestZip(Array.from({ length: 11 }, (_, i) => ({ name: `f${i}.xml` })));++ await expect(preflightXlsxZip(zip, limits)).rejects.toMatchObject({+ actual: 11,+ limit: 10,+ name: 'FileParseBudgetError',+ reason: 'zip-entries',+ });+ });++ it('rejects an honest archive whose total inflated size is over the budget', async () => {+ const zip = buildTestZip([+ { data: big(600), deflate: true, name: 'a.bin' },+ { data: big(600), deflate: true, name: 'b.bin' },+ ]);++ await expect(preflightXlsxZip(zip, limits)).rejects.toMatchObject({+ limit: 1000,+ name: 'FileParseBudgetError',+ reason: 'zip-expansion',+ });+ });++ it('rejects a single worksheet over its budget', async () => {+ const zip = buildTestZip([{ data: big(401), deflate: true, name: 'xl/worksheets/sheet3.xml' }]);++ await expect(preflightXlsxZip(zip, limits)).rejects.toMatchObject({+ actual: 401,+ limit: 400,+ name: 'FileParseBudgetError',+ reason: 'sheet-xml',+ });+ });++ it('does not apply the worksheet budget to other large parts', async () => {+ const zip = buildTestZip([{ data: big(900), deflate: true, name: 'xl/sharedStrings.xml' }]);++ await expect(preflightXlsxZip(zip, limits)).resolves.toBeUndefined();+ });++ it('keeps the budget error free of entry names', async () => {+ const zip = buildTestZip([{ data: big(500), deflate: true, name: 'xl/worksheets/SECRET.xml' }]);++ const error: any = await preflightXlsxZip(zip, limits).catch((e) => e);++ expect(error.name).toBe('FileParseBudgetError');+ expect(error.message).not.toContain('SECRET');+ });++ it('surfaces a truncated ZIP as an ordinary error, not a budget error', async () => {+ const zip = buildTestZip([{ data: 'x', name: 'a.xml' }]);+ const broken = zip.subarray(0, zip.length - 10);++ const error: any = await preflightXlsxZip(broken, limits).catch((e) => e);++ expect(error).toBeInstanceOf(Error);+ expect(error.name).not.toBe('FileParseBudgetError');+ });++ describe('forged central directory', () => {+ it('rejects a deflated entry that inflates to more than it declares (a ZIP bomb lie)', async () => {+ // Declares 10 bytes but really inflates to 5000: a budget that only trusted the+ // declaration (limit 1000) would let this through.+ const zip = buildTestZip([+ { data: big(5000), declaredSize: 10, deflate: true, name: 'xl/worksheets/sheet1.xml' },+ ]);++ const error: any = await preflightXlsxZip(zip, limits).catch((e) => e);++ expect(error).toBeInstanceOf(Error);+ expect(error.name).not.toBe('FileParseBudgetError');+ expect(error.message).toMatch(/too many bytes/);+ });++ it('rejects a deflated entry that inflates to less than it declares', async () => {+ const zip = buildTestZip([+ { data: big(50), declaredSize: 300, deflate: true, name: 'xl/worksheets/sheet1.xml' },+ ]);++ const error: any = await preflightXlsxZip(zip, limits).catch((e) => e);++ expect(error.message).toMatch(/not enough bytes/);+ });++ it('rejects a stored entry whose declared size disagrees with its stored size', async () => {+ const zip = buildTestZip([{ data: 'x', declaredSize: 9999, name: 'a.bin' }]);++ const error: any = await preflightXlsxZip(zip, limits).catch((e) => e);++ expect(error).toBeInstanceOf(Error);+ expect(error.name).not.toBe('FileParseBudgetError');+ });++ it('rejects a declared worksheet size over budget before streaming anything', async () => {+ const zip = buildTestZip([+ { data: big(500), deflate: true, name: 'xl/worksheets/sheet1.xml' },+ ]);+ const open = vi.spyOn(yauzl.ZipFile.prototype, 'openReadStream');++ await expect(preflightXlsxZip(zip, limits)).rejects.toMatchObject({ reason: 'sheet-xml' });+ expect(open).not.toHaveBeenCalled();+ });+ });++ describe('resources', () => {+ const captureHandles = () => {+ const handles: yauzl.ZipFile[] = [];+ const streams: Array<{ destroyed: boolean }> = [];+ const original = yauzl.fromBuffer.bind(yauzl);+ vi.spyOn(yauzl, 'fromBuffer').mockImplementation(((buffer: Buffer, opts: any, cb: any) =>+ original(buffer, opts, (err: Error | null, zipfile?: yauzl.ZipFile) => {+ if (zipfile) {+ handles.push(zipfile);+ const openRead = zipfile.openReadStream.bind(zipfile) as any;+ zipfile.openReadStream = ((entry: any, ...rest: any[]) => {+ const callback = rest.at(-1);+ return openRead(entry, ...rest.slice(0, -1), (e: any, stream: any) => {+ if (stream) streams.push(stream);+ callback(e, stream);+ });+ }) as any;+ }+ cb(err, zipfile);+ })) as any);+ return { handles, streams };+ };++ it.each([+ ['success', () => buildTestZip([{ data: big(100), deflate: true, name: 'a.xml' }])],+ [+ 'too many entries',+ () => buildTestZip(Array.from({ length: 11 }, (_, i) => ({ name: `${i}` }))),+ ],+ [+ 'declared expansion',+ () => buildTestZip([{ data: big(1500), deflate: true, name: 'a.bin' }]),+ ],+ [+ 'declared worksheet',+ () => buildTestZip([{ data: big(500), deflate: true, name: 'xl/worksheets/s.xml' }]),+ ],+ [+ 'forged larger real content',+ () => buildTestZip([{ data: big(5000), declaredSize: 10, deflate: true, name: 'a.bin' }]),+ ],+ [+ 'forged smaller real content',+ () => buildTestZip([{ data: big(10), declaredSize: 900, deflate: true, name: 'a.bin' }]),+ ],+ ])('closes the ZIP handle and entry streams on %s', async (_name, make) => {+ const { handles, streams } = captureHandles();++ await preflightXlsxZip(make(), limits).catch(() => {});++ expect(handles).toHaveLength(1);+ expect(handles[0].isOpen).toBe(false);+ for (const stream of streams) expect(stream.destroyed).toBe(true);+ });++ it('aborts on the actually inflated bytes and closes the active stream and zip', async () => {+ // A reader that misreports: declared 10 bytes but the stream yields far more. Chunks+ // are counted, the stream is destroyed at the first chunk over budget, nothing is kept.+ const stream = new PassThrough();+ const zipfile: any = new EventEmitter();+ zipfile.entryCount = 1;+ zipfile.isOpen = true;+ zipfile.close = vi.fn(() => {+ zipfile.isOpen = false;+ });+ zipfile.readEntry = vi.fn(() =>+ setImmediate(() =>+ zipfile.emit('entry', { fileName: 'xl/worksheets/s.xml', uncompressedSize: 10 }),+ ),+ );+ zipfile.openReadStream = vi.fn((_entry: unknown, cb: any) => {+ cb(null, stream);+ stream.write(Buffer.alloc(500));+ });+ vi.spyOn(yauzl, 'fromBuffer').mockImplementation(((_b: any, _o: any, cb: any) =>+ cb(null, zipfile)) as any);++ const zip = buildTestZip([{ data: 'x', name: 'a.xml' }]);+ await expect(preflightXlsxZip(zip, limits)).rejects.toMatchObject({+ actual: 500,+ limit: 400,+ name: 'FileParseBudgetError',+ reason: 'sheet-xml',+ });++ expect(stream.destroyed).toBe(true);+ expect(zipfile.close).toHaveBeenCalledTimes(1);+ expect(zipfile.isOpen).toBe(false);+ });++ it('aborts when the total of actually inflated bytes crosses the budget', async () => {+ const streams: PassThrough[] = [];+ const zipfile: any = new EventEmitter();+ zipfile.entryCount = 3;+ zipfile.isOpen = true;+ zipfile.close = vi.fn();+ let next = 0;+ zipfile.readEntry = vi.fn(() =>+ setImmediate(() =>+ zipfile.emit('entry', { fileName: `p${next++}.bin`, uncompressedSize: 10 }),+ ),+ );+ zipfile.openReadStream = vi.fn((_entry: unknown, cb: any) => {+ const stream = new PassThrough();+ streams.push(stream);+ cb(null, stream);+ stream.write(Buffer.alloc(600));+ stream.end();+ });+ vi.spyOn(yauzl, 'fromBuffer').mockImplementation(((_b: any, _o: any, cb: any) =>+ cb(null, zipfile)) as any);++ const zip = buildTestZip([{ data: 'x', name: 'a.xml' }]);+ await expect(preflightXlsxZip(zip, limits)).rejects.toMatchObject({+ limit: 1000,+ reason: 'zip-expansion',+ });++ expect(streams).toHaveLength(2);+ expect(streams.every((s) => s.destroyed)).toBe(true);+ expect(zipfile.close).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/packages/file-loaders/src/loaders/excel/zipBudget.ts b/packages/file-loaders/src/loaders/excel/zipBudget.tsnew file mode 100644index 00000000000..5e5ead3f461--- /dev/null+++ b/packages/file-loaders/src/loaders/excel/zipBudget.ts@@ -0,0 +1,132 @@+import type { Readable } from 'node:stream';++import yauzl from 'yauzl';++import { FileParseBudgetError } from '../../fileParseBudget';++export interface XlsxZipLimits {+ maxEntries: number;+ /** Compressed input size. */+ maxInputBytes: number;+ /** Uncompressed bytes over all entries, declared and actually inflated. */+ maxTotalBytes: number;+ /** Uncompressed bytes of any single worksheet part, declared and actually inflated. */+ maxWorksheetBytes: number;+}++/**+ * Fixed structural budgets for an xlsx archive. The input budget matches the 64 MiB in-memory+ * parse cap used elsewhere (`MAX_FILE_PARSE_SIZE`); it is enforced here too because this+ * helper cannot assume every caller applied that cap. No compression-ratio check: a styled but+ * empty sheet compresses extremely well and is legitimate.+ */+export const DEFAULT_XLSX_ZIP_LIMITS: XlsxZipLimits = {+ maxEntries: 5000,+ maxInputBytes: 64 * 1024 * 1024,+ maxTotalBytes: 512 * 1024 * 1024,+ maxWorksheetBytes: 256 * 1024 * 1024,+};++const WORKSHEET_PART = /(?:^|\/)worksheets\/[^/]+\.xml$/i;++const isZip = (data: Uint8Array) => data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b;++/**+ * Checks an xlsx (ZIP) before SheetJS inflates it, without ever holding inflated data:+ * 1. compressed input size and entry count,+ * 2. the sizes the central directory declares,+ * 3. every entry is streamed through yauzl (with its size validation on) and the bytes that+ * actually come out are counted against the same total / worksheet budgets. Chunks are+ * discarded, never accumulated, and the stream is aborted as soon as a budget is crossed.+ *+ * An archive whose real content disagrees with its declared sizes, or that cannot be read, is+ * rejected with yauzl's ordinary error (a corrupt file, not a budget refusal). Only a budget+ * overrun throws `FileParseBudgetError`. Both the active entry stream and the ZIP handle are+ * closed on every path. Data that is not a ZIP (legacy .xls) passes untouched.+ */+export const preflightXlsxZip = (+ input: Uint8Array,+ limits: XlsxZipLimits = DEFAULT_XLSX_ZIP_LIMITS,+): Promise<void> => {+ if (!isZip(input)) return Promise.resolve();++ if (input.byteLength > limits.maxInputBytes) {+ return Promise.reject(+ new FileParseBudgetError('zip-input', limits.maxInputBytes, input.byteLength),+ );+ }++ const buffer = Buffer.isBuffer(input)+ ? input+ : Buffer.from(input.buffer, input.byteOffset, input.byteLength);++ return new Promise((resolve, reject) => {+ yauzl.fromBuffer(buffer, { lazyEntries: true }, (err, zipfile) => {+ if (err || !zipfile) return reject(err || new Error('Failed to open zip from buffer'));++ let settled = false;+ let active: Readable | undefined;+ const finish = (error?: unknown) => {+ if (settled) return;+ settled = true;+ active?.destroy();+ active = undefined;+ zipfile.close();+ if (error) reject(error);+ else resolve();+ };++ if (zipfile.entryCount > limits.maxEntries) {+ return finish(+ new FileParseBudgetError('zip-entries', limits.maxEntries, zipfile.entryCount),+ );+ }++ let declaredTotal = 0;+ let inflatedTotal = 0;++ const checkSizes = (entryBytes: number, total: number, isSheet: boolean) => {+ if (isSheet && entryBytes > limits.maxWorksheetBytes) {+ return new FileParseBudgetError('sheet-xml', limits.maxWorksheetBytes, entryBytes);+ }+ if (total > limits.maxTotalBytes) {+ return new FileParseBudgetError('zip-expansion', limits.maxTotalBytes, total);+ }+ };++ zipfile.on('entry', (entry: yauzl.Entry) => {+ const isSheet = WORKSHEET_PART.test(entry.fileName);++ declaredTotal += entry.uncompressedSize;+ const declaredError = checkSizes(entry.uncompressedSize, declaredTotal, isSheet);+ if (declaredError) return finish(declaredError);++ // Directory entries have no content stream+ if (entry.fileName.endsWith('/')) return zipfile.readEntry();++ zipfile.openReadStream(entry, (streamErr, stream) => {+ if (streamErr || !stream) return finish(streamErr || new Error('Failed to open entry'));+ if (settled) return stream.destroy();++ active = stream;+ let entryBytes = 0;+ stream.on('data', (chunk: Buffer) => {+ entryBytes += chunk.length;+ inflatedTotal += chunk.length;+ const actualError = checkSizes(entryBytes, inflatedTotal, isSheet);+ if (actualError) finish(actualError);+ });+ stream.on('error', finish);+ stream.on('end', () => {+ if (settled) return;+ active = undefined;+ zipfile.readEntry();+ });+ });+ });+ zipfile.on('end', () => finish());+ zipfile.on('error', finish);+ zipfile.readEntry();+ });+ });+};diff --git a/packages/file-loaders/src/xlsxBudget.ts b/packages/file-loaders/src/xlsxBudget.tsnew file mode 100644index 00000000000..1494284bfce--- /dev/null+++ b/packages/file-loaders/src/xlsxBudget.ts@@ -0,0 +1,10 @@+/**+ * Lightweight entry for callers that parse spreadsheets themselves (for example the dataset+ * parser) and only need the budget helpers, without loading any file loader.+ */+export type { FileParseBudgetReason } from './fileParseBudget';+export { FileParseBudgetError, isFileParseBudgetError } from './fileParseBudget';+export type { SheetBoundsOptions } from './loaders/excel/sheetBounds';+export { clampSheetRefToData, MAX_SHEET_CELLS } from './loaders/excel/sheetBounds';+export type { XlsxZipLimits } from './loaders/excel/zipBudget';+export { DEFAULT_XLSX_ZIP_LIMITS, preflightXlsxZip } from './loaders/excel/zipBudget';diff --git a/scripts/buildFileParseWorker.mts b/scripts/buildFileParseWorker.mtsnew file mode 100644index 00000000000..70cd5737687--- /dev/null+++ b/scripts/buildFileParseWorker.mts@@ -0,0 +1,131 @@+/**+ * Builds the file-parse worker (`apps/server/src/services/fileParse/worker.ts`) into one+ * self-contained ESM file: `dist/file-parse-worker/fileParseWorker.mjs`.+ *+ * Every parser (pdfjs and its fake worker, mammoth, xlsx, officeparser, word-extractor, papaparse)+ * is inlined, so the artifact needs no `node_modules` next to it and travels by plain file copy:+ * Next standalone (`outputFileTracingIncludes`), and any other image that runs the server.+ *+ * bun run build:file-parse-worker # build + smoke check+ * FILE_PARSE_WORKER_PATH=/app/.../fileParseWorker.mjs # where a deployment keeps it+ */+import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { Worker } from 'node:worker_threads';++const appRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const require = createRequire(path.join(appRoot, 'package.json'));++const FILE_PARSE_WORKER_ENTRY = 'apps/server/src/services/fileParse/worker.ts';+const FILE_PARSE_WORKER_OUTDIR = path.join(appRoot, 'dist/file-parse-worker');+const FILE_PARSE_WORKER_FILENAME = 'fileParseWorker.mjs';++interface BuildOptions {+ outdir?: string;+}++/**+ * Runs the built worker on a text file, a CSV dataset and the two chunk jobs that load the heavy+ * dependencies (an xlsx through exceljs, markdown through the splitter): proves it starts, and+ * that what the knowledge base needs is inside the file and not only importable.+ */+const smokeCheckFileParseWorker = async (workerPath: string) => {+ const scratch = await mkdtemp(path.join(tmpdir(), 'file-parse-smoke-'));+ try {+ const textFile = path.join(scratch, 'smoke.txt');+ await writeFile(textFile, 'file parse worker smoke');++ const run = (workerData: unknown) =>+ new Promise<any>((resolve, reject) => {+ let message: unknown;+ const worker = new Worker(workerPath, { env: {}, execArgv: [], workerData });+ worker.on('message', (value) => (message = value));+ worker.on('error', reject);+ worker.on('exit', () =>+ message ? resolve(message) : reject(new Error('worker exited without a result')),+ );+ });++ const file = await run({ filePath: textFile, kind: 'file', mode: 'file' });+ if (file.type !== 'result' || !file.value.content.includes('smoke')) {+ throw new Error(`file job failed: ${JSON.stringify(file)}`);+ }+ const dataset = await run({+ content: 'a,b\n1,2\n',+ kind: 'dataset',+ options: { format: 'csv' },+ });+ if (dataset.type !== 'result' || dataset.value.totalCount !== 1) {+ throw new Error(`dataset job failed: ${JSON.stringify(dataset)}`);+ }++ const { Workbook } = require('exceljs') as typeof import('exceljs');+ const workbook = new Workbook();+ workbook.addWorksheet('Smoke').addRows([['name'], ['chunk smoke']]);+ const xlsx = await run({+ content: new Uint8Array(await workbook.xlsx.writeBuffer()),+ filename: 'smoke.xlsx',+ kind: 'chunk',+ });+ if (xlsx.type !== 'result' || xlsx.value[0]?.pageContent !== 'name: chunk smoke') {+ throw new Error(`xlsx chunk job failed: ${JSON.stringify(xlsx)}`);+ }+ const markdown = await run({+ content: new TextEncoder().encode('# smoke\n\nchunk smoke'),+ filename: 'smoke.md',+ kind: 'chunk',+ });+ if (markdown.type !== 'result' || !markdown.value[0]?.pageContent.includes('chunk smoke')) {+ throw new Error(`markdown chunk job failed: ${JSON.stringify(markdown)}`);+ }+ } finally {+ await rm(scratch, { force: true, recursive: true });+ }+};++export const buildFileParseWorker = async ({+ outdir = FILE_PARSE_WORKER_OUTDIR,+}: BuildOptions = {}) => {+ const { build } = require('esbuild') as typeof import('esbuild');+ await rm(outdir, { force: true, recursive: true });+ await mkdir(outdir, { recursive: true });++ await build({+ absWorkingDir: appRoot,+ banner: {+ // CommonJS dependencies inlined into an ES module still call `require`.+ js: "import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);",+ },+ bundle: true,+ conditions: ['node'],+ entryPoints: { fileParseWorker: FILE_PARSE_WORKER_ENTRY },+ format: 'esm',+ logLevel: 'warning',+ outExtension: { '.js': '.mjs' },+ outdir,+ platform: 'node',+ target: 'node24',+ tsconfig: path.join(appRoot, 'tsconfig.json'),+ });++ const workerPath = path.join(outdir, FILE_PARSE_WORKER_FILENAME);+ await smokeCheckFileParseWorker(workerPath);+ const { size } = await stat(workerPath);+ console.info(`[file-parse-worker] built ${workerPath} (${(size / 1024 / 1024).toFixed(1)} MiB)`);+ return workerPath;+};++const isMainModule = () => {+ const entry = process.argv[1];+ return !!entry && import.meta.url === pathToFileURL(path.resolve(entry)).href;+};++if (isMainModule()) {+ buildFileParseWorker().catch((error) => {+ console.error('[file-parse-worker] build failed:', error);+ process.exit(1);+ });+}diff --git a/scripts/buildFileParseWorker.test.ts b/scripts/buildFileParseWorker.test.tsnew file mode 100644index 00000000000..6f65305e149--- /dev/null+++ b/scripts/buildFileParseWorker.test.ts@@ -0,0 +1,97 @@+/**+ * @vitest-environment node+ */+import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { createFileParseRunner } from '../apps/server/src/services/fileParse/runner';+import { buildFileParseWorker } from './buildFileParseWorker.mjs';++const loaders = (relative: string) =>+ path.resolve(__dirname, '../packages/file-loaders/src/loaders', relative);++// Built into a directory with no node_modules above it, the way the artifact is copied into an+// image: every parser (pdfjs and its worker, mammoth, xlsx, officeparser, word-extractor) has to+// be inside the one file.+let dir: string;+let workerPath: string;++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'file-parse-build-'));+ workerPath = await buildFileParseWorker({ outdir: path.join(dir, 'dist/file-parse-worker') });+}, 60_000);++afterAll(() => rm(dir, { force: true, recursive: true }));++describe('buildFileParseWorker', () => {+ it('emits one self-contained file that imports nothing but Node built-ins', async () => {+ const source = await readFile(workerPath, 'utf8');+ const bare = [...source.matchAll(/^import [^'"\n]*?from\s*["']([^"']+)["']/gm)]+ .map((match) => match[1])+ .filter((specifier) => !specifier.startsWith('node:'));++ expect(bare).toEqual([]);+ });++ it.each([+ ['txt', 'text/fixtures/test.txt', 'text'],+ ['xlsx', 'excel/fixtures/test.xlsx', ''],+ ['docx', 'docx/fixtures/test.docx', ''],+ ['doc', 'doc/fixtures/test.doc', ''],+ ['pdf', 'pdf/fixtures/test.pdf', ''],+ ['pptx', 'pptx/fixtures/test.pptx', ''],+ ['ipynb', 'ipynb/fixtures/test.ipynb', ''],+ ])('parses a %s file with every dependency inside the artifact', async (_, fixture) => {+ const runner = createFileParseRunner({ workerPath: () => workerPath });++ const document = await runner.run<{ content: string; metadata: { error?: string } }>({+ filePath: loaders(fixture),+ kind: 'file',+ mode: 'file',+ });++ expect(document.content.trim().length).toBeGreaterThan(0);+ expect(document.metadata.error).toBeUndefined();+ });++ // The chunking job runs the knowledge-base loaders, which load their libraries lazily: each one+ // has to be inside the artifact and has to actually run there, not only be importable.+ it.each([+ ['txt', 'text/fixtures/test.txt', 'test.txt'],+ ['csv', 'text/fixtures/test-utf16le.csv', 'test.csv'],+ ['xlsx', 'excel/fixtures/test.xlsx', 'test.xlsx'],+ ['docx', 'docx/fixtures/test.docx', 'test.docx'],+ ['pdf', 'pdf/fixtures/test.pdf', 'test.pdf'],+ ['pptx', 'pptx/fixtures/test.pptx', 'test.pptx'],+ ['ipynb', 'ipynb/fixtures/test.ipynb', 'test.ipynb'],+ ['epub', '../../test/fixtures/test.epub', 'test.epub'],+ ])(+ 'chunks a %s file with every loader dependency inside the artifact',+ async (_, fixture, filename) => {+ const scratch = await mkdtemp(path.join(tmpdir(), 'file-parse-chunk-scratch-'));+ const previousTmp = process.env.TMPDIR;+ process.env.TMPDIR = scratch;+ try {+ const runner = createFileParseRunner({ workerPath: () => workerPath });++ const chunks = await runner.run<Array<{ metadata: object; pageContent: string }>>({+ content: new Uint8Array(await readFile(loaders(fixture))),+ filename,+ kind: 'chunk',+ });++ expect(chunks.length).toBeGreaterThan(0);+ expect(chunks.some((chunk) => chunk.pageContent.trim().length > 0)).toBe(true);+ // the epub loader's temp file is gone with the scratch directory+ expect(await readdir(scratch)).toEqual([]);+ } finally {+ if (previousTmp === undefined) delete process.env.TMPDIR;+ else process.env.TMPDIR = previousTmp;+ await rm(scratch, { force: true, recursive: true });+ }+ },+ );+});diff --git a/scripts/devStartupSequence.mts b/scripts/devStartupSequence.mtsindex 24315f3c9bd..9ee51690079 100644--- a/scripts/devStartupSequence.mts+++ b/scripts/devStartupSequence.mts@@ -7,6 +7,8 @@ import { pathToFileURL } from 'node:url';import dotenv from 'dotenv';import dotenvExpand from 'dotenv-expand';+import { buildFileParseWorker } from './buildFileParseWorker.mjs';+interface DevProcessHandle {directPid?: number;groupPid?: number;@@ -48,7 +50,9 @@ const findFreePort = async (startPort: number): Promise<number> => {for (let port = startPort; port < startPort + MAX_PORT_SCAN_ATTEMPTS; port++) {if (await isPortFree(port)) return port;}- throw new Error(`No free port found in range ${startPort}-${startPort + MAX_PORT_SCAN_ATTEMPTS - 1}`);+ throw new Error(+ `No free port found in range ${startPort}-${startPort + MAX_PORT_SCAN_ATTEMPTS - 1}`,+ );};/**@@ -291,6 +295,8 @@ const watchChildExit = (child: ChildProcess, name: 'next' | 'vite') => {const main = async () => {loadEnv();+ // Parsing runs in a prebuilt worker thread file; a stale or missing one would fail every parse.+ await buildFileParseWorker();nextPort = await resolveNextPort();process.env.PORT = String(nextPort);nextRootUrl = `http://${NEXT_HOST}:${nextPort}/`;diff --git a/src/libs/document-loaders/loaders/epub/index.cleanup.test.ts b/src/libs/document-loaders/loaders/epub/index.cleanup.test.tsnew file mode 100644index 00000000000..37d5521f697--- /dev/null+++ b/src/libs/document-loaders/loaders/epub/index.cleanup.test.ts@@ -0,0 +1,84 @@+// @vitest-environment node+import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';+import path from 'node:path';+import { setImmediate } from 'node:timers/promises';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TempFileManager } from '@/server/utils/tempFileManager';++import { EPubLoader } from './index';++const state = vi.hoisted(() => ({ root: '' }));+vi.mock('node:os', () => ({ tmpdir: () => state.root }));++beforeEach(async () => {+ const { tmpdir } = await vi.importActual<{ tmpdir: () => string }>('node:os');+ state.root = await mkdtemp(path.join(tmpdir(), 'epub-cleanup-'));+});+afterEach(async () => {+ vi.restoreAllMocks();+ await rm(state.root, { force: true, recursive: true });+});++describe('EPubLoader temp file cleanup', () => {+ it.each([false, true])(+ 'settles only after the real cleanup finished (parse fails = %s)',+ async (fails) => {+ const content = fails+ ? new Uint8Array([0, 1, 2])+ : await readFile(path.join(__dirname, '__tests__/demo.epub'));+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let entered!: () => void;+ const cleaning = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const cleanup = TempFileManager.prototype.cleanup;+ vi.spyOn(TempFileManager.prototype, 'cleanup').mockImplementation(async function (+ this: TempFileManager,+ ) {+ entered();+ await gate;+ await cleanup.call(this);+ });++ let settled = false;+ const result = EPubLoader(content)+ .then(+ (value) => ({ value }),+ (error: unknown) => ({ error }),+ )+ .finally(() => {+ settled = true;+ });+ try {+ await cleaning;+ await setImmediate();+ expect(await readdir(state.root)).toHaveLength(1);+ expect(settled).toBe(false);+ } finally {+ release();+ await result;+ // Even if a caller does not await the cleanup, the test must finish the real fs operation.+ await Promise.all(+ vi.mocked(TempFileManager.prototype.cleanup).mock.results.map((r) => r.value),+ );+ }++ if (fails)+ expect(await result).toMatchObject({+ error: { message: expect.stringContaining('EPubLoader error:') },+ });+ else+ expect(await result).toMatchObject({+ value: expect.arrayContaining([+ expect.objectContaining({ pageContent: expect.any(String) }),+ ]),+ });+ expect(await readdir(state.root)).toEqual([]);+ },+ );+});diff --git a/src/libs/document-loaders/loaders/epub/index.ts b/src/libs/document-loaders/loaders/epub/index.tsindex eacc5252bbf..2a9f67d3f40 100644--- a/src/libs/document-loaders/loaders/epub/index.ts+++ b/src/libs/document-loaders/loaders/epub/index.ts@@ -47,6 +47,6 @@ export const EPubLoader = async (content: Uint8Array): Promise<DocumentChunk[]>} catch (e) {throw new Error(`EPubLoader error: ${(e as Error).message}`, { cause: e });} finally {- tempManager.cleanup();+ await tempManager.cleanup();}};diff --git a/src/libs/document-loaders/loaders/excel/__tests__/index.budget.test.ts b/src/libs/document-loaders/loaders/excel/__tests__/index.budget.test.tsnew file mode 100644index 00000000000..a2c83f29f1a--- /dev/null+++ b/src/libs/document-loaders/loaders/excel/__tests__/index.budget.test.ts@@ -0,0 +1,56 @@+// @vitest-environment node+import { FileParseBudgetError } from '@lobechat/file-loaders';+import { buildTestZip } from '@lobechat/file-loaders/src/loaders/excel/testUtils';+import { afterEach, describe, expect, it, vi } from 'vitest';++const load = vi.hoisted(() => vi.fn());++// exceljs is the memory-heavy step: the budget must refuse before it is ever constructed.+vi.mock('exceljs', () => ({+ Workbook: class {+ xlsx = { load };+ worksheets = [];+ },+}));++const { ChunkingLoader } = await import('../../index');+const { ExcelLoader } = await import('../index');++afterEach(() => vi.clearAllMocks());++const oversizedSheetZip = () =>+ buildTestZip([+ {+ data: '<worksheet/>',+ declaredSize: 300 * 1024 * 1024,+ deflate: true,+ name: 'xl/worksheets/sheet1.xml',+ },+ ]);++describe('ExcelLoader zip budget', () => {+ it('refuses an over-budget archive before exceljs loads anything', async () => {+ const error = await ExcelLoader(new Blob([oversizedSheetZip()])).catch((e) => e);++ expect(error).toBeInstanceOf(FileParseBudgetError);+ expect(error).toMatchObject({ reason: 'sheet-xml' });+ expect(load).not.toHaveBeenCalled();+ });++ it('keeps the budget error typed through the chunking error boundary', async () => {+ const error = await new ChunkingLoader()+ .partitionContent('bomb.xlsx', new Uint8Array(oversizedSheetZip()))+ .catch((e) => e);++ expect(error).toMatchObject({ name: 'FileParseBudgetError', reason: 'sheet-xml' });+ expect(load).not.toHaveBeenCalled();+ });++ it('lets an archive within budget through to exceljs', async () => {+ load.mockResolvedValue(undefined);+ const small = buildTestZip([{ data: '<worksheet/>', name: 'xl/worksheets/sheet1.xml' }]);++ await expect(ExcelLoader(new Blob([small]))).resolves.toEqual([]);+ expect(load).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/libs/document-loaders/loaders/excel/index.ts b/src/libs/document-loaders/loaders/excel/index.tsindex cd2fb426ef5..5c4f764ebfa 100644--- a/src/libs/document-loaders/loaders/excel/index.ts+++ b/src/libs/document-loaders/loaders/excel/index.ts@@ -1,3 +1,4 @@+import { preflightXlsxZip } from '@lobechat/file-loaders/src/xlsxBudget';import type { CellValue } from 'exceljs';import type { DocumentChunk } from '../../types';@@ -25,10 +26,15 @@ const cellToText = (value: CellValue): string => {* uploaded in.*/export const ExcelLoader = async (fileBlob: Blob): Promise<DocumentChunk[]> => {+ const data = await fileBlob.arrayBuffer();+ // Structural budgets first (input size, entries, real inflated bytes): exceljs inflates the+ // whole workbook into objects, so an archive over budget must never reach it.+ await preflightXlsxZip(new Uint8Array(data));+const { Workbook } = await import('exceljs');const workbook = new Workbook();- await workbook.xlsx.load(await fileBlob.arrayBuffer());+ await workbook.xlsx.load(data);return workbook.worksheets.flatMap((sheet) => {const chunks: DocumentChunk[] = [];diff --git a/src/libs/document-loaders/loaders/index.ts b/src/libs/document-loaders/loaders/index.tsindex 02ca79d1009..62fcfb634fc 100644--- a/src/libs/document-loaders/loaders/index.ts+++ b/src/libs/document-loaders/loaders/index.ts@@ -1,4 +1,8 @@-import { convertIpynbToMarkdown, scrubIpynbFallbackText } from '@lobechat/file-loaders';+import {+ convertIpynbToMarkdown,+ isFileParseBudgetError,+ scrubIpynbFallbackText,+} from '@lobechat/file-loaders';import { getChunkingLoaderType } from '../loaderType';import { type DocumentChunk } from '../types';@@ -23,47 +27,49 @@ class DocumentLoaderError extends Error {export class ChunkingLoader {partitionContent = async (filename: string, content: Uint8Array): Promise<DocumentChunk[]> => {try {- const fileBlob = new Blob([Buffer.from(content)]);- const txt = this.uint8ArrayToString(content);+ // Both copy the whole file: built on first use, so a binary format does not also pay for+ // a text decode of itself (a 64MiB xlsx decoded as text is a ~100MB string of nothing).+ const blob = () => new Blob([Buffer.from(content)]);+ const text = () => this.uint8ArrayToString(content);const type = getChunkingLoaderType(filename ?? '');switch (type) {case 'code': {const ext = filename.split('.').pop();- return await CodeLoader(txt, ext!);+ return await CodeLoader(text(), ext!);}case 'ppt': {- return await PPTXLoader(fileBlob);+ return await PPTXLoader(blob());}case 'latex': {- return await LatexLoader(txt);+ return await LatexLoader(text());}case 'pdf': {- return await PdfLoader(fileBlob);+ return await PdfLoader(blob());}case 'markdown': {- return await MarkdownLoader(txt);+ return await MarkdownLoader(text());}case 'doc': {- return await DocxLoader(fileBlob);+ return await DocxLoader(blob());}case 'excel': {- return await ExcelLoader(fileBlob);+ return await ExcelLoader(blob());}case 'text': {- return await TextLoader(txt);+ return await TextLoader(text());}case 'csv': {- return await CsVLoader(fileBlob);+ return await CsVLoader(blob());}case 'epub': {@@ -73,9 +79,10 @@ export class ChunkingLoader {case 'ipynb': {// Notebook JSON → markdown so chunks carry semantic text instead// of base64 payloads; non-nbformat-v4 files fall back to raw text.- const markdown = convertIpynbToMarkdown(txt);+ const source = text();+ const markdown = convertIpynbToMarkdown(source);return markdown === null- ? await TextLoader(scrubIpynbFallbackText(txt))+ ? await TextLoader(scrubIpynbFallbackText(source)): await MarkdownLoader(markdown);}@@ -86,6 +93,9 @@ export class ChunkingLoader {}}} catch (e) {+ // A structural refusal is a deliberate "too large", not a loader failure: keep its type so+ // callers can tell the user, and so it is not retried as if the file were merely broken.+ if (isFileParseBudgetError(e)) throw e;throw new DocumentLoaderError((e as Error).message);}};diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.tsindex 54ee07ea864..b6df20809f8 100644--- a/src/libs/next/config/define-config.ts+++ b/src/libs/next/config/define-config.ts@@ -14,6 +14,13 @@ interface CustomNextConfig {turbopack?: NextConfig['turbopack'];}+/**+ * The file-parse worker is started by absolute path at runtime, which no tracer can follow, so the+ * built artifact (`bun run build:file-parse-worker`) is listed explicitly. Standalone and Vercel+ * output must both carry it; a deployment without it fails closed instead of parsing in-process.+ */+const FILE_PARSE_WORKER_TRACE = 'dist/file-parse-worker/**/*';+export function defineConfig(config: CustomNextConfig) {const isProd = process.env.NODE_ENV === 'production';const buildWithDocker = process.env.DOCKER === 'true';@@ -32,6 +39,7 @@ export function defineConfig(config: CustomNextConfig) {'*': ['public/**/*','.next/static/**/*',+ FILE_PARSE_WORKER_TRACE,// Only needed for Docker standalone builds.// On Vercel (serverless), including native bindings can easily exceed function size limits.@@ -55,7 +63,9 @@ export function defineConfig(config: CustomNextConfig) {);const nextConfig: NextConfig = {- ...(isStandaloneMode ? standaloneConfig : {}),+ ...(isStandaloneMode+ ? standaloneConfig+ : { outputFileTracingIncludes: { '*': [FILE_PARSE_WORKER_TRACE] } }),// Stop `next dev` from auto-injecting the nextjs-agent-rules block into AGENTS.md.agentRules: false,assetPrefix,