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.

⚡️ perf(workflow): add workflow run guard

Neko85b8e8222cc7
diff --git a/src/libs/redis/redis.test.ts b/src/libs/redis/redis.test.ts
index 6bb3f21d050..6868091168e 100644
--- a/src/libs/redis/redis.test.ts
+++ b/src/libs/redis/redis.test.ts
@@ -71,6 +71,7 @@ const createMockedProvider = async () => {
hdel: vi.fn().mockResolvedValue(1),
hgetall: vi.fn().mockResolvedValue({ a: '1' }),
eval: vi.fn().mockResolvedValue(null),
+ scan: vi.fn().mockResolvedValue(['0', []]),
pipeline: vi.fn().mockReturnValue(pipelineMocks),
};
@@ -102,6 +103,7 @@ const createMockedProvider = async () => {
hdel = mocks.hdel;
hgetall = mocks.hgetall;
eval = mocks.eval;
+ scan = mocks.scan;
pipeline = mocks.pipeline;
}
@@ -202,6 +204,17 @@ describe('mocked', () => {
await provider.disconnect();
});
+ it('forwards scan to ioredis', async () => {
+ const { mocks, provider } = await createMockedProvider();
+ mocks.scan.mockResolvedValue(['0', ['workflow:run-guard:global']]);
+
+ const result = await provider.scan('0', 'MATCH', 'workflow:run-guard:*', 'COUNT', 100);
+
+ expect(mocks.scan).toHaveBeenCalledWith('0', 'MATCH', 'workflow:run-guard:*', 'COUNT', 100);
+ expect(result).toEqual(['0', ['workflow:run-guard:global']]);
+ await provider.disconnect();
+ });
+
it('pipeline chains commands and executes in one round-trip', async () => {
const { mocks, provider } = await createMockedProvider();
const pipeMock = mocks.pipeline();
diff --git a/src/libs/redis/redis.ts b/src/libs/redis/redis.ts
index 117e65efc50..eaa21eeb01d 100644
--- a/src/libs/redis/redis.ts
+++ b/src/libs/redis/redis.ts
@@ -7,6 +7,8 @@ import {
type RedisKey,
type RedisMSetArgument,
type RedisPipeline,
+ type RedisScanArgs,
+ type RedisScanResult,
type RedisSetResult,
type RedisValue,
type SetOptions,
@@ -87,6 +89,19 @@ export class IoRedisRedisProvider implements BaseRedisProvider {
return this.ensureClient().ttl(key);
}
+ async scan(cursor: string, ...args: RedisScanArgs): Promise<RedisScanResult> {
+ const client = this.ensureClient();
+
+ if (args.length === 0) return client.scan(cursor);
+ if (args[0] === 'MATCH' && args.length === 2) return client.scan(cursor, 'MATCH', args[1]);
+ if (args[0] === 'COUNT' && args.length === 2) return client.scan(cursor, 'COUNT', args[1]);
+ if (args[0] === 'MATCH') {
+ return client.scan(cursor, 'MATCH', args[1], 'COUNT', args[3]);
+ }
+
+ return client.scan(cursor, 'MATCH', args[3], 'COUNT', args[1]);
+ }
+
async incr(key: RedisKey): Promise<number> {
return this.ensureClient().incr(key);
}
diff --git a/src/libs/redis/types.ts b/src/libs/redis/types.ts
index 2c0c65690a2..87e2dd42185 100644
--- a/src/libs/redis/types.ts
+++ b/src/libs/redis/types.ts
@@ -16,6 +16,13 @@ export interface SetOptions {
export type RedisSetResult = 'OK' | null | string;
export type RedisMSetArgument = Record<string, RedisValue> | Map<RedisKey, RedisValue>;
+export type RedisScanResult = [cursor: string, keys: string[]];
+export type RedisScanArgs =
+ | []
+ | ['MATCH', string]
+ | ['COUNT', number]
+ | ['MATCH', string, 'COUNT', number]
+ | ['COUNT', number, 'MATCH', string];
/**
* Chainable pipeline builder. Commands are buffered and sent in a single round-trip on exec().
@@ -50,6 +57,7 @@ export interface RedisClient {
mget: (...keys: RedisKey[]) => Promise<(string | null)[]>;
mset: (values: RedisMSetArgument) => Promise<'OK'>;
pipeline: () => RedisPipeline;
+ scan: (cursor: string, ...args: RedisScanArgs) => Promise<RedisScanResult>;
set: (key: RedisKey, value: RedisValue, options?: SetOptions) => Promise<RedisSetResult>;
setex: (key: RedisKey, seconds: number, value: RedisValue) => Promise<'OK'>;
ttl: (key: RedisKey) => Promise<number>;
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 6290dd749cc..5b380d3c858 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
@@ -35,6 +35,10 @@ vi.mock('@/server/services/memory/userMemory/extract', () => ({
normalizeMemoryExtractionPayload: (payload: unknown) => payload,
}));
+vi.mock('../runGuard', () => ({
+ assertMemoryWorkflowContextAllowed: vi.fn(),
+}));
+
describe('hourlyWorkflowHandler', () => {
beforeEach(() => {
vi.clearAllMocks();
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.ts
new file mode 100644
index 00000000000..f5693d549e8
--- /dev/null
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/runGuard.test.ts
@@ -0,0 +1,131 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ assertWorkflowRunAllowed: vi.fn(),
+ initializeRedis: vi.fn(),
+ isRedisEnabled: vi.fn(),
+}));
+
+vi.mock('@/libs/redis', () => ({
+ initializeRedis: mocks.initializeRedis,
+ isRedisEnabled: mocks.isRedisEnabled,
+}));
+
+vi.mock('@/envs/redis', () => ({
+ getRedisConfig: vi.fn(() => ({ enabled: true, url: 'redis://test' })),
+}));
+
+vi.mock('@/server/workflows/runGuard', () => ({
+ assertWorkflowRunAllowed: mocks.assertWorkflowRunAllowed,
+}));
+
+const { assertMemoryWorkflowContextAllowed, assertMemoryWorkflowRunAllowed } =
+ await import('../runGuard');
+
+describe('memory workflow run guard helper', () => {
+ beforeEach(() => {
+ mocks.assertWorkflowRunAllowed.mockReset();
+ mocks.initializeRedis.mockReset();
+ mocks.isRedisEnabled.mockReset();
+ mocks.isRedisEnabled.mockReturnValue(true);
+ mocks.initializeRedis.mockResolvedValue({ get: vi.fn() });
+ mocks.assertWorkflowRunAllowed.mockResolvedValue(undefined);
+ });
+
+ it('builds a memory workflow guard scope', async () => {
+ const redis = { get: vi.fn() };
+ mocks.initializeRedis.mockResolvedValue(redis);
+
+ 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',
+ });
+
+ expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(
+ redis,
+ expect.objectContaining({
+ stepName: 'memory:user-memory:extract:cepa',
+ userId: 'user-1',
+ workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ workflowRunId: 'wfr_1',
+ }),
+ );
+ expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses workflowRunId from workflow context when available', async () => {
+ const redis = { get: vi.fn() };
+ mocks.initializeRedis.mockResolvedValue(redis);
+
+ await assertMemoryWorkflowContextAllowed(
+ {
+ requestPayload: {
+ userIds: ['user-2'],
+ },
+ workflowRunId: 'wfr_context',
+ } as never,
+ 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',
+ 'memory:user-memory:extract:get-users',
+ );
+
+ expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(
+ redis,
+ expect.objectContaining({
+ stepName: 'memory:user-memory:extract:get-users',
+ userId: 'user-2',
+ workflowRunId: 'wfr_context',
+ }),
+ );
+ expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledTimes(1);
+ });
+
+ it('passes null Redis when Redis is disabled', async () => {
+ mocks.isRedisEnabled.mockReturnValue(false);
+
+ await assertMemoryWorkflowRunAllowed({
+ payload: { userId: 'user-1' },
+ workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',
+ });
+
+ expect(mocks.initializeRedis).not.toHaveBeenCalled();
+ expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(
+ null,
+ expect.objectContaining({ userId: 'user-1' }),
+ );
+ });
+
+ it('ignores malformed user ids from unknown payloads', async () => {
+ const redis = { get: vi.fn() };
+ mocks.initializeRedis.mockResolvedValue(redis);
+
+ await assertMemoryWorkflowRunAllowed({
+ payload: {
+ userId: 123,
+ userIds: [false, 'user-from-array'],
+ },
+ workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',
+ });
+
+ expect(mocks.assertWorkflowRunAllowed).toHaveBeenCalledWith(
+ redis,
+ expect.objectContaining({ userId: 'user-from-array' }),
+ );
+ });
+
+ it('propagates guard rejections', async () => {
+ const error = new Error('blocked');
+ mocks.assertWorkflowRunAllowed.mockRejectedValue(error);
+
+ await expect(
+ assertMemoryWorkflowRunAllowed({
+ payload: { userId: 'user-1' },
+ workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users',
+ }),
+ ).rejects.toBe(error);
+ });
+});
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 fbc362de9dd..033ef723510 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts
@@ -12,10 +12,12 @@ import {
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
+import { assertMemoryWorkflowContextAllowed } from './runGuard';
import { serializeWorkflowCursor } from './utils';
const USER_PAGE_SIZE = 200;
const USER_BATCH_SIZE = 20;
+const WORKFLOW_PATH = 'api/workflows/memory-user-memory/call-cron-hourly-analysis';
const { webhook, upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
@@ -25,6 +27,7 @@ export const hourlyWorkflowHandler = async (
context: WorkflowContext<MemoryExtractionHourlyWorkflowPayload>,
) => {
const { cursor, dryRun } = context.requestPayload || {};
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
const baseUrl = resolveBaseUrl();
if (!baseUrl) {
@@ -39,9 +42,10 @@ export const hourlyWorkflowHandler = async (
}
const executor = await MemoryExtractionExecutor.create();
- const userBatch = await context.run(
- `memory:user-memory:hourly:list-users:${parsedCursor?.id || 'root'}`,
- () => executor.getUsersForHourlyExtraction(USER_PAGE_SIZE, parsedCursor),
+ const listUsersStepName = `memory:user-memory:hourly:list-users:${parsedCursor?.id || 'root'}`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, listUsersStepName);
+ const userBatch = await context.run(listUsersStepName, () =>
+ executor.getUsersForHourlyExtraction(USER_PAGE_SIZE, parsedCursor),
);
const userIds = userBatch.ids;
@@ -59,8 +63,11 @@ export const hourlyWorkflowHandler = async (
if (!dryRun) {
const batches = chunk(userIds, USER_BATCH_SIZE);
await Promise.all(
- batches.map((batchUserIds, index) =>
- context.run(`memory:user-memory:hourly:trigger-users:${index}`, () =>
+ batches.map(async (batchUserIds, index) => {
+ const stepName = `memory:user-memory:hourly:trigger-users:${index}`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+
+ return context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUsers(
buildWorkflowPayloadInput(
normalizeMemoryExtractionPayload({
@@ -72,13 +79,15 @@ export const hourlyWorkflowHandler = async (
),
{ extraHeaders: upstashWorkflowExtraHeaders },
),
- ),
- ),
+ );
+ }),
);
}
if (nextCursor) {
- await context.run('memory:user-memory:hourly:schedule-next-page', () =>
+ const stepName = 'memory:user-memory:hourly:schedule-next-page';
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerHourly(
{
baseUrl,
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 0e4194d662e..0b227affa08 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
@@ -16,8 +16,10 @@ import {
MemoryExtractionExecutor,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
+import { WorkflowRunGuardError } from '@/server/workflows/runGuard';
import { createWorkflowQstashClient } from '../../qstashClient';
+import { assertMemoryWorkflowContextAllowed } from './runGuard';
const CEPA_LAYERS: LayersEnum[] = [
LayersEnum.Context,
@@ -27,6 +29,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>) =>
upstashWorkflowTracer.startActiveSpan(
@@ -43,35 +46,37 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
'workflow.name': 'memory-user-memory:process-topic',
});
- const topicId = payload.topicIds[0];
- const userId = payload.userIds[0];
+ try {
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
- if (!userId || !topicId) {
- span.setStatus({ code: SpanStatusCode.OK });
- return { message: 'Missing userId or topicId for topic workflow.' };
- }
+ const topicId = payload.topicIds[0];
+ const userId = payload.userIds[0];
- if (!payload.sources.includes(MemorySourceType.ChatTopic)) {
- span.setStatus({ code: SpanStatusCode.OK });
- return { message: 'Source not supported in topic workflow.' };
- }
+ if (!userId || !topicId) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return { message: 'Missing userId or topicId for topic workflow.' };
+ }
+
+ if (!payload.sources.includes(MemorySourceType.ChatTopic)) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return { message: 'Source not supported in topic workflow.' };
+ }
- const executor = await MemoryExtractionExecutor.create();
+ 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,
- payload.workspaceId,
- ).isUserMemoryExtractionCancellationRequested(payload.asyncTaskId!),
- ),
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:before`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ const cancelled = await context.run(stepName, () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(
+ db,
+ userId,
+ payload.workspaceId,
+ ).isUserMemoryExtractionCancellationRequested(payload.asyncTaskId!),
+ ),
);
if (cancelled) {
span.setStatus({ code: SpanStatusCode.OK });
@@ -85,39 +90,39 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
layers = payload.layers.filter((layer) => CEPA_LAYERS.includes(layer));
}
- await context.run(
- `memory:user-memory:extract:users:${userId}:topics:${topicId}:cepa`,
- () =>
- executor.extractTopic({
- asyncTaskId: payload.asyncTaskId,
- forceAll: payload.forceAll,
- forceTopics: payload.forceTopics,
- from: payload.from,
- layers,
- reportProgress: false,
- source: MemorySourceType.ChatTopic,
- to: payload.to,
- topicId,
- userId,
- userInitiated: payload.userInitiated,
- workspaceId: payload.workspaceId,
- }),
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cepa`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ await context.run(stepName, () =>
+ executor.extractTopic({
+ asyncTaskId: payload.asyncTaskId,
+ forceAll: payload.forceAll,
+ forceTopics: payload.forceTopics,
+ from: payload.from,
+ layers,
+ reportProgress: false,
+ source: MemorySourceType.ChatTopic,
+ to: payload.to,
+ topicId,
+ userId,
+ userInitiated: payload.userInitiated,
+ workspaceId: payload.workspaceId,
+ }),
);
}
{
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,
- payload.workspaceId,
- ).isUserMemoryExtractionCancellationRequested(payload.asyncTaskId!),
- ),
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:cancel-check:identity`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ const cancelled = await context.run(stepName, () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(
+ db,
+ userId,
+ payload.workspaceId,
+ ).isUserMemoryExtractionCancellationRequested(payload.asyncTaskId!),
+ ),
);
if (cancelled) {
span.setStatus({ code: SpanStatusCode.OK });
@@ -132,37 +137,37 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
layers = payload.layers.filter((layer) => IDENTITY_LAYERS.includes(layer));
}
- await context.run(
- `memory:user-memory:extract:users:${userId}:topics:${topicId}:identity`,
- () =>
- executor.extractTopic({
- asyncTaskId: payload.asyncTaskId,
- forceAll: payload.forceAll,
- forceTopics: payload.forceTopics,
- from: payload.from,
- layers,
- reportProgress: false,
- source: MemorySourceType.ChatTopic,
- to: payload.to,
- topicId,
- userId,
- userInitiated: payload.userInitiated,
- workspaceId: payload.workspaceId,
- }),
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:identity`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ await context.run(stepName, () =>
+ executor.extractTopic({
+ asyncTaskId: payload.asyncTaskId,
+ forceAll: payload.forceAll,
+ forceTopics: payload.forceTopics,
+ from: payload.from,
+ layers,
+ reportProgress: false,
+ source: MemorySourceType.ChatTopic,
+ to: payload.to,
+ topicId,
+ userId,
+ userInitiated: payload.userInitiated,
+ workspaceId: payload.workspaceId,
+ }),
);
}
if (payload.asyncTaskId && payload.userInitiated) {
- await context.run(
- `memory:user-memory:extract:users:${userId}:topics:${topicId}:progress`,
- () =>
- getServerDB().then((db) =>
- new AsyncTaskModel(
- db,
- userId,
- payload.workspaceId,
- ).incrementUserMemoryExtractionProgress(payload.asyncTaskId!),
- ),
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${topicId}:progress`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ await context.run(stepName, () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(
+ db,
+ userId,
+ payload.workspaceId,
+ ).incrementUserMemoryExtractionProgress(payload.asyncTaskId!),
+ ),
);
}
@@ -176,6 +181,7 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
} catch (error) {
// Let Upstash internal aborts bubble through but treat others as non-retry-able
if (error instanceof WorkflowAbort) throw error;
+ if (error instanceof WorkflowRunGuardError) throw error;
span.recordException(error as Error);
span.setStatus({
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 0ce91375b49..3620c8dce28 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopics.ts
@@ -17,8 +17,10 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { processTopicWorkflow } from './processTopic';
+import { assertMemoryWorkflowContextAllowed } from './runGuard';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
+const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topics';
const CEPA_LAYERS: LayersEnum[] = [
LayersEnum.Context,
@@ -46,6 +48,8 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
});
try {
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+
if (!payload.userIds.length) {
span.setStatus({ code: SpanStatusCode.OK });
@@ -78,16 +82,16 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
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,
- payload.workspaceId,
- ).isUserMemoryExtractionCancellationRequested(payload.asyncTaskId!),
- ),
+ const stepName = `memory:user-memory:extract:users:${userId}:cancel-check`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ const cancelled = await context.run(stepName, () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(
+ db,
+ userId,
+ payload.workspaceId,
+ ).isUserMemoryExtractionCancellationRequested(payload.asyncTaskId!),
+ ),
);
if (cancelled) {
span.setStatus({ code: SpanStatusCode.OK });
@@ -98,41 +102,38 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
};
}
}
- // Delegate per-topic extraction to dedicated workflow for better isolation
- await Promise.all(
- payload.topicIds.map(async (topicId, index) => {
- await context.invoke(
- `memory:user-memory:extract:users:${userId}:topics:${topicId}:invoke:${index}`,
- {
- body: {
- ...payload,
- layers: payload.layers.length
- ? payload.layers
- : [...CEPA_LAYERS, ...IDENTITY_LAYERS],
- topicIds: [topicId],
- 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,
- },
- );
- }),
- );
+ // 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}`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ await context.invoke(stepName, {
+ body: {
+ ...payload,
+ layers: payload.layers.length ? payload.layers : [...CEPA_LAYERS, ...IDENTITY_LAYERS],
+ topicIds: [topicId],
+ 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,
+ });
+ }
// Trigger user persona update after topic processing using the workflow client.
- await context.run(`memory:user-memory:users:${userId}`, async () => {
+ const personaUpdateStepName = `memory:user-memory:users:${userId}`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, personaUpdateStepName);
+ 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.ts
index b23e40ae5a7..e9c5b5c4109 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
@@ -14,8 +14,11 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { forEachBatchSequential } from '@/server/services/memory/userMemory/topicBatching';
+import { assertMemoryWorkflowContextAllowed } from './runGuard';
+
const TOPIC_PAGE_SIZE = 50;
const TOPIC_BATCH_SIZE = 4;
+const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
@@ -23,6 +26,8 @@ export const processUserTopicsHandler = async (
context: WorkflowContext<MemoryExtractionPayloadInput>,
) => {
const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+
if (!params.userIds.length) {
return { message: 'No user ids provided for topic processing.' };
}
@@ -55,16 +60,16 @@ export const processUserTopicsHandler = async (
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,
- params.workspaceId,
- ).isUserMemoryExtractionCancellationRequested(params.asyncTaskId!),
- ),
+ const stepName = `memory:user-memory:extract:users:${userId}:cancel-check`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ const cancelled = await context.run(stepName, () =>
+ getServerDB().then((db) =>
+ new AsyncTaskModel(
+ db,
+ userId,
+ params.workspaceId,
+ ).isUserMemoryExtractionCancellationRequested(params.asyncTaskId!),
+ ),
);
if (cancelled) {
continue;
@@ -79,25 +84,26 @@ export const processUserTopicsHandler = async (
}
: undefined;
- const topicsFromPayload =
- params.topicIds && params.topicIds.length > 0
- ? await context.run(
- `memory:user-memory:extract:users:${userId}:filter-topic-ids`,
- async () => {
- const filtered = await executor.filterTopicIdsForUser(
- userId,
- params.topicIds,
- params.workspaceId,
- );
- return filtered.length > 0 ? filtered : undefined;
- },
- )
- : undefined;
+ let topicsFromPayload: string[] | undefined;
+ if (params.topicIds && params.topicIds.length > 0) {
+ const stepName = `memory:user-memory:extract:users:${userId}:filter-topic-ids`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ topicsFromPayload = await context.run(stepName, async () => {
+ const filtered = await executor.filterTopicIdsForUser(
+ userId,
+ params.topicIds,
+ params.workspaceId,
+ );
+ return filtered.length > 0 ? filtered : undefined;
+ });
+ }
+ const listTopicsStepName = `memory:user-memory:extract:users:${userId}:list-topics:${topicCursor?.id || 'root'}`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, listTopicsStepName);
const topicBatch = await context.run<{
cursor?: ListTopicsForMemoryExtractorCursor;
ids: string[];
- }>(`memory:user-memory:extract:users:${userId}:list-topics:${topicCursor?.id || 'root'}`, () =>
+ }>(listTopicsStepName, () =>
topicsFromPayload && topicsFromPayload.length > 0
? Promise.resolve({ ids: topicsFromPayload })
: executor.getTopicsForUser(
@@ -127,38 +133,37 @@ export const processUserTopicsHandler = async (
// 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.
- await context.run(
- `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`,
- () =>
- MemoryExtractionWorkflowService.triggerProcessTopics(
+ const stepName = `memory:user-memory:extract:users:${userId}:process-topics-batch:${batchIndex}`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ await context.run(stepName, () =>
+ MemoryExtractionWorkflowService.triggerProcessTopics(
+ userId,
+ {
+ ...buildWorkflowPayloadInput(params),
+ topicCursor: undefined,
+ topicIds,
userId,
- {
- ...buildWorkflowPayloadInput(params),
- topicCursor: undefined,
- topicIds,
- userId,
- userIds: [userId],
- },
- { extraHeaders: upstashWorkflowExtraHeaders },
- ),
+ userIds: [userId],
+ },
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ ),
);
});
if (!topicsFromPayload && cursor) {
- await context.run(
- `memory:user-memory:extract:users:${userId}:topics:${cursor.id}:schedule-next-batch`,
- () => {
- // 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.
- const createdAt = new Date(cursor.createdAt);
- if (Number.isNaN(createdAt.getTime())) {
- throw new Error('Invalid cursor date when scheduling next topic page');
- }
-
- return scheduleNextPage(userId, createdAt, cursor.id);
- },
- );
+ const stepName = `memory:user-memory:extract:users:${userId}:topics:${cursor.id}:schedule-next-batch`;
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ 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.
+ const createdAt = new Date(cursor.createdAt);
+ if (Number.isNaN(createdAt.getTime())) {
+ throw new Error('Invalid cursor date when scheduling next topic page');
+ }
+
+ return scheduleNextPage(userId, createdAt, cursor.id);
+ });
}
}
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 ad666e7b2d9..24e47013dd6 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts
@@ -12,10 +12,12 @@ import {
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
+import { assertMemoryWorkflowContextAllowed } from './runGuard';
import { serializeWorkflowCursor } from './utils';
const USER_PAGE_SIZE = 50;
const USER_BATCH_SIZE = 10;
+const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-users';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
@@ -23,13 +25,17 @@ export const processUsersHandler = async (
context: WorkflowContext<MemoryExtractionPayloadInput>,
) => {
const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+
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', () =>
+ const stepName = 'memory:user-memory:extract:cancel-check:root';
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ const cancelled = await context.run(stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
db,
@@ -52,7 +58,9 @@ export const processUsersHandler = async (
? { createdAt: new Date(params.userCursor.createdAt), id: params.userCursor.id }
: undefined;
- const userBatch = await context.run('memory:user-memory:extract:get-users', () =>
+ const getUsersStepName = 'memory:user-memory:extract:get-users';
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, getUsersStepName);
+ const userBatch = await context.run(getUsersStepName, () =>
params.userIds.length > 0
? { ids: params.userIds }
: executor.getUsers(USER_PAGE_SIZE, userCursor),
@@ -67,8 +75,11 @@ export const processUsersHandler = async (
const batches = chunk(ids, USER_BATCH_SIZE);
await Promise.all(
- batches.map((userIds) =>
- context.run(`memory:user-memory:extract:users:process-topic-batches`, () =>
+ batches.map(async (userIds) => {
+ const stepName = 'memory:user-memory:extract:users:process-topic-batches';
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+
+ return context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUserTopics(
{
...buildWorkflowPayloadInput(params),
@@ -78,12 +89,14 @@ export const processUsersHandler = async (
},
{ extraHeaders: upstashWorkflowExtraHeaders },
),
- ),
- ),
+ );
+ }),
);
if (params.userIds.length === 0 && cursor) {
- await context.run('memory:user-memory:extract:users:schedule-next-user-batch', () =>
+ const stepName = 'memory:user-memory:extract:users:schedule-next-user-batch';
+ await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
+ await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessUsers(
{
...buildWorkflowPayloadInput({
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts b/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts
new file mode 100644
index 00000000000..497589debb0
--- /dev/null
+++ b/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts
@@ -0,0 +1,94 @@
+import { type WorkflowContext } from '@upstash/workflow';
+
+import { getRedisConfig } from '@/envs/redis';
+import { initializeRedis, isRedisEnabled } from '@/libs/redis';
+import { type BaseRedisProvider } from '@/libs/redis/types';
+import { assertWorkflowRunAllowed } 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;
+
+ return initializeRedis(config);
+};
+
+const getPayloadUserId = (payload: unknown): string | undefined => {
+ if (!payload || typeof payload !== 'object') return undefined;
+
+ const userId = 'userId' in payload ? payload.userId : undefined;
+ if (typeof userId === 'string' && userId) return userId;
+
+ const userIds = 'userIds' in payload ? payload.userIds : undefined;
+ if (!Array.isArray(userIds)) return undefined;
+
+ return userIds.find((id): id is string => typeof id === 'string' && id.length > 0);
+};
+
+/**
+ * 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.
+ */
+export const assertMemoryWorkflowRunAllowed = async ({
+ payload,
+ stepName,
+ workflowPath,
+ workflowRunId,
+}: MemoryWorkflowGuardInput): Promise<void> => {
+ const redis = await getRedis();
+
+ await assertWorkflowRunAllowed(redis, {
+ stepName,
+ userId: getPayloadUserId(payload),
+ workflowPath,
+ workflowRunId,
+ });
+};
+
+/**
+ * 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.
+ *
+ * Expects:
+ * - `workflowPath` is the route path serving the current workflow.
+ * - `stepName` is passed before the matching `context.run` or `context.invoke` call.
+ *
+ * Returns:
+ * - Resolves when no guard blocks the workflow.
+ * - Rejects with the shared guard error when a matching guard exists.
+ */
+export const assertMemoryWorkflowContextAllowed = async (
+ context: WorkflowContext<unknown>,
+ workflowPath: string,
+ stepName?: string,
+): Promise<void> => {
+ await assertMemoryWorkflowRunAllowed({
+ payload: context.requestPayload,
+ stepName,
+ workflowPath,
+ workflowRunId: getWorkflowRunId(context),
+ });
+};
diff --git a/src/server/workflows/runGuard/__tests__/keys.test.ts b/src/server/workflows/runGuard/__tests__/keys.test.ts
new file mode 100644
index 00000000000..0076cd7532d
--- /dev/null
+++ b/src/server/workflows/runGuard/__tests__/keys.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildWorkflowRunGuardKeys,
+ buildWorkflowRunGuardRedisKey,
+ hashWorkflowRunGuardStepName,
+ normalizeWorkflowRunGuardPath,
+} from '../keys';
+
+describe('workflow run guard keys', () => {
+ /**
+ * @example
+ * normalizeWorkflowRunGuardPath('/api/workflows/memory-user-memory/')
+ * // returns 'api/workflows/memory-user-memory'
+ */
+ it('normalizes workflow paths without origin or leading slash', () => {
+ expect(
+ normalizeWorkflowRunGuardPath(
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ ),
+ ).toBe('api/workflows/memory-user-memory/pipelines/chat-topic/process-topic');
+
+ expect(normalizeWorkflowRunGuardPath('/api/workflows/memory-user-memory/')).toBe(
+ 'api/workflows/memory-user-memory',
+ );
+ });
+
+ /**
+ * @example
+ * normalizeWorkflowRunGuardPath('/api/workflows/demo?x=1#hash')
+ * // returns 'api/workflows/demo'
+ */
+ it('normalizes relative workflow paths without query or hash', () => {
+ // ROOT CAUSE:
+ //
+ // Relative paths with query strings did not go through URL parsing because
+ // `new URL(value)` requires an absolute URL. The fallback returned the raw
+ // value, so `/api/workflows/demo?x=1#hash` and the absolute URL form built
+ // different guard keys.
+ //
+ // We fixed this by parsing relative paths with a dummy base URL before
+ // trimming leading and trailing slashes.
+ expect(normalizeWorkflowRunGuardPath('/api/workflows/demo?x=1#hash')).toBe(
+ 'api/workflows/demo',
+ );
+ expect(normalizeWorkflowRunGuardPath('api/workflows/demo?x=1#hash')).toBe('api/workflows/demo');
+ });
+
+ /**
+ * @example
+ * buildWorkflowRunGuardRedisKey({ type: 'global' })
+ * // returns 'workflow:run-guard:global'
+ */
+ it('builds direct scope keys', () => {
+ expect(buildWorkflowRunGuardRedisKey({ type: 'global' })).toBe('workflow:run-guard:global');
+ expect(
+ buildWorkflowRunGuardRedisKey({
+ type: 'path',
+ workflowPath: 'api/workflows/memory-user-memory',
+ }),
+ ).toBe('workflow:run-guard:path:api/workflows/memory-user-memory');
+ expect(buildWorkflowRunGuardRedisKey({ type: 'user', userId: 'user-1' })).toBe(
+ 'workflow:run-guard:user:user-1',
+ );
+ expect(buildWorkflowRunGuardRedisKey({ type: 'run', workflowRunId: 'wfr_1' })).toBe(
+ 'workflow:run-guard:run:wfr_1',
+ );
+ });
+
+ /**
+ * @example
+ * hashWorkflowRunGuardStepName('memory:user-memory:extract:cepa')
+ * // returns a stable 16-character lowercase hex string
+ */
+ it('hashes step names into stable short keys', () => {
+ expect(hashWorkflowRunGuardStepName('memory:user-memory:extract:cepa')).toMatch(
+ /^[a-f0-9]{16}$/,
+ );
+ expect(hashWorkflowRunGuardStepName('memory:user-memory:extract:cepa')).toBe(
+ hashWorkflowRunGuardStepName('memory:user-memory:extract:cepa'),
+ );
+ });
+
+ /**
+ * @example
+ * buildWorkflowRunGuardKeys({ workflowPath: 'api/workflows/demo' })
+ * // returns global and path-prefix candidates in check order
+ */
+ it('builds check keys in guard order with path prefixes', () => {
+ expect(
+ buildWorkflowRunGuardKeys({
+ stepName: 'memory:user-memory:extract:cepa',
+ userId: 'user-1',
+ workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ workflowRunId: 'wfr_1',
+ }).map((item) => item.key),
+ ).toEqual([
+ 'workflow:run-guard:global',
+ 'workflow:run-guard:path:api',
+ 'workflow:run-guard:path:api/workflows',
+ 'workflow:run-guard:path:api/workflows/memory-user-memory',
+ 'workflow:run-guard:path:api/workflows/memory-user-memory/pipelines',
+ 'workflow:run-guard:path:api/workflows/memory-user-memory/pipelines/chat-topic',
+ 'workflow:run-guard:path:api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ 'workflow:run-guard:user:user-1',
+ 'workflow:run-guard:run:wfr_1',
+ `workflow:run-guard:step:wfr_1:${hashWorkflowRunGuardStepName('memory:user-memory:extract:cepa')}`,
+ ]);
+ });
+});
diff --git a/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts b/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts
new file mode 100644
index 00000000000..2d95987ec22
--- /dev/null
+++ b/src/server/workflows/runGuard/__tests__/qstashCancel.test.ts
@@ -0,0 +1,206 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { cancelWorkflowRunsByGuardPolicy } from '../qstashCancel';
+
+describe('workflow run guard qstash cancel', () => {
+ /**
+ * @example
+ * cancelWorkflowRunsByGuardPolicy(client, {
+ * appUrl: 'https://app.lobehub.com',
+ * workflowPath: 'api/workflows/memory-user-memory',
+ * })
+ * // cancels RUN_STARTED workflow ids whose URL starts with the workflow prefix
+ */
+ it('resolves matching run ids from logs and cancels by id', async () => {
+ const client = {
+ cancel: vi.fn().mockResolvedValue({ cancelled: 2 }),
+ logs: vi.fn().mockResolvedValue({
+ runs: [
+ {
+ workflowRunId: 'wfr_1',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ },
+ {
+ workflowRunId: 'wfr_2',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics',
+ },
+ {
+ workflowRunId: 'wfr_other',
+ workflowState: 'RUN_STARTED',
+ workflowUrl: 'https://app.lobehub.com/api/workflows/agent-eval-run/execute-test-case',
+ },
+ ],
+ }),
+ };
+
+ await expect(
+ cancelWorkflowRunsByGuardPolicy(
+ client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],
+ {
+ appUrl: 'https://app.lobehub.com',
+ workflowPath: 'api/workflows/memory-user-memory',
+ },
+ ),
+ ).resolves.toEqual({
+ cancelled: 2,
+ matchedRunIds: ['wfr_1', 'wfr_2'],
+ workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',
+ });
+
+ expect(client.logs).toHaveBeenCalledWith({ count: 100, state: 'RUN_STARTED' });
+ expect(client.cancel).toHaveBeenCalledWith({ ids: ['wfr_1', 'wfr_2'] });
+ });
+
+ /**
+ * @example
+ * cancelWorkflowRunsByGuardPolicy(client, {
+ * appUrl: 'https://app.lobehub.com/',
+ * workflowPath: '/api/workflows/memory-user-memory/',
+ * })
+ * // deduplicates matching workflow run ids before cancellation
+ */
+ it('normalizes the URL prefix and deduplicates matched run ids', async () => {
+ const client = {
+ cancel: vi.fn().mockResolvedValue({ cancelled: 1 }),
+ logs: vi.fn().mockResolvedValue({
+ runs: [
+ {
+ workflowRunId: 'wfr_1',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ },
+ {
+ workflowRunId: 'wfr_1',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ },
+ {
+ workflowRunId: 'wfr_other',
+ workflowState: 'RUN_STARTED',
+ workflowUrl: 'https://app.lobehub.com/api/workflows/agent-eval-run/execute-test-case',
+ },
+ ],
+ }),
+ };
+
+ await expect(
+ cancelWorkflowRunsByGuardPolicy(
+ client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],
+ {
+ appUrl: 'https://app.lobehub.com/',
+ workflowPath: '/api/workflows/memory-user-memory/',
+ },
+ ),
+ ).resolves.toEqual({
+ cancelled: 1,
+ matchedRunIds: ['wfr_1'],
+ workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',
+ });
+
+ expect(client.cancel).toHaveBeenCalledWith({ ids: ['wfr_1'] });
+ });
+
+ /**
+ * @example
+ * cancelWorkflowRunsByGuardPolicy(client, {
+ * appUrl: 'https://app.lobehub.com',
+ * workflowPath: 'api/workflows/memory-user-memory/pipelines/process-topic',
+ * })
+ * // does not cancel sibling routes with the same string prefix
+ */
+ it('matches workflow URL prefixes on path segment boundaries', async () => {
+ const client = {
+ cancel: vi.fn().mockResolvedValue({ cancelled: 2 }),
+ logs: vi.fn().mockResolvedValue({
+ runs: [
+ {
+ workflowRunId: 'wfr_exact',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic',
+ },
+ {
+ workflowRunId: 'wfr_child',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic/child',
+ },
+ {
+ workflowRunId: 'wfr_query',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic?cursor=1',
+ },
+ {
+ workflowRunId: 'wfr_sibling',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topics',
+ },
+ {
+ workflowRunId: 'wfr_v2',
+ workflowState: 'RUN_STARTED',
+ workflowUrl:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory-v2/pipelines/process-topic',
+ },
+ ],
+ }),
+ };
+
+ await expect(
+ cancelWorkflowRunsByGuardPolicy(
+ client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],
+ {
+ appUrl: 'https://app.lobehub.com',
+ workflowPath: 'api/workflows/memory-user-memory/pipelines/process-topic',
+ },
+ ),
+ ).resolves.toEqual({
+ cancelled: 2,
+ matchedRunIds: ['wfr_exact', 'wfr_child', 'wfr_query'],
+ workflowUrlPrefix:
+ 'https://app.lobehub.com/api/workflows/memory-user-memory/pipelines/process-topic',
+ });
+
+ expect(client.cancel).toHaveBeenCalledWith({
+ ids: ['wfr_exact', 'wfr_child', 'wfr_query'],
+ });
+ });
+
+ /**
+ * @example
+ * cancelWorkflowRunsByGuardPolicy(client, {
+ * appUrl: 'https://app.lobehub.com',
+ * workflowPath: 'api/workflows/memory-user-memory',
+ * })
+ * // returns zero and does not call cancel when logs have no matches
+ */
+ it('returns zero when no started runs match', async () => {
+ const client = {
+ cancel: vi.fn(),
+ logs: vi.fn().mockResolvedValue({ runs: [] }),
+ };
+
+ await expect(
+ cancelWorkflowRunsByGuardPolicy(
+ client as unknown as Parameters<typeof cancelWorkflowRunsByGuardPolicy>[0],
+ {
+ appUrl: 'https://app.lobehub.com',
+ workflowPath: 'api/workflows/memory-user-memory',
+ },
+ ),
+ ).resolves.toEqual({
+ cancelled: 0,
+ matchedRunIds: [],
+ workflowUrlPrefix: 'https://app.lobehub.com/api/workflows/memory-user-memory',
+ });
+
+ expect(client.cancel).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/workflows/runGuard/__tests__/store.test.ts b/src/server/workflows/runGuard/__tests__/store.test.ts
new file mode 100644
index 00000000000..0c1ada0bccc
--- /dev/null
+++ b/src/server/workflows/runGuard/__tests__/store.test.ts
@@ -0,0 +1,165 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ assertWorkflowRunAllowed,
+ clearWorkflowRunGuard,
+ listWorkflowRunGuards,
+ setWorkflowRunGuard,
+} from '../store';
+
+const redis = {
+ del: vi.fn(),
+ get: vi.fn(),
+ scan: vi.fn(),
+ set: vi.fn(),
+ ttl: vi.fn(),
+};
+
+describe('workflow run guard store', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('sets a guard key with a bounded ttl and createdAt', async () => {
+ redis.set.mockResolvedValue('OK');
+
+ await setWorkflowRunGuard(redis as unknown as Parameters<typeof setWorkflowRunGuard>[0], {
+ scope: { type: 'path', workflowPath: 'api/workflows/memory-user-memory' },
+ ttlSeconds: 99_999,
+ value: { reason: 'stop memory', policy: { cancelQstash: true } },
+ });
+
+ const [key, raw, options] = redis.set.mock.calls[0];
+ expect(key).toBe('workflow:run-guard:path:api/workflows/memory-user-memory');
+ expect(JSON.parse(raw)).toMatchObject({
+ policy: { cancelQstash: true },
+ reason: 'stop memory',
+ });
+ expect(JSON.parse(raw).createdAt).toEqual(expect.any(String));
+ expect(options).toEqual({ ex: 86_400 });
+ });
+
+ it('sets a guard key with a finite integer ttl', async () => {
+ redis.set.mockResolvedValue('OK');
+
+ await setWorkflowRunGuard(redis as unknown as Parameters<typeof setWorkflowRunGuard>[0], {
+ scope: { type: 'global' },
+ ttlSeconds: 3.9,
+ value: { reason: 'fractional ttl' },
+ });
+
+ expect(redis.set).toHaveBeenCalledWith('workflow:run-guard:global', expect.any(String), {
+ ex: 3,
+ });
+
+ await setWorkflowRunGuard(redis as unknown as Parameters<typeof setWorkflowRunGuard>[0], {
+ scope: { type: 'global' },
+ ttlSeconds: Number.NaN,
+ value: { reason: 'nan ttl' },
+ });
+
+ expect(redis.set).toHaveBeenLastCalledWith('workflow:run-guard:global', expect.any(String), {
+ ex: 3600,
+ });
+ });
+
+ it('throws WorkflowRunGuardError on the first matching key', async () => {
+ redis.get.mockImplementation(async (key: string) =>
+ key === 'workflow:run-guard:path:api/workflows/memory-user-memory'
+ ? JSON.stringify({ reason: 'blocked' })
+ : null,
+ );
+
+ await expect(
+ assertWorkflowRunAllowed(redis as unknown as Parameters<typeof assertWorkflowRunAllowed>[0], {
+ workflowPath: 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ }),
+ ).rejects.toMatchObject({
+ matchedKey: 'workflow:run-guard:path:api/workflows/memory-user-memory',
+ name: 'WorkflowRunGuardError',
+ reason: 'blocked',
+ });
+ });
+
+ it('ignores malformed guard values during execution checks', async () => {
+ redis.get.mockResolvedValue('{broken');
+
+ await expect(
+ assertWorkflowRunAllowed(redis as unknown as Parameters<typeof assertWorkflowRunAllowed>[0], {
+ workflowPath: 'api/workflows/memory-user-memory',
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('ignores array guard values during execution checks', async () => {
+ redis.get.mockResolvedValue('[]');
+
+ await expect(
+ assertWorkflowRunAllowed(redis as unknown as Parameters<typeof assertWorkflowRunAllowed>[0], {
+ workflowPath: 'api/workflows/memory-user-memory',
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('fails open when Redis get throws during execution checks', async () => {
+ redis.get.mockRejectedValue(new Error('redis unavailable'));
+
+ await expect(
+ assertWorkflowRunAllowed(redis as unknown as Parameters<typeof assertWorkflowRunAllowed>[0], {
+ workflowPath: 'api/workflows/memory-user-memory',
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('clears a guard key', async () => {
+ redis.del.mockResolvedValue(1);
+
+ await expect(
+ clearWorkflowRunGuard(redis as unknown as Parameters<typeof clearWorkflowRunGuard>[0], {
+ type: 'user',
+ userId: 'user-1',
+ }),
+ ).resolves.toEqual({ deleted: 1, key: 'workflow:run-guard:user:user-1' });
+ });
+
+ it('lists guard keys using scan and ttl', async () => {
+ redis.scan
+ .mockResolvedValueOnce([
+ '12',
+ ['workflow:run-guard:global', 'workflow:run-guard:user:user-1'],
+ ])
+ .mockResolvedValueOnce(['0', ['workflow:run-guard:run:wfr_1']]);
+ redis.get.mockImplementation(async (key: string) => JSON.stringify({ reason: key }));
+ redis.ttl.mockResolvedValue(3600);
+
+ await expect(
+ listWorkflowRunGuards(redis as unknown as Parameters<typeof listWorkflowRunGuards>[0]),
+ ).resolves.toEqual([
+ {
+ key: 'workflow:run-guard:global',
+ ttlSeconds: 3600,
+ value: { reason: 'workflow:run-guard:global' },
+ },
+ {
+ key: 'workflow:run-guard:user:user-1',
+ ttlSeconds: 3600,
+ value: { reason: 'workflow:run-guard:user:user-1' },
+ },
+ {
+ key: 'workflow:run-guard:run:wfr_1',
+ ttlSeconds: 3600,
+ value: { reason: 'workflow:run-guard:run:wfr_1' },
+ },
+ ]);
+ expect(redis.scan).toHaveBeenCalledWith('0', 'MATCH', 'workflow:run-guard:*', 'COUNT', 100);
+ expect(redis.scan).toHaveBeenCalledWith('12', 'MATCH', 'workflow:run-guard:*', 'COUNT', 100);
+ expect(redis.get).toHaveBeenCalledTimes(3);
+ expect(redis.get).toHaveBeenNthCalledWith(1, 'workflow:run-guard:global');
+ expect(redis.get).toHaveBeenNthCalledWith(2, 'workflow:run-guard:user:user-1');
+ expect(redis.get).toHaveBeenNthCalledWith(3, 'workflow:run-guard:run:wfr_1');
+ expect(redis.ttl).toHaveBeenCalledTimes(3);
+ expect(redis.ttl).toHaveBeenNthCalledWith(1, 'workflow:run-guard:global');
+ expect(redis.ttl).toHaveBeenNthCalledWith(2, 'workflow:run-guard:user:user-1');
+ expect(redis.ttl).toHaveBeenNthCalledWith(3, 'workflow:run-guard:run:wfr_1');
+ });
+});
diff --git a/src/server/workflows/runGuard/errors.ts b/src/server/workflows/runGuard/errors.ts
new file mode 100644
index 00000000000..55e6b67a09c
--- /dev/null
+++ b/src/server/workflows/runGuard/errors.ts
@@ -0,0 +1,90 @@
+import type {
+ WorkflowRunGuardCheckScope,
+ WorkflowRunGuardMatch,
+ WorkflowRunGuardScopeType,
+ WorkflowRunGuardValue,
+} from './types';
+
+/**
+ * Options required to create a workflow run guard error.
+ */
+export interface WorkflowRunGuardErrorOptions {
+ /**
+ * Guard match that blocked execution.
+ */
+ match: WorkflowRunGuardMatch;
+
+ /**
+ * Scope being evaluated when the guard matched.
+ */
+ scope: WorkflowRunGuardCheckScope;
+}
+
+/**
+ * Error thrown when workflow execution is blocked by a run guard.
+ *
+ * Use when:
+ * - A guard lookup finds a matching block key.
+ *
+ * Expects:
+ * - `match` contains the guard value and Redis key.
+ * - `scope` contains the workflow context that was checked.
+ *
+ * Returns:
+ * - An Error carrying both the matched key and checked workflow context.
+ */
+export class WorkflowRunGuardError extends Error {
+ /**
+ * Logical guard scope that matched.
+ */
+ guardScope: WorkflowRunGuardScopeType;
+
+ /**
+ * Redis key that blocked the workflow run.
+ */
+ matchedKey: string;
+
+ /**
+ * Human-readable reason from the matched guard value.
+ */
+ reason?: string;
+
+ /**
+ * Step name checked when the guard matched.
+ */
+ stepName?: string;
+
+ /**
+ * User id checked when the guard matched.
+ */
+ userId?: string;
+
+ /**
+ * Decoded guard payload from the matched key.
+ */
+ value: WorkflowRunGuardValue;
+
+ /**
+ * Workflow path checked when the guard matched.
+ */
+ workflowPath: string;
+
+ /**
+ * Workflow run id checked when the guard matched.
+ */
+ workflowRunId?: string;
+
+ constructor({ match, scope }: WorkflowRunGuardErrorOptions) {
+ super(match.value.reason || `Workflow execution blocked by run guard: ${match.key}`);
+
+ this.name = 'WorkflowRunGuardError';
+ this.guardScope = match.scope;
+ this.matchedKey = match.key;
+ this.reason = match.value.reason;
+ this.stepName = scope.stepName;
+ this.userId = scope.userId;
+ this.value = match.value;
+ this.workflowPath = scope.workflowPath;
+ this.workflowRunId = scope.workflowRunId;
+ }
+}
diff --git a/src/server/workflows/runGuard/index.ts b/src/server/workflows/runGuard/index.ts
new file mode 100644
index 00000000000..dcd61cc27f2
--- /dev/null
+++ b/src/server/workflows/runGuard/index.ts
@@ -0,0 +1,5 @@
+export * from './errors';
+export * from './keys';
+export * from './qstashCancel';
+export * from './store';
+export * from './types';
diff --git a/src/server/workflows/runGuard/keys.ts b/src/server/workflows/runGuard/keys.ts
new file mode 100644
index 00000000000..3788f7a8f45
--- /dev/null
+++ b/src/server/workflows/runGuard/keys.ts
@@ -0,0 +1,150 @@
+import { createHash } from 'node:crypto';
+
+import type {
+ WorkflowRunGuardCheckScope,
+ WorkflowRunGuardKeyCandidate,
+ WorkflowRunGuardMutationScope,
+} from './types';
+import { WORKFLOW_RUN_GUARD_KEY_PREFIX } from './types';
+
+/**
+ * Normalizes workflow paths for guard key construction.
+ *
+ * Before:
+ * - "https://app.lobehub.com/api/workflows/demo/"
+ * - "/api/workflows/demo/?x=1#hash"
+ * - "api/workflows/demo?x=1#hash"
+ *
+ * After:
+ * - "api/workflows/demo"
+ * - "api/workflows/demo"
+ * - "api/workflows/demo"
+ */
+export const normalizeWorkflowRunGuardPath = (value: string): string => {
+ const { pathname } = (() => {
+ try {
+ return new URL(value);
+ } catch {
+ return new URL(value, 'https://workflow-run-guard.local');
+ }
+ })();
+
+ return pathname.replace(/^\/+/, '').replace(/\/+$/, '');
+};
+
+/**
+ * Hashes a workflow step name into a short stable key fragment.
+ *
+ * Use when:
+ * - Building step-scoped run guard keys.
+ *
+ * Expects:
+ * - The input is the exact workflow step name to protect.
+ *
+ * Returns:
+ * - A 16-character lowercase hexadecimal SHA-256 prefix.
+ */
+export const hashWorkflowRunGuardStepName = (stepName: string): string =>
+ createHash('sha256').update(stepName).digest('hex').slice(0, 16);
+
+/**
+ * Builds the Redis key for one workflow run guard mutation scope.
+ *
+ * Use when:
+ * - Creating, deleting, or reading a direct guard key.
+ *
+ * Expects:
+ * - Path scopes may pass a path or URL.
+ * - Step scopes include both workflow run id and step name.
+ *
+ * Returns:
+ * - The Redis key for the provided scope.
+ */
+export const buildWorkflowRunGuardRedisKey = (scope: WorkflowRunGuardMutationScope): string => {
+ switch (scope.type) {
+ case 'global': {
+ return `${WORKFLOW_RUN_GUARD_KEY_PREFIX}:global`;
+ }
+
+ case 'path': {
+ return `${WORKFLOW_RUN_GUARD_KEY_PREFIX}:path:${normalizeWorkflowRunGuardPath(
+ scope.workflowPath,
+ )}`;
+ }
+
+ case 'user': {
+ return `${WORKFLOW_RUN_GUARD_KEY_PREFIX}:user:${scope.userId}`;
+ }
+
+ case 'run': {
+ return `${WORKFLOW_RUN_GUARD_KEY_PREFIX}:run:${scope.workflowRunId}`;
+ }
+
+ case 'step': {
+ return `${WORKFLOW_RUN_GUARD_KEY_PREFIX}:step:${scope.workflowRunId}:${hashWorkflowRunGuardStepName(
+ scope.stepName,
+ )}`;
+ }
+ }
+};
+
+const buildPathPrefixKeys = (workflowPath: string): WorkflowRunGuardKeyCandidate[] => {
+ const normalized = normalizeWorkflowRunGuardPath(workflowPath);
+
+ if (!normalized) return [];
+
+ const segments = normalized.split('/').filter(Boolean);
+
+ return segments.map((_, index) => ({
+ key: `${WORKFLOW_RUN_GUARD_KEY_PREFIX}:path:${segments.slice(0, index + 1).join('/')}`,
+ scope: 'path-prefix',
+ }));
+};
+
+/**
+ * Builds all workflow run guard candidate keys in check order.
+ *
+ * Use when:
+ * - Evaluating whether a workflow request or step should be blocked.
+ *
+ * Expects:
+ * - `workflowPath` is always present.
+ * - `workflowRunId` is present when step-level matching is needed.
+ *
+ * Returns:
+ * - Candidate keys ordered from broadest guard to narrowest guard.
+ */
+export const buildWorkflowRunGuardKeys = (
+ scope: WorkflowRunGuardCheckScope,
+): WorkflowRunGuardKeyCandidate[] => [
+ { key: buildWorkflowRunGuardRedisKey({ type: 'global' }), scope: 'global' },
+ ...buildPathPrefixKeys(scope.workflowPath),
+ ...(scope.userId
+ ? [
+ {
+ key: buildWorkflowRunGuardRedisKey({ type: 'user', userId: scope.userId }),
+ scope: 'user' as const,
+ },
+ ]
+ : []),
+ ...(scope.workflowRunId
+ ? [
+ {
+ key: buildWorkflowRunGuardRedisKey({ type: 'run', workflowRunId: scope.workflowRunId }),
+ scope: 'run' as const,
+ },
+ ]
+ : []),
+ ...(scope.workflowRunId && scope.stepName
+ ? [
+ {
+ key: buildWorkflowRunGuardRedisKey({
+ stepName: scope.stepName,
+ type: 'step',
+ workflowRunId: scope.workflowRunId,
+ }),
+ scope: 'step' as const,
+ },
+ ]
+ : []),
+];
diff --git a/src/server/workflows/runGuard/qstashCancel.ts b/src/server/workflows/runGuard/qstashCancel.ts
new file mode 100644
index 00000000000..8f9c3befdf1
--- /dev/null
+++ b/src/server/workflows/runGuard/qstashCancel.ts
@@ -0,0 +1,107 @@
+import type { Client as WorkflowClient } from '@upstash/workflow';
+
+import { normalizeWorkflowRunGuardPath } from './keys';
+
+/**
+ * Input used to resolve active QStash workflow runs affected by a run guard.
+ */
+export interface CancelWorkflowRunsByGuardPolicyParams {
+ /**
+ * Public application origin used by QStash workflow URLs.
+ */
+ appUrl: string;
+
+ /**
+ * Workflow path or URL to match as a normalized URL prefix.
+ */
+ workflowPath: string;
+}
+
+/**
+ * Result returned after resolving and optionally cancelling QStash workflow runs.
+ */
+export interface CancelWorkflowRunsByGuardPolicyResult {
+ /**
+ * Number of workflow runs QStash reported as cancelled.
+ */
+ cancelled: number;
+
+ /**
+ * Deduplicated workflow run ids selected from active QStash logs.
+ */
+ matchedRunIds: string[];
+
+ /**
+ * Absolute workflow URL prefix used for local log filtering.
+ */
+ workflowUrlPrefix: string;
+}
+
+/**
+ * Builds the absolute workflow URL prefix used for QStash log matching.
+ *
+ * Use when:
+ * - Resolving workflow runs from QStash logs by workflow path.
+ * - Matching child workflow endpoint prefixes under a route group.
+ *
+ * Expects:
+ * - `appUrl` is an absolute application origin or URL.
+ * - `workflowPath` may include a leading slash, query, hash, or full origin.
+ *
+ * Returns:
+ * - A trailing-slash-free URL prefix.
+ */
+export const buildWorkflowUrlPrefix = ({
+ appUrl,
+ workflowPath,
+}: CancelWorkflowRunsByGuardPolicyParams): string =>
+ new URL(`/${normalizeWorkflowRunGuardPath(workflowPath)}`, appUrl).toString().replace(/\/$/, '');
+
+const matchesWorkflowUrlPrefix = (workflowUrl: string, workflowUrlPrefix: string): boolean => {
+ if (workflowUrl === workflowUrlPrefix) return true;
+ if (!workflowUrl.startsWith(workflowUrlPrefix)) return false;
+
+ const boundary = workflowUrl.at(workflowUrlPrefix.length);
+ return boundary === '/' || boundary === '?' || boundary === '#';
+};
+
+/**
+ * Cancels active QStash workflow runs selected by a workflow run guard policy.
+ *
+ * Use when:
+ * - A guard with QStash cancellation enabled should stop already-started workflow runs.
+ * - SDK `urlStartingWith` cancellation cannot be trusted and run ids must be resolved first.
+ *
+ * Expects:
+ * - `client.logs` supports filtering with `{ count: 100, state: 'RUN_STARTED' }`.
+ * - QStash log entries include workflow URL, state, and run id fields.
+ *
+ * Returns:
+ * - The workflow URL prefix, matched run ids, and QStash cancellation count.
+ */
+export const cancelWorkflowRunsByGuardPolicy = async (
+ client: Pick<WorkflowClient, 'cancel' | 'logs'>,
+ params: CancelWorkflowRunsByGuardPolicyParams,
+): Promise<CancelWorkflowRunsByGuardPolicyResult> => {
+ const workflowUrlPrefix = buildWorkflowUrlPrefix(params);
+ const logs = await client.logs({ count: 100, state: 'RUN_STARTED' });
+ const matchedRunIds = Array.from(
+ new Set(
+ logs.runs
+ .filter((run) => matchesWorkflowUrlPrefix(run.workflowUrl, workflowUrlPrefix))
+ .map((run) => run.workflowRunId),
+ ),
+ );
+
+ if (matchedRunIds.length === 0) {
+ return { cancelled: 0, matchedRunIds, workflowUrlPrefix };
+ }
+
+ const result = await client.cancel({ ids: matchedRunIds });
+
+ return {
+ cancelled: result.cancelled || 0,
+ matchedRunIds,
+ workflowUrlPrefix,
+ };
+};
diff --git a/src/server/workflows/runGuard/store.ts b/src/server/workflows/runGuard/store.ts
new file mode 100644
index 00000000000..15685b8a000
--- /dev/null
+++ b/src/server/workflows/runGuard/store.ts
@@ -0,0 +1,194 @@
+import debug from 'debug';
+
+import type { BaseRedisProvider } from '@/libs/redis/types';
+
+import { WorkflowRunGuardError } from './errors';
+import { buildWorkflowRunGuardKeys, buildWorkflowRunGuardRedisKey } from './keys';
+import type {
+ WorkflowRunGuardCheckScope,
+ WorkflowRunGuardMatch,
+ WorkflowRunGuardMutationScope,
+ WorkflowRunGuardValue,
+} from './types';
+import {
+ WORKFLOW_RUN_GUARD_DEFAULT_TTL_SECONDS,
+ WORKFLOW_RUN_GUARD_KEY_PREFIX,
+ WORKFLOW_RUN_GUARD_MAX_TTL_SECONDS,
+} from './types';
+
+const log = debug('lobe-server:workflows:run-guard');
+
+/**
+ * Normalizes workflow run guard TTL seconds into the supported Redis range.
+ *
+ * Before:
+ * - Number.NaN
+ * - 3.9
+ * - 99_999
+ *
+ * After:
+ * - 3600
+ * - 3
+ * - 86_400
+ */
+const normalizeTtlSeconds = (ttlSeconds?: number): number => {
+ const integerTtlSeconds =
+ typeof ttlSeconds === 'number' && Number.isFinite(ttlSeconds)
+ ? Math.floor(ttlSeconds)
+ : WORKFLOW_RUN_GUARD_DEFAULT_TTL_SECONDS;
+
+ return Math.min(Math.max(1, integerTtlSeconds), WORKFLOW_RUN_GUARD_MAX_TTL_SECONDS);
+};
+
+const parseGuardValue = (raw: string | null): WorkflowRunGuardValue | undefined => {
+ if (!raw) return undefined;
+
+ try {
+ const parsed = JSON.parse(raw) as unknown;
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as WorkflowRunGuardValue)
+ : undefined;
+ } catch (error) {
+ log('Ignoring malformed workflow run guard value: %O', error);
+ return undefined;
+ }
+};
+
+/**
+ * Throws when a workflow run guard matches the provided workflow scope.
+ *
+ * Use when:
+ * - Checking workflow execution before starting or continuing a run.
+ * - Redis errors should fail open so workflow execution can continue.
+ *
+ * Expects:
+ * - `workflowPath` is present and can be converted into guard candidates.
+ * - Redis returns serialized {@link WorkflowRunGuardValue} payloads.
+ *
+ * Returns:
+ * - Resolves when no guard matches.
+ * - Rejects with {@link WorkflowRunGuardError} when the first matching guard blocks execution.
+ */
+export const assertWorkflowRunAllowed = async (
+ redis: Pick<BaseRedisProvider, 'get'> | null,
+ scope: WorkflowRunGuardCheckScope,
+): Promise<void> => {
+ if (!redis) return;
+
+ try {
+ for (const candidate of buildWorkflowRunGuardKeys(scope)) {
+ const value = parseGuardValue(await redis.get(candidate.key));
+ if (!value) continue;
+
+ const match: WorkflowRunGuardMatch = {
+ key: candidate.key,
+ scope: candidate.scope,
+ value,
+ };
+
+ throw new WorkflowRunGuardError({ match, scope });
+ }
+ } catch (error) {
+ if (error instanceof WorkflowRunGuardError) throw error;
+
+ log('Workflow run guard Redis check failed open: %O', error);
+ }
+};
+
+/**
+ * Creates or replaces one workflow run guard Redis entry.
+ *
+ * Use when:
+ * - Admin or operational code needs to block a workflow scope.
+ * - Mutation errors should surface to the caller.
+ *
+ * Expects:
+ * - `scope` identifies exactly one Redis guard key.
+ * - `value` is JSON-serializable.
+ *
+ * Returns:
+ * - The Redis key, normalized TTL, and stored guard value.
+ */
+export const setWorkflowRunGuard = async (
+ redis: Pick<BaseRedisProvider, 'set'>,
+ input: {
+ scope: WorkflowRunGuardMutationScope;
+ ttlSeconds?: number;
+ value: WorkflowRunGuardValue;
+ },
+) => {
+ const key = buildWorkflowRunGuardRedisKey(input.scope);
+ const ttlSeconds = normalizeTtlSeconds(input.ttlSeconds);
+ const value: WorkflowRunGuardValue = {
+ ...input.value,
+ createdAt: input.value.createdAt ?? new Date().toISOString(),
+ stepName: input.scope.type === 'step' ? input.scope.stepName : input.value.stepName,
+ };
+
+ await redis.set(key, JSON.stringify(value), { ex: ttlSeconds });
+
+ return { key, ttlSeconds, value };
+};
+
+/**
+ * Deletes one workflow run guard Redis entry.
+ *
+ * Use when:
+ * - Admin or operational code needs to unblock one workflow scope.
+ * - Mutation errors should surface to the caller.
+ *
+ * Expects:
+ * - `scope` identifies exactly one Redis guard key.
+ *
+ * Returns:
+ * - The Redis key and Redis deletion count.
+ */
+export const clearWorkflowRunGuard = async (
+ redis: Pick<BaseRedisProvider, 'del'>,
+ scope: WorkflowRunGuardMutationScope,
+) => {
+ const key = buildWorkflowRunGuardRedisKey(scope);
+ const deleted = await redis.del(key);
+ return { deleted, key };
+};
+
+/**
+ * Lists current workflow run guard Redis entries.
+ *
+ * Use when:
+ * - Admin or operational code needs to inspect active guard state.
+ * - Scan/listing errors should surface to the caller.
+ *
+ * Expects:
+ * - Redis supports cursor scan with MATCH and COUNT arguments.
+ *
+ * Returns:
+ * - Guard entries with their key, remaining TTL seconds, and parsed value when valid.
+ */
+export const listWorkflowRunGuards = async (
+ redis: Pick<BaseRedisProvider, 'get' | 'scan' | 'ttl'>,
+) => {
+ const items: Array<{ key: string; ttlSeconds: number; value?: WorkflowRunGuardValue }> = [];
+ let cursor = '0';
+
+ do {
+ const [nextCursor, keys] = await redis.scan(
+ cursor,
+ 'MATCH',
+ `${WORKFLOW_RUN_GUARD_KEY_PREFIX}:*`,
+ 'COUNT',
+ 100,
+ );
+ cursor = nextCursor;
+
+ for (const key of keys) {
+ items.push({
+ key,
+ ttlSeconds: await redis.ttl(key),
+ value: parseGuardValue(await redis.get(key)),
+ });
+ }
+ } while (cursor !== '0');
+
+ return items;
+};
diff --git a/src/server/workflows/runGuard/types.ts b/src/server/workflows/runGuard/types.ts
new file mode 100644
index 00000000000..4ab59b1b9d1
--- /dev/null
+++ b/src/server/workflows/runGuard/types.ts
@@ -0,0 +1,152 @@
+/**
+ * Prefix shared by all workflow run guard Redis keys.
+ *
+ * Use when:
+ * - Building guard keys for mutation or lookup.
+ * - Scanning workflow run guard state.
+ *
+ * Expects:
+ * - Callers append a scope segment after the prefix.
+ *
+ * Returns:
+ * - The stable namespace prefix for run guard keys.
+ */
+export const WORKFLOW_RUN_GUARD_KEY_PREFIX = 'workflow:run-guard';
+
+/**
+ * Default expiration for workflow run guard entries in seconds.
+ *
+ * Use when:
+ * - A caller creates a guard without specifying an explicit TTL.
+ *
+ * Expects:
+ * - Store implementations apply the value as seconds.
+ *
+ * Returns:
+ * - One hour in seconds.
+ */
+export const WORKFLOW_RUN_GUARD_DEFAULT_TTL_SECONDS = 60 * 60;
+
+/**
+ * Maximum supported expiration for workflow run guard entries in seconds.
+ *
+ * Use when:
+ * - Validating user or admin supplied TTL values.
+ *
+ * Expects:
+ * - Store implementations clamp or reject values above this limit.
+ *
+ * Returns:
+ * - Twenty-four hours in seconds.
+ */
+export const WORKFLOW_RUN_GUARD_MAX_TTL_SECONDS = 24 * 60 * 60;
+
+/**
+ * Policy attached to a workflow run guard value.
+ */
+export interface WorkflowRunGuardPolicy {
+ /**
+ * Whether downstream QStash work should be canceled when this guard matches.
+ */
+ cancelQstash?: boolean;
+}
+
+/**
+ * Serialized value stored for a workflow run guard key.
+ */
+export interface WorkflowRunGuardValue {
+ /**
+ * ISO timestamp indicating when the guard was created.
+ */
+ createdAt?: string;
+
+ /**
+ * Optional behavior controls to apply when the guard matches.
+ */
+ policy?: WorkflowRunGuardPolicy;
+
+ /**
+ * Human-readable reason for blocking workflow execution.
+ */
+ reason?: string;
+
+ /**
+ * Original step name for step-scoped guards.
+ */
+ stepName?: string;
+}
+
+/**
+ * Scope used when checking whether a workflow run should be blocked.
+ */
+export interface WorkflowRunGuardCheckScope {
+ /**
+ * Optional workflow step name used for step-level guard checks.
+ */
+ stepName?: string;
+
+ /**
+ * Optional user id used for user-level guard checks.
+ */
+ userId?: string;
+
+ /**
+ * Workflow request path or URL used for path-prefix guard checks.
+ */
+ workflowPath: string;
+
+ /**
+ * Optional workflow run id used for run-level and step-level guard checks.
+ */
+ workflowRunId?: string;
+}
+
+/**
+ * Scope accepted when creating or deleting a single workflow run guard key.
+ */
+export type WorkflowRunGuardMutationScope =
+ | { type: 'global' }
+ | { type: 'path'; workflowPath: string }
+ | { type: 'user'; userId: string }
+ | { type: 'run'; workflowRunId: string }
+ | { stepName: string; type: 'step'; workflowRunId: string };
+
+/**
+ * Scope labels returned by guard key builders and matches.
+ */
+export type WorkflowRunGuardScopeType = WorkflowRunGuardMutationScope['type'] | 'path-prefix';
+
+/**
+ * Candidate key checked while evaluating workflow run guard state.
+ */
+export interface WorkflowRunGuardKeyCandidate {
+ /**
+ * Redis key to check.
+ */
+ key: string;
+
+ /**
+ * Logical scope represented by the candidate key.
+ */
+ scope: WorkflowRunGuardScopeType;
+}
+
+/**
+ * Matched workflow run guard key and decoded value.
+ */
+export interface WorkflowRunGuardMatch {
+ /**
+ * Redis key that matched.
+ */
+ key: string;
+
+ /**
+ * Logical scope represented by the matched key.
+ */
+ scope: WorkflowRunGuardScopeType;
+
+ /**
+ * Decoded guard payload stored at the matched key.
+ */
+ value: WorkflowRunGuardValue;
+}