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): start workflows before guard checks (#16775)

Neko797e196570fd
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 bcce08f6273..78595f0047d 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', () => ({
checkGuard: vi.fn().mockResolvedValue({ result: true }),
+ ensureWorkflowStarted: vi.fn().mockResolvedValue({ started: true }),
}));
describe('hourlyWorkflowHandler', () => {
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
index fe0e9f78a72..9b13e4c1d93 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/personaUpdate.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
checkGuard: vi.fn(),
+ ensureWorkflowStarted: vi.fn(),
}));
vi.mock('@/database/server', () => ({
@@ -15,6 +16,7 @@ vi.mock('@/server/services/memory/userMemory/persona/service', () => ({
vi.mock('../runGuard', () => ({
checkGuard: mocks.checkGuard,
+ ensureWorkflowStarted: mocks.ensureWorkflowStarted,
}));
const { personaUpdateHandler } = await import('../personaUpdate');
@@ -22,9 +24,11 @@ const { personaUpdateHandler } = await import('../personaUpdate');
describe('personaUpdateHandler run guard', () => {
beforeEach(() => {
mocks.checkGuard.mockReset();
+ mocks.ensureWorkflowStarted.mockReset();
+ mocks.ensureWorkflowStarted.mockResolvedValue({ started: true });
});
- it('checks the run guard before parsing payload', async () => {
+ it('starts the workflow before checking the run guard or parsing payload', async () => {
/**
* @example
* await expect(personaUpdateHandler(context)).resolves.toMatchObject({ skipped: true });
@@ -56,6 +60,10 @@ describe('personaUpdateHandler run guard', () => {
});
expect(context.run).not.toHaveBeenCalled();
+ expect(mocks.ensureWorkflowStarted).toHaveBeenCalledWith(
+ context,
+ 'api/workflows/memory-user-memory/pipelines/persona/update-writing',
+ );
expect(mocks.checkGuard).toHaveBeenCalledWith(
context,
'api/workflows/memory-user-memory/pipelines/persona/update-writing',
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
index a29070c827c..f6d2a2f21fb 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/__tests__/runGuard.test.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/runGuard.test.ts
@@ -24,7 +24,7 @@ vi.mock('@/server/workflows/runGuard', () => ({
},
}));
-const { checkGuard } = await import('../runGuard');
+const { checkGuard, ensureWorkflowStarted } = await import('../runGuard');
const createContext = (payload: unknown, workflowRunId = 'wfr_context') => ({
requestPayload: payload,
@@ -42,6 +42,22 @@ describe('memory workflow run guard helper', () => {
mocks.assertWorkflowRunAllowed.mockResolvedValue(undefined);
});
+ it('records an initial no-op step before entry guard work can fail', async () => {
+ const context = createContext({ userId: 'user-1' });
+
+ await expect(
+ ensureWorkflowStarted(
+ context as never,
+ 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ ),
+ ).resolves.toEqual({ started: true });
+
+ expect(context.run).toHaveBeenCalledWith(
+ 'memory:user-memory:workflow-started:api/workflows/memory-user-memory/pipelines/chat-topic/process-topic',
+ expect.any(Function),
+ );
+ });
+
it('runs the Redis guard lookup inside a workflow step', async () => {
const redis = { get: vi.fn() };
mocks.initializeRedis.mockResolvedValue(redis);
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 fcc0349be5c..74001bdefef 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 { checkGuard } from './runGuard';
+import { checkGuard, ensureWorkflowStarted } from './runGuard';
import { serializeWorkflowCursor } from './utils';
const USER_PAGE_SIZE = 200;
@@ -26,6 +26,8 @@ const resolveBaseUrl = () => webhook.baseUrl || appEnv.INTERNAL_APP_URL || appEn
export const hourlyWorkflowHandler = async (
context: WorkflowContext<MemoryExtractionHourlyWorkflowPayload>,
) => {
+ await ensureWorkflowStarted(context, WORKFLOW_PATH);
+
const { cursor, dryRun } = context.requestPayload || {};
// NOTICE: A run guard match must terminate the workflow by returning, never by throwing.
diff --git a/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
index 30b55dc6fb8..f1b4cc2da1f 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/personaUpdate.ts
@@ -7,7 +7,7 @@ import {
UserPersonaService,
} from '@/server/services/memory/userMemory/persona/service';
-import { checkGuard } from './runGuard';
+import { checkGuard, ensureWorkflowStarted } from './runGuard';
const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/persona/update-writing';
@@ -16,6 +16,8 @@ const workflowPayloadSchema = z.object({
});
export const personaUpdateHandler = async (context: WorkflowContext) => {
+ await ensureWorkflowStarted(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 entryGuard = await checkGuard(context, WORKFLOW_PATH, {
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 08078bfce80..5c61d6728df 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/processTopic.ts
@@ -16,7 +16,7 @@ import {
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { checkGuard } from './runGuard';
+import { checkGuard, ensureWorkflowStarted } from './runGuard';
const CEPA_LAYERS: LayersEnum[] = [
LayersEnum.Context,
@@ -32,6 +32,8 @@ export const processTopicHandler = async (context: WorkflowContext<MemoryExtract
upstashWorkflowTracer.startActiveSpan(
'workflow:memory-user-memory:process-topic',
async (span) => {
+ await ensureWorkflowStarted(context, WORKFLOW_PATH);
+
const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});
span.setAttributes({
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 a2d69accf2f..9b492770510 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 {
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { checkGuard } from './runGuard';
+import { checkGuard, ensureWorkflowStarted } from './runGuard';
const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
const WORKFLOW_PATH = 'api/workflows/memory-user-memory/pipelines/chat-topic/process-topics';
@@ -34,6 +34,8 @@ export const processTopicsHandler = (context: WorkflowContext<MemoryExtractionPa
upstashWorkflowTracer.startActiveSpan(
'workflow:memory-user-memory:process-topics',
async (span) => {
+ await ensureWorkflowStarted(context, WORKFLOW_PATH);
+
const payload = normalizeMemoryExtractionPayload(context.requestPayload || {});
span.setAttributes({
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 8d36d1a3911..340a31418f7 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 {
normalizeMemoryExtractionPayload,
} from '@/server/services/memory/userMemory/extract';
-import { checkGuard } from './runGuard';
+import { checkGuard, ensureWorkflowStarted } from './runGuard';
const TOPIC_PAGE_SIZE = 50;
const TOPIC_BATCH_SIZE = 4;
@@ -32,6 +32,8 @@ const MAX_TOPICS_PER_USER_PER_RUN = workflow?.maxTopicsPerUserPerRun ?? 100;
export const processUserTopicsHandler = async (
context: WorkflowContext<MemoryExtractionPayloadInput>,
) => {
+ await ensureWorkflowStarted(context, WORKFLOW_PATH);
+
const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
// NOTICE: Return (never throw) on a guard match β€” a throw before the first step makes Upstash
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 18ea4eb4052..f491f138e57 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 { checkGuard } from './runGuard';
+import { checkGuard, ensureWorkflowStarted } from './runGuard';
import { serializeWorkflowCursor } from './utils';
const USER_PAGE_SIZE = 50;
@@ -25,6 +25,8 @@ const { upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
export const processUsersHandler = async (
context: WorkflowContext<MemoryExtractionPayloadInput>,
) => {
+ await ensureWorkflowStarted(context, WORKFLOW_PATH);
+
const params = normalizeMemoryExtractionPayload(context.requestPayload || {});
// NOTICE: Return (never throw) on a guard match β€” a throw before the first step makes Upstash
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 d274a45deda..43599b706cd 100644
--- a/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts
+++ b/src/server/workflows-hono/memory-user-memory/workflows/runGuard.ts
@@ -126,6 +126,18 @@ const createBlockedResponse = <TExtra extends MemoryWorkflowRunGuardResponseExtr
skipped: true,
});
+// NOTICE: Upstash retries/DLQs a workflow if it throws before the first persisted step.
+// Keep this no-op as the first entry action so later guard/config failures are normal steps.
+export const ensureWorkflowStarted = (
+ context: WorkflowContext<unknown>,
+ workflowPath: string,
+): Promise<{ started: true }> =>
+ Promise.resolve(
+ context.run(`memory:user-memory:workflow-started:${workflowPath}`, () => ({
+ started: true as const,
+ })),
+ );
+
/**
* Checks a memory workflow run guard as one explicit Upstash workflow step.
*