π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(memory): run guard Redis checks in workflow steps (#16770)
Nekocaf04377bacf
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.tsindex 1b2c613ea5b..bcce08f6273 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@@ -36,8 +36,7 @@ vi.mock('@/server/services/memory/userMemory/extract', () => ({}));vi.mock('../runGuard', () => ({- assertMemoryWorkflowContextAllowed: vi.fn(),- resolveMemoryWorkflowRunGuard: vi.fn().mockResolvedValue(null),+ checkGuard: vi.fn().mockResolvedValue({ result: true }),}));describe('hourlyWorkflowHandler', () => {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.tsnew file mode 100644index 00000000000..fe0e9f78a72--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts@@ -0,0 +1,65 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ checkGuard: vi.fn(),+}));++vi.mock('@/database/server', () => ({+ getServerDB: vi.fn(),+}));++vi.mock('@/server/services/memory/userMemory/persona/service', () => ({+ buildUserPersonaJobInput: vi.fn(),+ UserPersonaService: vi.fn(),+}));++vi.mock('../runGuard', () => ({+ checkGuard: mocks.checkGuard,+}));++const { personaUpdateHandler } = await import('../personaUpdate');++describe('personaUpdateHandler run guard', () => {+ beforeEach(() => {+ mocks.checkGuard.mockReset();+ });++ it('checks the run guard before parsing payload', async () => {+ /**+ * @example+ * await expect(personaUpdateHandler(context)).resolves.toMatchObject({ skipped: true });+ */+ mocks.checkGuard.mockResolvedValue({+ block: {+ matchedKey: 'workflow:run-guard:global',+ reason: 'maintenance',+ scope: 'global',+ },+ response: {+ message: 'Memory workflow disabled by run guard (maintenance); skipping.',+ processedUsers: 0,+ skipped: true,+ },+ result: false,+ });++ const context = {+ requestPayload: { userIds: ['user-1'] },+ run: vi.fn((_name: string, callback: () => unknown) => callback()),+ workflowRunId: 'wfr_persona',+ };++ await expect(personaUpdateHandler(context as never)).resolves.toEqual({+ message: 'Memory workflow disabled by run guard (maintenance); skipping.',+ processedUsers: 0,+ skipped: true,+ });++ expect(context.run).not.toHaveBeenCalled();+ expect(mocks.checkGuard).toHaveBeenCalledWith(+ context,+ 'api/workflows/memory-user-memory/pipelines/persona/update-writing',+ { response: { processedUsers: 0 } },+ );+ });+});diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/runGuard.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/runGuard.test.tsindex f5693d549e8..a29070c827c 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/runGuard.test.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/runGuard.test.ts@@ -17,10 +17,20 @@ vi.mock('@/envs/redis', () => ({vi.mock('@/server/workflows/runGuard', () => ({assertWorkflowRunAllowed: mocks.assertWorkflowRunAllowed,+ WorkflowRunGuardError: class WorkflowRunGuardError extends Error {+ guardScope = 'workflow';+ matchedKey = 'workflow-run-guard:test';+ reason = 'maintenance';+ },}));-const { assertMemoryWorkflowContextAllowed, assertMemoryWorkflowRunAllowed } =- await import('../runGuard');+const { checkGuard } = await import('../runGuard');++const createContext = (payload: unknown, workflowRunId = 'wfr_context') => ({+ requestPayload: payload,+ run: vi.fn((_name: string, callback: () => unknown) => callback()),+ workflowRunId,+});describe('memory workflow run guard helper', () => {beforeEach(() => {@@ -32,47 +42,50 @@ describe('memory workflow run guard helper', () => {mocks.assertWorkflowRunAllowed.mockResolvedValue(undefined);});- it('builds a memory workflow guard scope', async () => {+ it('runs the Redis guard lookup inside a workflow step', async () => {const redis = { get: vi.fn() };mocks.initializeRedis.mockResolvedValue(redis);+ const context = createContext({ userId: 'user-1', userIds: ['user-1'] });- await assertMemoryWorkflowRunAllowed({- payload: {- userId: 'user-1',- userIds: ['user-1'],- },- stepName: 'memory:user-memory:extract:cepa',- workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',- workflowRunId: 'wfr_1',- });-+ await expect(+ checkGuard(+ context as never,+ 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',+ ),+ ).resolves.toEqual({ result: true });++ expect(context.run).toHaveBeenCalledWith(+ 'memory:user-memory:run-guard:api/workflows/memory-user-memory/pipelines/chat-topic/process-topic:entry',+ expect.any(Function),+ );expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(redis,expect.objectContaining({- stepName: 'memory:user-memory:extract:cepa',+ stepName: undefined,userId: 'user-1',workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',- workflowRunId: 'wfr_1',+ workflowRunId: 'wfr_context',}),);- expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledTimes(1);});- it('uses workflowRunId from workflow context when available', async () => {+ it('includes step scope when checking a step boundary', async () => {const redis = { get: vi.fn() };mocks.initializeRedis.mockResolvedValue(redis);+ const context = createContext({ userIds: ['user-2'] });- await assertMemoryWorkflowContextAllowed(- {- requestPayload: {- userIds: ['user-2'],- },- workflowRunId: 'wfr_context',- } as never,+ await checkGuard(+ context as never,'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',- 'memory:user-memory:extract:get-users',+ {+ stepName: 'memory:user-memory:extract:get-users',+ },);+ expect(context.run).toHaveBeenCalledWith(+ 'memory:user-memory:run-guard:api/workflows/memory-user-memory/pipelines/chat-topic/process-users:memory:user-memory:extract:get-users',+ expect.any(Function),+ );expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(redis,expect.objectContaining({@@ -81,16 +94,18 @@ describe('memory workflow run guard helper', () => {workflowRunId: 'wfr_context',}),);- expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledTimes(1);});it('passes null Redis when Redis is disabled', async () => {mocks.isRedisEnabled.mockReturnValue(false);+ const context = createContext({ userId: 'user-1' });- await assertMemoryWorkflowRunAllowed({- payload: { userId: 'user-1' },- workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',- });+ await expect(+ checkGuard(+ context as never,+ 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',+ ),+ ).resolves.toEqual({ result: true });expect(mocks.initializeRedis).not.toHaveBeenCalled();expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(@@ -102,14 +117,14 @@ describe('memory workflow run guard helper', () => {it('ignores malformed user ids from unknown payloads', async () => {const redis = { get: vi.fn() };mocks.initializeRedis.mockResolvedValue(redis);+ const context = createContext({ userId: 123, userIds: [false, 'user-from-array'] });- await assertMemoryWorkflowRunAllowed({- payload: {- userId: 123,- userIds: [false, 'user-from-array'],- },- workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',- });+ await expect(+ checkGuard(+ context as never,+ 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',+ ),+ ).resolves.toEqual({ result: true });expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(redis,@@ -117,15 +132,55 @@ describe('memory workflow run guard helper', () => {);});- it('propagates guard rejections', async () => {+ it('propagates unexpected guard rejections', async () => {const error = new Error('blocked');mocks.assertWorkflowRunAllowed.mockRejectedValue(error);+ const context = createContext({ userId: 'user-1' });await expect(- assertMemoryWorkflowRunAllowed({- payload: { userId: 'user-1' },- workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',- }),+ checkGuard(+ context as never,+ 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',+ ),).rejects.toBe(error);});++ it('converts workflow guard rejections into block details and a response', async () => {+ const { WorkflowRunGuardError } = await import('@/server/workflows/runGuard');+ mocks.assertWorkflowRunAllowed.mockRejectedValue(+ new WorkflowRunGuardError({+ match: {+ key: 'workflow-run-guard:test',+ scope: 'global',+ value: { reason: 'maintenance' },+ },+ scope: {+ workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',+ },+ }),+ );+ const context = createContext({ userId: 'user-1' });++ await expect(+ checkGuard(+ context as never,+ 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',+ {+ response: { processedUsers: 0 },+ },+ ),+ ).resolves.toEqual({+ block: {+ matchedKey: 'workflow-run-guard:test',+ reason: 'maintenance',+ scope: 'workflow',+ },+ response: {+ message: 'Memory workflow disabled by run guard (maintenance); skipping.',+ processedUsers: 0,+ skipped: true,+ },+ result: false,+ });+ });});diff --git a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts b/src/server/workflows-hono/memory-user-memory/workflows/hourly.tsindex e9cdc207285..fcc0349be5c 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts@@ -12,7 +12,7 @@ import {normalizeMemoryExtractionPayload,} from '@/server/services/memory/userMemory/extract';-import { resolveMemoryWorkflowRunGuard } from './runGuard';+import { checkGuard } from './runGuard';import { serializeWorkflowCursor } from './utils';const USER_PAGE_SIZE = 200;@@ -31,14 +31,10 @@ export const hourlyWorkflowHandler = async (// 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// into an infinite retry storm.- const guardBlock = await resolveMemoryWorkflowRunGuard(context, WORKFLOW_PATH);- if (guardBlock) {- return {- message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,- processedUsers: 0,- skipped: true,- };- }+ const entryGuard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedUsers: 0 },+ });+ if (!entryGuard.result) return entryGuard.response;const baseUrl = resolveBaseUrl();if (!baseUrl) {@@ -54,6 +50,12 @@ export const hourlyWorkflowHandler = async (const executor = await MemoryExtractionExecutor.create();const listUsersStepName = `memory:user-memory:hourly:list-users:${parsedCursor?.id || 'root'}`;+ const listUsersGuard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedUsers: 0 },+ stepName: listUsersStepName,+ });+ if (!listUsersGuard.result) return listUsersGuard.response;+const userBatch = await context.run(listUsersStepName, () =>executor.getUsersForHourlyExtraction(USER_PAGE_SIZE, parsedCursor),);@@ -72,28 +74,38 @@ export const hourlyWorkflowHandler = async (if (!dryRun) {const batches = chunk(userIds, USER_BATCH_SIZE);- await Promise.all(- batches.map(async (batchUserIds, index) => {- const stepName = `memory:user-memory:hourly:trigger-users:${index}`;- return context.run(stepName, () =>- MemoryExtractionWorkflowService.triggerProcessUsers(- buildWorkflowPayloadInput(- normalizeMemoryExtractionPayload({- baseUrl,- mode: 'workflow',- sources: [MemorySourceType.ChatTopic],- userIds: batchUserIds,- }),- ),- { extraHeaders: upstashWorkflowExtraHeaders },+ for (const [index, batchUserIds] of batches.entries()) {+ const stepName = `memory:user-memory:hourly:trigger-users:${index}`;+ const guard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedUsers: 0 },+ stepName,+ });+ if (!guard.result) return guard.response;++ await context.run(stepName, () =>+ MemoryExtractionWorkflowService.triggerProcessUsers(+ buildWorkflowPayloadInput(+ normalizeMemoryExtractionPayload({+ baseUrl,+ mode: 'workflow',+ sources: [MemorySourceType.ChatTopic],+ userIds: batchUserIds,+ }),),- );- }),- );+ { extraHeaders: upstashWorkflowExtraHeaders },+ ),+ );+ }}if (nextCursor) {const stepName = 'memory:user-memory:hourly:schedule-next-page';+ const guard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedUsers: 0 },+ stepName,+ });+ if (!guard.result) return guard.response;+await context.run(stepName, () =>MemoryExtractionWorkflowService.triggerHourly({diff --git a/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.tsindex 8960f222a8f..526f056ad27 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts@@ -7,7 +7,7 @@ import {UserPersonaService,} from '@/server/services/memory/userMemory/persona/service';-import { resolveMemoryWorkflowRunGuard } from './runGuard';+import { checkGuard } from './runGuard';const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/persona/update-writing';@@ -18,16 +18,19 @@ const workflowPayloadSchema = z.object({export const personaUpdateHandler = async (context: WorkflowContext) => {// NOTICE: Return (never throw) on a guard match β a throw before the first step makes Upstash// re-enqueue the run, turning a "disable" guard into an infinite retry storm.- const guardBlock = await resolveMemoryWorkflowRunGuard(context, WORKFLOW_PATH);- if (guardBlock) {- return {- message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,- processedUsers: 0,- skipped: true,- };- }+ const entryGuard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedUsers: 0 },+ });+ if (!entryGuard.result) return entryGuard.response;++ const parsePayloadStepName = 'memory:pipelines:persona:update-writing:parse-payload';+ const parsePayloadGuard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedUsers: 0 },+ stepName: parsePayloadStepName,+ });+ if (!parsePayloadGuard.result) return parsePayloadGuard.response;- const payload = await context.run('memory:pipelines:persona:update-writing:parse-payload', () =>+ const payload = await context.run(parsePayloadStepName, () =>workflowPayloadSchema.parse(context.requestPayload || {}),);const db = await getServerDB();@@ -39,20 +42,25 @@ export const personaUpdateHandler = async (context: WorkflowContext) => {const service = new UserPersonaService(db);- await Promise.all(- userIds.map(async (userId) =>- context.run(`memory:pipelines:persona:update-writing:users:${userId}`, async () => {- const jobInput = await buildUserPersonaJobInput(db, userId);- const result = await service.composeWriting({ ...jobInput, userId });- return {- diffId: result.diff?.id,- documentId: result.document.id,- userId,- version: result.document.version,- };- }),- ),- );+ for (const userId of userIds) {+ const stepName = `memory:pipelines:persona:update-writing:users:${userId}`;+ const guard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedUsers: 0 },+ stepName,+ });+ if (!guard.result) return guard.response;++ await context.run(stepName, async () => {+ const jobInput = await buildUserPersonaJobInput(db, userId);+ const result = await service.composeWriting({ ...jobInput, userId });+ return {+ diffId: result.diff?.id,+ documentId: result.document.id,+ userId,+ version: result.document.version,+ };+ });+ }return {message: 'User persona processed via workflow.',diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.tsindex d5ceb6d7968..6ce88a380d2 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts@@ -19,7 +19,7 @@ import {} from '@/server/services/memory/userMemory/extract';import { createWorkflowQstashClient } from '../../qstashClient';-import { resolveMemoryWorkflowRunGuard } from './runGuard';+import { checkGuard } from './runGuard';const CEPA_LAYERS: LayersEnum[] = [LayersEnum.Context,@@ -49,13 +49,10 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloatry {// NOTICE: Return (never throw) on a guard match β a throw before the first step makes// Upstash re-enqueue the run, turning a "disable" guard into an infinite retry storm.- const guardBlock = await resolveMemoryWorkflowRunGuard(context, WORKFLOW_PATH);- if (guardBlock) {+ const entryGuard = await checkGuard(context, WORKFLOW_PATH);+ if (!entryGuard.result) {span.setStatus({ code: SpanStatusCode.OK });- return {- message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,- skipped: true,- };+ return entryGuard.response;}const topicId = payload.topicIds[0];@@ -77,6 +74,12 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa// NOTICE: Cooperative cascading cancellation for the workflow tree.// Check before CEPA extraction so cancelled tasks stop at the earliest safe boundary.const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:before`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return guard.response;+ }+const cancelled = await context.run(stepName, () =>getServerDB().then((db) =>new AsyncTaskModel(@@ -99,6 +102,12 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa}const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cepa`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return guard.response;+ }+await context.run(stepName, () =>executor.extractTopic({asyncTaskId: payload.asyncTaskId,@@ -121,6 +130,12 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa// NOTICE: Cooperative cascading cancellation for the workflow tree.// Re-check before identity extraction to avoid running sequential identity step after cancel.const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:identity`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return guard.response;+ }+const cancelled = await context.run(stepName, () =>getServerDB().then((db) =>new AsyncTaskModel(@@ -144,6 +159,12 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa}const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:identity`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return guard.response;+ }+await context.run(stepName, () =>executor.extractTopic({asyncTaskId: payload.asyncTaskId,@@ -164,6 +185,12 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloaif (payload.asyncTaskId && payload.userInitiated) {const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:progress`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return guard.response;+ }+await context.run(stepName, () =>getServerDB().then((db) =>new AsyncTaskModel(diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.tsindex 45444670eff..079d6c506fb 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts@@ -17,7 +17,7 @@ import {} from '@/server/services/memory/userMemory/extract';import { processTopicWorkflow } from './processTopic';-import { resolveMemoryWorkflowRunGuard } from './runGuard';+import { checkGuard } from './runGuard';const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topics';@@ -50,16 +50,12 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPatry {// NOTICE: Return (never throw) on a guard match β a throw before the first step makes// Upstash re-enqueue the run, turning a "disable" guard into an infinite retry storm.- const guardBlock = await resolveMemoryWorkflowRunGuard(context, WORKFLOW_PATH);- if (guardBlock) {+ const entryGuard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedTopics: 0, processedUsers: 0 },+ });+ if (!entryGuard.result) {span.setStatus({ code: SpanStatusCode.OK });-- return {- message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,- processedTopics: 0,- processedUsers: 0,- skipped: true,- };+ return entryGuard.response;}if (!payload.userIds.length) {@@ -95,6 +91,15 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa// NOTICE: Cooperative cascading cancellation for the workflow tree.// If cancelled, stop before fan-out into per-topic child workflows.const stepName = `memory:user-memory:extract:users:${userId}:cancel-check`;+ const guard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedTopics: 0, processedUsers: 0 },+ stepName,+ });+ if (!guard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return guard.response;+ }+const cancelled = await context.run(stepName, () =>getServerDB().then((db) =>new AsyncTaskModel(@@ -116,6 +121,15 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa// Delegate per-topic extraction to dedicated workflow for better isolation.for (const [index, topicId] of payload.topicIds.entries()) {const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:invoke:${index}`;+ const guard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedTopics: 0, processedUsers: 0 },+ stepName,+ });+ if (!guard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return guard.response;+ }+await context.invoke(stepName, {body: {...payload,@@ -142,6 +156,15 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa// Trigger user persona update after topic processing using the workflow client.const personaUpdateStepName = `memory:user-memory:users:${userId}`;+ const personaUpdateGuard = await checkGuard(context, WORKFLOW_PATH, {+ response: { processedTopics: 0, processedUsers: 0 },+ stepName: personaUpdateStepName,+ });+ if (!personaUpdateGuard.result) {+ span.setStatus({ code: SpanStatusCode.OK });+ return personaUpdateGuard.response;+ }+await context.run(personaUpdateStepName, async () => {await MemoryExtractionWorkflowService.triggerPersonaUpdate(userId, payload.baseUrl, {extraHeaders: upstashWorkflowExtraHeaders,diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.tsindex 4c53e12904f..087e02dd9f7 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts@@ -1,5 +1,6 @@import { MemorySourceType } from '@lobechat/types';import { type WorkflowContext } from '@upstash/workflow';+import { chunk } from 'es-toolkit/compat';import { AsyncTaskModel } from '@/database/models/asyncTask';import { type ListTopicsForMemoryExtractorCursor } from '@/database/models/topic';@@ -12,9 +13,8 @@ import {MemoryExtractionWorkflowService,normalizeMemoryExtractionPayload,} from '@/server/services/memory/userMemory/extract';-import { forEachBatchSequential } from '@/server/services/memory/userMemory/topicBatching';-import { resolveMemoryWorkflowRunGuard } from './runGuard';+import { checkGuard } from './runGuard';const TOPIC_PAGE_SIZE = 50;const TOPIC_BATCH_SIZE = 4;@@ -31,13 +31,8 @@ export const processUserTopicsHandler = async (// NOTICE: Return (never throw) on a guard match β a throw before the first step makes Upstash// re-enqueue the run, turning a "disable" guard into an infinite retry storm.- const guardBlock = await resolveMemoryWorkflowRunGuard(context, WORKFLOW_PATH);- if (guardBlock) {- return {- message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,- skipped: true,- };- }+ const entryGuard = await checkGuard(context, WORKFLOW_PATH);+ if (!entryGuard.result) return entryGuard.response;if (!params.userIds.length) {return { message: 'No user ids provided for topic processing.' };@@ -72,6 +67,9 @@ export const processUserTopicsHandler = async (// NOTICE: Cooperative cascading cancellation for the workflow tree.// A cancelled root task should stop at user-topic pagination and avoid enqueuing topic batches.const stepName = `memory:user-memory:extract:users:${userId}:cancel-check`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) return guard.response;+const cancelled = await context.run(stepName, () =>getServerDB().then((db) =>new AsyncTaskModel(@@ -97,6 +95,9 @@ export const processUserTopicsHandler = async (let topicsFromPayload: string[] | undefined;if (params.topicIds && params.topicIds.length > 0) {const stepName = `memory:user-memory:extract:users:${userId}:filter-topic-ids`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) return guard.response;+topicsFromPayload = await context.run(stepName, async () => {const filtered = await executor.filterTopicIdsForUser(userId,@@ -108,6 +109,11 @@ export const processUserTopicsHandler = async (}const listTopicsStepName = `memory:user-memory:extract:users:${userId}:list-topics:${topicCursor?.id || 'root'}`;+ const listTopicsGuard = await checkGuard(context, WORKFLOW_PATH, {+ stepName: listTopicsStepName,+ });+ if (!listTopicsGuard.result) return listTopicsGuard.response;+const topicBatch = await context.run<{cursor?: ListTopicsForMemoryExtractorCursor;ids: string[];@@ -135,13 +141,14 @@ export const processUserTopicsHandler = async (const cursor = 'cursor' in topicBatch ? topicBatch.cursor : undefined;- // TODO: follow the new pattern of process-topic- // remove the batch sequential, replace it with context.invoke(...) pattern- await forEachBatchSequential(ids, TOPIC_BATCH_SIZE, async (topicIds, batchIndex) => {+ 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.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;+await context.run(stepName, () =>MemoryExtractionWorkflowService.triggerProcessTopics(userId,@@ -155,10 +162,13 @@ export const processUserTopicsHandler = async ({ extraHeaders: upstashWorkflowExtraHeaders },),);- });+ }if (!topicsFromPayload && cursor) {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, () => {// NOTICE: Upstash Workflow only supports serializable data into plain JSON,// this causes the Date object to be converted into string when passed as parameter fromdiff --git a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.tsindex 69f8262fd93..18ea4eb4052 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts@@ -12,7 +12,7 @@ import {normalizeMemoryExtractionPayload,} from '@/server/services/memory/userMemory/extract';-import { resolveMemoryWorkflowRunGuard } from './runGuard';+import { checkGuard } from './runGuard';import { serializeWorkflowCursor } from './utils';const USER_PAGE_SIZE = 50;@@ -29,13 +29,8 @@ export const processUsersHandler = async (// NOTICE: Return (never throw) on a guard match β a throw before the first step makes Upstash// re-enqueue the run, turning a "disable" guard into an infinite retry storm.- const guardBlock = await resolveMemoryWorkflowRunGuard(context, WORKFLOW_PATH);- if (guardBlock) {- return {- message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,- skipped: true,- };- }+ const entryGuard = await checkGuard(context, WORKFLOW_PATH);+ if (!entryGuard.result) return entryGuard.response;if (params.sources.length === 0) {return { message: 'No sources provided, skip memory extraction.' };@@ -44,6 +39,9 @@ export const processUsersHandler = async (// NOTICE: Cooperative cascading cancellation for the workflow tree.// If root task has cancelRequestedAt, this stage stops scheduling child workflows.const stepName = 'memory:user-memory:extract:cancel-check:root';+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) return guard.response;+const cancelled = await context.run(stepName, () =>getServerDB().then((db) =>new AsyncTaskModel(@@ -68,6 +66,9 @@ export const processUsersHandler = async (: undefined;const getUsersStepName = 'memory:user-memory:extract:get-users';+ const getUsersGuard = await checkGuard(context, WORKFLOW_PATH, { stepName: getUsersStepName });+ if (!getUsersGuard.result) return getUsersGuard.response;+const userBatch = await context.run(getUsersStepName, () =>params.userIds.length > 0? { ids: params.userIds }@@ -82,25 +83,29 @@ export const processUsersHandler = async (const cursor = 'cursor' in userBatch ? userBatch.cursor : undefined;const batches = chunk(ids, USER_BATCH_SIZE);- await Promise.all(- batches.map(async (userIds) => {- const stepName = 'memory:user-memory:extract:users:process-topic-batches';- return context.run(stepName, () =>- MemoryExtractionWorkflowService.triggerProcessUserTopics(- {- ...buildWorkflowPayloadInput(params),- topicCursor: undefined,- userId: userIds[0],- userIds,- },- { extraHeaders: upstashWorkflowExtraHeaders },- ),- );- }),- );+ for (const [index, userIds] of batches.entries()) {+ const stepName = `memory:user-memory:extract:users:process-topic-batches:${index}`;+ const guard = await checkGuard(context, WORKFLOW_PATH, { stepName });+ if (!guard.result) return guard.response;++ await context.run(stepName, () =>+ MemoryExtractionWorkflowService.triggerProcessUserTopics(+ {+ ...buildWorkflowPayloadInput(params),+ topicCursor: undefined,+ userId: userIds[0],+ userIds,+ },+ { extraHeaders: upstashWorkflowExtraHeaders },+ ),+ );+ }if (params.userIds.length === 0 && cursor) {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, () =>MemoryExtractionWorkflowService.triggerProcessUsers({diff --git a/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts b/src/server/workflows-hono/memory-user-memory/workflows/runGuard.tsindex 48a3d961dfc..d274a45deda 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts@@ -5,16 +5,6 @@ import { initializeRedis, isRedisEnabled } from '@/libs/redis';import { type BaseRedisProvider } from '@/libs/redis/types';import { assertWorkflowRunAllowed, WorkflowRunGuardError } from '@/server/workflows/runGuard';-interface MemoryWorkflowGuardInput {- payload?: unknown;- stepName?: string;- workflowPath: string;- workflowRunId?: string;-}--const getWorkflowRunId = (context: WorkflowContext<unknown>): string | undefined =>- (context as unknown as { workflowRunId?: string }).workflowRunId;-const getRedis = async (): Promise<BaseRedisProvider | null> => {const config = getRedisConfig();if (!isRedisEnabled(config)) return null;@@ -34,102 +24,157 @@ const getPayloadUserId = (payload: unknown): string | undefined => {return userIds.find((id): id is string => typeof id === 'string' && id.length > 0);};+const getWorkflowRunId = (context: WorkflowContext<unknown>): string | undefined =>+ (context as unknown as { workflowRunId?: string }).workflowRunId;+/**- * Checks whether a memory workflow run may continue for the provided scope.- *- * Use when:- * - Memory workflow handlers start or reach an expensive step boundary.- * - Redis failures should inherit the shared run guard fail-open behavior.- *- * Expects:- * - `workflowPath` identifies the current memory workflow route.- * - `payload` may include `userId` or `userIds` for user-level guard checks.- *- * Returns:- * - Resolves when no guard blocks the workflow.- * - Rejects with the shared guard error when a matching guard exists.+ * Details of a run guard that blocks a memory workflow.*/-export const assertMemoryWorkflowRunAllowed = async ({- payload,- stepName,- workflowPath,- workflowRunId,-}: MemoryWorkflowGuardInput): Promise<void> => {- const redis = await getRedis();-- await assertWorkflowRunAllowed(redis, {- stepName,- userId: getPayloadUserId(payload),- workflowPath,- workflowRunId,- });-};+export interface MemoryWorkflowRunGuardBlock {+ /**+ * Redis key that matched the current workflow scope.+ */+ matchedKey: string;++ /**+ * Human-readable operator reason stored with the guard.+ */+ reason?: string;++ /**+ * Logical guard scope that matched.+ */+ scope: string;+}/**- * Checks whether a memory workflow context may continue for a route or step.- *- * Use when:- * - A Hono Upstash workflow handler has a concrete {@link WorkflowContext}.- * - The caller wants to include the current workflow run id when available.+ * Extra response fields for a blocked memory workflow.+ */+type MemoryWorkflowRunGuardResponseExtra = Record<string, unknown>;++/**+ * Response returned when a memory workflow run guard blocks execution.*- * Expects:- * - `workflowPath` is the route path serving the current workflow.- * - `stepName` is passed before the matching `context.run` or `context.invoke` call.+ * @param TExtra Additional fields expected by the current workflow response shape.+ */+export type MemoryWorkflowRunGuardResponse<TExtra extends MemoryWorkflowRunGuardResponseExtra> = {+ /**+ * Human-readable skip message.+ */+ message: string;++ /**+ * Whether this workflow stopped because of a guard.+ */+ skipped: true;+} & TExtra;++/**+ * Result of a memory workflow run guard check.*- * Returns:- * - Resolves when no guard blocks the workflow.- * - Rejects with the shared guard error when a matching guard exists.+ * @param TExtra Additional fields expected by the current workflow response shape.*/-export const assertMemoryWorkflowContextAllowed = async (- context: WorkflowContext<unknown>,- workflowPath: string,- stepName?: string,-): Promise<void> => {- await assertMemoryWorkflowRunAllowed({- payload: context.requestPayload,- stepName,- workflowPath,- workflowRunId: getWorkflowRunId(context),- });-};+export type MemoryWorkflowRunGuardCheck<TExtra extends MemoryWorkflowRunGuardResponseExtra> =+ | {+ /**+ * Whether workflow execution may continue.+ */+ result: true;+ }+ | {+ /**+ * Matched guard details for observability or custom handling.+ */+ block: MemoryWorkflowRunGuardBlock;++ /**+ * Whether workflow execution may continue.+ */+ result: false;++ /**+ * Handler-specific response to return immediately.+ */+ response: MemoryWorkflowRunGuardResponse<TExtra>;+ };/**- * Details of a run guard that blocks a memory workflow.+ * Options for checking a memory workflow run guard.+ *+ * @param TExtra Additional fields expected by the current workflow response shape.*/-export interface MemoryWorkflowRunGuardBlock {- matchedKey: string;- reason?: string;- scope: string;+export interface MemoryWorkflowRunGuardCheckOptions<+ TExtra extends MemoryWorkflowRunGuardResponseExtra,+> {+ /**+ * Extra fields merged into the blocked response.+ */+ response?: TExtra;++ /**+ * Step name guarded before the matching workflow operation.+ */+ stepName?: string;}+const createBlockedResponse = <TExtra extends MemoryWorkflowRunGuardResponseExtra>(+ block: MemoryWorkflowRunGuardBlock,+ extra?: TExtra,+): MemoryWorkflowRunGuardResponse<TExtra> => ({+ ...(extra ?? ({} as TExtra)),+ message: `Memory workflow disabled by run guard (${block.reason ?? block.scope}); skipping.`,+ skipped: true,+});+/**- * Resolves whether a run guard blocks this memory workflow, WITHOUT throwing.+ * Checks a memory workflow run guard as one explicit Upstash workflow step.** Use when:- * - A memory workflow handler wants to stop a blocked run at its entry.+ * - A workflow handler wants a lightweight guard check before continuing.+ * - Redis-backed guard state must be read inside `context.run`.+ * - Redis failures should inherit the shared run guard fail-open behavior.*- * Why not throw:- * - Upstash Workflow treats an error thrown before the first step as an authorization- * failure and re-enqueues the run. A "disable" guard implemented via throw therefore turns- * into an infinite retry storm instead of stopping work. Handlers must translate a match into- * a graceful `return` (a completed run with no steps β HTTP 2xx β no retry).+ * Expects:+ * - `context` is the active Upstash workflow context.+ * - `workflowPath` identifies the current memory workflow route.+ * - `stepName` is only provided for step-boundary checks.** Returns:- * - The matched guard details when a guard blocks the run.- * - `null` when no guard matches (or Redis fails open).+ * - `result: true` when no guard matches.+ * - `result: false` and a workflow-shaped response when blocked.*/-export const resolveMemoryWorkflowRunGuard = async (+export const checkGuard = async <+ TExtra extends MemoryWorkflowRunGuardResponseExtra = MemoryWorkflowRunGuardResponseExtra,+>(context: WorkflowContext<unknown>,workflowPath: string,-): Promise<MemoryWorkflowRunGuardBlock | null> => {- try {- await assertMemoryWorkflowContextAllowed(context, workflowPath);- return null;- } catch (error) {- if (error instanceof WorkflowRunGuardError) {- return { matchedKey: error.matchedKey, reason: error.reason, scope: error.guardScope };- }- // The underlying guard check fails open on Redis errors, so anything else is unexpected.- throw error;- }+ options: MemoryWorkflowRunGuardCheckOptions<TExtra> = {},+): Promise<MemoryWorkflowRunGuardCheck<TExtra>> => {+ const { response, stepName } = options;+ const block = await context.run<MemoryWorkflowRunGuardBlock | null>(+ `memory:user-memory:run-guard:${workflowPath}:${stepName ?? 'entry'}`,+ async () => {+ const redis = await getRedis();++ try {+ await assertWorkflowRunAllowed(redis, {+ stepName,+ userId: getPayloadUserId(context.requestPayload),+ workflowPath,+ workflowRunId: getWorkflowRunId(context),+ });+ return null;+ } catch (error) {+ if (error instanceof WorkflowRunGuardError) {+ return { matchedKey: error.matchedKey, reason: error.reason, scope: error.guardScope };+ }+ // The underlying guard check fails open on Redis errors, so anything else is unexpected.+ throw error;+ }+ },+ );++ return block+ ? { block, response: createBlockedResponse(block, response), result: false }+ : { result: true };};