Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(file): keep batch file chunking from blocking the event loop (#22796)

Mocha284acf354397
diff --git a/apps/server/src/routers/async/__tests__/file.test.ts b/apps/server/src/routers/async/__tests__/file.test.ts
index f105786a8ff..1592c8d7fa3 100644
--- a/apps/server/src/routers/async/__tests__/file.test.ts
+++ b/apps/server/src/routers/async/__tests__/file.test.ts
@@ -208,4 +208,174 @@ describe('fileRouter.parseFileToChunks β€” NoSuchKey + internal:// branches', ()
expect.objectContaining({ status: AsyncTaskStatus.Error }),
);
});
+
+ describe('parse concurrency', () => {
+ // lets every already-unblocked promise chain run to its next real wait
+ const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+ const deferred = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+ };
+
+ beforeEach(() => {
+ fileModelMock.findById.mockImplementation(async (id: string) => ({
+ fileType: 'text/plain',
+ id,
+ name: `${id}.txt`,
+ size: 10,
+ url: `https://example.com/${id}.txt`,
+ }));
+ asyncTaskModelMock.findById.mockResolvedValue({ id: 'task' });
+ chunkServiceMock.chunkContent.mockResolvedValue({
+ chunks: [{ index: 0, text: 'hello', type: 'DocumentChunk' }],
+ });
+ });
+
+ it('holds a batch of files back so only two are downloaded and parsed at a time', async () => {
+ const gates = new Map<string, ReturnType<typeof deferred>>();
+ let inFlight = 0;
+ let peak = 0;
+ fileServiceMock.getFileByteArray.mockImplementation(async (url: string) => {
+ inFlight++;
+ peak = Math.max(peak, inFlight);
+ const gate = deferred();
+ gates.set(url, gate);
+ await gate.promise;
+ inFlight--;
+ return new Uint8Array([1]);
+ });
+
+ const caller = fileRouter.createCaller(mockCtx);
+ const ids = ['f1', 'f2', 'f3', 'f4', 'f5'];
+ const runs = ids.map((id) => caller.parseFileToChunks({ fileId: id, taskId: `task_${id}` }));
+
+ await flush();
+ expect(gates.size).toBe(2);
+
+ // release files one by one; every finished file lets exactly one waiting file start
+ for (let done = 0; done < ids.length; done++) {
+ const [url, gate] = [...gates.entries()][0];
+ gates.delete(url);
+ gate.resolve();
+ await flush();
+ expect(gates.size).toBe(Math.min(2, ids.length - done - 1));
+ }
+
+ const results = await Promise.all(runs);
+ expect(results).toEqual(ids.map(() => ({ success: true })));
+ expect(peak).toBe(2);
+ });
+
+ it('frees the slot of a file that fails, so later files still run', async () => {
+ fileServiceMock.getFileByteArray
+ .mockRejectedValueOnce({ Code: 'NoSuchKey' })
+ .mockRejectedValueOnce({ Code: 'AccessDenied', message: 'forbidden' })
+ .mockResolvedValue(new Uint8Array([1]));
+
+ const caller = fileRouter.createCaller(mockCtx);
+ const results = await Promise.allSettled(
+ ['f1', 'f2', 'f3', 'f4'].map((id) =>
+ caller.parseFileToChunks({ fileId: id, taskId: `task_${id}` }),
+ ),
+ );
+
+ expect(results.map((r) => r.status)).toEqual([
+ 'rejected',
+ 'rejected',
+ 'fulfilled',
+ 'fulfilled',
+ ]);
+ });
+
+ it('keeps the slot of a file that timed out until its parsing really ends', async () => {
+ vi.useFakeTimers();
+ try {
+ const stuck = deferred();
+ fileServiceMock.getFileByteArray.mockResolvedValue(new Uint8Array([1]));
+ chunkServiceMock.chunkContent.mockImplementation(async () => {
+ await stuck.promise;
+ return { chunks: [{ index: 0, text: 'hello', type: 'DocumentChunk' }] };
+ });
+
+ const caller = fileRouter.createCaller(mockCtx);
+ const runs = ['f1', 'f2', 'f3'].map((id) =>
+ caller.parseFileToChunks({ fileId: id, taskId: `task_${id}` }),
+ );
+
+ // both running files give up waiting, but their parsing is still going on
+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
+ await expect(runs[0]).resolves.toMatchObject({ success: false });
+ await expect(runs[1]).resolves.toMatchObject({ success: false });
+ expect(fileServiceMock.getFileByteArray).toHaveBeenCalledTimes(2);
+
+ stuck.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fileServiceMock.getFileByteArray).toHaveBeenCalledTimes(3);
+ await expect(runs[2]).resolves.toEqual({ success: true });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('restarts the task clock when a queued file finally starts parsing', async () => {
+ vi.useFakeTimers();
+ try {
+ const gates: ReturnType<typeof deferred>[] = [];
+ fileServiceMock.getFileByteArray.mockResolvedValue(new Uint8Array([1]));
+ chunkServiceMock.chunkContent.mockImplementation(async () => {
+ const gate = deferred();
+ gates.push(gate);
+ await gate.promise;
+ return { chunks: [{ index: 0, text: 'hello', type: 'DocumentChunk' }] };
+ });
+
+ const caller = fileRouter.createCaller(mockCtx);
+ const runs = ['f1', 'f2', 'f3'].map((id) =>
+ caller.parseFileToChunks({ fileId: id, taskId: `task_${id}` }),
+ );
+
+ // f3 waits four minutes behind the two running files
+ await vi.advanceTimersByTimeAsync(4 * 60 * 1000);
+ expect(asyncTaskModelMock.update).not.toHaveBeenCalledWith('task_f3', expect.anything());
+ const admittedAt = new Date();
+ gates[0].resolve();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(asyncTaskModelMock.update).toHaveBeenCalledWith('task_f3', {
+ createdAt: admittedAt,
+ error: null,
+ status: AsyncTaskStatus.Processing,
+ });
+
+ gates.forEach((gate) => gate.resolve());
+ await vi.advanceTimersByTimeAsync(0);
+ gates.forEach((gate) => gate.resolve());
+ await Promise.all(runs);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not keep a parse slot while the embedding task of a finished file runs', async () => {
+ const embedding = deferred();
+ chunkServiceMock.asyncEmbeddingFileChunks.mockImplementation(() => embedding.promise);
+ fileServiceMock.getFileByteArray.mockResolvedValue(new Uint8Array([1]));
+
+ const caller = fileRouter.createCaller(mockCtx);
+ const runs = ['f1', 'f2', 'f3', 'f4'].map((id) =>
+ caller.parseFileToChunks({ fileId: id, taskId: `task_${id}` }),
+ );
+
+ await flush();
+ // all four are chunked although every one of them is still waiting on its embedding call
+ expect(chunkModelMock.bulkCreate).toHaveBeenCalledTimes(4);
+
+ embedding.resolve();
+ await Promise.all(runs);
+ });
+ });
});
diff --git a/apps/server/src/routers/async/file.ts b/apps/server/src/routers/async/file.ts
index 7da60d052c0..38120214895 100644
--- a/apps/server/src/routers/async/file.ts
+++ b/apps/server/src/routers/async/file.ts
@@ -48,6 +48,50 @@ 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.
+ */
+const PARSE_CONCURRENCY = 2;
+let activeParses = 0;
+const waitingParses: (() => void)[] = [];
+
+interface ParseSlot {
+ /** Keeps the slot until `work` settles, even when the caller stops waiting for it. */
+ holdUntil: (work: Promise<unknown>) => void;
+ release: () => void;
+}
+
+const withParseSlot = async <T>(fn: (slot: ParseSlot) => Promise<T>): Promise<T> => {
+ if (activeParses < PARSE_CONCURRENCY) activeParses++;
+ // a finishing task hands its slot straight to the next waiter
+ else await new Promise<void>((resolve) => waitingParses.push(resolve));
+
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ const next = waitingParses.shift();
+ if (next) next();
+ else activeParses--;
+ };
+
+ let held: Promise<unknown> | undefined;
+ try {
+ return await fn({
+ holdUntil: (work) => {
+ held = work;
+ },
+ release,
+ });
+ } finally {
+ if (held) void held.then(release, release);
+ else release();
+ }
+};
+
const resolveWorkspaceIdFromFile = async (
serverDB: LobeChatDatabase,
userId: string,
@@ -282,146 +326,169 @@ export const fileRouter = router({
};
}
- let content: Uint8Array | undefined;
- try {
- content = await fileService.getFileByteArray(file.url);
- } catch (e) {
- console.error(e);
- const errorCode = (e as any).Code;
- // Storage returned NoSuchKey. Do NOT delete the file row β€” transient S3
- // outages, IAM misconfig, or already-orphaned DB rows must not cascade
- // into destroying chunks/embeddings/documents. Mark the task as Error
- // so users see a clear message and can re-upload or retry.
- if (errorCode === 'NoSuchKey') {
+ const parse = async (slot: ParseSlot) => {
+ let content: Uint8Array | undefined;
+ try {
+ content = await fileService.getFileByteArray(file.url);
+ } catch (e) {
+ console.error(e);
+ const errorCode = (e as any).Code;
+ // Storage returned NoSuchKey. Do NOT delete the file row β€” transient S3
+ // outages, IAM misconfig, or already-orphaned DB rows must not cascade
+ // into destroying chunks/embeddings/documents. Mark the task as Error
+ // so users see a clear message and can re-upload or retry.
+ if (errorCode === 'NoSuchKey') {
+ await asyncTaskModel.update(input.taskId, {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.TaskTriggerError,
+ 'File content unavailable in storage. Verify storage access or re-upload.',
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'File content unavailable in storage.',
+ });
+ }
+ // Other fetch errors (network, IAM, etc.) β€” mark the task as Error so
+ // the user surface stays consistent, then propagate.
await asyncTaskModel.update(input.taskId, {
error: new AsyncTaskError(
AsyncTaskErrorType.TaskTriggerError,
- 'File content unavailable in storage. Verify storage access or re-upload.',
+ `Failed to fetch file content: ${(e as Error)?.message ?? errorCode ?? 'unknown error'}`,
),
status: AsyncTaskStatus.Error,
});
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'File content unavailable in storage.',
- });
+ throw e;
}
- // Other fetch errors (network, IAM, etc.) β€” mark the task as Error so
- // the user surface stays consistent, then propagate.
- await asyncTaskModel.update(input.taskId, {
- error: new AsyncTaskError(
- AsyncTaskErrorType.TaskTriggerError,
- `Failed to fetch file content: ${(e as Error)?.message ?? errorCode ?? 'unknown error'}`,
- ),
- status: AsyncTaskStatus.Error,
- });
- throw e;
- }
- if (!content) return;
+ if (!content) return;
- const asyncTask = await asyncTaskModel.findById(input.taskId);
+ const asyncTask = await asyncTaskModel.findById(input.taskId);
- if (!asyncTask) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Async Task not found' });
-
- try {
- const startAt = Date.now();
-
- const timeoutPromise = new Promise((_, reject) => {
- setTimeout(() => {
- reject(
- new AsyncTaskError(
- AsyncTaskErrorType.Timeout,
- 'chunking task is timeout, please try again',
- ),
- );
- }, ASYNC_TASK_TIMEOUT);
- });
-
- const chunkingPromise = async () => {
- // update the task status to processing
- await asyncTaskModel.update(input.taskId, { status: AsyncTaskStatus.Processing });
+ if (!asyncTask)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Async Task not found' });
- // parse file to document record first (for detailed content viewing)
- try {
- await documentService.parseFile(input.fileId);
- } catch (e) {
- // document parsing failure should not block chunking
- console.warn(
- '[parseFileToChunks] document parsing failed, continuing with chunking:',
- e,
- );
- }
+ try {
+ const startAt = Date.now();
- // partition file to chunks
- const chunkResult = await chunkService.chunkContent({
- content,
- fileType: file.fileType,
- filename: file.name,
+ const timeoutPromise = new Promise((_, reject) => {
+ setTimeout(() => {
+ reject(
+ new AsyncTaskError(
+ AsyncTaskErrorType.Timeout,
+ 'chunking task is timeout, please try again',
+ ),
+ );
+ }, ASYNC_TASK_TIMEOUT);
});
- // after finish partition, we need to filter out some elements
- const chunks = chunkResult.chunks.map(({ text, ...item }): NewChunkItem => ({
- ...item,
- text: text ? sanitizeUTF8(text) : '',
- userId: ctx.userId,
- workspaceId,
- }));
-
- const duration = Date.now() - startAt;
-
- // if no chunk found, throw error
- if (chunks.length === 0) {
- throw {
- message:
- 'No chunk found in this file. it may due to current chunking method can not parse file accurately',
- name: AsyncTaskErrorType.NoChunkError,
- };
- }
-
- await chunkModel.bulkCreate(chunks, input.fileId);
-
- if (chunkResult.unstructuredChunks) {
- const unstructuredChunks = chunkResult.unstructuredChunks.map((item): NewChunkItem => ({
+ const chunkingPromise = async () => {
+ // The task was created before it queued for a slot, and the stale-task watchdog
+ // expires tasks by `createdAt`. Restart that clock now that parsing really begins,
+ // and clear an expiry the watchdog may have written while the file was waiting.
+ await asyncTaskModel.update(input.taskId, {
+ createdAt: new Date(),
+ error: null,
+ status: AsyncTaskStatus.Processing,
+ });
+
+ // parse file to document record first (for detailed content viewing)
+ try {
+ await documentService.parseFile(input.fileId);
+ } catch (e) {
+ // document parsing failure should not block chunking
+ console.warn(
+ '[parseFileToChunks] document parsing failed, continuing with chunking:',
+ e,
+ );
+ }
+
+ // partition file to chunks
+ const chunkResult = await chunkService.chunkContent({
+ content,
+ fileType: file.fileType,
+ filename: file.name,
+ });
+
+ // after finish partition, we need to filter out some elements
+ const chunks = chunkResult.chunks.map(({ text, ...item }): NewChunkItem => ({
...item,
- fileId: input.fileId,
+ text: text ? sanitizeUTF8(text) : '',
userId: ctx.userId,
workspaceId,
}));
- await chunkModel.bulkCreateUnstructuredChunks(unstructuredChunks);
- }
- // update the task status to success
+ const duration = Date.now() - startAt;
+
+ // if no chunk found, throw error
+ if (chunks.length === 0) {
+ throw {
+ message:
+ 'No chunk found in this file. it may due to current chunking method can not parse file accurately',
+ name: AsyncTaskErrorType.NoChunkError,
+ };
+ }
+
+ await chunkModel.bulkCreate(chunks, input.fileId);
+
+ if (chunkResult.unstructuredChunks) {
+ const unstructuredChunks = chunkResult.unstructuredChunks.map(
+ (item): NewChunkItem => ({
+ ...item,
+ fileId: input.fileId,
+ userId: ctx.userId,
+ workspaceId,
+ }),
+ );
+ await chunkModel.bulkCreateUnstructuredChunks(unstructuredChunks);
+ }
+
+ // update the task status to success
+ await asyncTaskModel.update(input.taskId, {
+ duration,
+ status: AsyncTaskStatus.Success,
+ });
+
+ // if enable auto embedding, trigger the embedding task
+ if (fileEnv.CHUNKS_AUTO_EMBEDDING) {
+ // It is network-bound and can run long: free the parse slot first, so it never
+ // holds back the files still waiting to be parsed.
+ slot.release();
+ await chunkService.asyncEmbeddingFileChunks(input.fileId);
+ }
+
+ return { success: true };
+ };
+ // Race between the chunking process and the timeout
+ // A timeout only stops the wait: the work keeps running and keeps the file in memory,
+ // so the slot stays taken until it is really done.
+ const chunking = chunkingPromise();
+ slot.holdUntil(chunking);
+ return await Promise.race([chunking, timeoutPromise]);
+ } catch (e) {
+ const error = e as any;
+
+ const asyncTaskError = error.body
+ ? ({
+ body: safeParseJSON(error.body) ?? error.body,
+ name: error.name,
+ } as IAsyncTaskError)
+ : new AsyncTaskError((error as Error).name, error.message);
+
+ console.error('[Chunking Error]', asyncTaskError);
await asyncTaskModel.update(input.taskId, {
- duration,
- status: AsyncTaskStatus.Success,
+ error: asyncTaskError,
+ status: AsyncTaskStatus.Error,
});
- // if enable auto embedding, trigger the embedding task
- if (fileEnv.CHUNKS_AUTO_EMBEDDING) {
- await chunkService.asyncEmbeddingFileChunks(input.fileId);
- }
-
- return { success: true };
- };
- // Race between the chunking process and the timeout
- return await Promise.race([chunkingPromise(), timeoutPromise]);
- } catch (e) {
- const error = e as any;
-
- const asyncTaskError = error.body
- ? ({ body: safeParseJSON(error.body) ?? error.body, name: error.name } as IAsyncTaskError)
- : new AsyncTaskError((error as Error).name, error.message);
-
- console.error('[Chunking Error]', asyncTaskError);
- await asyncTaskModel.update(input.taskId, {
- error: asyncTaskError,
- status: AsyncTaskStatus.Error,
- });
+ return {
+ message: `File ${file.name}(${input.taskId}) failed to chunking: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ };
- return {
- message: `File ${file.name}(${input.taskId}) failed to chunking: ${(e as Error).message}`,
- success: false,
- };
- }
+ return withParseSlot(parse);
}),
});
diff --git a/src/libs/document-loaders/splitter/__tests__/index.test.ts b/src/libs/document-loaders/splitter/__tests__/index.test.ts
new file mode 100644
index 00000000000..a11089f0559
--- /dev/null
+++ b/src/libs/document-loaders/splitter/__tests__/index.test.ts
@@ -0,0 +1,45 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { splitCode, splitText } from '../index';
+
+const config = { chunkOverlap: 400, chunkSize: 800 };
+
+describe('splitter line locations', () => {
+ it('reports the lines each chunk spans in a file that splits into many chunks', () => {
+ const lines = Array.from(
+ { length: 400 },
+ (_, i) => `const value${i} = compute(${i}); // line ${i + 1}`,
+ );
+ const text = lines.join('\n');
+
+ const chunks = splitText(text, config);
+
+ expect(chunks.length).toBeGreaterThan(10);
+ for (const chunk of chunks) {
+ const chunkLines = chunk.pageContent.split('\n');
+ const { from, to } = chunk.metadata.loc.lines;
+ // every source line carries its own number, so the expected span is read off the chunk
+ expect(lines[from - 1]).toContain(chunkLines[0]);
+ expect(lines[to - 1]).toContain(chunkLines.at(-1));
+ expect(to - from + 1).toBe(chunkLines.length);
+ }
+ });
+
+ it('keeps counting lines across blank lines and repeated content', () => {
+ const block = 'function same() {\n return 1;\n}\n';
+ const text = Array.from({ length: 120 }, () => block).join('\n');
+
+ const chunks = splitCode(text, 'js', config);
+
+ expect(chunks.length).toBeGreaterThan(2);
+ let previousFrom = 1;
+ for (const chunk of chunks) {
+ const { from, to } = chunk.metadata.loc.lines;
+ expect(from).toBeGreaterThanOrEqual(previousFrom);
+ expect(to - from).toBe(chunk.pageContent.split('\n').length - 1);
+ previousFrom = from;
+ }
+ expect(chunks.at(-1)!.metadata.loc.lines.to).toBeLessThanOrEqual(text.split('\n').length);
+ });
+});
diff --git a/src/libs/document-loaders/splitter/index.ts b/src/libs/document-loaders/splitter/index.ts
index 77b02244330..f7ac0d73552 100644
--- a/src/libs/document-loaders/splitter/index.ts
+++ b/src/libs/document-loaders/splitter/index.ts
@@ -115,22 +115,15 @@ function mergeSplits(splits: string[], separator: string, config: SplitterConfig
return chunks;
}
-/**
- * Calculate line location metadata for a chunk within the original text.
- */
-function getLineLocation(fullText: string, chunk: string): { from: number; to: number } {
- const index = fullText.indexOf(chunk);
- if (index === -1) {
- return { from: 1, to: 1 };
- }
+const NEWLINE = 10;
- const beforeChunk = fullText.slice(0, index);
- const from = beforeChunk.split('\n').length;
- const chunkLines = chunk.split('\n').length;
- const to = from + chunkLines - 1;
-
- return { from, to };
-}
+const countNewlines = (text: string, from: number, to: number): number => {
+ let count = 0;
+ for (let i = from; i < to; i++) {
+ if (text.charCodeAt(i) === NEWLINE) count++;
+ }
+ return count;
+};
/**
* Create document chunks from text using given separators.
@@ -145,16 +138,21 @@ function createDocuments(
// Track search position to handle duplicate chunks correctly
let searchFrom = 0;
+ // Chunks are located in document order, so the line number is carried forward from the
+ // previous match. Recounting from the start of the text for every chunk made a 2 MB source
+ // file hold the event loop for seconds.
+ let lineCursor = 0;
+ let lineAtCursor = 1;
return chunks.map((chunk) => {
const index = text.indexOf(chunk, searchFrom);
let loc = { from: 1, to: 1 };
if (index !== -1) {
- const beforeChunk = text.slice(0, index);
- const from = beforeChunk.split('\n').length;
- const chunkLines = chunk.split('\n').length;
- loc = { from, to: from + chunkLines - 1 };
+ lineAtCursor += countNewlines(text, lineCursor, index);
+ lineCursor = index;
+ const from = lineAtCursor;
+ loc = { from, to: from + countNewlines(chunk, 0, chunk.length) };
// Advance search position past this match (but allow overlap)
searchFrom = index + 1;
}