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(memory-user-memory): cap per-user topic fan-out + fire-and-forget process-topic + serve-side flow control (#16768)

Arvin Xuf194b12f5def
diff --git a/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts b/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts
index a98793b480b..bb61f57b754 100644
--- a/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts
+++ b/apps/server/src/globalConfig/parseMemoryExtractionConfig.ts
@@ -18,6 +18,13 @@ const MEMORY_LAYERS: GlobalMemoryLayer[] = [
const DEFAULT_WORKFLOW_PROCESS_USER_TOPICS_PARALLELISM = 25;
+// NOTICE: Hard per-user, per-run fan-out ceiling. A single user with a large backlog of
+// un-extracted topics must never enqueue an unbounded flood of process-topic runs (we have seen a
+// single user back up 650k+ QStash messages). flowControl only caps concurrency, not queue depth,
+// so this count cap is the actual backlog guard. Remaining topics stay "un-extracted" and are
+// picked up by later hourly runs, so the cap self-drains without dropping data.
+const DEFAULT_WORKFLOW_MAX_TOPICS_PER_USER_PER_RUN = 100;
+
const parseTokenLimitEnv = (value?: string) => {
if (value === undefined) return undefined;
const parsed = Number(value);
@@ -89,6 +96,8 @@ export interface MemoryExtractionPrivateConfig {
};
whitelistUsers?: string[];
workflow?: {
+ /** Hard cap on topics fanned out per user per run; guards against QStash backlog storms. */
+ maxTopicsPerUserPerRun: number;
/** Maximum active process-user-topics workflow workers across all users. */
processUserTopicsParallelism: number;
};
@@ -269,6 +278,10 @@ export const parseMemoryExtractionConfig = (): MemoryExtractionPrivateConfig =>
process.env.MEMORY_USER_MEMORY_WORKFLOW_PROCESS_USER_TOPICS_PARALLELISM,
DEFAULT_WORKFLOW_PROCESS_USER_TOPICS_PARALLELISM,
);
+ const maxTopicsPerUserPerRun = parsePositiveIntegerEnv(
+ process.env.MEMORY_USER_MEMORY_WORKFLOW_MAX_TOPICS_PER_USER_PER_RUN,
+ DEFAULT_WORKFLOW_MAX_TOPICS_PER_USER_PER_RUN,
+ );
const whitelistUsers = process.env.MEMORY_USER_MEMORY_WHITELIST_USERS?.split(',')
.filter(Boolean)
@@ -337,6 +350,7 @@ export const parseMemoryExtractionConfig = (): MemoryExtractionPrivateConfig =>
},
whitelistUsers,
workflow: {
+ maxTopicsPerUserPerRun,
processUserTopicsParallelism,
},
};
diff --git a/apps/server/src/services/memory/userMemory/__tests__/extract.payload.test.ts b/apps/server/src/services/memory/userMemory/__tests__/extract.payload.test.ts
index ab20320d49d..482de710e97 100644
--- a/apps/server/src/services/memory/userMemory/__tests__/extract.payload.test.ts
+++ b/apps/server/src/services/memory/userMemory/__tests__/extract.payload.test.ts
@@ -71,6 +71,7 @@ describe('buildWorkflowPayloadInput', () => {
sources: [MemorySourceType.ChatTopic],
to: undefined,
topicCursor: undefined,
+ topicFanoutCount: 0,
topicIds: [],
userCursor: undefined,
userId: undefined,
diff --git a/apps/server/src/services/memory/userMemory/extract.ts b/apps/server/src/services/memory/userMemory/extract.ts
index 957127fd024..8ab50203478 100644
--- a/apps/server/src/services/memory/userMemory/extract.ts
+++ b/apps/server/src/services/memory/userMemory/extract.ts
@@ -142,6 +142,7 @@ export interface MemoryExtractionNormalizedPayload {
sources: MemorySourceType[];
to?: Date;
topicCursor?: TopicWorkflowCursor;
+ topicFanoutCount: number;
topicIds: string[];
userCursor?: MemoryExtractionWorkflowCursor;
userId?: string;
@@ -169,6 +170,9 @@ export const memoryExtractionPayloadSchema = z.object({
userId: z.string(),
})
.optional(),
+ // Running count of topics already fanned out for this user in the current pagination chain.
+ // Used by process-user-topics to enforce a hard per-user, per-run fan-out ceiling.
+ topicFanoutCount: z.coerce.number().int().nonnegative().optional(),
topicIds: z.array(z.string()).optional(),
userCursor: z
.object({
@@ -225,6 +229,7 @@ export const normalizeMemoryExtractionPayload = (
sources: normalizeSources(parsed.sources),
to: parsed.toDate,
topicCursor: parsed.topicCursor,
+ topicFanoutCount: parsed.topicFanoutCount ?? 0,
topicIds: Array.from(new Set(parsed.topicIds || [])).filter(Boolean),
userCursor: parsed.userCursor,
userId: parsed.userId ?? parsed.userIds?.[0],
@@ -263,6 +268,7 @@ export const buildWorkflowPayloadInput = (
sources: payload.sources,
toDate: payload.to,
topicCursor: payload.topicCursor,
+ topicFanoutCount: payload.topicFanoutCount,
topicIds: payload.topicIds,
userCursor: payload.userCursor,
userId: payload.userId ?? payload.userIds[0],
@@ -2708,6 +2714,7 @@ export class MemoryExtractionExecutor {
const WORKFLOW_PATHS = {
hourly: '/api/workflows/memory-user-memory/call-cron-hourly-analysis',
personaUpdate: '/api/workflows/memory-user-memory/pipelines/persona/update-writing',
+ topic: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
topicBatch: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics',
userTopics: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics',
users: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-users',
@@ -2832,6 +2839,31 @@ export class MemoryExtractionWorkflowService {
});
}
+ static triggerProcessTopic(
+ userId: string,
+ payload: MemoryExtractionPayloadInput,
+ options?: { extraHeaders?: Record<string, string> },
+ ) {
+ if (!payload.baseUrl) {
+ throw new Error('Missing baseUrl for workflow trigger');
+ }
+
+ const url = getWorkflowUrl(WORKFLOW_PATHS.topic, payload.baseUrl);
+ return this.getClient().trigger({
+ body: payload,
+ // NOTICE: fire-and-forget fan-out (replaces the old context.invoke). The per-user key bounds
+ // how many process-topic runs a single user can start concurrently, so one heavy user can't
+ // monopolize extraction. Serve-side flow control (processTopicWorkflowOptions) additionally
+ // keeps this workflow's own step-continuation messages out of the shared "$" (unbound) bucket.
+ flowControl: {
+ key: `memory-user-memory.pipelines.chat-topic.process-topic.user.${userId}`,
+ parallelism: 5,
+ } satisfies FlowControl,
+ headers: options?.extraHeaders,
+ url,
+ });
+ }
+
static triggerPersonaUpdate(
userId: string,
baseUrl: string,
diff --git a/src/server/workflows-hono/memory-user-memory/index.ts b/src/server/workflows-hono/memory-user-memory/index.ts
index 034610d736b..9a0aaab0d03 100644
--- a/src/server/workflows-hono/memory-user-memory/index.ts
+++ b/src/server/workflows-hono/memory-user-memory/index.ts
@@ -1,12 +1,12 @@
import { withOtelMetricsForUpstashWorkflows } from '@lobechat/observability-otel/modules/upstash-workflow';
-import { serve, serveMany } from '@upstash/workflow/hono';
+import { serve } from '@upstash/workflow/hono';
import { Hono } from 'hono';
import { createWorkflowQstashClient } from '../qstashClient';
import { hourlyWorkflowHandler, hourlyWorkflowOptions } from './workflows/hourly';
-import { personaUpdateHandler } from './workflows/personaUpdate';
-import { processTopicWorkflow } from './workflows/processTopic';
-import { processTopicsHandler } from './workflows/processTopics';
+import { personaUpdateHandler, personaUpdateWorkflowOptions } from './workflows/personaUpdate';
+import { processTopicHandler, processTopicWorkflowOptions } from './workflows/processTopic';
+import { processTopicsHandler, processTopicsWorkflowOptions } from './workflows/processTopics';
import { processUsersHandler, processUsersWorkflowOptions } from './workflows/processUsers';
import {
processUserTopicsHandler,
@@ -34,7 +34,7 @@ app.post(
withOtelMetricsForUpstashWorkflows(personaUpdateHandler, {
url: '/api/workflows/memory-user-memory/pipelines/persona/update-writing',
}),
- { qstashClient: createWorkflowQstashClient() },
+ { ...personaUpdateWorkflowOptions, qstashClient: createWorkflowQstashClient() },
),
);
@@ -70,18 +70,17 @@ app.post(
withOtelMetricsForUpstashWorkflows(processTopicsHandler, {
url: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics',
}),
- { qstashClient: createWorkflowQstashClient() },
+ { ...processTopicsWorkflowOptions, qstashClient: createWorkflowQstashClient() },
),
);
-// NOTICE: Must use serveMany here. The `context.invoke(processTopicWorkflow)` call in
-// process-topics rewrites the URL last segment to the workflowId ("process-topic"). serveMany
-// multiplexes by that final segment to dispatch to the right workflow.
app.post(
'/pipelines/chat-topic/process-topic',
- serveMany(
- { 'process-topic': processTopicWorkflow },
- { qstashClient: createWorkflowQstashClient() },
+ serve(
+ withOtelMetricsForUpstashWorkflows(processTopicHandler, {
+ url: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ }),
+ { ...processTopicWorkflowOptions, qstashClient: createWorkflowQstashClient() },
),
);
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUserTopics.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUserTopics.test.ts
new file mode 100644
index 00000000000..a5055bb870c
--- /dev/null
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/processUserTopics.test.ts
@@ -0,0 +1,117 @@
+import { MemorySourceType } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { processUserTopicsHandler } from '../processUserTopics';
+
+const mocks = vi.hoisted(() => ({
+ createExecutor: vi.fn(),
+ getTopicsForUser: vi.fn(),
+ triggerProcessTopics: vi.fn(),
+ triggerProcessUserTopics: vi.fn(),
+}));
+
+// NOTICE: The module reads MAX_TOPICS_PER_USER_PER_RUN from this config at import time, so the cap
+// is fixed to 4 for the whole file to keep the fixtures small.
+vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({
+ parseMemoryExtractionConfig: () => ({
+ upstashWorkflowExtraHeaders: {},
+ workflow: { maxTopicsPerUserPerRun: 4 },
+ }),
+}));
+
+vi.mock('@/server/services/memory/userMemory/extract', () => ({
+ buildWorkflowPayloadInput: (payload: unknown) => payload,
+ MemoryExtractionExecutor: {
+ create: mocks.createExecutor,
+ },
+ MemoryExtractionWorkflowService: {
+ triggerProcessTopics: mocks.triggerProcessTopics,
+ triggerProcessUserTopics: mocks.triggerProcessUserTopics,
+ },
+ // Mirror the real default so params.topicFanoutCount is always a number.
+ normalizeMemoryExtractionPayload: (payload: Record<string, unknown>) => ({
+ ...payload,
+ layers: payload.layers ?? [],
+ sources: payload.sources ?? [],
+ topicFanoutCount: payload.topicFanoutCount ?? 0,
+ topicIds: payload.topicIds ?? [],
+ userIds: payload.userIds ?? [],
+ }),
+}));
+
+vi.mock('@/database/models/asyncTask', () => ({ AsyncTaskModel: class {} }));
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn() }));
+
+vi.mock('../runGuard', () => ({
+ checkGuard: vi.fn().mockResolvedValue({ result: true }),
+}));
+
+const createContext = () => ({
+ run: vi.fn((_name: string, callback: () => unknown) => callback()),
+});
+
+const basePayload = {
+ baseUrl: 'https://app.example.com',
+ sources: [MemorySourceType.ChatTopic],
+ userIds: ['u1'],
+};
+
+describe('processUserTopicsHandler per-user fan-out ceiling', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createExecutor.mockResolvedValue({ getTopicsForUser: mocks.getTopicsForUser });
+ mocks.triggerProcessTopics.mockResolvedValue({ workflowRunId: 'process-topics-run' });
+ mocks.triggerProcessUserTopics.mockResolvedValue({ workflowRunId: 'next-page-run' });
+ });
+
+ it('truncates the page to the remaining budget and stops paginating at the ceiling', async () => {
+ // Cap is 4 and this user has already fanned out 2 topics, so only 2 more may be triggered even
+ // though the page returns 4 β€” and no next page is scheduled because the ceiling is reached.
+ mocks.getTopicsForUser.mockResolvedValue({
+ cursor: { createdAt: '2024-07-02T09:36:44.073Z', id: 'cursor1' },
+ ids: ['t1', 't2', 't3', 't4'],
+ });
+
+ const context = createContext();
+ await processUserTopicsHandler({
+ requestPayload: { ...basePayload, topicFanoutCount: 2 },
+ ...context,
+ } as never);
+
+ expect(mocks.triggerProcessTopics).toHaveBeenCalledTimes(1);
+ expect(mocks.triggerProcessTopics).toHaveBeenCalledWith(
+ 'u1',
+ expect.objectContaining({ topicIds: ['t1', 't2'] }),
+ { extraHeaders: {} },
+ );
+ // Ceiling reached (2 + 2 === 4) β†’ never schedule the next page.
+ expect(mocks.triggerProcessUserTopics).not.toHaveBeenCalled();
+ });
+
+ it('threads the running fan-out count into the next page when under the ceiling', async () => {
+ mocks.getTopicsForUser.mockResolvedValue({
+ cursor: { createdAt: '2024-07-02T09:36:44.073Z', id: 'cursor1' },
+ ids: ['t1', 't2'],
+ });
+
+ const context = createContext();
+ await processUserTopicsHandler({
+ requestPayload: { ...basePayload, topicFanoutCount: 0 },
+ ...context,
+ } as never);
+
+ expect(mocks.triggerProcessTopics).toHaveBeenCalledWith(
+ 'u1',
+ expect.objectContaining({ topicIds: ['t1', 't2'] }),
+ { extraHeaders: {} },
+ );
+ // 0 + 2 === 2 < 4 β†’ schedule the next page carrying the accumulated count.
+ expect(mocks.triggerProcessUserTopics).toHaveBeenCalledWith(
+ expect.objectContaining({
+ topicCursor: { createdAt: '2024-07-02T09:36:44.073Z', id: 'cursor1', userId: 'u1' },
+ topicFanoutCount: 2,
+ }),
+ { extraHeaders: {} },
+ );
+ });
+});
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 526f056ad27..30b55dc6fb8 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
@@ -67,3 +67,15 @@ export const personaUpdateHandler = async (context: WorkflowContext) => {
processedUsers: userIds.length,
};
};
+
+// NOTICE: Serve-side flow control governs this workflow's own step-continuation messages so they
+// carry a flow-control key instead of falling into the shared "$" (unbound) bucket, which floods
+// when steps retry. `triggerPersonaUpdate` sets a per-user key for the *initial* delivery; this
+// static global key bounds concurrent step execution across users. Parallelism is a conservative
+// global cap.
+export const personaUpdateWorkflowOptions = {
+ flowControl: {
+ key: 'memory-user-memory.pipelines.persona.update-write',
+ parallelism: 4,
+ },
+};
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 6ce88a380d2..08078bfce80 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
@@ -2,13 +2,11 @@ import { SpanStatusCode } from '@lobechat/observability-otel/api';
import {
buildUpstashWorkflowMetricAttributes,
tracer as upstashWorkflowTracer,
- withOtelMetricsForUpstashWorkflows,
} from '@lobechat/observability-otel/modules/upstash-workflow';
import { LayersEnum, MemorySourceType } from '@lobechat/types';
import { errorMessageFrom } from '@lobechat/utils';
import { type WorkflowContext } from '@upstash/workflow';
import { WorkflowAbort, WorkflowNonRetryableError } from '@upstash/workflow';
-import { createWorkflow } from '@upstash/workflow/hono';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { getServerDB } from '@/database/server';
@@ -18,7 +16,6 @@ import {
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { createWorkflowQstashClient } from '../../qstashClient';
import { checkGuard } from './runGuard';
const CEPA_LAYERS: LayersEnum[] = [
@@ -31,7 +28,7 @@ const CEPA_LAYERS: LayersEnum[] = [
const IDENTITY_LAYERS: LayersEnum[] = [LayersEnum.Identity];
const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic';
-const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloadInput>) =>
+export const processTopicHandler = async (context: WorkflowContext<MemoryExtractionPayloadInput>) =>
upstashWorkflowTracer.startActiveSpan(
'workflow:memory-user-memory:process-topic',
async (span) => {
@@ -229,45 +226,56 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
},
);
-export const processTopicWorkflow = createWorkflow<MemoryExtractionPayloadInput, unknown>(
- withOtelMetricsForUpstashWorkflows(processTopicRoute, {
- url: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
- }),
- {
- failureFunction: async ({ context, failStatus, failResponse }) => {
- try {
- const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});
-
- const userId = payload.userId || payload.userIds?.[0];
- const topicId = payload.topicIds?.[0];
- if (!userId || !payload.asyncTaskId) {
- return 'no-async-task';
- }
+// NOTICE: Serve-side flow control governs this workflow's own step-continuation messages (the
+// QStash callbacks that advance each `context.run`) so they carry a key instead of landing in the
+// shared "$" (unbound) bucket, which floods when steps retry. `triggerProcessTopic` sets a per-user
+// key for the *initial* delivery; serve-side flow control can only use a static (config-time) key,
+// so this global key bounds concurrent step execution and, more importantly, keeps step callbacks
+// out of "$". Parallelism is a conservative global cap β€” the per-user trigger key (parallelism 5)
+// remains the primary per-user throttle.
+export const processTopicWorkflowOptions = {
+ failureFunction: async ({
+ context,
+ failResponse,
+ failStatus,
+ }: {
+ context: Pick<WorkflowContext<MemoryExtractionPayloadInput>, 'requestPayload'>;
+ failResponse: string;
+ failStatus: number;
+ }) => {
+ try {
+ const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});
- const db = await getServerDB();
- const asyncTaskModel = new AsyncTaskModel(db, userId, payload.workspaceId);
+ const userId = payload.userId || payload.userIds?.[0];
+ const topicId = payload.topicIds?.[0];
+ if (!userId || !payload.asyncTaskId) {
+ return 'no-async-task';
+ }
- // NOTICE: Progress here means "topic processed", not "topic succeeded".
- // The async task model now guards against flipping errored tasks back to success,
- // so failed topics can still advance progress bookkeeping safely.
- await asyncTaskModel.incrementUserMemoryExtractionProgress(payload.asyncTaskId);
+ const db = await getServerDB();
+ const asyncTaskModel = new AsyncTaskModel(db, userId, payload.workspaceId);
- console.error(
- `[process-topic][failureFunction] marking async task as failed for user ${userId}, topic ${topicId}`,
- {
- failResponse,
- failStatus,
- },
- );
+ // NOTICE: Progress here means "topic processed", not "topic succeeded".
+ // The async task model now guards against flipping errored tasks back to success,
+ // so failed topics can still advance progress bookkeeping safely.
+ await asyncTaskModel.incrementUserMemoryExtractionProgress(payload.asyncTaskId);
- return 'async-task-updated';
- } catch (error) {
- console.error('[process-topic][failureFunction] failed to record async task error', error);
- return 'async-task-update-failed';
- }
- },
- qstashClient: createWorkflowQstashClient(),
+ console.error(
+ `[process-topic][failureFunction] marking async task as failed for user ${userId}, topic ${topicId}`,
+ {
+ failResponse,
+ failStatus,
+ },
+ );
+
+ return 'async-task-updated';
+ } catch (error) {
+ console.error('[process-topic][failureFunction] failed to record async task error', error);
+ return 'async-task-update-failed';
+ }
},
-);
-
-processTopicWorkflow.workflowId = 'process-topic';
+ flowControl: {
+ key: 'memory-user-memory.pipelines.chat-topic.process-topic',
+ parallelism: 25,
+ },
+};
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 079d6c506fb..a2d69accf2f 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts
@@ -12,11 +12,11 @@ import { getServerDB } from '@/database/server';
import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
import { type MemoryExtractionPayloadInput } from '@/server/services/memory/userMemory/extract';
import {
+ buildWorkflowPayloadInput,
MemoryExtractionWorkflowService,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { processTopicWorkflow } from './processTopic';
import { checkGuard } from './runGuard';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
@@ -118,9 +118,12 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
};
}
}
- // Delegate per-topic extraction to dedicated workflow for better isolation.
+ // 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
+ // ceiling is enforced upstream in process-user-topics.
for (const [index, topicId] of payload.topicIds.entries()) {
- const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:invoke:${index}`;
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:trigger:${index}`;
const guard = await checkGuard(context, WORKFLOW_PATH, {
response: { processedTopics: 0, processedUsers: 0 },
stepName,
@@ -130,28 +133,21 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
return guard.response;
}
- await context.invoke(stepName, {
- body: {
- ...payload,
- layers: payload.layers.length ? payload.layers : [...CEPA_LAYERS, ...IDENTITY_LAYERS],
- topicIds: [topicId],
+ await context.run(stepName, () =>
+ MemoryExtractionWorkflowService.triggerProcessTopic(
userId,
- userIds: [userId],
- },
- // CEPA: run in parallel across the batch
- //
- // NOTICE: if modified the parallelism of CEPA_LAYERS
- // or added new memory layer, make sure to update the number below.
- //
- // Currently, CEPA (context, experience, preference, activity) + identity = 5 layers.
- // and since identity requires sequential processing, we set parallelism to 5.
- flowControl: {
- key: `memory-user-memory.pipelines.chat-topic.process-topic.user.${userId}.topic.${topicId}`,
- parallelism: 5,
- },
- headers: upstashWorkflowExtraHeaders,
- workflow: processTopicWorkflow,
- });
+ {
+ ...buildWorkflowPayloadInput(payload),
+ layers: payload.layers.length
+ ? payload.layers
+ : [...CEPA_LAYERS, ...IDENTITY_LAYERS],
+ topicIds: [topicId],
+ userId,
+ userIds: [userId],
+ },
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ ),
+ );
}
// Trigger user persona update after topic processing using the workflow client.
@@ -196,3 +192,18 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
}
},
);
+
+// NOTICE: Serve-side flow control governs a running workflow's own step-continuation messages
+// (the QStash callbacks that advance each `context.run`). Without it, every process-topics step
+// callback is published with NO flow-control key and lands in the shared "$" (unbound) bucket,
+// which floods when steps retry (e.g. the auth-failure retry storm). `triggerProcessTopics`
+// additionally sets a per-user key for the *initial* delivery; serve-side flow control can only
+// use a static (config-time) key, so this global key bounds concurrent step execution and, more
+// importantly, keeps step callbacks out of "$". Parallelism is a conservative global cap β€” the
+// per-user trigger key (parallelism 20) remains the primary per-user throttle.
+export const processTopicsWorkflowOptions = {
+ flowControl: {
+ key: 'memory-user-memory.pipelines.chat-topic.process-topics',
+ parallelism: 20,
+ },
+};
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 087e02dd9f7..8d36d1a3911 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
@@ -24,6 +24,11 @@ const PROCESS_USER_TOPICS_FLOW_CONTROL_KEY =
const { upstashWorkflowExtraHeaders, workflow } = parseMemoryExtractionConfig();
+// NOTICE: Hard per-user, per-run fan-out ceiling. flowControl only bounds concurrency, not queue
+// depth, so this count cap is what actually prevents one heavy user from backing up a massive
+// QStash fan-out. Remaining un-extracted topics resume on later hourly runs, so it self-drains.
+const MAX_TOPICS_PER_USER_PER_RUN = workflow?.maxTopicsPerUserPerRun ?? 100;
+
export const processUserTopicsHandler = async (
context: WorkflowContext<MemoryExtractionPayloadInput>,
) => {
@@ -43,7 +48,12 @@ export const processUserTopicsHandler = async (
const executor = await MemoryExtractionExecutor.create();
- const scheduleNextPage = async (userId: string, cursorCreatedAt: Date, cursorId: string) => {
+ const scheduleNextPage = async (
+ userId: string,
+ cursorCreatedAt: Date,
+ cursorId: string,
+ fanoutCount: number,
+ ) => {
await MemoryExtractionWorkflowService.triggerProcessUserTopics(
{
...buildWorkflowPayloadInput({
@@ -53,6 +63,8 @@ export const processUserTopicsHandler = async (
id: cursorId,
userId,
},
+ // Carry the running fan-out count so the per-user ceiling spans the whole page chain.
+ topicFanoutCount: fanoutCount,
topicIds: [],
userId,
userIds: [userId],
@@ -141,10 +153,20 @@ export const processUserTopicsHandler = async (
const cursor = 'cursor' in topicBatch ? topicBatch.cursor : undefined;
- for (const [batchIndex, topicIds] of chunk(ids, TOPIC_BATCH_SIZE).entries()) {
- // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last path
- // segment with the workflowId. If we invoked directly from /process-user-topics, child workflow
- // URLs would inherit that base and lose the desired /process-topics/workflows prefix.
+ // NOTICE: Enforce the hard per-user, per-run fan-out ceiling on the paginated discovery path.
+ // Explicit topicIds requests (topicsFromPayload) are user-intended and never capped. The count
+ // rides in the payload across pages; any topics beyond the ceiling stay un-extracted and are
+ // picked up by later hourly runs, so no data is dropped.
+ const fanoutCount = params.topicFanoutCount;
+ const remainingBudget = topicsFromPayload
+ ? ids.length
+ : Math.max(0, MAX_TOPICS_PER_USER_PER_RUN - fanoutCount);
+ const idsToProcess = topicsFromPayload ? ids : ids.slice(0, remainingBudget);
+
+ for (const [batchIndex, topicIds] of chunk(idsToProcess, TOPIC_BATCH_SIZE).entries()) {
+ // NOTICE: We trigger via QStash instead of context.invoke because invoke only swaps the last
+ // path segment with the workflowId. If we invoked directly from /process-user-topics, child
+ // workflow URLs would inherit that base and lose the desired /process-topics prefix.
const stepName = `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`;
const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });
if (!guard.result) return guard.response;
@@ -164,7 +186,10 @@ export const processUserTopicsHandler = async (
);
}
- if (!topicsFromPayload && cursor) {
+ 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 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;
@@ -178,7 +203,7 @@ export const processUserTopicsHandler = async (
throw new Error('Invalid cursor date when scheduling next topic page');
}
- return scheduleNextPage(userId, createdAt, cursor.id);
+ return scheduleNextPage(userId, createdAt, cursor.id, nextFanoutCount);
});
}
}