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(userMemories): missing cancel webhook api for cascading cancellation (#13742)

Nekoe0f97c4920d8
diff --git a/packages/database/src/models/__tests__/asyncTask.test.ts b/packages/database/src/models/__tests__/asyncTask.test.ts
index 031a82ae7b0..b6b538c4779 100644
--- a/packages/database/src/models/__tests__/asyncTask.test.ts
+++ b/packages/database/src/models/__tests__/asyncTask.test.ts
@@ -279,6 +279,88 @@ describe('AsyncTaskModel', () => {
expect(updatedTask?.error).toBeNull();
});
});
+
+ describe('isUserMemoryExtractionCancellationRequested', () => {
+ it('should return true when cancellation is requested for current user memory extraction task', async () => {
+ const [task] = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ control: {
+ cancelRequestedAt: new Date().toISOString(),
+ },
+ progress: {
+ completedTopics: 0,
+ totalTopics: 1,
+ },
+ source: 'chat_topic',
+ },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.UserMemoryExtractionWithChatTopic,
+ userId,
+ })
+ .returning();
+
+ const requested = await asyncTaskModel.isUserMemoryExtractionCancellationRequested(task.id);
+
+ expect(requested).toBe(true);
+ });
+
+ it('should return false when task is not user memory extraction type', async () => {
+ const [task] = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ control: {
+ cancelRequestedAt: new Date().toISOString(),
+ },
+ progress: {
+ completedTopics: 0,
+ totalTopics: 1,
+ },
+ source: 'chat_topic',
+ },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.Chunking,
+ userId,
+ })
+ .returning();
+
+ const requested = await asyncTaskModel.isUserMemoryExtractionCancellationRequested(task.id);
+
+ expect(requested).toBe(false);
+ });
+
+ it('should return false when task belongs to another user', async () => {
+ const otherUserId = 'other-user-for-cancel-test';
+ await serverDB.insert(users).values([{ id: otherUserId }]);
+
+ const [task] = await serverDB
+ .insert(asyncTasks)
+ .values({
+ metadata: {
+ control: {
+ cancelRequestedAt: new Date().toISOString(),
+ },
+ progress: {
+ completedTopics: 0,
+ totalTopics: 1,
+ },
+ source: 'chat_topic',
+ },
+ status: AsyncTaskStatus.Processing,
+ type: AsyncTaskType.UserMemoryExtractionWithChatTopic,
+ userId: otherUserId,
+ })
+ .returning();
+
+ const requested = await asyncTaskModel.isUserMemoryExtractionCancellationRequested(task.id);
+
+ expect(requested).toBe(false);
+
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ });
+ });
});
describe('initUserMemoryExtractionMetadata', () => {
@@ -286,6 +368,7 @@ describe('initUserMemoryExtractionMetadata', () => {
const result = initUserMemoryExtractionMetadata(undefined);
expect(result).toEqual({
+ control: undefined,
progress: {
completedTopics: 0,
totalTopics: null,
@@ -299,6 +382,7 @@ describe('initUserMemoryExtractionMetadata', () => {
const result = initUserMemoryExtractionMetadata();
expect(result).toEqual({
+ control: undefined,
progress: {
completedTopics: 0,
totalTopics: null,
@@ -318,6 +402,7 @@ describe('initUserMemoryExtractionMetadata', () => {
});
expect(result).toEqual({
+ control: undefined,
progress: {
completedTopics: 5,
totalTopics: 10,
@@ -339,6 +424,7 @@ describe('initUserMemoryExtractionMetadata', () => {
});
expect(result).toEqual({
+ control: undefined,
progress: {
completedTopics: 3,
totalTopics: 7,
diff --git a/packages/database/src/models/asyncTask.ts b/packages/database/src/models/asyncTask.ts
index 0def9c36e20..06753274651 100644
--- a/packages/database/src/models/asyncTask.ts
+++ b/packages/database/src/models/asyncTask.ts
@@ -1,6 +1,11 @@
import { ASYNC_TASK_TIMEOUT } from '@lobechat/business-config/server';
-import type { AsyncTaskType, UserMemoryExtractionMetadata } from '@lobechat/types';
-import { AsyncTaskError, AsyncTaskErrorType, AsyncTaskStatus } from '@lobechat/types';
+import type { UserMemoryExtractionMetadata } from '@lobechat/types';
+import {
+ AsyncTaskError,
+ AsyncTaskErrorType,
+ AsyncTaskStatus,
+ AsyncTaskType,
+} from '@lobechat/types';
import { and, eq, inArray, lt, or, sql } from 'drizzle-orm';
import type { AsyncTaskSelectItem, NewAsyncTaskItem } from '../schemas';
@@ -110,6 +115,17 @@ export class AsyncTaskModel {
return chunkTasks;
};
+ isUserMemoryExtractionCancellationRequested = async (taskId: string) => {
+ // NOTICE: Shared cancellation gate for cooperative cascading cancellation.
+ // Workflow stages call this before fan-out/heavy steps to stop the remaining task tree.
+ const task = await this.findById(taskId);
+ if (!task || task.userId !== this.userId) return false;
+ if (task.type !== AsyncTaskType.UserMemoryExtractionWithChatTopic) return false;
+
+ const metadata = task.metadata as UserMemoryExtractionMetadata | undefined;
+ return Boolean(metadata?.control?.cancelRequestedAt);
+ };
+
/**
* make the task status to be `error` if the task is not finished in 20 seconds
*/
@@ -151,6 +167,18 @@ export class AsyncTaskModel {
export const initUserMemoryExtractionMetadata = (
metadata?: UserMemoryExtractionMetadata,
): UserMemoryExtractionMetadata => ({
+ control: metadata?.control
+ ? {
+ cancelReason: metadata.control.cancelReason,
+ cancelRequestedAt: metadata.control.cancelRequestedAt,
+ cancelledBy: metadata.control.cancelledBy,
+ upstash: metadata.control.upstash
+ ? {
+ workflowRunIds: metadata.control.upstash.workflowRunIds || [],
+ }
+ : undefined,
+ }
+ : undefined,
progress: {
completedTopics: metadata?.progress?.completedTopics ?? 0,
totalTopics: metadata?.progress?.totalTopics ?? null,
diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.ts
index afe740c356e..4354fcd7bb1 100644
--- a/packages/types/src/asyncTask.ts
+++ b/packages/types/src/asyncTask.ts
@@ -38,6 +38,10 @@ export enum AsyncTaskErrorType {
* Subscription plan limit reached (paid users run out of credits)
*/
SubscriptionPlanLimit = 'SubscriptionPlanLimit',
+ /**
+ * this happens when a task is intentionally cancelled
+ */
+ TaskCancelled = 'TaskCancelled',
/**
* this happens when the task is not trigger successfully
*/
@@ -76,6 +80,29 @@ export interface UserMemoryExtractionProgress {
}
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[];
+ };
+ };
progress: UserMemoryExtractionProgress;
range?: {
from?: string;
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
new file mode 100644
index 00000000000..f30b77268cb
--- /dev/null
+++ b/src/app/(backend)/api/webhooks/memory-user-memory/pipelines/extract/chat-topic/cancel/route.ts
@@ -0,0 +1,143 @@
+import {
+ AsyncTaskError,
+ AsyncTaskErrorType,
+ AsyncTaskStatus,
+ AsyncTaskType,
+ type UserMemoryExtractionMetadata,
+} from '@lobechat/types';
+import { Client as WorkflowClient } from '@upstash/workflow';
+import { and, eq } from 'drizzle-orm';
+import { NextResponse } from 'next/server';
+import { z } from 'zod';
+
+import { AsyncTaskModel, initUserMemoryExtractionMetadata } from '@/database/models/asyncTask';
+import { asyncTasks } from '@/database/schemas';
+import { getServerDB } from '@/database/server';
+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
+
+const cancelPayloadSchema = z.object({
+ // Optional human-readable cancellation reason.
+ reason: z.string().trim().max(1000).optional(),
+ // Async task id for user memory extraction.
+ taskId: z.string().uuid(),
+ // Optional ownership guard; when provided, must match task owner.
+ userId: z.string().optional(),
+ // Optional single workflow run id associated with the task.
+ workflowRunId: z.string().optional(),
+ // Optional additional workflow run ids for bulk cancellation.
+ workflowRunIds: z.array(z.string()).optional(),
+});
+
+const getWorkflowClient = () => {
+ const token = process.env.QSTASH_TOKEN;
+ if (!token) throw new Error('QSTASH_TOKEN is required to cancel workflow runs');
+
+ const config: ConstructorParameters<typeof WorkflowClient>[0] = { token };
+ if (process.env.QSTASH_URL) {
+ (config as Record<string, unknown>).url = process.env.QSTASH_URL;
+ }
+
+ return new WorkflowClient(config);
+};
+
+export const POST = async (req: Request) => {
+ const { webhook } = parseMemoryExtractionConfig();
+
+ if (webhook.headers && Object.keys(webhook.headers).length > 0) {
+ for (const [key, value] of Object.entries(webhook.headers)) {
+ const headerValue = req.headers.get(key);
+ if (headerValue !== value) {
+ return NextResponse.json(
+ { error: `Unauthorized: Missing or invalid header '${key}'` },
+ { status: 403 },
+ );
+ }
+ }
+ }
+
+ try {
+ const payload = cancelPayloadSchema.parse(await req.json());
+ const db = await getServerDB();
+
+ const task = await db.query.asyncTasks.findFirst({
+ where: and(
+ eq(asyncTasks.id, payload.taskId),
+ eq(asyncTasks.type, AsyncTaskType.UserMemoryExtractionWithChatTopic),
+ ),
+ });
+
+ if (!task) {
+ return NextResponse.json(
+ { error: `Memory extraction task not found for id '${payload.taskId}'` },
+ { status: 404 },
+ );
+ }
+
+ if (payload.userId && payload.userId !== task.userId) {
+ return NextResponse.json(
+ { error: `Task '${payload.taskId}' does not belong to the provided userId` },
+ { status: 403 },
+ );
+ }
+
+ const metadata = initUserMemoryExtractionMetadata(
+ task.metadata as UserMemoryExtractionMetadata | undefined,
+ );
+
+ const workflowRunIds = Array.from(
+ new Set([
+ ...(metadata.control?.upstash?.workflowRunIds || []),
+ ...(payload.workflowRunId ? [payload.workflowRunId] : []),
+ ...(payload.workflowRunIds || []),
+ ]),
+ );
+
+ const nextMetadata: UserMemoryExtractionMetadata = {
+ ...metadata,
+ control: {
+ cancelReason: payload.reason || metadata.control?.cancelReason,
+ cancelRequestedAt: metadata.control?.cancelRequestedAt || new Date().toISOString(),
+ cancelledBy: 'webhook',
+ upstash: {
+ workflowRunIds,
+ },
+ },
+ };
+
+ const asyncTaskModel = new AsyncTaskModel(db, task.userId);
+ await asyncTaskModel.update(task.id, {
+ error: new AsyncTaskError(
+ AsyncTaskErrorType.TaskCancelled,
+ payload.reason || 'Memory extraction cancelled from webhook',
+ ),
+ metadata: nextMetadata,
+ status: AsyncTaskStatus.Error,
+ });
+
+ let cancelledWorkflowRuns = 0;
+ if (workflowRunIds.length > 0) {
+ try {
+ const result = await getWorkflowClient().cancel({ ids: workflowRunIds });
+ cancelledWorkflowRuns = result.cancelled || 0;
+ } catch (error) {
+ console.error(
+ '[memory-user-memory/pipelines/extract/chat-topic/cancel] failed to cancel workflow runs',
+ error,
+ );
+ }
+ }
+
+ return NextResponse.json(
+ {
+ cancelledWorkflowRuns,
+ message: 'Memory extraction cancellation has been requested.',
+ status: AsyncTaskStatus.Error,
+ taskId: task.id,
+ },
+ { status: 200 },
+ );
+ } catch (error) {
+ console.error('[memory-user-memory/pipelines/extract/chat-topic/cancel] failed', error);
+ return NextResponse.json({ error: (error as Error).message }, { status: 500 });
+ }
+};
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic/workflows/topic.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic/workflows/topic.ts
index 799675310d8..649ae7bd3d4 100644
--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic/workflows/topic.ts
+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic/workflows/topic.ts
@@ -61,6 +61,24 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
const executor = await MemoryExtractionExecutor.create();
try {
+ if (payload.asyncTaskId) {
+ // NOTICE: Cooperative cascading cancellation for the workflow tree.
+ // Check before CEPA extraction so cancelled tasks stop at the earliest safe boundary.
+ const cancelled = await context.run(
+ `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:before`,
+ () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(
+ payload.asyncTaskId!,
+ ),
+ ),
+ );
+ if (cancelled) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return { message: 'Memory extraction task cancellation requested, skip topic.' };
+ }
+ }
+
{
let layers = CEPA_LAYERS;
if (payload.layers.length) {
@@ -85,6 +103,26 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
);
}
{
+ if (payload.asyncTaskId) {
+ // NOTICE: Cooperative cascading cancellation for the workflow tree.
+ // Re-check before identity extraction to avoid running sequential identity step after cancel.
+ const cancelled = await context.run(
+ `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:identity`,
+ () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(
+ payload.asyncTaskId!,
+ ),
+ ),
+ );
+ if (cancelled) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return {
+ message: 'Memory extraction task cancellation requested, skip identity extraction.',
+ };
+ }
+ }
+
let layers = IDENTITY_LAYERS;
if (payload.layers.length) {
layers = payload.layers.filter((layer) => IDENTITY_LAYERS.includes(layer));
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts
index a5d542e3381..f928cb0ed62 100644
--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts
+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics/route.ts
@@ -8,6 +8,8 @@ import { Client } from '@upstash/qstash';
import { WorkflowAbort } from '@upstash/workflow';
import { serve } from '@upstash/workflow/nextjs';
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { getServerDB } from '@/database/server';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';
import {
@@ -75,6 +77,27 @@ export const { POST } = serve<MemoryExtractionPayloadInput>(
}
const userId = payload.userIds[0];
+ if (payload.asyncTaskId && userId) {
+ // NOTICE: Cooperative cascading cancellation for the workflow tree.
+ // If cancelled, stop before fan-out into per-topic child workflows.
+ const cancelled = await context.run(
+ `memory:user-memory:extract:users:${userId}:cancel-check`,
+ () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(
+ payload.asyncTaskId!,
+ ),
+ ),
+ );
+ if (cancelled) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return {
+ message: 'Memory extraction task cancellation requested, skip topic batch.',
+ processedTopics: 0,
+ processedUsers: 0,
+ };
+ }
+ }
// Delegate per-topic extraction to dedicated workflow for better isolation
await Promise.all(
payload.topicIds.map(async (topicId, index) => {
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts
index 7a25b8a03b1..5185caca0a9 100644
--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts
+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics/route.ts
@@ -2,7 +2,9 @@ import { MemorySourceType } from '@lobechat/types';
import { Client } from '@upstash/qstash';
import { serve } from '@upstash/workflow/nextjs';
+import { AsyncTaskModel } from '@/database/models/asyncTask';
import { type ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';
+import { getServerDB } from '@/database/server';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';
import {
@@ -50,6 +52,23 @@ export const { POST } = serve<MemoryExtractionPayloadInput>(
};
for (const userId of params.userIds) {
+ if (params.asyncTaskId) {
+ // NOTICE: Cooperative cascading cancellation for the workflow tree.
+ // A cancelled root task should stop at user-topic pagination and avoid enqueuing topic batches.
+ const cancelled = await context.run(
+ `memory:user-memory:extract:users:${userId}:cancel-check`,
+ () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(db, userId).isUserMemoryExtractionCancellationRequested(
+ params.asyncTaskId!,
+ ),
+ ),
+ );
+ if (cancelled) {
+ continue;
+ }
+ }
+
const topicCursor =
params.topicCursor && params.topicCursor.userId === userId
? {
@@ -132,7 +151,7 @@ export const { POST } = serve<MemoryExtractionPayloadInput>(
throw new Error('Invalid cursor date when scheduling next topic page');
}
- scheduleNextPage(userId, createdAt, cursor.id);
+ return scheduleNextPage(userId, createdAt, cursor.id);
},
);
}
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts
index d8199fe763a..3d7d74ea27f 100644
--- a/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts
+++ b/src/app/(backend)/api/workflows/memory-user-memory/pipelines/chat-topic/process-users/route.ts
@@ -2,6 +2,8 @@ import { Client } from '@upstash/qstash';
import { serve } from '@upstash/workflow/nextjs';
import { chunk } from 'es-toolkit/compat';
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { getServerDB } from '@/database/server';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';
import {
@@ -22,6 +24,20 @@ export const { POST } = serve<MemoryExtractionPayloadInput>(
if (params.sources.length === 0) {
return { message: 'No sources provided, skip memory extraction.' };
}
+ if (params.asyncTaskId && params.userIds[0]) {
+ // NOTICE: Cooperative cascading cancellation for the workflow tree.
+ // If root task has cancelRequestedAt, this stage stops scheduling child workflows.
+ const cancelled = await context.run('memory:user-memory:extract:cancel-check:root', () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(db, params.userIds[0]!).isUserMemoryExtractionCancellationRequested(
+ params.asyncTaskId!,
+ ),
+ ),
+ );
+ if (cancelled) {
+ return { message: 'Memory extraction task cancellation requested, skip processing users.' };
+ }
+ }
const executor = await MemoryExtractionExecutor.create();
diff --git a/src/server/routers/lambda/__tests__/userMemory.test.ts b/src/server/routers/lambda/__tests__/userMemory.test.ts
index 09f187ef03f..8523c79b6c8 100644
--- a/src/server/routers/lambda/__tests__/userMemory.test.ts
+++ b/src/server/routers/lambda/__tests__/userMemory.test.ts
@@ -78,6 +78,7 @@ const createCaller = (ctxOverrides: Partial<any> = {}) => {
describe('userMemoryRouter.requestMemoryFromChatTopic', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockTriggerProcessUsers.mockResolvedValue({ workflowRunId: 'workflow-run-1' });
});
it('dedupes when an active task exists', async () => {
@@ -135,6 +136,15 @@ describe('userMemoryRouter.requestMemoryFromChatTopic', () => {
}),
{ extraHeaders: { 'x-test': 'ok' } },
);
+ expect(mockUpdate).toHaveBeenCalledWith('new-task', {
+ metadata: expect.objectContaining({
+ control: {
+ upstash: {
+ workflowRunIds: ['workflow-run-1'],
+ },
+ },
+ }),
+ });
expect(result).toMatchObject({
deduped: false,
id: 'new-task',
diff --git a/src/server/routers/lambda/userMemory.ts b/src/server/routers/lambda/userMemory.ts
index 7d2bd50c94e..a608c7305d2 100644
--- a/src/server/routers/lambda/userMemory.ts
+++ b/src/server/routers/lambda/userMemory.ts
@@ -275,7 +275,7 @@ export const userMemoryRouter = router({
const baseUrl = webhook.baseUrl || appEnv.INTERNAL_APP_URL || appEnv.APP_URL;
try {
- await MemoryExtractionWorkflowService.triggerProcessUsers(
+ const { workflowRunId } = await MemoryExtractionWorkflowService.triggerProcessUsers(
buildWorkflowPayloadInput(
normalizeMemoryExtractionPayload({
asyncTaskId: taskId,
@@ -292,6 +292,17 @@ export const userMemoryRouter = router({
),
{ extraHeaders: upstashWorkflowExtraHeaders },
);
+
+ await ctx.asyncTaskModel.update(taskId, {
+ metadata: {
+ ...metadata,
+ control: {
+ upstash: {
+ workflowRunIds: workflowRunId ? [workflowRunId] : [],
+ },
+ },
+ } as UserMemoryExtractionMetadata,
+ });
} catch (error) {
await ctx.asyncTaskModel.update(taskId, {
error: new AsyncTaskError(