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.

🔨 chore(userMemories): support to auto calculate the timeout of the memory analysis task (#12325)

Neko487713361a95
diff --git a/src/app/(backend)/api/webhooks/memory-extraction/route.ts b/src/app/(backend)/api/webhooks/memory-extraction/route.ts
index 41210eca9dc..3807b4e8e0e 100644
--- a/src/app/(backend)/api/webhooks/memory-extraction/route.ts
+++ b/src/app/(backend)/api/webhooks/memory-extraction/route.ts
@@ -45,6 +45,7 @@ export const POST = async (req: Request) => {
buildWorkflowPayloadInput(params),
{ extraHeaders: upstashWorkflowExtraHeaders },
);
+
return NextResponse.json(
{ message: 'Memory extraction scheduled via workflow.', workflowRunId },
{ status: 202 },
diff --git a/src/server/routers/lambda/__tests__/userMemory.test.ts b/src/server/routers/lambda/__tests__/userMemory.test.ts
index b8a933eac62..ace7da8c0e4 100644
--- a/src/server/routers/lambda/__tests__/userMemory.test.ts
+++ b/src/server/routers/lambda/__tests__/userMemory.test.ts
@@ -2,7 +2,7 @@ import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { userMemoryRouter } from '@/server/routers/lambda/userMemory';
-import { AsyncTaskStatus, AsyncTaskType } from '@/types/asyncTask';
+import { AsyncTaskErrorType, AsyncTaskStatus, AsyncTaskType } from '@/types/asyncTask';
import { MemorySourceType } from '@/types/userMemory';
const mockFindActiveByType = vi.fn();
@@ -162,6 +162,7 @@ describe('userMemoryRouter.requestMemoryFromChatTopic', () => {
describe('userMemoryRouter.getMemoryExtractionTask', () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.useRealTimers();
});
it('returns null when no active task', async () => {
@@ -219,4 +220,51 @@ describe('userMemoryRouter.getMemoryExtractionTask', () => {
expect(mockFindById).toHaveBeenCalledWith('a0a0a0a0-a0a0-4a0a-a0a0-a0a0a0a0a0a0');
expect(result?.id).toBe('a0a0a0a0-a0a0-4a0a-a0a0-a0a0a0a0a0a0');
});
+
+ it('marks active task as error when topic-based timeout is exceeded', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2024-03-01T01:00:00.000Z'));
+
+ mockFindActiveByType.mockResolvedValue({
+ createdAt: new Date('2024-03-01T00:00:00.000Z'),
+ id: 'task-timeout',
+ metadata: {
+ progress: { completedTopics: 1, totalTopics: 6 },
+ source: 'chat_topic',
+ },
+ status: AsyncTaskStatus.Processing,
+ userId: 'user-1',
+ });
+
+ const caller = createCaller();
+ const result = await caller.getMemoryExtractionTask();
+
+ expect(mockUpdate).toHaveBeenCalledWith(
+ 'task-timeout',
+ expect.objectContaining({
+ error: expect.objectContaining({
+ body: expect.objectContaining({
+ detail: expect.stringContaining('timed out after 30 minutes'),
+ }),
+ name: AsyncTaskErrorType.Timeout,
+ }),
+ status: AsyncTaskStatus.Error,
+ }),
+ );
+ expect(result).toEqual({
+ error: expect.objectContaining({
+ body: expect.objectContaining({
+ detail: expect.stringContaining('timed out after 30 minutes'),
+ }),
+ name: AsyncTaskErrorType.Timeout,
+ }),
+ id: 'task-timeout',
+ metadata: {
+ progress: { completedTopics: 1, totalTopics: 6 },
+ range: undefined,
+ source: 'chat_topic',
+ },
+ status: AsyncTaskStatus.Error,
+ });
+ });
});
diff --git a/src/server/routers/lambda/userMemory.ts b/src/server/routers/lambda/userMemory.ts
index c54ca668c3e..d20ddd00d23 100644
--- a/src/server/routers/lambda/userMemory.ts
+++ b/src/server/routers/lambda/userMemory.ts
@@ -6,29 +6,27 @@ import {
CreateUserMemoryIdentitySchema,
MemorySourceType,
UpdateUserMemoryIdentitySchema,
- UserMemoryExtractionMetadata,
+ type UserMemoryExtractionMetadata,
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { AsyncTaskModel, initUserMemoryExtractionMetadata } from '@/database/models/asyncTask';
import { TopicModel } from '@/database/models/topic';
-import { UserMemoryModel } from '@/database/models/userMemory';
-import {
- UserMemoryActivityModel,
+import { UserMemoryActivityModel,
UserMemoryContextModel,
UserMemoryExperienceModel,
UserMemoryIdentityModel,
- UserMemoryPreferenceModel,
-} from '@/database/models/userMemory/index';
+UserMemoryModel,
+ UserMemoryPreferenceModel } from '@/database/models/userMemory';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
import { appEnv } from '@/envs/app';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import {
- MemoryExtractionWorkflowService,
buildWorkflowPayloadInput,
+ MemoryExtractionWorkflowService,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
@@ -61,6 +59,18 @@ const userMemoryExtractionTaskInputSchema = z
})
.optional();
+// NOTICE(@nekomeowww): Memory extraction time scales with topic count. We estimate
+// an average of ~5 minutes per topic to derive a dynamic timeout budget.
+const USER_MEMORY_EXTRACTION_TIMEOUT_PER_TOPIC_MS = 5 * 60 * 1000;
+
+const getUserMemoryExtractionTimeoutMs = (metadata: UserMemoryExtractionMetadata) => {
+ const totalTopics = metadata.progress.totalTopics;
+
+ if (!Number.isFinite(totalTopics) || !totalTopics || totalTopics <= 0) return null;
+
+ return totalTopics * USER_MEMORY_EXTRACTION_TIMEOUT_PER_TOPIC_MS;
+};
+
export const userMemoryRouter = router({
// ============ Identity CRUD ============
createIdentity: userMemoryProcedure
@@ -140,12 +150,44 @@ export const userMemoryRouter = router({
if (!task || task.userId !== ctx.userId) return null;
+ const metadata = initUserMemoryExtractionMetadata(
+ task.metadata as UserMemoryExtractionMetadata | undefined,
+ );
+
+ const timeoutMs = getUserMemoryExtractionTimeoutMs(metadata);
+ const taskCreatedAt = task.createdAt ? new Date(task.createdAt).getTime() : Number.NaN;
+ const isActiveTask =
+ task.status === AsyncTaskStatus.Pending || task.status === AsyncTaskStatus.Processing;
+
+ if (
+ isActiveTask &&
+ timeoutMs !== null &&
+ Number.isFinite(taskCreatedAt) &&
+ Date.now() - taskCreatedAt > timeoutMs
+ ) {
+ const timeoutMinutes = Math.ceil(timeoutMs / (60 * 1000));
+ const timeoutError = new AsyncTaskError(
+ AsyncTaskErrorType.Timeout,
+ `User memory extraction timed out after ${timeoutMinutes} minutes for ${metadata.progress.totalTopics} topics (estimated at 5 minutes per topic). Please retry.`,
+ );
+
+ await ctx.asyncTaskModel.update(task.id, {
+ error: timeoutError,
+ status: AsyncTaskStatus.Error,
+ });
+
+ return {
+ error: timeoutError,
+ id: task.id,
+ metadata,
+ status: AsyncTaskStatus.Error,
+ };
+ }
+
return {
error: task.error,
id: task.id,
- metadata: initUserMemoryExtractionMetadata(
- task.metadata as UserMemoryExtractionMetadata | undefined,
- ),
+ metadata,
status: task.status as AsyncTaskStatus,
};
}),