Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(memory-user-memory): return instead of throw on run-guard match to stop Upstash retry storm (#16758)

Arvin Xu19b85e11c4ed
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 5b380d3c858..1b2c613ea5b 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
@@ -37,6 +37,7 @@ vi.mock('@/server/services/memory/userMemory/extract', () => ({
vi.mock('../runGuard', () => ({
assertMemoryWorkflowContextAllowed: vi.fn(),
+ resolveMemoryWorkflowRunGuard: vi.fn().mockResolvedValue(null),
}));
describe('hourlyWorkflowHandler', () => {
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 033ef723510..e9cdc207285 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 { assertMemoryWorkflowContextAllowed } from './runGuard';
+import { resolveMemoryWorkflowRunGuard } from './runGuard';
import { serializeWorkflowCursor } from './utils';
const USER_PAGE_SIZE = 200;
@@ -27,7 +27,18 @@ export const hourlyWorkflowHandler = async (
context: WorkflowContext<MemoryExtractionHourlyWorkflowPayload>,
) => {
const { cursor, dryRun } = context.requestPayload || {};
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+
+ // 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 baseUrl = resolveBaseUrl();
if (!baseUrl) {
@@ -43,7 +54,6 @@ export const hourlyWorkflowHandler = async (
const executor = await MemoryExtractionExecutor.create();
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),
);
@@ -65,8 +75,6 @@ export const hourlyWorkflowHandler = async (
await Promise.all(
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(
@@ -86,7 +94,6 @@ export const hourlyWorkflowHandler = async (
if (nextCursor) {
const stepName = 'memory:user-memory:hourly:schedule-next-page';
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerHourly(
{
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 a0c162f435e..d5ceb6d7968 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
@@ -17,10 +17,9 @@ import {
MemoryExtractionExecutor,
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { WorkflowRunGuardError } from '@/server/workflows/runGuard';
import { createWorkflowQstashClient } from '../../qstashClient';
-import { assertMemoryWorkflowContextAllowed } from './runGuard';
+import { resolveMemoryWorkflowRunGuard } from './runGuard';
const CEPA_LAYERS: LayersEnum[] = [
LayersEnum.Context,
@@ -48,7 +47,16 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
});
try {
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+ // 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) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ return {
+ message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,
+ skipped: true,
+ };
+ }
const topicId = payload.topicIds[0];
const userId = payload.userIds[0];
@@ -69,7 +77,6 @@ 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`;
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
const cancelled = await context.run(stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
@@ -92,7 +99,6 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
}
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,
@@ -115,7 +121,6 @@ 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`;
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
const cancelled = await context.run(stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
@@ -139,7 +144,6 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
}
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,
@@ -160,7 +164,6 @@ const processTopicRoute = async (context: WorkflowContext<MemoryExtractionPayloa
if (payload.asyncTaskId && payload.userInitiated) {
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(
@@ -182,7 +185,6 @@ 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 9264f4e3945..45444670eff 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 { assertMemoryWorkflowContextAllowed } from './runGuard';
+import { resolveMemoryWorkflowRunGuard } from './runGuard';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topics';
@@ -48,7 +48,19 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
});
try {
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+ // 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) {
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return {
+ message: `Memory workflow disabled by run guard (${guardBlock.reason ?? guardBlock.scope}); skipping.`,
+ processedTopics: 0,
+ processedUsers: 0,
+ skipped: true,
+ };
+ }
if (!payload.userIds.length) {
span.setStatus({ code: SpanStatusCode.OK });
@@ -83,7 +95,6 @@ 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`;
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
const cancelled = await context.run(stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
@@ -105,7 +116,6 @@ 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}`;
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
await context.invoke(stepName, {
body: {
...payload,
@@ -132,7 +142,6 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
// Trigger user persona update after topic processing using the workflow client.
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 72a58bb7a16..4c53e12904f 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUserTopics.ts
@@ -14,7 +14,7 @@ import {
} from '@/server/services/memory/userMemory/extract';
import { forEachBatchSequential } from '@/server/services/memory/userMemory/topicBatching';
-import { assertMemoryWorkflowContextAllowed } from './runGuard';
+import { resolveMemoryWorkflowRunGuard } from './runGuard';
const TOPIC_PAGE_SIZE = 50;
const TOPIC_BATCH_SIZE = 4;
@@ -28,7 +28,16 @@ export const processUserTopicsHandler = async (
context: WorkflowContext<MemoryExtractionPayloadInput>,
) => {
const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+
+ // 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,
+ };
+ }
if (!params.userIds.length) {
return { message: 'No user ids provided for topic processing.' };
@@ -63,7 +72,6 @@ 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`;
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
const cancelled = await context.run(stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
@@ -89,7 +97,6 @@ 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`;
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
topicsFromPayload = await context.run(stepName, async () => {
const filtered = await executor.filterTopicIdsForUser(
userId,
@@ -101,7 +108,6 @@ export const processUserTopicsHandler = async (
}
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[];
@@ -136,7 +142,6 @@ export const processUserTopicsHandler = async (
// 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}`;
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
await context.run(stepName, () =>
MemoryExtractionWorkflowService.triggerProcessTopics(
userId,
@@ -154,7 +159,6 @@ export const processUserTopicsHandler = async (
if (!topicsFromPayload && cursor) {
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
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 d15a7d0c37f..69f8262fd93 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 { assertMemoryWorkflowContextAllowed } from './runGuard';
+import { resolveMemoryWorkflowRunGuard } from './runGuard';
import { serializeWorkflowCursor } from './utils';
const USER_PAGE_SIZE = 50;
@@ -26,7 +26,16 @@ export const processUsersHandler = async (
context: WorkflowContext<MemoryExtractionPayloadInput>,
) => {
const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH);
+
+ // 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,
+ };
+ }
if (params.sources.length === 0) {
return { message: 'No sources provided, skip memory extraction.' };
@@ -35,7 +44,6 @@ 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';
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
const cancelled = await context.run(stepName, () =>
getServerDB().then((db) =>
new AsyncTaskModel(
@@ -60,7 +68,6 @@ export const processUsersHandler = async (
: undefined;
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 }
@@ -78,8 +85,6 @@ export const processUsersHandler = async (
await Promise.all(
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(
{
@@ -96,7 +101,6 @@ export const processUsersHandler = async (
if (params.userIds.length === 0 && cursor) {
const stepName = 'memory:user-memory:extract:users:schedule-next-user-batch';
- await assertMemoryWorkflowContextAllowed(context, WORKFLOW_PATH, stepName);
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.ts
index 497589debb0..48a3d961dfc 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts
@@ -3,7 +3,7 @@ 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';
+import { assertWorkflowRunAllowed, WorkflowRunGuardError } from '@/server/workflows/runGuard';
interface MemoryWorkflowGuardInput {
payload?: unknown;
@@ -92,3 +92,44 @@ export const assertMemoryWorkflowContextAllowed = async (
workflowRunId: getWorkflowRunId(context),
});
};
+
+/**
+ * Details of a run guard that blocks a memory workflow.
+ */
+export interface MemoryWorkflowRunGuardBlock {
+ matchedKey: string;
+ reason?: string;
+ scope: string;
+}
+
+/**
+ * Resolves whether a run guard blocks this memory workflow, WITHOUT throwing.
+ *
+ * Use when:
+ * - A memory workflow handler wants to stop a blocked run at its entry.
+ *
+ * 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).
+ *
+ * Returns:
+ * - The matched guard details when a guard blocks the run.
+ * - `null` when no guard matches (or Redis fails open).
+ */
+export const resolveMemoryWorkflowRunGuard = async (
+ 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;
+ }
+};