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(app,memory-user-memory): track hourly extraction tasks (#16795)

Nekoc9577fb5a0c7
diff --git a/apps/server/src/services/memory/userMemory/__tests__/extract.workflow.test.ts b/apps/server/src/services/memory/userMemory/__tests__/extract.workflow.test.ts
new file mode 100644
index 00000000000..0fe15bdaaa0
--- /dev/null
+++ b/apps/server/src/services/memory/userMemory/__tests__/extract.workflow.test.ts
@@ -0,0 +1,272 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ AsyncTaskError,
+ AsyncTaskErrorType,
+ AsyncTaskStatus,
+ AsyncTaskType,
+} from '@/types/asyncTask';
+
+import { MemoryExtractionWorkflowService } from '../extract';
+
+interface HourlyMetadataInput {
+ cursor?: {
+ createdAt: string;
+ id: string;
+ };
+ startedAt: string;
+}
+
+const {
+ mockAppendUserMemoryWorkflowRunIds,
+ mockAsyncTaskModel,
+ mockCreate,
+ mockFindFirst,
+ mockGetServerDB,
+ mockTrigger,
+ mockUpdate,
+} = vi.hoisted(() => ({
+ mockAppendUserMemoryWorkflowRunIds: vi.fn(),
+ mockAsyncTaskModel: vi.fn(),
+ mockCreate: vi.fn(),
+ mockFindFirst: vi.fn(),
+ mockGetServerDB: vi.fn(),
+ mockTrigger: vi.fn(),
+ mockUpdate: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: mockGetServerDB,
+}));
+
+vi.mock('@/database/models/asyncTask', () => ({
+ AsyncTaskModel: mockAsyncTaskModel,
+ initHourlyUserMemoryExtractionMetadata: vi.fn((metadata: HourlyMetadataInput) => ({
+ control: (metadata as HourlyMetadataInput & { control?: unknown }).control,
+ cursor: metadata.cursor,
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: metadata.startedAt,
+ })),
+}));
+
+vi.mock('@/libs/qstash', () => ({
+ OtelWorkflowClient: vi.fn(() => ({
+ trigger: mockTrigger,
+ })),
+}));
+
+describe('MemoryExtractionWorkflowService.triggerHourlyTracked', () => {
+ const originalServiceUserId = process.env.MEMORY_EXTRACTION_HOURLY_TASK_USER_ID;
+ const originalQstashToken = process.env.QSTASH_TOKEN;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-07-06T00:00:00.000Z'));
+
+ process.env.MEMORY_EXTRACTION_HOURLY_TASK_USER_ID = 'service-account-user';
+ process.env.QSTASH_TOKEN = 'test-qstash-token';
+
+ mockGetServerDB.mockResolvedValue({
+ db: 'server',
+ query: { asyncTasks: { findFirst: mockFindFirst } },
+ });
+ mockCreate.mockResolvedValue('00000000-0000-4000-8000-000000000001');
+ mockFindFirst.mockResolvedValue(undefined);
+ mockAppendUserMemoryWorkflowRunIds.mockResolvedValue(undefined);
+ mockUpdate.mockResolvedValue(undefined);
+ mockTrigger.mockResolvedValue({ workflowRunId: 'workflow-run-1' });
+ mockAsyncTaskModel.mockImplementation(() => ({
+ appendUserMemoryWorkflowRunIds: mockAppendUserMemoryWorkflowRunIds,
+ create: mockCreate,
+ update: mockUpdate,
+ }));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+
+ if (originalServiceUserId === undefined) {
+ delete process.env.MEMORY_EXTRACTION_HOURLY_TASK_USER_ID;
+ } else {
+ process.env.MEMORY_EXTRACTION_HOURLY_TASK_USER_ID = originalServiceUserId;
+ }
+
+ if (originalQstashToken === undefined) {
+ delete process.env.QSTASH_TOKEN;
+ } else {
+ process.env.QSTASH_TOKEN = originalQstashToken;
+ }
+ });
+
+ it('creates an hourly async task, triggers the workflow, and appends the root run id', async () => {
+ /**
+ * @example
+ * await MemoryExtractionWorkflowService.triggerHourlyTracked({ baseUrl });
+ */
+ const result = await MemoryExtractionWorkflowService.triggerHourlyTracked(
+ {
+ baseUrl: 'https://app.example.com',
+ cursor: {
+ createdAt: '2026-07-05T23:00:00.000Z',
+ id: 'cursor-user',
+ },
+ },
+ { extraHeaders: { 'x-test-header': '1' } },
+ );
+
+ expect(result).toEqual({
+ taskId: '00000000-0000-4000-8000-000000000001',
+ workflowRunId: 'workflow-run-1',
+ });
+ expect(mockGetServerDB).toHaveBeenCalledTimes(1);
+ expect(mockAsyncTaskModel).toHaveBeenCalledWith(
+ { db: 'server', query: { asyncTasks: { findFirst: mockFindFirst } } },
+ 'service-account-user',
+ );
+ expect(mockCreate).toHaveBeenCalledWith({
+ metadata: {
+ control: undefined,
+ cursor: {
+ createdAt: '2026-07-05T23:00:00.000Z',
+ id: 'cursor-user',
+ },
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ });
+ expect(mockTrigger).toHaveBeenCalledWith({
+ body: {
+ baseUrl: 'https://app.example.com',
+ cursor: {
+ createdAt: '2026-07-05T23:00:00.000Z',
+ id: 'cursor-user',
+ },
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ },
+ headers: { 'x-test-header': '1' },
+ url: 'https://app.example.com/api/workflows/memory-user-memory/call-cron-hourly-analysis',
+ });
+ expect(mockAppendUserMemoryWorkflowRunIds).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ ['workflow-run-1'],
+ );
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it('uses deterministic workflow run ids when an entry workflow run id is provided', async () => {
+ /**
+ * @example
+ * await MemoryExtractionWorkflowService.triggerHourlyTracked({ baseUrl }, { entryWorkflowRunId });
+ */
+ const result = await MemoryExtractionWorkflowService.triggerHourlyTracked(
+ {
+ baseUrl: 'https://app.example.com',
+ },
+ { entryWorkflowRunId: 'entry-run-1' },
+ );
+
+ expect(result).toEqual({
+ taskId: '00000000-0000-4000-8000-000000000001',
+ workflowRunId: 'workflow-run-1',
+ });
+ expect(mockCreate).toHaveBeenCalledWith({
+ metadata: {
+ control: {
+ upstash: {
+ entryWorkflowRunId: 'entry-run-1',
+ workflowRunIds: ['entry-run-1', 'memory-user-memory-hourly-entry-run-1'],
+ },
+ },
+ cursor: undefined,
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ });
+ expect(mockTrigger).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workflowRunId: 'memory-user-memory-hourly-entry-run-1',
+ }),
+ );
+ });
+
+ it('marks the created async task as error and rethrows when workflow scheduling fails', async () => {
+ /**
+ * @example
+ * await expect(MemoryExtractionWorkflowService.triggerHourlyTracked({ baseUrl })).rejects.toThrow();
+ */
+ const triggerError = new Error('upstash unavailable');
+ mockTrigger.mockRejectedValue(triggerError);
+
+ await expect(
+ MemoryExtractionWorkflowService.triggerHourlyTracked({
+ baseUrl: 'https://app.example.com',
+ }),
+ ).rejects.toBe(triggerError);
+
+ expect(mockCreate).toHaveBeenCalledWith({
+ metadata: {
+ control: undefined,
+ cursor: undefined,
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ });
+ expect(mockUpdate).toHaveBeenCalledWith('00000000-0000-4000-8000-000000000001', {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.TaskTriggerError,
+ 'Failed to schedule hourly memory extraction workflow',
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+ expect(mockAppendUserMemoryWorkflowRunIds).not.toHaveBeenCalled();
+ });
+
+ it('throws before triggering when the service-account user id env is missing', async () => {
+ /**
+ * @example
+ * await expect(MemoryExtractionWorkflowService.triggerHourlyTracked({ baseUrl })).rejects.toThrow();
+ */
+ delete process.env.MEMORY_EXTRACTION_HOURLY_TASK_USER_ID;
+
+ await expect(
+ MemoryExtractionWorkflowService.triggerHourlyTracked({
+ baseUrl: 'https://app.example.com',
+ }),
+ ).rejects.toThrow(
+ 'MEMORY_EXTRACTION_HOURLY_TASK_USER_ID is required for tracked hourly extraction',
+ );
+
+ expect(mockGetServerDB).not.toHaveBeenCalled();
+ expect(mockAsyncTaskModel).not.toHaveBeenCalled();
+ expect(mockCreate).not.toHaveBeenCalled();
+ expect(mockTrigger).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/memory/userMemory/extract.ts b/apps/server/src/services/memory/userMemory/extract.ts
index 8ab50203478..ae219332bc9 100644
--- a/apps/server/src/services/memory/userMemory/extract.ts
+++ b/apps/server/src/services/memory/userMemory/extract.ts
@@ -51,12 +51,15 @@ import { RequestTrigger } from '@lobechat/types';
import { type FlowControl } from '@upstash/qstash';
import type { Client } from '@upstash/workflow';
import debug from 'debug';
-import { and, asc, eq, inArray } from 'drizzle-orm';
+import { and, asc, eq, inArray, sql } from 'drizzle-orm';
import { join } from 'pathe';
import { z } from 'zod';
import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';
-import { AsyncTaskModel } from '@/database/models/asyncTask';
+import {
+ AsyncTaskModel,
+ initHourlyUserMemoryExtractionMetadata,
+} from '@/database/models/asyncTask';
import { type ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';
import { TopicModel } from '@/database/models/topic';
import { type ListUsersForMemoryExtractorCursor } from '@/database/models/user';
@@ -65,6 +68,7 @@ import type { UserMemoryHybridSearchAggregatedResult } from '@/database/models/u
import { UserMemoryModel } from '@/database/models/userMemory';
import { UserMemorySourceBenchmarkLoCoMoModel } from '@/database/models/userMemory/sources/benchmarkLoCoMo';
import { AiInfraRepos } from '@/database/repositories/aiInfra';
+import { asyncTasks } from '@/database/schemas';
import { getServerDB } from '@/database/server';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { OtelWorkflowClient } from '@/libs/qstash';
@@ -79,6 +83,7 @@ import {
AsyncTaskErrorType,
AsyncTaskStatus,
type AsyncTaskStructuredErrorItem,
+ AsyncTaskType,
} from '@/types/asyncTask';
import { type GlobalMemoryLayer } from '@/types/serverConfig';
import { type ProviderConfig } from '@/types/user/settings';
@@ -123,6 +128,7 @@ export interface MemoryExtractionHourlyWorkflowPayload {
baseUrl?: string;
cursor?: MemoryExtractionWorkflowCursor;
dryRun?: boolean;
+ hourlyTaskId?: string;
}
export interface MemoryExtractionNormalizedPayload {
@@ -131,6 +137,7 @@ export interface MemoryExtractionNormalizedPayload {
forceAll: boolean;
forceTopics: boolean;
from?: Date;
+ hourlyTaskId?: string;
identityCursor: number;
layers: LayersEnum[];
/**
@@ -157,6 +164,7 @@ export const memoryExtractionPayloadSchema = z.object({
forceAll: z.boolean().optional(),
forceTopics: z.boolean().optional(),
fromDate: z.coerce.date().optional(),
+ hourlyTaskId: z.string().uuid().optional(),
identityCursor: z.coerce.number().int().nonnegative().optional(),
layers: z.array(z.nativeEnum(LayersEnum)).optional(),
mode: z.enum(['workflow', 'direct']).optional(),
@@ -222,6 +230,7 @@ export const normalizeMemoryExtractionPayload = (
forceAll: parsed.forceAll ?? false,
forceTopics: parsed.forceTopics ?? false,
from: parsed.fromDate,
+ hourlyTaskId: parsed.hourlyTaskId,
identityCursor: parsed.identityCursor ?? 0,
layers: normalizeLayers(parsed.layers),
mode: parsed.mode ?? 'workflow',
@@ -261,6 +270,7 @@ export const buildWorkflowPayloadInput = (
forceAll: payload.forceAll,
forceTopics: payload.forceTopics,
fromDate: payload.from,
+ hourlyTaskId: payload.hourlyTaskId,
identityCursor: payload.identityCursor,
layers: payload.layers,
mode: payload.mode,
@@ -2738,6 +2748,9 @@ const getProcessUserTopicsFlowControl = (): FlowControl => {
};
};
+const buildHourlyChildWorkflowRunId = (entryWorkflowRunId: string) =>
+ `memory-user-memory-hourly-${entryWorkflowRunId.replaceAll(/[^\w-]/g, '_')}`;
+
const getWorkflowUrl = (path: string, baseUrl: string) => {
const url = new URL(path, baseUrl);
@@ -2787,14 +2800,119 @@ export class MemoryExtractionWorkflowService {
static triggerHourly(
payload: MemoryExtractionHourlyWorkflowPayload,
- options?: { extraHeaders?: Record<string, string> },
+ options?: { extraHeaders?: Record<string, string>; workflowRunId?: string },
) {
if (!payload.baseUrl) {
throw new Error('Missing baseUrl for workflow trigger');
}
const url = getWorkflowUrl(WORKFLOW_PATHS.hourly, payload.baseUrl);
- return this.getClient().trigger({ body: payload, headers: options?.extraHeaders, url });
+ return this.getClient().trigger({
+ body: payload,
+ headers: options?.extraHeaders,
+ url,
+ workflowRunId: options?.workflowRunId,
+ });
+ }
+
+ /**
+ * Creates a batch-level async task and triggers hourly memory extraction.
+ *
+ * Use when:
+ * - Starting the hourly user-memory extraction workflow from cron or an operator action
+ * - Tracking the root workflow run id for later cooperative cancellation
+ *
+ * Expects:
+ * - `payload.baseUrl` is present for workflow URL construction
+ * - `MEMORY_EXTRACTION_HOURLY_TASK_USER_ID` identifies the service-account task owner
+ *
+ * Returns:
+ * - The created async task id and root Upstash workflow run id
+ */
+ static async triggerHourlyTracked(
+ payload: MemoryExtractionHourlyWorkflowPayload,
+ options?: { entryWorkflowRunId?: string; extraHeaders?: Record<string, string> },
+ ) {
+ if (!payload.baseUrl) {
+ throw new Error('Missing baseUrl for workflow trigger');
+ }
+
+ const userId = process.env.MEMORY_EXTRACTION_HOURLY_TASK_USER_ID;
+ if (!userId) {
+ throw new Error(
+ 'MEMORY_EXTRACTION_HOURLY_TASK_USER_ID is required for tracked hourly extraction',
+ );
+ }
+
+ const db = await getServerDB();
+ const startedAt = new Date().toISOString();
+ const childWorkflowRunId = options?.entryWorkflowRunId
+ ? buildHourlyChildWorkflowRunId(options.entryWorkflowRunId)
+ : undefined;
+ const existingTask = options?.entryWorkflowRunId
+ ? await db.query.asyncTasks.findFirst({
+ where: and(
+ eq(asyncTasks.type, AsyncTaskType.UserMemoryExtractionHourly),
+ eq(asyncTasks.userId, userId),
+ sql`${asyncTasks.metadata} #>> '{control,upstash,entryWorkflowRunId}' = ${options.entryWorkflowRunId}`,
+ ),
+ })
+ : undefined;
+ const asyncTaskModel = new AsyncTaskModel(db, userId);
+ const taskId =
+ existingTask?.id ??
+ (await asyncTaskModel.create({
+ metadata: initHourlyUserMemoryExtractionMetadata({
+ control: options?.entryWorkflowRunId
+ ? {
+ upstash: {
+ entryWorkflowRunId: options.entryWorkflowRunId,
+ workflowRunIds: [
+ options.entryWorkflowRunId,
+ ...(childWorkflowRunId ? [childWorkflowRunId] : []),
+ ],
+ },
+ }
+ : undefined,
+ cursor: payload.cursor,
+ startedAt,
+ }),
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ }));
+ let workflowRunId: string;
+ try {
+ ({ workflowRunId } = await this.triggerHourly(
+ { ...payload, hourlyTaskId: taskId },
+ { extraHeaders: options?.extraHeaders, workflowRunId: childWorkflowRunId },
+ ));
+ } catch (error) {
+ const statusCode =
+ (error as { status?: number; statusCode?: number }).status ??
+ (error as { statusCode?: number }).statusCode;
+ const message = error instanceof Error ? error.message.toLowerCase() : '';
+ if (
+ existingTask &&
+ childWorkflowRunId &&
+ (statusCode === 409 || message.includes('already'))
+ ) {
+ await asyncTaskModel.appendUserMemoryWorkflowRunIds(taskId, [childWorkflowRunId]);
+ return { taskId, workflowRunId: childWorkflowRunId };
+ }
+
+ await asyncTaskModel.update(taskId, {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.TaskTriggerError,
+ 'Failed to schedule hourly memory extraction workflow',
+ ),
+ status: AsyncTaskStatus.Error,
+ });
+ throw error;
+ }
+
+ await asyncTaskModel.appendUserMemoryWorkflowRunIds(taskId, [workflowRunId]);
+
+ return { taskId, workflowRunId };
}
static triggerProcessUserTopics(
@@ -2867,7 +2985,7 @@ export class MemoryExtractionWorkflowService {
static triggerPersonaUpdate(
userId: string,
baseUrl: string,
- options?: { extraHeaders?: Record<string, string> },
+ options?: { extraHeaders?: Record<string, string>; hourlyTaskId?: string },
) {
if (!baseUrl) {
throw new Error('Missing baseUrl for workflow trigger');
@@ -2875,7 +2993,7 @@ export class MemoryExtractionWorkflowService {
const url = getWorkflowUrl(WORKFLOW_PATHS.personaUpdate, baseUrl);
return this.getClient().trigger({
- body: { userIds: [userId] },
+ body: { hourlyTaskId: options?.hourlyTaskId, userIds: [userId] },
flowControl: {
key: `memory-user-memory.pipelines.persona.update-write.${userId}`,
parallelism: 1,
diff --git a/packages/database/src/models/__tests__/asyncTask.test.ts b/packages/database/src/models/__tests__/asyncTask.test.ts
index ece9d93282a..49442086094 100644
--- a/packages/database/src/models/__tests__/asyncTask.test.ts
+++ b/packages/database/src/models/__tests__/asyncTask.test.ts
@@ -1,6 +1,9 @@
// @vitest-environment node
import { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';
-import type { UserMemoryExtractionMetadata } from '@lobechat/types';
+import type {
+ HourlyUserMemoryExtractionMetadata,
+ UserMemoryExtractionMetadata,
+} from '@lobechat/types';
import {
AsyncTaskError,
AsyncTaskErrorType,
@@ -13,7 +16,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import { asyncTasks, users } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
-import { AsyncTaskModel, initUserMemoryExtractionMetadata } from '../asyncTask';
+import {
+ AsyncTaskModel,
+ initHourlyUserMemoryExtractionMetadata,
+ initUserMemoryExtractionMetadata,
+} from '../asyncTask';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -397,6 +404,247 @@ describe('AsyncTaskModel', () => {
await serverDB.delete(users).where(eq(users.id, otherUserId));
});
});
+
+ describe('appendUserMemoryWorkflowRunIds', () => {
+ it('should append workflow run ids into hourly metadata control', async () => {
+ /**
+ * @example
+ * await asyncTaskModel.appendUserMemoryWorkflowRunIds(id, ['run-1']);
+ */
+ const task = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ userId,
+ })
+ .returning()
+ .then((res) => res[0]);
+
+ await asyncTaskModel.appendUserMemoryWorkflowRunIds(task.id, ['run-1']);
+
+ const updated = await serverDB.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, task.id),
+ });
+ const metadata = updated?.metadata as HourlyUserMemoryExtractionMetadata | undefined;
+
+ expect(metadata?.control?.upstash?.workflowRunIds).toEqual(['run-1']);
+ expect(metadata?.progress).toEqual({
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ });
+ });
+
+ it('should append and dedupe workflow run ids without dropping existing metadata', async () => {
+ /**
+ * @example
+ * await asyncTaskModel.appendUserMemoryWorkflowRunIds(id, ['run-2']);
+ */
+ const task = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ control: {
+ cancelReason: 'operator_request',
+ upstash: {
+ workflowRunIds: ['run-1'],
+ },
+ },
+ cursor: {
+ createdAt: '2026-07-06T00:30:00.000Z',
+ id: 'cursor-user-id',
+ },
+ progress: {
+ processedUsers: 2,
+ scheduledBatches: 1,
+ scheduledChildRuns: 1,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ userId,
+ })
+ .returning()
+ .then((res) => res[0]);
+
+ await asyncTaskModel.appendUserMemoryWorkflowRunIds(task.id, ['run-2', 'run-1']);
+
+ const updated = await serverDB.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, task.id),
+ });
+ const metadata = updated?.metadata as HourlyUserMemoryExtractionMetadata | undefined;
+
+ expect(metadata).toMatchObject({
+ control: {
+ cancelReason: 'operator_request',
+ upstash: {
+ workflowRunIds: ['run-1', 'run-2'],
+ },
+ },
+ cursor: {
+ createdAt: '2026-07-06T00:30:00.000Z',
+ id: 'cursor-user-id',
+ },
+ progress: {
+ processedUsers: 2,
+ scheduledBatches: 1,
+ scheduledChildRuns: 1,
+ },
+ source: 'hourly_chat_topic',
+ });
+ });
+
+ it('should ignore an empty workflow run id list', async () => {
+ /**
+ * @example
+ * await asyncTaskModel.appendUserMemoryWorkflowRunIds(id, []);
+ */
+ const task = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ userId,
+ })
+ .returning()
+ .then((res) => res[0]);
+
+ await asyncTaskModel.appendUserMemoryWorkflowRunIds(task.id, []);
+
+ const updated = await serverDB.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, task.id),
+ });
+
+ expect(updated?.metadata).toEqual(task.metadata);
+ });
+ });
+
+ describe('markHourlyMemoryExtractionSuccess', () => {
+ it('should mark an hourly task as success and persist final scheduling progress', async () => {
+ const task = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ userId,
+ })
+ .returning()
+ .then((res) => res[0]);
+
+ await asyncTaskModel.markHourlyMemoryExtractionSuccess(task.id, {
+ processedUsers: 21,
+ scheduledBatches: 2,
+ scheduledChildRuns: 2,
+ status: AsyncTaskStatus.Success,
+ });
+
+ const updated = await serverDB.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, task.id),
+ });
+ const metadata = updated?.metadata as HourlyUserMemoryExtractionMetadata | undefined;
+
+ expect(updated?.status).toBe(AsyncTaskStatus.Success);
+ expect(metadata?.progress).toEqual({
+ processedUsers: 21,
+ scheduledBatches: 2,
+ scheduledChildRuns: 2,
+ });
+ });
+ });
+
+ describe('isHourlyMemoryExtractionCancellationRequested', () => {
+ it('should return true for a cancelled hourly memory extraction task', async () => {
+ /**
+ * @example
+ * expect(requested).toBe(true);
+ */
+ const task = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ control: {
+ cancelRequestedAt: '2026-07-06T01:00:00.000Z',
+ },
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ userId,
+ })
+ .returning()
+ .then((res) => res[0]);
+
+ const requested = await asyncTaskModel.isHourlyMemoryExtractionCancellationRequested(task.id);
+
+ expect(requested).toBe(true);
+ });
+
+ it('should return false for a manual memory extraction task even if cancelled', async () => {
+ /**
+ * @example
+ * expect(requested).toBe(false);
+ */
+ const task = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ control: {
+ cancelRequestedAt: '2026-07-06T01:00:00.000Z',
+ },
+ progress: {
+ completedTopics: 0,
+ totalTopics: 1,
+ },
+ source: 'chat_topic',
+ },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.UserMemoryExtractionWithChatTopic,
+ userId,
+ })
+ .returning()
+ .then((res) => res[0]);
+
+ const requested = await asyncTaskModel.isHourlyMemoryExtractionCancellationRequested(task.id);
+
+ expect(requested).toBe(false);
+ });
+ });
});
describe('initUserMemoryExtractionMetadata', () => {
@@ -511,6 +759,7 @@ describe('initUserMemoryExtractionMetadata', () => {
cancelRequestedAt,
cancelledBy: 'user-1',
upstash: {
+ entryWorkflowRunId: 'entry-run',
workflowRunIds: ['run-1', 'run-2'],
},
},
@@ -526,6 +775,7 @@ describe('initUserMemoryExtractionMetadata', () => {
cancelRequestedAt,
cancelledBy: 'user-1',
upstash: {
+ entryWorkflowRunId: 'entry-run',
workflowRunIds: ['run-1', 'run-2'],
},
});
@@ -565,6 +815,66 @@ describe('initUserMemoryExtractionMetadata', () => {
});
});
+describe('initHourlyUserMemoryExtractionMetadata', () => {
+ it('should return default hourly metadata with startedAt and empty progress', () => {
+ /**
+ * @example
+ * expect(initHourlyUserMemoryExtractionMetadata({ startedAt })).toMatchObject({
+ * source: 'hourly_chat_topic',
+ * });
+ */
+ const startedAt = '2026-07-06T00:00:00.000Z';
+
+ const result = initHourlyUserMemoryExtractionMetadata({ startedAt });
+
+ expect(result).toEqual({
+ control: undefined,
+ cursor: undefined,
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt,
+ });
+ });
+
+ it('should preserve hourly control workflow run ids', () => {
+ /**
+ * @example
+ * expect(result.control?.upstash?.workflowRunIds).toEqual(['run-1']);
+ */
+ const result = initHourlyUserMemoryExtractionMetadata({
+ control: {
+ cancelReason: 'operator_request',
+ cancelRequestedAt: '2026-07-06T01:00:00.000Z',
+ cancelledBy: 'webhook',
+ upstash: { entryWorkflowRunId: 'entry-run', workflowRunIds: ['run-1'] },
+ },
+ progress: {
+ processedUsers: 4,
+ scheduledBatches: 2,
+ scheduledChildRuns: 3,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ });
+
+ expect(result.control).toEqual({
+ cancelReason: 'operator_request',
+ cancelRequestedAt: '2026-07-06T01:00:00.000Z',
+ cancelledBy: 'webhook',
+ upstash: { entryWorkflowRunId: 'entry-run', workflowRunIds: ['run-1'] },
+ });
+ expect(result.progress).toEqual({
+ processedUsers: 4,
+ scheduledBatches: 2,
+ scheduledChildRuns: 3,
+ });
+ });
+});
+
describe('AsyncTaskModel.findByInferenceId', () => {
it('should find a task by inferenceId', async () => {
const [task] = await serverDB
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index 6f6c72b3865..63a7ebf0bc2 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -1,5 +1,9 @@
import { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';
-import type { UserMemoryExtractionMetadata } from '@lobechat/types';
+import type {
+ HourlyUserMemoryExtractionMetadata,
+ HourlyUserMemoryExtractionProgress,
+ UserMemoryExtractionMetadata,
+} from '@lobechat/types';
import {
AsyncTaskError,
AsyncTaskErrorType,
@@ -139,6 +143,105 @@ export class AsyncTaskModel {
return Boolean(metadata?.control?.cancelRequestedAt);
};
+ appendUserMemoryWorkflowRunIds = async (taskId: string, workflowRunIds: string[]) => {
+ const uniqueIds = Array.from(new Set(workflowRunIds.filter(Boolean)));
+ if (uniqueIds.length === 0) return;
+
+ const incomingIdsJson = JSON.stringify(uniqueIds);
+ const mergedIdsExpr = sql`
+ (
+ SELECT COALESCE(jsonb_agg(value ORDER BY first_ordinal), '[]'::jsonb)
+ FROM (
+ SELECT value, MIN(ordinality) AS first_ordinal
+ FROM jsonb_array_elements_text(
+ COALESCE(
+ ${asyncTasks.metadata} #> '{control,upstash,workflowRunIds}',
+ '[]'::jsonb
+ ) || ${incomingIdsJson}::jsonb
+ ) WITH ORDINALITY AS ids(value, ordinality)
+ GROUP BY value
+ ) AS deduped_ids
+ )
+ `;
+
+ await this.db
+ .update(asyncTasks)
+ .set({
+ metadata: sql`
+ jsonb_set(
+ jsonb_set(
+ jsonb_set(
+ ${asyncTasks.metadata},
+ '{control}',
+ COALESCE(${asyncTasks.metadata} -> 'control', '{}'::jsonb),
+ true
+ ),
+ '{control,upstash}',
+ COALESCE(${asyncTasks.metadata} #> '{control,upstash}', '{}'::jsonb),
+ true
+ ),
+ '{control,upstash,workflowRunIds}',
+ ${mergedIdsExpr},
+ true
+ )
+ `,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(asyncTasks.id, taskId), this.ownership()));
+ };
+
+ markHourlyMemoryExtractionSuccess = async (
+ taskId: string,
+ progress: HourlyUserMemoryExtractionProgress & { status: AsyncTaskStatus.Success },
+ ) => {
+ await this.db
+ .update(asyncTasks)
+ .set({
+ metadata: sql`
+ jsonb_set(
+ jsonb_set(
+ jsonb_set(
+ ${asyncTasks.metadata},
+ '{progress,processedUsers}',
+ to_jsonb(${progress.processedUsers}::int),
+ true
+ ),
+ '{progress,scheduledBatches}',
+ to_jsonb(${progress.scheduledBatches}::int),
+ true
+ ),
+ '{progress,scheduledChildRuns}',
+ to_jsonb(${progress.scheduledChildRuns}::int),
+ true
+ )
+ `,
+ status: sql`
+ CASE
+ WHEN ${asyncTasks.status} = ${AsyncTaskStatus.Error} OR ${asyncTasks.error} IS NOT NULL
+ THEN ${AsyncTaskStatus.Error}
+ ELSE ${progress.status}
+ END
+ `,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(asyncTasks.id, taskId),
+ eq(asyncTasks.type, AsyncTaskType.UserMemoryExtractionHourly),
+ this.ownership(),
+ ),
+ );
+ };
+
+ isHourlyMemoryExtractionCancellationRequested = async (taskId: string) => {
+ const task = await this.findById(taskId);
+ if (!task || task.userId !== this.userId) return false;
+ if (task.type !== AsyncTaskType.UserMemoryExtractionHourly) return false;
+
+ const metadata = task.metadata as HourlyUserMemoryExtractionMetadata | undefined;
+ return Boolean(metadata?.control?.cancelRequestedAt);
+ };
+
/**
* make the task status to be `error` if the task is not finished in 20 seconds
*/
@@ -191,6 +294,7 @@ export const initUserMemoryExtractionMetadata = (
cancelledBy: metadata.control.cancelledBy,
upstash: metadata.control.upstash
? {
+ entryWorkflowRunId: metadata.control.upstash.entryWorkflowRunId,
workflowRunIds: metadata.control.upstash.workflowRunIds || [],
}
: undefined,
@@ -203,3 +307,42 @@ export const initUserMemoryExtractionMetadata = (
range: metadata?.range,
source: metadata?.source ?? 'chat_topic',
});
+
+/**
+ * Initializes hourly user memory extraction metadata.
+ *
+ * Use when:
+ * - Creating the batch-level hourly extraction async task
+ * - Normalizing persisted hourly extraction metadata before updates
+ *
+ * Expects:
+ * - `startedAt` is the ISO timestamp for the hourly scheduler run
+ *
+ * Returns:
+ * - Hourly metadata with progress counters defaulted to zero
+ */
+export const initHourlyUserMemoryExtractionMetadata = (
+ metadata: Partial<HourlyUserMemoryExtractionMetadata> & { startedAt: string },
+): HourlyUserMemoryExtractionMetadata => ({
+ control: metadata.control
+ ? {
+ cancelReason: metadata.control.cancelReason,
+ cancelRequestedAt: metadata.control.cancelRequestedAt,
+ cancelledBy: metadata.control.cancelledBy,
+ upstash: metadata.control.upstash
+ ? {
+ entryWorkflowRunId: metadata.control.upstash.entryWorkflowRunId,
+ workflowRunIds: metadata.control.upstash.workflowRunIds || [],
+ }
+ : undefined,
+ }
+ : undefined,
+ cursor: metadata.cursor,
+ progress: {
+ processedUsers: metadata.progress?.processedUsers ?? 0,
+ scheduledBatches: metadata.progress?.scheduledBatches ?? 0,
+ scheduledChildRuns: metadata.progress?.scheduledChildRuns ?? 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: metadata.startedAt,
+});
diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.ts
index 7ee19727cf4..4dd939a49e1 100644
--- a/packages/types/src/asyncTask.ts
+++ b/packages/types/src/asyncTask.ts
@@ -2,6 +2,7 @@ export enum AsyncTaskType {
Chunking = 'chunk',
Embedding = 'embedding',
ImageGeneration = 'image_generation',
+ UserMemoryExtractionHourly = 'user_memory_extraction:hourly',
UserMemoryExtractionWithChatTopic = 'user_memory_extraction:chat_topic',
VideoGeneration = 'video_generation',
}
@@ -122,30 +123,44 @@ export interface UserMemoryExtractionProgress {
totalTopics: number | null;
}
+/**
+ * Provider metadata for Upstash workflow-backed async task runs.
+ */
+export interface UpstashWorkflowRunMetadata {
+ /**
+ * Workflow run id of the wrapper run that created this async task.
+ */
+ entryWorkflowRunId?: string;
+ /**
+ * Known workflow run ids associated with this task.
+ */
+ workflowRunIds?: string[];
+}
+
+/**
+ * Shared cancellation metadata for memory extraction async tasks.
+ */
+export interface MemoryExtractionControlMetadata {
+ /**
+ * Who initiated cancellation.
+ */
+ cancelledBy?: 'system' | 'user' | 'webhook';
+ /**
+ * Human-readable reason for cancellation when available.
+ */
+ cancelReason?: string;
+ /**
+ * ISO timestamp indicating when cancellation was requested.
+ */
+ cancelRequestedAt?: string;
+ /**
+ * Provider-specific cancellation metadata.
+ */
+ upstash?: UpstashWorkflowRunMetadata;
+}
+
export interface UserMemoryExtractionMetadata {
- control?: {
- /**
- * Human-readable reason for cancellation when available.
- */
- cancelReason?: string;
- /**
- * ISO timestamp indicating when cancellation was requested.
- */
- cancelRequestedAt?: string;
- /**
- * Who initiated cancellation.
- */
- cancelledBy?: 'system' | 'user' | 'webhook';
- /**
- * Provider-specific cancellation metadata.
- */
- upstash?: {
- /**
- * Known workflow run ids associated with this task.
- */
- workflowRunIds?: string[];
- };
- };
+ control?: MemoryExtractionControlMetadata;
progress: UserMemoryExtractionProgress;
range?: {
from?: string;
@@ -154,6 +169,29 @@ export interface UserMemoryExtractionMetadata {
source: 'chat_topic';
}
+/**
+ * Progress counters for hourly user memory extraction scheduler runs.
+ */
+export interface HourlyUserMemoryExtractionProgress {
+ processedUsers: number;
+ scheduledBatches: number;
+ scheduledChildRuns: number;
+}
+
+/**
+ * Metadata persisted for hourly user memory extraction async tasks.
+ */
+export interface HourlyUserMemoryExtractionMetadata {
+ control?: MemoryExtractionControlMetadata;
+ cursor?: {
+ createdAt: string;
+ id: string;
+ };
+ progress: HourlyUserMemoryExtractionProgress;
+ source: 'hourly_chat_topic';
+ startedAt: string;
+}
+
export interface VideoGenerationTaskMetadata {
precharge?: Record<string, unknown>;
webhookToken?: string;
diff --git a/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.test.ts b/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.test.ts
new file mode 100644
index 00000000000..8cb21f681dd
--- /dev/null
+++ b/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.test.ts
@@ -0,0 +1,226 @@
+import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as AsyncTaskModelModule from '@/database/models/asyncTask';
+
+const mocks = vi.hoisted(() => ({
+ cancel: vi.fn(),
+ findFirst: vi.fn(),
+ update: vi.fn(),
+}));
+
+vi.mock('@upstash/workflow', () => ({
+ Client: vi.fn(() => ({
+ cancel: mocks.cancel,
+ })),
+}));
+
+vi.mock('@/database/models/asyncTask', async (importOriginal) => {
+ const actual = await importOriginal<typeof AsyncTaskModelModule>();
+
+ return {
+ ...actual,
+ AsyncTaskModel: vi.fn(() => ({
+ update: mocks.update,
+ })),
+ };
+});
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn(async () => ({
+ query: {
+ asyncTasks: {
+ findFirst: mocks.findFirst,
+ },
+ },
+ })),
+}));
+
+vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({
+ parseMemoryExtractionConfig: () => ({
+ webhook: { headers: { 'x-memory-secret': 'secret' } },
+ }),
+}));
+
+const { POST } = await import('./route');
+
+const createRequest = (body: Record<string, unknown>) =>
+ new Request(
+ 'https://app.example.com/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel',
+ {
+ body: JSON.stringify(body),
+ headers: {
+ 'content-type': 'application/json',
+ 'x-memory-secret': 'secret',
+ },
+ method: 'POST',
+ },
+ );
+
+describe('memory extraction cancel route', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv('QSTASH_TOKEN', 'test-qstash-token');
+ mocks.cancel.mockResolvedValue({ cancelled: 2 });
+ mocks.update.mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('cancels an hourly memory extraction task using stored and requested workflow run ids', async () => {
+ /**
+ * @example
+ * await POST(cancelHourlyTaskRequest);
+ */
+ mocks.findFirst.mockResolvedValue({
+ id: '00000000-0000-4000-8000-000000000001',
+ metadata: {
+ control: {
+ upstash: { workflowRunIds: ['root-run', 'child-run'] },
+ },
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T00:00:00.000Z',
+ },
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ userId: 'service-user',
+ workspaceId: null,
+ });
+
+ const response = await POST(
+ createRequest({
+ reason: 'operator stop',
+ taskId: '00000000-0000-4000-8000-000000000001',
+ workflowRunId: 'child-run',
+ workflowRunIds: ['late-run'],
+ }),
+ );
+
+ await expect(response.json()).resolves.toMatchObject({
+ cancelledWorkflowRuns: 2,
+ status: AsyncTaskStatus.Error,
+ taskId: '00000000-0000-4000-8000-000000000001',
+ });
+
+ expect(response.status).toBe(200);
+ expect(mocks.cancel).toHaveBeenCalledWith({ ids: ['root-run', 'child-run', 'late-run'] });
+ expect(mocks.update).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ control: expect.objectContaining({
+ cancelReason: 'operator stop',
+ cancelledBy: 'webhook',
+ upstash: { workflowRunIds: ['root-run', 'child-run', 'late-run'] },
+ }),
+ source: 'hourly_chat_topic',
+ }),
+ status: AsyncTaskStatus.Error,
+ }),
+ );
+ });
+
+ it('keeps manual chat-topic cancellation behavior', async () => {
+ /**
+ * @example
+ * await POST(cancelManualTaskRequest);
+ */
+ mocks.findFirst.mockResolvedValue({
+ id: '00000000-0000-4000-8000-000000000002',
+ metadata: {
+ control: {
+ upstash: { workflowRunIds: ['manual-run'] },
+ },
+ progress: {
+ completedTopics: 0,
+ failedTopics: 0,
+ totalTopics: 1,
+ },
+ source: 'chat_topic',
+ },
+ type: AsyncTaskType.UserMemoryExtractionWithChatTopic,
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+
+ const response = await POST(
+ createRequest({
+ taskId: '00000000-0000-4000-8000-000000000002',
+ userId: 'user-1',
+ }),
+ );
+
+ await expect(response.json()).resolves.toMatchObject({
+ cancelledWorkflowRuns: 2,
+ status: AsyncTaskStatus.Error,
+ taskId: '00000000-0000-4000-8000-000000000002',
+ });
+
+ expect(response.status).toBe(200);
+ expect(mocks.cancel).toHaveBeenCalledWith({ ids: ['manual-run'] });
+ expect(mocks.update).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000002',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ control: expect.objectContaining({
+ cancelledBy: 'webhook',
+ upstash: { workflowRunIds: ['manual-run'] },
+ }),
+ source: 'chat_topic',
+ }),
+ status: AsyncTaskStatus.Error,
+ }),
+ );
+ });
+
+ it('normalizes hourly tasks with missing metadata before cancellation', async () => {
+ /**
+ * @example
+ * await POST(cancelHourlyTaskWithMissingMetadataRequest);
+ */
+ mocks.findFirst.mockResolvedValue({
+ createdAt: new Date('2026-07-06T01:00:00.000Z'),
+ id: '00000000-0000-4000-8000-000000000003',
+ metadata: undefined,
+ type: AsyncTaskType.UserMemoryExtractionHourly,
+ userId: 'service-user',
+ workspaceId: null,
+ });
+
+ const response = await POST(
+ createRequest({
+ taskId: '00000000-0000-4000-8000-000000000003',
+ }),
+ );
+
+ await expect(response.json()).resolves.toMatchObject({
+ cancelledWorkflowRuns: 0,
+ status: AsyncTaskStatus.Error,
+ taskId: '00000000-0000-4000-8000-000000000003',
+ });
+
+ expect(response.status).toBe(200);
+ expect(mocks.cancel).not.toHaveBeenCalled();
+ expect(mocks.update).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000003',
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ progress: {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ },
+ source: 'hourly_chat_topic',
+ startedAt: '2026-07-06T01:00:00.000Z',
+ }),
+ status: AsyncTaskStatus.Error,
+ }),
+ );
+ });
+});
diff --git a/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.ts b/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.ts
index 041248f9c45..f05b9ab88e8 100644
--- a/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.ts
+++ b/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.ts
@@ -3,14 +3,19 @@ import {
AsyncTaskErrorType,
AsyncTaskStatus,
AsyncTaskType,
+ type HourlyUserMemoryExtractionMetadata,
type UserMemoryExtractionMetadata,
} from '@lobechat/types';
import { Client as WorkflowClient } from '@upstash/workflow';
-import { and, eq } from 'drizzle-orm';
+import { and, eq, inArray } from 'drizzle-orm';
import { NextResponse } from 'next/server';
import { z } from 'zod';
-import { AsyncTaskModel, initUserMemoryExtractionMetadata } from '@/database/models/asyncTask';
+import {
+ AsyncTaskModel,
+ initHourlyUserMemoryExtractionMetadata,
+ initUserMemoryExtractionMetadata,
+} from '@/database/models/asyncTask';
import { asyncTasks } from '@/database/schemas';
import { getServerDB } from '@/database/server';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
@@ -40,6 +45,26 @@ const getWorkflowClient = () => {
return new WorkflowClient(config);
};
+const supportedTaskTypes = [
+ AsyncTaskType.UserMemoryExtractionHourly,
+ AsyncTaskType.UserMemoryExtractionWithChatTopic,
+];
+
+const initMemoryExtractionMetadata = (task: typeof asyncTasks.$inferSelect) => {
+ if (task.type === AsyncTaskType.UserMemoryExtractionHourly) {
+ const metadata = task.metadata as Partial<HourlyUserMemoryExtractionMetadata> | undefined;
+
+ return initHourlyUserMemoryExtractionMetadata({
+ ...metadata,
+ startedAt: metadata?.startedAt || task.createdAt?.toISOString() || new Date().toISOString(),
+ });
+ }
+
+ return initUserMemoryExtractionMetadata(
+ task.metadata as UserMemoryExtractionMetadata | undefined,
+ );
+};
+
export const POST = async (req: Request) => {
const { webhook } = parseMemoryExtractionConfig();
@@ -60,10 +85,7 @@ export const POST = async (req: Request) => {
const db = await getServerDB();
const task = await db.query.asyncTasks.findFirst({
- where: and(
- eq(asyncTasks.id, payload.taskId),
- eq(asyncTasks.type, AsyncTaskType.UserMemoryExtractionWithChatTopic),
- ),
+ where: and(eq(asyncTasks.id, payload.taskId), inArray(asyncTasks.type, supportedTaskTypes)),
});
if (!task) {
@@ -80,9 +102,7 @@ export const POST = async (req: Request) => {
);
}
- const metadata = initUserMemoryExtractionMetadata(
- task.metadata as UserMemoryExtractionMetadata | undefined,
- );
+ const metadata = initMemoryExtractionMetadata(task);
const workflowRunIds = Array.from(
new Set([
@@ -92,13 +112,14 @@ export const POST = async (req: Request) => {
]),
);
- const nextMetadata: UserMemoryExtractionMetadata = {
+ const nextMetadata: typeof metadata = {
...metadata,
control: {
cancelReason: payload.reason || metadata.control?.cancelReason,
cancelRequestedAt: metadata.control?.cancelRequestedAt || new Date().toISOString(),
cancelledBy: 'webhook',
upstash: {
+ ...metadata.control?.upstash,
workflowRunIds,
},
},
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/hourly.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/hourly.test.ts
index 78595f0047d..81122b7b099 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/hourly.test.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/hourly.test.ts
@@ -1,11 +1,16 @@
+import { AsyncTaskStatus } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { hourlyWorkflowHandler } from '../hourly';
const mocks = vi.hoisted(() => ({
+ appendUserMemoryWorkflowRunIds: vi.fn(),
createExecutor: vi.fn(),
getUsersForHourlyExtraction: vi.fn(),
+ isHourlyMemoryExtractionCancellationRequested: vi.fn(),
+ markHourlyMemoryExtractionSuccess: vi.fn(),
triggerHourly: vi.fn(),
+ triggerHourlyTracked: vi.fn(),
triggerProcessUsers: vi.fn(),
}));
@@ -30,11 +35,31 @@ vi.mock('@/server/services/memory/userMemory/extract', () => ({
},
MemoryExtractionWorkflowService: {
triggerHourly: mocks.triggerHourly,
+ triggerHourlyTracked: mocks.triggerHourlyTracked,
triggerProcessUsers: mocks.triggerProcessUsers,
},
normalizeMemoryExtractionPayload: (payload: unknown) => payload,
}));
+vi.mock('@/database/models/asyncTask', () => ({
+ AsyncTaskModel: vi.fn(() => ({
+ appendUserMemoryWorkflowRunIds: mocks.appendUserMemoryWorkflowRunIds,
+ isHourlyMemoryExtractionCancellationRequested:
+ mocks.isHourlyMemoryExtractionCancellationRequested,
+ markHourlyMemoryExtractionSuccess: mocks.markHourlyMemoryExtractionSuccess,
+ })),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn(async () => ({
+ query: {
+ asyncTasks: {
+ findFirst: vi.fn(async () => ({ userId: 'hourly-task-user', workspaceId: null })),
+ },
+ },
+ })),
+}));
+
vi.mock('../runGuard', () => ({
checkGuard: vi.fn().mockResolvedValue({ result: true }),
ensureWorkflowStarted: vi.fn().mockResolvedValue({ started: true }),
@@ -46,10 +71,48 @@ describe('hourlyWorkflowHandler', () => {
mocks.createExecutor.mockResolvedValue({
getUsersForHourlyExtraction: mocks.getUsersForHourlyExtraction,
});
+ mocks.appendUserMemoryWorkflowRunIds.mockResolvedValue(undefined);
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(false);
+ mocks.markHourlyMemoryExtractionSuccess.mockResolvedValue(undefined);
mocks.triggerHourly.mockResolvedValue({ workflowRunId: 'next-page-run' });
+ mocks.triggerHourlyTracked.mockResolvedValue({
+ taskId: '00000000-0000-4000-8000-000000000001',
+ workflowRunId: 'tracked-hourly-run',
+ });
mocks.triggerProcessUsers.mockResolvedValue({ workflowRunId: 'process-users-run' });
});
+ it('creates a tracked hourly task when the entrypoint has no hourlyTaskId', async () => {
+ /**
+ * @example
+ * await expect(hourlyWorkflowHandler(cronContext)).resolves.toMatchObject({ scheduled: true });
+ */
+ const context = {
+ requestPayload: { dryRun: true },
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ workflowRunId: 'entry-hourly-run',
+ };
+
+ await expect(hourlyWorkflowHandler(context as never)).resolves.toEqual({
+ dryRun: true,
+ message: 'Tracked hourly memory extraction task scheduled.',
+ scheduled: true,
+ taskId: '00000000-0000-4000-8000-000000000001',
+ workflowRunId: 'tracked-hourly-run',
+ });
+
+ expect(mocks.triggerHourlyTracked).toHaveBeenCalledWith(
+ {
+ baseUrl: 'https://app.example.com',
+ cursor: undefined,
+ dryRun: true,
+ },
+ { entryWorkflowRunId: 'entry-hourly-run', extraHeaders: {} },
+ );
+ expect(mocks.createExecutor).not.toHaveBeenCalled();
+ expect(mocks.triggerProcessUsers).not.toHaveBeenCalled();
+ });
+
it('continues pagination when Upstash restores the user batch cursor as JSON', async () => {
/**
* @example
@@ -73,7 +136,10 @@ describe('hourlyWorkflowHandler', () => {
});
const context = {
- requestPayload: { dryRun: true },
+ requestPayload: {
+ dryRun: true,
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ },
run: vi.fn((_name: string, callback: () => unknown) => callback()),
};
@@ -91,8 +157,90 @@ describe('hourlyWorkflowHandler', () => {
id: 'user_2igX4ULK7Q2tADwibFkEpng0xRc',
},
dryRun: true,
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
},
{ extraHeaders: {} },
);
});
+
+ it('propagates hourlyTaskId and records process-users workflow run ids', async () => {
+ /**
+ * @example
+ * await hourlyWorkflowHandler(contextWithHourlyTask);
+ */
+ mocks.getUsersForHourlyExtraction.mockResolvedValue({
+ ids: Array.from({ length: 21 }, (_, index) => `user-${index + 1}`),
+ });
+
+ const context = {
+ requestPayload: { hourlyTaskId: '00000000-0000-4000-8000-000000000001' },
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ };
+
+ await expect(hourlyWorkflowHandler(context as never)).resolves.toMatchObject({
+ processedUsers: 21,
+ scheduledBatches: 2,
+ });
+
+ expect(mocks.triggerProcessUsers).toHaveBeenCalledWith(
+ expect.objectContaining({
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ userIds: expect.any(Array),
+ }),
+ { extraHeaders: {} },
+ );
+ expect(mocks.appendUserMemoryWorkflowRunIds).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ ['process-users-run'],
+ );
+ });
+
+ it('skips hourly fan-out when the hourly task is cancelled', async () => {
+ /**
+ * @example
+ * await expect(hourlyWorkflowHandler(context)).resolves.toMatchObject({ skipped: true });
+ */
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(true);
+ mocks.getUsersForHourlyExtraction.mockResolvedValue({
+ ids: ['user-1'],
+ });
+
+ const context = {
+ requestPayload: { hourlyTaskId: '00000000-0000-4000-8000-000000000001' },
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ };
+
+ await expect(hourlyWorkflowHandler(context as never)).resolves.toEqual({
+ message: 'Hourly memory extraction task cancellation requested, skip hourly fan-out.',
+ processedUsers: 0,
+ skipped: true,
+ });
+ expect(mocks.triggerProcessUsers).not.toHaveBeenCalled();
+ });
+
+ it('marks the hourly task as success when the final user page has been scheduled', async () => {
+ mocks.getUsersForHourlyExtraction.mockResolvedValue({
+ ids: Array.from({ length: 21 }, (_, index) => `user-${index + 1}`),
+ });
+
+ const context = {
+ requestPayload: { hourlyTaskId: '00000000-0000-4000-8000-000000000001' },
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ };
+
+ await expect(hourlyWorkflowHandler(context as never)).resolves.toMatchObject({
+ processedUsers: 21,
+ scheduledBatches: 2,
+ });
+
+ expect(mocks.markHourlyMemoryExtractionSuccess).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ {
+ processedUsers: 21,
+ scheduledBatches: 2,
+ scheduledChildRuns: 2,
+ status: AsyncTaskStatus.Success,
+ },
+ );
+ });
});
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
index 9b13e4c1d93..4aa4827542d 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
@@ -1,17 +1,21 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ buildUserPersonaJobInput: vi.fn(),
checkGuard: vi.fn(),
+ composeWriting: vi.fn(),
ensureWorkflowStarted: vi.fn(),
+ getServerDB: vi.fn(),
+ isHourlyMemoryExtractionCancellationRequested: vi.fn(),
}));
vi.mock('@/database/server', () => ({
- getServerDB: vi.fn(),
+ getServerDB: mocks.getServerDB,
}));
vi.mock('@/server/services/memory/userMemory/persona/service', () => ({
- buildUserPersonaJobInput: vi.fn(),
- UserPersonaService: vi.fn(),
+ buildUserPersonaJobInput: mocks.buildUserPersonaJobInput,
+ UserPersonaService: vi.fn(() => ({ composeWriting: mocks.composeWriting })),
}));
vi.mock('../runGuard', () => ({
@@ -19,13 +23,22 @@ vi.mock('../runGuard', () => ({
ensureWorkflowStarted: mocks.ensureWorkflowStarted,
}));
+vi.mock('../utils', () => ({
+ isHourlyMemoryExtractionCancelled: mocks.isHourlyMemoryExtractionCancellationRequested,
+}));
+
const { personaUpdateHandler } = await import('../personaUpdate');
describe('personaUpdateHandler run guard', () => {
beforeEach(() => {
mocks.checkGuard.mockReset();
+ mocks.composeWriting.mockReset();
mocks.ensureWorkflowStarted.mockReset();
+ mocks.getServerDB.mockReset();
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockReset();
mocks.ensureWorkflowStarted.mockResolvedValue({ started: true });
+ mocks.getServerDB.mockResolvedValue({});
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(false);
});
it('starts the workflow before checking the run guard or parsing payload', async () => {
@@ -70,4 +83,33 @@ describe('personaUpdateHandler run guard', () => {
{ response: { processedUsers: 0 } },
);
});
+
+ it('skips persona writing when the hourly task is cancelled', async () => {
+ /**
+ * @example
+ * await expect(personaUpdateHandler(context)).resolves.toMatchObject({ processedUsers: 0 });
+ */
+ mocks.checkGuard.mockResolvedValue({ result: true });
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(true);
+
+ const context = {
+ requestPayload: {
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ userIds: ['user-1'],
+ },
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+ workflowRunId: 'wfr_persona',
+ };
+
+ await expect(personaUpdateHandler(context as never)).resolves.toEqual({
+ message: 'User persona processed via workflow.',
+ processedUsers: 0,
+ });
+
+ expect(mocks.isHourlyMemoryExtractionCancellationRequested).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ );
+ expect(mocks.buildUserPersonaJobInput).not.toHaveBeenCalled();
+ expect(mocks.composeWriting).not.toHaveBeenCalled();
+ });
});
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processTopic.hourlyTask.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processTopic.hourlyTask.test.ts
new file mode 100644
index 00000000000..363bf5715fc
--- /dev/null
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processTopic.hourlyTask.test.ts
@@ -0,0 +1,122 @@
+import { MemorySourceType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { processTopicHandler } from '../processTopic';
+
+const mocks = vi.hoisted(() => ({
+ createExecutor: vi.fn(),
+ extractTopic: vi.fn(),
+ isHourlyMemoryExtractionCancellationRequested: vi.fn(),
+}));
+
+vi.mock('@lobechat/observability-otel/modules/upstash-workflow', () => ({
+ buildUpstashWorkflowMetricAttributes: vi.fn(() => ({})),
+ tracer: {
+ startActiveSpan: vi.fn((_name: string, callback: (span: unknown) => unknown) =>
+ callback({
+ end: vi.fn(),
+ recordException: vi.fn(),
+ setAttributes: vi.fn(),
+ setStatus: vi.fn(),
+ }),
+ ),
+ },
+}));
+
+vi.mock('@/server/services/memory/userMemory/extract', () => ({
+ MemoryExtractionExecutor: {
+ create: mocks.createExecutor,
+ },
+ normalizeMemoryExtractionPayload: (payload: Record<string, unknown>) => ({
+ ...payload,
+ forceAll: payload.forceAll ?? false,
+ forceTopics: payload.forceTopics ?? false,
+ layers: payload.layers ?? [],
+ mode: payload.mode ?? 'workflow',
+ sources: payload.sources ?? [],
+ topicFanoutCount: payload.topicFanoutCount ?? 0,
+ topicIds: payload.topicIds ?? [],
+ userIds: payload.userIds ?? [],
+ }),
+}));
+
+vi.mock('@/database/models/asyncTask', () => ({
+ AsyncTaskModel: vi.fn(() => ({
+ isHourlyMemoryExtractionCancellationRequested:
+ mocks.isHourlyMemoryExtractionCancellationRequested,
+ })),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn(async () => ({
+ query: {
+ asyncTasks: {
+ findFirst: vi.fn(async () => ({ userId: 'hourly-task-user', workspaceId: null })),
+ },
+ },
+ })),
+}));
+
+vi.mock('../runGuard', () => ({
+ checkGuard: vi.fn().mockResolvedValue({ result: true }),
+ ensureWorkflowStarted: vi.fn().mockResolvedValue({ started: true }),
+}));
+
+const createContext = (requestPayload: Record<string, unknown>) => ({
+ requestPayload,
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+});
+
+describe('processTopicHandler hourly task behavior', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createExecutor.mockResolvedValue({ extractTopic: mocks.extractTopic });
+ mocks.extractTopic.mockResolvedValue(undefined);
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(false);
+ });
+
+ it('checks hourly cancellation before CEPA and identity extraction', async () => {
+ /**
+ * @example
+ * await processTopicHandler(contextWithHourlyTask);
+ */
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ topicIds: ['t1'],
+ userIds: ['u1'],
+ });
+
+ await expect(processTopicHandler(context as never)).resolves.toMatchObject({
+ processedTopics: 1,
+ processedUsers: 1,
+ });
+
+ expect(mocks.isHourlyMemoryExtractionCancellationRequested).toHaveBeenCalledTimes(2);
+ expect(mocks.extractTopic).toHaveBeenCalledTimes(2);
+ });
+
+ it('skips CEPA extraction when the hourly task is cancelled before heavy work', async () => {
+ /**
+ * @example
+ * await expect(processTopicHandler(context)).resolves.toMatchObject({ skipped: true });
+ */
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(true);
+
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ topicIds: ['t1'],
+ userIds: ['u1'],
+ });
+
+ await expect(processTopicHandler(context as never)).resolves.toEqual({
+ message: 'Hourly memory extraction task cancellation requested, skip topic.',
+ skipped: true,
+ });
+ expect(mocks.createExecutor).not.toHaveBeenCalled();
+ expect(mocks.extractTopic).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processTopics.hourlyTask.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processTopics.hourlyTask.test.ts
new file mode 100644
index 00000000000..fb35f6aed20
--- /dev/null
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processTopics.hourlyTask.test.ts
@@ -0,0 +1,153 @@
+import { MemorySourceType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { processTopicsHandler } from '../processTopics';
+
+const mocks = vi.hoisted(() => ({
+ appendUserMemoryWorkflowRunIds: vi.fn(),
+ isHourlyMemoryExtractionCancellationRequested: vi.fn(),
+ triggerPersonaUpdate: vi.fn(),
+ triggerProcessTopic: vi.fn(),
+}));
+
+vi.mock('@lobechat/observability-otel/modules/upstash-workflow', () => ({
+ buildUpstashWorkflowMetricAttributes: vi.fn(() => ({})),
+ tracer: {
+ startActiveSpan: vi.fn((_name: string, callback: (span: unknown) => unknown) =>
+ callback({
+ end: vi.fn(),
+ recordException: vi.fn(),
+ setAttributes: vi.fn(),
+ setStatus: vi.fn(),
+ }),
+ ),
+ },
+}));
+
+vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({
+ parseMemoryExtractionConfig: () => ({
+ upstashWorkflowExtraHeaders: {},
+ }),
+}));
+
+vi.mock('@/server/services/memory/userMemory/extract', () => ({
+ buildWorkflowPayloadInput: (payload: unknown) => payload,
+ MemoryExtractionWorkflowService: {
+ triggerPersonaUpdate: mocks.triggerPersonaUpdate,
+ triggerProcessTopic: mocks.triggerProcessTopic,
+ },
+ normalizeMemoryExtractionPayload: (payload: Record<string, unknown>) => ({
+ ...payload,
+ forceAll: payload.forceAll ?? false,
+ forceTopics: payload.forceTopics ?? false,
+ layers: payload.layers ?? [],
+ mode: payload.mode ?? 'workflow',
+ sources: payload.sources ?? [],
+ topicFanoutCount: payload.topicFanoutCount ?? 0,
+ topicIds: payload.topicIds ?? [],
+ userIds: payload.userIds ?? [],
+ }),
+}));
+
+vi.mock('@/database/models/asyncTask', () => ({
+ AsyncTaskModel: vi.fn(() => ({
+ appendUserMemoryWorkflowRunIds: mocks.appendUserMemoryWorkflowRunIds,
+ isHourlyMemoryExtractionCancellationRequested:
+ mocks.isHourlyMemoryExtractionCancellationRequested,
+ })),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn(async () => ({
+ query: {
+ asyncTasks: {
+ findFirst: vi.fn(async () => ({ userId: 'hourly-task-user', workspaceId: null })),
+ },
+ },
+ })),
+}));
+
+vi.mock('../runGuard', () => ({
+ checkGuard: vi.fn().mockResolvedValue({ result: true }),
+ ensureWorkflowStarted: vi.fn().mockResolvedValue({ started: true }),
+}));
+
+const createContext = (requestPayload: Record<string, unknown>) => ({
+ requestPayload,
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+});
+
+describe('processTopicsHandler hourly task behavior', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.appendUserMemoryWorkflowRunIds.mockResolvedValue(undefined);
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(false);
+ mocks.triggerPersonaUpdate.mockResolvedValue({ workflowRunId: 'persona-update-run' });
+ mocks.triggerProcessTopic.mockResolvedValue({ workflowRunId: 'process-topic-run' });
+ });
+
+ it('propagates hourlyTaskId and records process-topic plus persona workflow run ids', async () => {
+ /**
+ * @example
+ * await processTopicsHandler(contextWithHourlyTask);
+ */
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ topicIds: ['t1'],
+ userIds: ['u1'],
+ });
+
+ await expect(processTopicsHandler(context as never)).resolves.toMatchObject({
+ processedTopics: 1,
+ processedUsers: 1,
+ });
+
+ expect(mocks.triggerProcessTopic).toHaveBeenCalledWith(
+ 'u1',
+ expect.objectContaining({
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ topicIds: ['t1'],
+ }),
+ { extraHeaders: {} },
+ );
+ expect(mocks.appendUserMemoryWorkflowRunIds).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ ['process-topic-run'],
+ );
+ expect(mocks.triggerPersonaUpdate).toHaveBeenCalledWith('u1', 'https://app.example.com', {
+ extraHeaders: {},
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ });
+ expect(mocks.appendUserMemoryWorkflowRunIds).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ ['persona-update-run'],
+ );
+ });
+
+ it('skips topic fan-out and persona update when the hourly task is cancelled', async () => {
+ /**
+ * @example
+ * await expect(processTopicsHandler(context)).resolves.toMatchObject({ skipped: true });
+ */
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(true);
+
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ topicIds: ['t1'],
+ userIds: ['u1'],
+ });
+
+ await expect(processTopicsHandler(context as never)).resolves.toEqual({
+ message: 'Hourly memory extraction task cancellation requested, skip topic batch.',
+ processedTopics: 0,
+ processedUsers: 0,
+ skipped: true,
+ });
+ expect(mocks.triggerProcessTopic).not.toHaveBeenCalled();
+ expect(mocks.triggerPersonaUpdate).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUserTopics.hourlyTask.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUserTopics.hourlyTask.test.ts
new file mode 100644
index 00000000000..c66c0fe2e11
--- /dev/null
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUserTopics.hourlyTask.test.ts
@@ -0,0 +1,134 @@
+import { MemorySourceType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { processUserTopicsHandler } from '../processUserTopics';
+
+const mocks = vi.hoisted(() => ({
+ appendUserMemoryWorkflowRunIds: vi.fn(),
+ createExecutor: vi.fn(),
+ getTopicsForUser: vi.fn(),
+ isHourlyMemoryExtractionCancellationRequested: vi.fn(),
+ triggerProcessTopics: vi.fn(),
+ triggerProcessUserTopics: vi.fn(),
+}));
+
+vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({
+ parseMemoryExtractionConfig: () => ({
+ upstashWorkflowExtraHeaders: {},
+ workflow: { maxTopicsPerUserPerRun: 10 },
+ }),
+}));
+
+vi.mock('@/server/services/memory/userMemory/extract', () => ({
+ buildWorkflowPayloadInput: (payload: unknown) => payload,
+ MemoryExtractionExecutor: {
+ create: mocks.createExecutor,
+ },
+ MemoryExtractionWorkflowService: {
+ triggerProcessTopics: mocks.triggerProcessTopics,
+ triggerProcessUserTopics: mocks.triggerProcessUserTopics,
+ },
+ normalizeMemoryExtractionPayload: (payload: Record<string, unknown>) => ({
+ ...payload,
+ layers: payload.layers ?? [],
+ mode: payload.mode ?? 'workflow',
+ sources: payload.sources ?? [],
+ topicFanoutCount: payload.topicFanoutCount ?? 0,
+ topicIds: payload.topicIds ?? [],
+ userIds: payload.userIds ?? [],
+ }),
+}));
+
+vi.mock('@/database/models/asyncTask', () => ({
+ AsyncTaskModel: vi.fn(() => ({
+ appendUserMemoryWorkflowRunIds: mocks.appendUserMemoryWorkflowRunIds,
+ isHourlyMemoryExtractionCancellationRequested:
+ mocks.isHourlyMemoryExtractionCancellationRequested,
+ })),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn(async () => ({
+ query: {
+ asyncTasks: {
+ findFirst: vi.fn(async () => ({ userId: 'hourly-task-user', workspaceId: null })),
+ },
+ },
+ })),
+}));
+
+vi.mock('../runGuard', () => ({
+ checkGuard: vi.fn().mockResolvedValue({ result: true }),
+ ensureWorkflowStarted: vi.fn().mockResolvedValue({ started: true }),
+}));
+
+const createContext = (requestPayload: Record<string, unknown>) => ({
+ requestPayload,
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+});
+
+describe('processUserTopicsHandler hourly task behavior', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.appendUserMemoryWorkflowRunIds.mockResolvedValue(undefined);
+ mocks.createExecutor.mockResolvedValue({ getTopicsForUser: mocks.getTopicsForUser });
+ mocks.getTopicsForUser.mockResolvedValue({ ids: ['t1', 't2'] });
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(false);
+ mocks.triggerProcessTopics.mockResolvedValue({ workflowRunId: 'process-topics-run' });
+ mocks.triggerProcessUserTopics.mockResolvedValue({ workflowRunId: 'next-user-topics-run' });
+ });
+
+ it('propagates hourlyTaskId and records process-topics workflow run ids', async () => {
+ /**
+ * @example
+ * await processUserTopicsHandler(contextWithHourlyTask);
+ */
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ userIds: ['u1'],
+ });
+
+ await expect(processUserTopicsHandler(context as never)).resolves.toEqual({
+ processedUsers: 1,
+ });
+
+ expect(mocks.triggerProcessTopics).toHaveBeenCalledWith(
+ 'u1',
+ expect.objectContaining({
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ topicIds: ['t1', 't2'],
+ }),
+ { extraHeaders: {} },
+ );
+ expect(mocks.appendUserMemoryWorkflowRunIds).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ ['process-topics-run'],
+ );
+ });
+
+ it('skips process-user-topics fan-out when the hourly task is cancelled', async () => {
+ /**
+ * @example
+ * await expect(processUserTopicsHandler(context)).resolves.toMatchObject({ skipped: true });
+ */
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(true);
+
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ userIds: ['u1'],
+ });
+
+ await expect(processUserTopicsHandler(context as never)).resolves.toEqual({
+ message: 'Hourly memory extraction task cancellation requested, skip user topic fan-out.',
+ processedUsers: 0,
+ skipped: true,
+ });
+ expect(mocks.createExecutor).not.toHaveBeenCalled();
+ expect(mocks.getTopicsForUser).not.toHaveBeenCalled();
+ expect(mocks.triggerProcessTopics).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUsers.hourlyTask.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUsers.hourlyTask.test.ts
new file mode 100644
index 00000000000..fa3eb263b9f
--- /dev/null
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUsers.hourlyTask.test.ts
@@ -0,0 +1,130 @@
+import { MemorySourceType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { processUsersHandler } from '../processUsers';
+
+const mocks = vi.hoisted(() => ({
+ appendUserMemoryWorkflowRunIds: vi.fn(),
+ createExecutor: vi.fn(),
+ getUsers: vi.fn(),
+ isHourlyMemoryExtractionCancellationRequested: vi.fn(),
+ triggerProcessUsers: vi.fn(),
+ triggerProcessUserTopics: vi.fn(),
+}));
+
+vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({
+ parseMemoryExtractionConfig: () => ({
+ upstashWorkflowExtraHeaders: {},
+ }),
+}));
+
+vi.mock('@/server/services/memory/userMemory/extract', () => ({
+ buildWorkflowPayloadInput: (payload: unknown) => payload,
+ MemoryExtractionExecutor: {
+ create: mocks.createExecutor,
+ },
+ MemoryExtractionWorkflowService: {
+ triggerProcessUsers: mocks.triggerProcessUsers,
+ triggerProcessUserTopics: mocks.triggerProcessUserTopics,
+ },
+ normalizeMemoryExtractionPayload: (payload: Record<string, unknown>) => ({
+ ...payload,
+ layers: payload.layers ?? [],
+ mode: payload.mode ?? 'workflow',
+ sources: payload.sources ?? [],
+ topicFanoutCount: payload.topicFanoutCount ?? 0,
+ topicIds: payload.topicIds ?? [],
+ userIds: payload.userIds ?? [],
+ }),
+}));
+
+vi.mock('@/database/models/asyncTask', () => ({
+ AsyncTaskModel: vi.fn(() => ({
+ appendUserMemoryWorkflowRunIds: mocks.appendUserMemoryWorkflowRunIds,
+ isHourlyMemoryExtractionCancellationRequested:
+ mocks.isHourlyMemoryExtractionCancellationRequested,
+ })),
+}));
+
+vi.mock('@/database/server', () => ({
+ getServerDB: vi.fn(async () => ({
+ query: {
+ asyncTasks: {
+ findFirst: vi.fn(async () => ({ userId: 'hourly-task-user', workspaceId: null })),
+ },
+ },
+ })),
+}));
+
+vi.mock('../runGuard', () => ({
+ checkGuard: vi.fn().mockResolvedValue({ result: true }),
+ ensureWorkflowStarted: vi.fn().mockResolvedValue({ started: true }),
+}));
+
+const createContext = (requestPayload: Record<string, unknown>) => ({
+ requestPayload,
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+});
+
+describe('processUsersHandler hourly task behavior', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.appendUserMemoryWorkflowRunIds.mockResolvedValue(undefined);
+ mocks.createExecutor.mockResolvedValue({ getUsers: mocks.getUsers });
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(false);
+ mocks.triggerProcessUsers.mockResolvedValue({ workflowRunId: 'next-process-users-run' });
+ mocks.triggerProcessUserTopics.mockResolvedValue({ workflowRunId: 'process-user-topics-run' });
+ });
+
+ it('propagates hourlyTaskId and records process-user-topics workflow run ids', async () => {
+ /**
+ * @example
+ * await processUsersHandler(contextWithHourlyTask);
+ */
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ userIds: ['u1', 'u2'],
+ });
+
+ await expect(processUsersHandler(context as never)).resolves.toMatchObject({
+ processedUsers: 2,
+ });
+
+ expect(mocks.triggerProcessUserTopics).toHaveBeenCalledWith(
+ expect.objectContaining({
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ userIds: ['u1', 'u2'],
+ }),
+ { extraHeaders: {} },
+ );
+ expect(mocks.appendUserMemoryWorkflowRunIds).toHaveBeenCalledWith(
+ '00000000-0000-4000-8000-000000000001',
+ ['process-user-topics-run'],
+ );
+ });
+
+ it('skips process-users fan-out when the hourly task is cancelled', async () => {
+ /**
+ * @example
+ * await expect(processUsersHandler(context)).resolves.toMatchObject({ skipped: true });
+ */
+ mocks.isHourlyMemoryExtractionCancellationRequested.mockResolvedValue(true);
+
+ const context = createContext({
+ baseUrl: 'https://app.example.com',
+ hourlyTaskId: '00000000-0000-4000-8000-000000000001',
+ sources: [MemorySourceType.ChatTopic],
+ userIds: ['u1'],
+ });
+
+ await expect(processUsersHandler(context as never)).resolves.toEqual({
+ message: 'Hourly memory extraction task cancellation requested, skip processing users.',
+ skipped: true,
+ });
+ expect(mocks.createExecutor).not.toHaveBeenCalled();
+ expect(mocks.getUsers).not.toHaveBeenCalled();
+ expect(mocks.triggerProcessUserTopics).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts b/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts
index 74001bdefef..15c9b2ac07d 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts
@@ -13,7 +13,12 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
-import { serializeWorkflowCursor } from './utils';
+import {
+ appendHourlyWorkflowRunId,
+ isHourlyMemoryExtractionCancelled,
+ markHourlyMemoryExtractionSuccess,
+ serializeWorkflowCursor,
+} from './utils';
const USER_PAGE_SIZE = 200;
const USER_BATCH_SIZE = 20;
@@ -28,7 +33,7 @@ export const hourlyWorkflowHandler = async (
) => {
await ensureWorkflowStarted(context, WORKFLOW_PATH);
- const { cursor, dryRun } = context.requestPayload || {};
+ const { cursor, dryRun, hourlyTaskId } = context.requestPayload || {};
// NOTICE: A run guard match must terminate the workflow by returning, never by throwing.
// Throwing before the first step makes Upstash re-enqueue the run, turning a "disable" guard
@@ -43,6 +48,55 @@ export const hourlyWorkflowHandler = async (
throw new Error('Missing baseUrl for hourly memory extraction workflow');
}
+ if (!hourlyTaskId) {
+ const stepName = 'memory:user-memory:hourly:create-tracked-task';
+ const guard = await checkGuard(context, WORKFLOW_PATH, {
+ response: { processedUsers: 0 },
+ stepName,
+ });
+ if (!guard.result) return guard.response;
+
+ const result = await context.run(stepName, () =>
+ MemoryExtractionWorkflowService.triggerHourlyTracked(
+ {
+ baseUrl,
+ cursor,
+ dryRun,
+ },
+ {
+ entryWorkflowRunId: context.workflowRunId,
+ extraHeaders: upstashWorkflowExtraHeaders,
+ },
+ ),
+ );
+
+ return {
+ dryRun: !!dryRun,
+ message: 'Tracked hourly memory extraction task scheduled.',
+ scheduled: true,
+ taskId: result.taskId,
+ workflowRunId: result.workflowRunId,
+ };
+ }
+
+ const cancellationStepName = 'memory:user-memory:hourly:cancel-check';
+ const cancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ response: { processedUsers: 0 },
+ stepName: cancellationStepName,
+ });
+ if (!cancellationGuard.result) return cancellationGuard.response;
+
+ const cancelled = await context.run(cancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(hourlyTaskId),
+ );
+ if (cancelled) {
+ return {
+ message: 'Hourly memory extraction task cancellation requested, skip hourly fan-out.',
+ processedUsers: 0,
+ skipped: true,
+ };
+ }
+
const parsedCursor = cursor
? { createdAt: new Date(cursor.createdAt), id: cursor.id }
: undefined;
@@ -64,6 +118,12 @@ export const hourlyWorkflowHandler = async (
const userIds = userBatch.ids;
if (userIds.length === 0) {
+ await markHourlyMemoryExtractionSuccess(hourlyTaskId, {
+ processedUsers: 0,
+ scheduledBatches: 0,
+ scheduledChildRuns: 0,
+ });
+
return { message: 'No eligible users for hourly memory extraction.', processedUsers: 0 };
}
@@ -74,8 +134,8 @@ export const hourlyWorkflowHandler = async (
)
: undefined;
+ const batches = dryRun ? [] : chunk(userIds, USER_BATCH_SIZE);
if (!dryRun) {
- const batches = chunk(userIds, USER_BATCH_SIZE);
for (const [index, batchUserIds] of batches.entries()) {
const stepName = `memory:user-memory:hourly:trigger-users:${index}`;
const guard = await checkGuard(context, WORKFLOW_PATH, {
@@ -84,11 +144,12 @@ export const hourlyWorkflowHandler = async (
});
if (!guard.result) return guard.response;
- await context.run(stepName, () =>
+ const result = await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUsers(
buildWorkflowPayloadInput(
normalizeMemoryExtractionPayload({
baseUrl,
+ hourlyTaskId,
mode: 'workflow',
sources: [MemorySourceType.ChatTopic],
userIds: batchUserIds,
@@ -97,10 +158,29 @@ export const hourlyWorkflowHandler = async (
{ extraHeaders: upstashWorkflowExtraHeaders },
),
);
+ await appendHourlyWorkflowRunId(hourlyTaskId, result.workflowRunId);
}
}
if (nextCursor) {
+ const cancellationStepName = 'memory:user-memory:hourly:cancel-check:next-page';
+ const cancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ response: { processedUsers: 0 },
+ stepName: cancellationStepName,
+ });
+ if (!cancellationGuard.result) return cancellationGuard.response;
+
+ const cancelled = await context.run(cancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(hourlyTaskId),
+ );
+ if (cancelled) {
+ return {
+ message: 'Hourly memory extraction task cancellation requested, skip next hourly page.',
+ processedUsers: userIds.length,
+ skipped: true,
+ };
+ }
+
const stepName = 'memory:user-memory:hourly:schedule-next-page';
const guard = await checkGuard(context, WORKFLOW_PATH, {
response: { processedUsers: 0 },
@@ -108,23 +188,33 @@ export const hourlyWorkflowHandler = async (
});
if (!guard.result) return guard.response;
- await context.run(stepName, () =>
+ const result = await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerHourly(
{
baseUrl,
cursor: nextCursor,
dryRun,
+ hourlyTaskId,
},
{ extraHeaders: upstashWorkflowExtraHeaders },
),
);
+ await appendHourlyWorkflowRunId(hourlyTaskId, result.workflowRunId);
+ }
+
+ if (!nextCursor) {
+ await markHourlyMemoryExtractionSuccess(hourlyTaskId, {
+ processedUsers: userIds.length,
+ scheduledBatches: batches.length,
+ scheduledChildRuns: batches.length,
+ });
}
return {
dryRun: !!dryRun,
hasNextPage: !!nextCursor,
processedUsers: userIds.length,
- scheduledBatches: dryRun ? 0 : chunk(userIds, USER_BATCH_SIZE).length,
+ scheduledBatches: batches.length,
};
};
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
index f1b4cc2da1f..3f0507f0a20 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
@@ -8,10 +8,12 @@ import {
} from '@/server/services/memory/userMemory/persona/service';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
+import { isHourlyMemoryExtractionCancelled } from './utils';
const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/persona/update-writing';
const workflowPayloadSchema = z.object({
+ hourlyTaskId: z.string().uuid().optional(),
userIds: z.array(z.string()).optional(),
});
@@ -43,8 +45,21 @@ export const personaUpdateHandler = async (context: WorkflowContext) => {
}
const service = new UserPersonaService(db);
+ let processedUsers = 0;
for (const userId of userIds) {
+ const hourlyCancellationStepName = `memory:pipelines:persona:update-writing:users:${userId}:cancel-check:hourly`;
+ const hourlyCancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ response: { processedUsers: 0 },
+ stepName: hourlyCancellationStepName,
+ });
+ if (!hourlyCancellationGuard.result) return hourlyCancellationGuard.response;
+
+ const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
+ );
+ if (hourlyCancelled) continue;
+
const stepName = `memory:pipelines:persona:update-writing:users:${userId}`;
const guard = await checkGuard(context, WORKFLOW_PATH, {
response: { processedUsers: 0 },
@@ -62,11 +77,12 @@ export const personaUpdateHandler = async (context: WorkflowContext) => {
version: result.document.version,
};
});
+ processedUsers += 1;
}
return {
message: 'User persona processed via workflow.',
- processedUsers: userIds.length,
+ processedUsers,
};
};
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
index 5c61d6728df..338ab538686 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
@@ -17,6 +17,7 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
+import { isHourlyMemoryExtractionCancelled } from './utils';
const CEPA_LAYERS: LayersEnum[] = [
LayersEnum.Context,
@@ -67,8 +68,6 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
return { message: 'Source not supported in topic workflow.' };
}
- const executor = await MemoryExtractionExecutor.create();
-
if (payload.asyncTaskId) {
// NOTICE: Cooperative cascading cancellation for the workflow tree.
// Check before CEPA extraction so cancelled tasks stop at the earliest safe boundary.
@@ -94,6 +93,30 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
}
}
+ {
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:hourly-before`;
+ const guard = await checkGuard(context, WORKFLOW_PATH, {
+ stepName,
+ });
+ if (!guard.result) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return guard.response;
+ }
+
+ const hourlyCancelled = await context.run(stepName, () =>
+ isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
+ );
+ if (hourlyCancelled) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return {
+ message: 'Hourly memory extraction task cancellation requested, skip topic.',
+ skipped: true,
+ };
+ }
+ }
+
+ const executor = await MemoryExtractionExecutor.create();
+
{
let layers = CEPA_LAYERS;
if (payload.layers.length) {
@@ -125,6 +148,29 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
);
}
{
+ {
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:hourly-identity`;
+ const guard = await checkGuard(context, WORKFLOW_PATH, {
+ stepName,
+ });
+ if (!guard.result) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return guard.response;
+ }
+
+ const hourlyCancelled = await context.run(stepName, () =>
+ isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
+ );
+ if (hourlyCancelled) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return {
+ message:
+ 'Hourly memory extraction task cancellation requested, skip identity extraction.',
+ skipped: true,
+ };
+ }
+ }
+
if (payload.asyncTaskId) {
// NOTICE: Cooperative cascading cancellation for the workflow tree.
// Re-check before identity extraction to avoid running sequential identity step after cancel.
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts
index 9b492770510..ed4c1531d17 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts
@@ -18,6 +18,7 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
+import { appendHourlyWorkflowRunId, isHourlyMemoryExtractionCancelled } from './utils';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topics';
@@ -120,6 +121,30 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
};
}
}
+
+ const hourlyCancellationStepName = `memory:user-memory:extract:users:${userId}:topics:cancel-check:hourly`;
+ const hourlyCancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ response: { processedTopics: 0, processedUsers: 0 },
+ stepName: hourlyCancellationStepName,
+ });
+ if (!hourlyCancellationGuard.result) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return hourlyCancellationGuard.response;
+ }
+
+ const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
+ );
+ if (hourlyCancelled) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return {
+ message: 'Hourly memory extraction task cancellation requested, skip topic batch.',
+ processedTopics: 0,
+ processedUsers: 0,
+ skipped: true,
+ };
+ }
+
// Fan out per-topic extraction as independent fire-and-forget workflow runs (replaces the
// former context.invoke). triggerProcessTopic applies a per-user flowControl key so a single
// user's concurrent process-topic runs stay bounded; the hard per-user, per-run topic
@@ -135,7 +160,7 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return guard.response;
}
- await context.run(stepName, () =>
+ const result = await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessTopic(
userId,
{
@@ -150,9 +175,34 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
{ extraHeaders: upstashWorkflowExtraHeaders },
),
);
+ await appendHourlyWorkflowRunId(payload.hourlyTaskId, result.workflowRunId);
}
// Trigger user persona update after topic processing using the workflow client.
+ const hourlyPersonaCancellationStepName = `memory:user-memory:users:${userId}:cancel-check:hourly`;
+ const hourlyPersonaCancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ response: { processedTopics: 0, processedUsers: 0 },
+ stepName: hourlyPersonaCancellationStepName,
+ });
+ if (!hourlyPersonaCancellationGuard.result) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return hourlyPersonaCancellationGuard.response;
+ }
+
+ const hourlyPersonaCancelled = await context.run(hourlyPersonaCancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(payload.hourlyTaskId),
+ );
+ if (hourlyPersonaCancelled) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return {
+ message:
+ 'Hourly memory extraction task cancellation requested, skip persona update scheduling.',
+ processedTopics: payload.topicIds.length,
+ processedUsers: payload.userIds.length,
+ skipped: true,
+ };
+ }
+
const personaUpdateStepName = `memory:user-memory:users:${userId}`;
const personaUpdateGuard = await checkGuard(context, WORKFLOW_PATH, {
response: { processedTopics: 0, processedUsers: 0 },
@@ -163,11 +213,13 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return personaUpdateGuard.response;
}
- await context.run(personaUpdateStepName, async () => {
- await MemoryExtractionWorkflowService.triggerPersonaUpdate(userId, payload.baseUrl, {
+ const personaUpdateResult = await context.run(personaUpdateStepName, async () => {
+ return MemoryExtractionWorkflowService.triggerPersonaUpdate(userId, payload.baseUrl, {
extraHeaders: upstashWorkflowExtraHeaders,
+ hourlyTaskId: payload.hourlyTaskId,
});
});
+ await appendHourlyWorkflowRunId(payload.hourlyTaskId, personaUpdateResult.workflowRunId);
span.setStatus({ code: SpanStatusCode.OK });
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
index 340a31418f7..ff6c4360cd6 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
@@ -15,6 +15,7 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
+import { appendHourlyWorkflowRunId, isHourlyMemoryExtractionCancelled } from './utils';
const TOPIC_PAGE_SIZE = 50;
const TOPIC_BATCH_SIZE = 4;
@@ -48,7 +49,11 @@ export const processUserTopicsHandler = async (
return { message: 'No supported sources requested, skip topic processing.' };
}
- const executor = await MemoryExtractionExecutor.create();
+ let executor: Awaited<ReturnType<typeof MemoryExtractionExecutor.create>> | undefined;
+ const getExecutor = async () => {
+ executor ??= await MemoryExtractionExecutor.create();
+ return executor;
+ };
const scheduleNextPage = async (
userId: string,
@@ -56,7 +61,7 @@ export const processUserTopicsHandler = async (
cursorId: string,
fanoutCount: number,
) => {
- await MemoryExtractionWorkflowService.triggerProcessUserTopics(
+ return MemoryExtractionWorkflowService.triggerProcessUserTopics(
{
...buildWorkflowPayloadInput({
...params,
@@ -98,6 +103,25 @@ export const processUserTopicsHandler = async (
}
}
+ const hourlyCancellationStepName = `memory:user-memory:extract:users:${userId}:cancel-check:hourly`;
+ const hourlyCancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ stepName: hourlyCancellationStepName,
+ });
+ if (!hourlyCancellationGuard.result) return hourlyCancellationGuard.response;
+
+ const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
+ );
+ if (hourlyCancelled) {
+ return {
+ message: 'Hourly memory extraction task cancellation requested, skip user topic fan-out.',
+ processedUsers: 0,
+ skipped: true,
+ };
+ }
+
+ const activeExecutor = await getExecutor();
+
const topicCursor =
params.topicCursor && params.topicCursor.userId === userId
? {
@@ -113,7 +137,7 @@ export const processUserTopicsHandler = async (
if (!guard.result) return guard.response;
topicsFromPayload = await context.run(stepName, async () => {
- const filtered = await executor.filterTopicIdsForUser(
+ const filtered = await activeExecutor.filterTopicIdsForUser(
userId,
params.topicIds,
params.workspaceId,
@@ -134,7 +158,7 @@ export const processUserTopicsHandler = async (
}>(listTopicsStepName, () =>
topicsFromPayload && topicsFromPayload.length > 0
? Promise.resolve({ ids: topicsFromPayload })
- : executor.getTopicsForUser(
+ : activeExecutor.getTopicsForUser(
{
cursor: topicCursor,
forceAll: params.forceAll,
@@ -173,7 +197,7 @@ export const processUserTopicsHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- await context.run(stepName, () =>
+ const result = await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessTopics(
userId,
{
@@ -186,17 +210,38 @@ export const processUserTopicsHandler = async (
{ extraHeaders: upstashWorkflowExtraHeaders },
),
);
+ await appendHourlyWorkflowRunId(params.hourlyTaskId, result.workflowRunId);
}
const nextFanoutCount = fanoutCount + idsToProcess.length;
// Stop paginating once the per-user ceiling is reached; the remainder resumes next hourly run.
if (!topicsFromPayload && cursor && nextFanoutCount < MAX_TOPICS_PER_USER_PER_RUN) {
+ const hourlyNextPageCancellationStepName = `memory:user-memory:extract:users:${userId}:cancel-check:hourly-next-page`;
+ const hourlyNextPageCancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ stepName: hourlyNextPageCancellationStepName,
+ });
+ if (!hourlyNextPageCancellationGuard.result) {
+ return hourlyNextPageCancellationGuard.response;
+ }
+
+ const hourlyNextPageCancelled = await context.run(hourlyNextPageCancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
+ );
+ if (hourlyNextPageCancelled) {
+ return {
+ message:
+ 'Hourly memory extraction task cancellation requested, skip next user topics page.',
+ processedUsers: 1,
+ skipped: true,
+ };
+ }
+
const stepName = `memory:user-memory:extract:users:${userId}:topics:${cursor.id}:schedule-next-batch`;
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- await context.run(stepName, () => {
+ const result = await context.run(stepName, () => {
// NOTICE: Upstash Workflow only supports serializable data into plain JSON,
// this causes the Date object to be converted into string when passed as parameter from
// context to child workflow. So we need to convert it back to Date object here.
@@ -207,6 +252,7 @@ export const processUserTopicsHandler = async (
return scheduleNextPage(userId, createdAt, cursor.id, nextFanoutCount);
});
+ await appendHourlyWorkflowRunId(params.hourlyTaskId, result.workflowRunId);
}
}
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts
index f491f138e57..68e4f385c67 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts
@@ -13,7 +13,11 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { checkGuard, ensureWorkflowStarted } from './runGuard';
-import { serializeWorkflowCursor } from './utils';
+import {
+ appendHourlyWorkflowRunId,
+ isHourlyMemoryExtractionCancelled,
+ serializeWorkflowCursor,
+} from './utils';
const USER_PAGE_SIZE = 50;
const USER_BATCH_SIZE = 10;
@@ -58,6 +62,22 @@ export const processUsersHandler = async (
}
}
+ const hourlyCancellationStepName = 'memory:user-memory:extract:users:cancel-check:hourly';
+ const hourlyCancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ stepName: hourlyCancellationStepName,
+ });
+ if (!hourlyCancellationGuard.result) return hourlyCancellationGuard.response;
+
+ const hourlyCancelled = await context.run(hourlyCancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
+ );
+ if (hourlyCancelled) {
+ return {
+ message: 'Hourly memory extraction task cancellation requested, skip processing users.',
+ skipped: true,
+ };
+ }
+
const executor = await MemoryExtractionExecutor.create();
// NOTICE: Upstash Workflow only supports serializable data into plain JSON,
@@ -90,7 +110,7 @@ export const processUsersHandler = async (
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- await context.run(stepName, () =>
+ const result = await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUserTopics(
{
...buildWorkflowPayloadInput(params),
@@ -101,14 +121,34 @@ export const processUsersHandler = async (
{ extraHeaders: upstashWorkflowExtraHeaders },
),
);
+ await appendHourlyWorkflowRunId(params.hourlyTaskId, result.workflowRunId);
}
if (params.userIds.length === 0 && cursor) {
+ const hourlyNextPageCancellationStepName =
+ 'memory:user-memory:extract:users:cancel-check:hourly-next-page';
+ const hourlyNextPageCancellationGuard = await checkGuard(context, WORKFLOW_PATH, {
+ stepName: hourlyNextPageCancellationStepName,
+ });
+ if (!hourlyNextPageCancellationGuard.result) return hourlyNextPageCancellationGuard.response;
+
+ const hourlyNextPageCancelled = await context.run(hourlyNextPageCancellationStepName, () =>
+ isHourlyMemoryExtractionCancelled(params.hourlyTaskId),
+ );
+ if (hourlyNextPageCancelled) {
+ return {
+ batches: batches.length,
+ message: 'Hourly memory extraction task cancellation requested, skip next users page.',
+ processedUsers: ids.length,
+ skipped: true,
+ };
+ }
+
const stepName = 'memory:user-memory:extract:users:schedule-next-user-batch';
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
- await context.run(stepName, () =>
+ const result = await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUsers(
{
...buildWorkflowPayloadInput({
@@ -122,6 +162,7 @@ export const processUsersHandler = async (
{ extraHeaders: upstashWorkflowExtraHeaders },
),
);
+ await appendHourlyWorkflowRunId(params.hourlyTaskId, result.workflowRunId);
}
return {
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/utils.ts b/src/server/workflows-hono/memory-user-memory/workflows/utils.ts
index 781e5c929bf..619f79d8d87 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/utils.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/utils.ts
@@ -1,3 +1,10 @@
+import { AsyncTaskStatus } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { asyncTasks } from '@/database/schemas';
+import { getServerDB } from '@/database/server';
+
/**
* Cursor shape accepted by workflow pagination serializers.
*/
@@ -47,3 +54,97 @@ export const serializeWorkflowCursor = (
return { createdAt: createdAt.toISOString(), id: cursor.id };
};
+
+/**
+ * Checks whether an hourly user-memory extraction task has requested cancellation.
+ *
+ * Use when:
+ * - A workflow stage is about to schedule child workflow fan-out
+ * - A workflow stage is about to run heavyweight extraction work for hourly processing
+ *
+ * Expects:
+ * - `hourlyTaskId` is the batch-level async task id from the workflow payload
+ * - The async task row owns the user/workspace needed by AsyncTaskModel ownership checks
+ *
+ * Returns:
+ * - `true` when the hourly task exists and has requested cancellation
+ * - `false` when no hourly task id is present, the task is missing, or cancellation is absent
+ */
+export const isHourlyMemoryExtractionCancelled = async (hourlyTaskId?: string) => {
+ if (!hourlyTaskId) return false;
+
+ const db = await getServerDB();
+ const task = await db.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, hourlyTaskId),
+ });
+ if (!task) return false;
+
+ return new AsyncTaskModel(
+ db,
+ task.userId,
+ task.workspaceId ?? undefined,
+ ).isHourlyMemoryExtractionCancellationRequested(hourlyTaskId);
+};
+
+/**
+ * Appends a child workflow run id to an hourly user-memory extraction task.
+ *
+ * Use when:
+ * - A workflow fan-out trigger returns a child `workflowRunId`
+ * - The hourly async task should retain known Upstash workflow run ids for cancellation
+ *
+ * Expects:
+ * - `hourlyTaskId` is optional because the same workflow handlers support non-hourly entrypoints
+ * - `workflowRunId` may be absent when a trigger implementation returns no child id
+ *
+ * Returns:
+ * - Nothing; append failures are logged and never fail the workflow stage
+ */
+export const appendHourlyWorkflowRunId = async (
+ hourlyTaskId: string | undefined,
+ workflowRunId?: string,
+) => {
+ if (!hourlyTaskId || !workflowRunId) return;
+
+ try {
+ const db = await getServerDB();
+ const task = await db.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, hourlyTaskId),
+ });
+ if (!task) return;
+
+ await new AsyncTaskModel(
+ db,
+ task.userId,
+ task.workspaceId ?? undefined,
+ ).appendUserMemoryWorkflowRunIds(hourlyTaskId, [workflowRunId]);
+ } catch (error) {
+ console.error('[memory-user-memory] failed to append hourly workflow run id', error);
+ }
+};
+
+export const markHourlyMemoryExtractionSuccess = async (
+ hourlyTaskId: string | undefined,
+ progress: {
+ processedUsers: number;
+ scheduledBatches: number;
+ scheduledChildRuns: number;
+ },
+) => {
+ if (!hourlyTaskId) return;
+
+ const db = await getServerDB();
+ const task = await db.query.asyncTasks.findFirst({
+ where: eq(asyncTasks.id, hourlyTaskId),
+ });
+ if (!task) return;
+
+ await new AsyncTaskModel(
+ db,
+ task.userId,
+ task.workspaceId ?? undefined,
+ ).markHourlyMemoryExtractionSuccess(hourlyTaskId, {
+ ...progress,
+ status: AsyncTaskStatus.Success,
+ });
+};