🤯 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): show a full vector quota instead of the APP_URL hint (#22317)
YuTengjing52118c8cf4bc
diff --git a/apps/server/src/routers/async/__tests__/file.embeddingChunks.test.ts b/apps/server/src/routers/async/__tests__/file.embeddingChunks.test.tsnew file mode 100644index 00000000000..cd5d2437ec2--- /dev/null+++ b/apps/server/src/routers/async/__tests__/file.embeddingChunks.test.ts@@ -0,0 +1,134 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AsyncTaskModel } from '@/database/models/asyncTask';+import { ChunkModel } from '@/database/models/chunk';+import { EmbeddingModel } from '@/database/models/embedding';+import { FileModel } from '@/database/models/file';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';++import { fileRouter } from '../file';++vi.mock('@lobechat/business-config/server', () => ({ ASYNC_TASK_TIMEOUT: 20 }));+vi.mock('@/envs/file', () => ({ fileEnv: { EMBEDDING_BATCH_SIZE: 1, EMBEDDING_CONCURRENCY: 2 } }));+vi.mock('@/database/models/asyncTask', () => ({ AsyncTaskModel: vi.fn() }));+vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));+vi.mock('@/database/models/embedding', () => ({ EmbeddingModel: vi.fn() }));+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));+vi.mock('@/server/services/chunk', () => ({ ChunkService: vi.fn() }));+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));+vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));+vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));+vi.mock('@/business/server/trpc-middlewares/async', () => ({+ checkEmbeddingUsage: async (opts: any) => opts.next({ ctx: opts.ctx }),+}));++vi.mock('@/libs/trpc/async', async () => {+ const init = await vi.importActual<{ asyncTrpc: any }>('@/libs/trpc/async/init');+ const { asyncTrpc } = init;+ return {+ asyncAuthedProcedure: asyncTrpc.procedure,+ asyncRouter: asyncTrpc.router,+ createAsyncCallerFactory: asyncTrpc.createCallerFactory,+ publicProcedure: asyncTrpc.procedure,+ };+});++describe('fileRouter.embeddingChunks timeout', () => {+ const asyncTaskModelMock = { findById: vi.fn(), update: vi.fn() };+ const embeddingModelMock = { bulkCreate: vi.fn() };++ beforeEach(() => {+ vi.clearAllMocks();++ asyncTaskModelMock.findById.mockResolvedValue({ id: 'task-1' });+ vi.mocked(AsyncTaskModel).mockImplementation(function () {+ return asyncTaskModelMock as any;+ });+ vi.mocked(FileModel).mockImplementation(function () {+ return { findById: vi.fn().mockResolvedValue({ id: 'file-1', name: 'a.csv' }) } as any;+ });+ vi.mocked(ChunkModel).mockImplementation(function () {+ return {+ getChunksTextByFileId: vi.fn().mockResolvedValue([{ id: 'chunk-1', text: 'row' }]),+ } as any;+ });+ vi.mocked(EmbeddingModel).mockImplementation(function () {+ return embeddingModelMock as any;+ });+ Reflect.set(FileModel, 'getFileById', undefined);+ });++ const deferred = () => {+ let resolve!: (value: number[][]) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<number[][]>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, reject, resolve };+ };+ const tick = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+ const errorUpdates = () =>+ asyncTaskModelMock.update.mock.calls.filter(+ ([, value]) => value.status === AsyncTaskStatus.Error,+ );++ it('holds the task until a late batch settles after a timeout, and does not write it', async () => {+ const late = deferred();+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ embeddings: vi.fn(() => late.promise),+ } as any);++ const caller = fileRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);+ const run = caller.embeddingChunks({ fileId: 'file-1', taskId: 'task-1' });++ await tick(60);+ // Timed out, but a batch is still in flight: the task must not be released yet.+ expect(errorUpdates()).toHaveLength(0);++ late.resolve([[0.1]]);+ await expect(run).resolves.toMatchObject({ success: false });++ expect(embeddingModelMock.bulkCreate).not.toHaveBeenCalled();+ expect(errorUpdates()).toEqual([+ [+ 'task-1',+ expect.objectContaining({+ error: expect.objectContaining({ name: AsyncTaskErrorType.Timeout }),+ }),+ ],+ ]);+ });++ it('stops sibling batches from writing after one batch fails', async () => {+ vi.mocked(ChunkModel).mockImplementation(function () {+ return {+ getChunksTextByFileId: vi.fn().mockResolvedValue([+ { id: 'chunk-1', text: 'row 1' },+ { id: 'chunk-2', text: 'row 2' },+ ]),+ } as any;+ });+ const failing = deferred();+ const sibling = deferred();+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ embeddings: vi.fn().mockReturnValueOnce(failing.promise).mockReturnValueOnce(sibling.promise),+ } as any);++ const caller = fileRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);+ const run = caller.embeddingChunks({ fileId: 'file-1', taskId: 'task-1' });++ await tick(5);+ failing.reject(new Error('provider error'));+ await tick(5);+ expect(errorUpdates()).toHaveLength(0);++ sibling.resolve([[0.2]]);+ await expect(run).resolves.toMatchObject({ success: false });++ expect(embeddingModelMock.bulkCreate).not.toHaveBeenCalled();+ expect(errorUpdates()).toHaveLength(1);+ });+});diff --git a/apps/server/src/routers/async/file.ts b/apps/server/src/routers/async/file.tsindex 8c3baab953f..7da60d052c0 100644--- a/apps/server/src/routers/async/file.ts+++ b/apps/server/src/routers/async/file.ts@@ -26,6 +26,12 @@ import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyimport { safeParseJSON } from '@/utils/safeParseJSON';import { sanitizeUTF8 } from '@/utils/sanitizeUTF8';+/**+ * How long a failed embedding task waits for its in-flight batches before it is marked+ * failed. Keep it below the margin any quota reservation tied to the `processing` state allows.+ */+const IN_FLIGHT_BATCH_GRACE_MS = 30_000;+const fileProcedure = asyncAuthedProcedure.use(async (opts) => {const { ctx } = opts;@@ -92,9 +98,19 @@ export const fileRouter = router({if (!asyncTask) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Async Task not found' });+ // `Promise.race` and `pMap` only stop waiting: without these, batches already running+ // keep calling the provider and writing vectors after the task is reported failed, which+ // is also when the vector quota stops reserving room for this task.+ let stopped = false;+ const inFlightBatches = new Set<Promise<void>>();+ const assertWritable = () => {+ if (stopped) throw new Error('embedding task already stopped');+ };+try {const timeoutPromise = new Promise((_, reject) => {setTimeout(() => {+ stopped = true;reject(new AsyncTaskError(AsyncTaskErrorType.Timeout,@@ -121,32 +137,47 @@ export const fileRouter = router({await pMap(requestArray,async (chunks) => {- // Read user's provider config from database- const modelRuntime = await initModelRuntimeFromDB(- ctx.serverDB,- ctx.userId,- provider,- workspaceId,- );-- const embeddings = await modelRuntime.embeddings(- {- dimensions: 1024,- input: chunks.map((c) => c.text),- model,- },- { metadata: { trigger: RequestTrigger.FileEmbedding }, user: ctx.userId },- );-- const items: NewEmbeddingsItem[] =- embeddings?.map((e, idx) => ({- chunkId: chunks[idx].id,- embeddings: e,- fileId: input.fileId,- model,- })) || [];-- await embeddingModel.bulkCreate(items);+ const batch = (async () => {+ assertWritable();+ // Read user's provider config from database+ const modelRuntime = await initModelRuntimeFromDB(+ ctx.serverDB,+ ctx.userId,+ provider,+ workspaceId,+ );++ const embeddings = await modelRuntime.embeddings(+ {+ dimensions: 1024,+ input: chunks.map((c) => c.text),+ model,+ },+ { metadata: { trigger: RequestTrigger.FileEmbedding }, user: ctx.userId },+ );++ const items: NewEmbeddingsItem[] =+ embeddings?.map((e, idx) => ({+ chunkId: chunks[idx].id,+ embeddings: e,+ fileId: input.fileId,+ model,+ })) || [];++ assertWritable();+ await embeddingModel.bulkCreate(items);+ })();++ inFlightBatches.add(batch);+ try {+ await batch;+ } catch (e) {+ // One failed batch fails the task: stop its siblings from writing more.+ stopped = true;+ throw e;+ } finally {+ inFlightBatches.delete(batch);+ }},{ concurrency: CONCURRENCY },);@@ -172,6 +203,15 @@ export const fileRouter = router({} catch (e) {console.error('embeddingChunks error', e);+ // Keep the task processing, which holds its vector reservation, until the batches+ // already writing settle. Bounded so a hung provider call cannot pin the task; once+ // `stopped` is set such a batch can no longer write anyway.+ stopped = true;+ await Promise.race([+ Promise.allSettled(inFlightBatches),+ new Promise((resolve) => setTimeout(resolve, IN_FLIGHT_BATCH_GRACE_MS)),+ ]);+await asyncTaskModel.update(input.taskId, {error: new AsyncTaskError((e as Error).name, (e as Error).message),status: AsyncTaskStatus.Error,diff --git a/apps/server/src/services/chunk/index.test.ts b/apps/server/src/services/chunk/index.test.tsindex 979107f3e41..a548666efaf 100644--- a/apps/server/src/services/chunk/index.test.ts+++ b/apps/server/src/services/chunk/index.test.ts@@ -12,6 +12,7 @@ import { ChunkService } from './index';const {mockAsyncTaskModelCreate,+ mockAsyncTaskModelFindById,mockAsyncTaskModelUpdate,mockChunkContent,mockCreateAsyncCaller,@@ -21,6 +22,7 @@ const {mockParseFileToChunks,} = vi.hoisted(() => ({mockAsyncTaskModelCreate: vi.fn(),+ mockAsyncTaskModelFindById: vi.fn(),mockAsyncTaskModelUpdate: vi.fn(),mockChunkContent: vi.fn(),mockCreateAsyncCaller: vi.fn(),@@ -34,6 +36,7 @@ vi.mock('@/database/models/asyncTask', () => ({AsyncTaskModel: vi.fn(function () {return {create: mockAsyncTaskModelCreate,+ findById: mockAsyncTaskModelFindById,update: mockAsyncTaskModelUpdate,};}),@@ -148,6 +151,21 @@ describe('ChunkService', () => {status: AsyncTaskStatus.Error,});});++ it('should keep the error the async procedure recorded instead of the APP_URL hint', async () => {+ mockEmbeddingChunks.mockRejectedValue(+ new Error('embedding storage is beyond the plan limit'),+ );+ mockAsyncTaskModelFindById.mockResolvedValue({+ error: new AsyncTaskError(AsyncTaskErrorType.EmbeddingQuotaExceeded, 'quota is full'),+ id: 'task-1',+ status: AsyncTaskStatus.Error,+ });++ await expect(service.asyncEmbeddingFileChunks('file-1')).resolves.toBe('task-1');++ expect(mockAsyncTaskModelUpdate).not.toHaveBeenCalled();+ });});describe('asyncParseFileToChunks', () => {diff --git a/apps/server/src/services/chunk/index.ts b/apps/server/src/services/chunk/index.tsindex e2b12009c97..8adcd95202e 100644--- a/apps/server/src/services/chunk/index.ts+++ b/apps/server/src/services/chunk/index.ts@@ -64,6 +64,12 @@ export class ChunkService {} catch (e) {console.error('[embeddingFileChunks] error:', e);+ // The async procedure ran and rejected the task itself (for example, a business+ // middleware recorded that the vector quota is full). Keep that error: the generic+ // APP_URL hint below is only right when the request never reached the server.+ const task = await this.asyncTaskModel.findById(asyncTaskId);+ if (task?.status === AsyncTaskStatus.Error) return asyncTaskId;+await this.asyncTaskModel.update(asyncTaskId, {error: new AsyncTaskError(AsyncTaskErrorType.TaskTriggerError,diff --git a/locales/en-US/components.json b/locales/en-US/components.jsonindex bd8acfbcfbe..f10845f9d5c 100644--- a/locales/en-US/components.json+++ b/locales/en-US/components.json@@ -102,6 +102,8 @@"FileParsingStatus.chunks.embeddingStatus.error": "Embedding failed","FileParsingStatus.chunks.embeddingStatus.errorResult": "Vectorization failed, please check and try again. Error detail:","FileParsingStatus.chunks.embeddingStatus.processing": "Text chunks are being embedded, please be patient.",+ "FileParsingStatus.chunks.embeddingStatus.quotaExceeded": "Vector storage full",+ "FileParsingStatus.chunks.embeddingStatus.quotaExceededResult": "Vector storage is full, so this file was not embedded. Upgrade your plan or delete files you no longer need to free up space, then retry.","FileParsingStatus.chunks.embeddingStatus.success": "All current text chunks have been embedded","FileParsingStatus.chunks.embeddings": "Embedding","FileParsingStatus.chunks.status.error": "Chunking failed",diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.jsonindex 5778796f26a..a9e91f81f78 100644--- a/locales/zh-CN/components.json+++ b/locales/zh-CN/components.json@@ -102,6 +102,8 @@"FileParsingStatus.chunks.embeddingStatus.error": "向量化失败","FileParsingStatus.chunks.embeddingStatus.errorResult": "向量化失败,请检查后重试。失败原因:","FileParsingStatus.chunks.embeddingStatus.processing": "文本块正在向量化,请稍等",+ "FileParsingStatus.chunks.embeddingStatus.quotaExceeded": "向量存储已满",+ "FileParsingStatus.chunks.embeddingStatus.quotaExceededResult": "向量存储空间已用完,这个文件没有进行向量化。升级套餐或删除不再需要的文件以释放空间,然后重试。","FileParsingStatus.chunks.embeddingStatus.success": "当前文本块均已向量化","FileParsingStatus.chunks.embeddings": "向量化","FileParsingStatus.chunks.status.error": "分块失败",diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.tsindex 0be23c159d7..daa134608f4 100644--- a/packages/locales/src/default/components.ts+++ b/packages/locales/src/default/components.ts@@ -116,6 +116,9 @@ export default {'Vectorization failed, please check and try again. Error detail:','FileParsingStatus.chunks.embeddingStatus.processing':'Text chunks are being embedded, please be patient.',+ 'FileParsingStatus.chunks.embeddingStatus.quotaExceeded': 'Vector storage full',+ 'FileParsingStatus.chunks.embeddingStatus.quotaExceededResult':+ 'Vector storage is full, so this file was not embedded. Upgrade your plan or delete files you no longer need to free up space, then retry.','FileParsingStatus.chunks.embeddingStatus.success': 'All current text chunks have been embedded','FileParsingStatus.chunks.embeddings': 'Embedding','FileParsingStatus.chunks.status.error': 'Chunking failed',diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.tsindex 22aca81010d..73b718b4764 100644--- a/packages/types/src/asyncTask.ts+++ b/packages/types/src/asyncTask.ts@@ -21,6 +21,11 @@ export enum AsyncTaskStatus {export enum AsyncTaskErrorType {EmbeddingError = 'EmbeddingError',+ /**+ * The plan's vector storage cannot hold this file's vectors; nothing was embedded.+ */+ EmbeddingQuotaExceeded = 'EmbeddingQuotaExceeded',+/*** File exceeds the in-memory parser limit and cannot be chunked.*/diff --git a/src/components/FileParsingStatus/EmbeddingStatus.tsx b/src/components/FileParsingStatus/EmbeddingStatus.tsxindex 422374db71e..b943eb4eebe 100644--- a/src/components/FileParsingStatus/EmbeddingStatus.tsx+++ b/src/components/FileParsingStatus/EmbeddingStatus.tsx@@ -6,7 +6,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { type FileParsingTask } from '@/types/asyncTask';-import { AsyncTaskStatus } from '@/types/asyncTask';+import { AsyncTaskErrorType, AsyncTaskStatus } from '@/types/asyncTask';const styles = stylex.create({errorReason: {@@ -54,27 +54,39 @@ const EmbeddingStatus = memo<EmbeddingStatusProps>(}case AsyncTaskStatus.Error: {+ // A full vector quota is not a failure retrying can fix by itself: name the quota+ // and how to free it instead of showing the raw error as a generic failure.+ const isQuotaExceeded = embeddingError?.name === AsyncTaskErrorType.EmbeddingQuotaExceeded;+return (<Tooltipstyles={{root: { maxWidth: 340, pointerEvents: 'none' },}}title={- <Flexbox gap={4}>- {t('FileParsingStatus.chunks.embeddingStatus.errorResult')}- {embeddingError && (- <Flexbox className={stylex.props(styles.errorReason).className}>- [{embeddingError.name}]:{' '}- {embeddingError.body && typeof embeddingError.body !== 'string'- ? embeddingError.body.detail- : embeddingError.body}- </Flexbox>- )}- </Flexbox>+ isQuotaExceeded ? (+ t('FileParsingStatus.chunks.embeddingStatus.quotaExceededResult')+ ) : (+ <Flexbox gap={4}>+ {t('FileParsingStatus.chunks.embeddingStatus.errorResult')}+ {embeddingError && (+ <Flexbox className={stylex.props(styles.errorReason).className}>+ [{embeddingError.name}]:{' '}+ {embeddingError.body && typeof embeddingError.body !== 'string'+ ? embeddingError.body.detail+ : embeddingError.body}+ </Flexbox>+ )}+ </Flexbox>+ )}><Tag className={className} color={'error'} variant={'filled'}>- {t('FileParsingStatus.chunks.embeddingStatus.error')}{' '}+ {t(+ isQuotaExceeded+ ? 'FileParsingStatus.chunks.embeddingStatus.quotaExceeded'+ : 'FileParsingStatus.chunks.embeddingStatus.error',+ )}{' '}<Iconicon={RotateCwIcon}style={{ cursor: 'pointer' }}