🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: serialize memory workflow cursors safely
Neko587f565d7952
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.tsnew file mode 100644index 00000000000..6290dd749cc--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/workflows/__tests__/hourly.test.ts@@ -0,0 +1,93 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { hourlyWorkflowHandler } from '../hourly';++const mocks = vi.hoisted(() => ({+ createExecutor: vi.fn(),+ getUsersForHourlyExtraction: vi.fn(),+ triggerHourly: vi.fn(),+ triggerProcessUsers: vi.fn(),+}));++vi.mock('@/envs/app', () => ({+ appEnv: {+ APP_URL: 'https://app.example.com',+ INTERNAL_APP_URL: undefined,+ },+}));++vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({+ parseMemoryExtractionConfig: () => ({+ upstashWorkflowExtraHeaders: {},+ webhook: { baseUrl: 'https://app.example.com' },+ }),+}));++vi.mock('@/server/services/memory/userMemory/extract', () => ({+ buildWorkflowPayloadInput: (payload: unknown) => payload,+ MemoryExtractionExecutor: {+ create: mocks.createExecutor,+ },+ MemoryExtractionWorkflowService: {+ triggerHourly: mocks.triggerHourly,+ triggerProcessUsers: mocks.triggerProcessUsers,+ },+ normalizeMemoryExtractionPayload: (payload: unknown) => payload,+}));++describe('hourlyWorkflowHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.createExecutor.mockResolvedValue({+ getUsersForHourlyExtraction: mocks.getUsersForHourlyExtraction,+ });+ mocks.triggerHourly.mockResolvedValue({ workflowRunId: 'next-page-run' });+ mocks.triggerProcessUsers.mockResolvedValue({ workflowRunId: 'process-users-run' });+ });++ it('continues pagination when Upstash restores the user batch cursor as JSON', async () => {+ /**+ * @example+ * await expect(hourlyWorkflowHandler(context)).resolves.toMatchObject({ hasNextPage: true });+ */+ // ROOT CAUSE:+ //+ // Upstash Workflow persists context.run results as JSON between steps.+ // Date values returned from the user listing step come back as ISO strings.+ //+ // Before the fix, hourlyWorkflowHandler called:+ // userBatch.cursor.createdAt.toISOString()+ //+ // We should normalize that boundary before scheduling the next page.+ mocks.getUsersForHourlyExtraction.mockResolvedValue({+ cursor: {+ createdAt: '2024-07-02T09:36:44.073Z',+ id: 'user_2igX4ULK7Q2tADwibFkEpng0xRc',+ },+ ids: ['user_2gmT7yMAt730UeHuzNpjZiw4Z2X'],+ });++ const context = {+ requestPayload: { dryRun: true },+ run: vi.fn((_name: string, callback: () => unknown) => callback()),+ };++ await expect(hourlyWorkflowHandler(context as never)).resolves.toMatchObject({+ dryRun: true,+ hasNextPage: true,+ processedUsers: 1,+ scheduledBatches: 0,+ });+ expect(mocks.triggerHourly).toHaveBeenCalledWith(+ {+ baseUrl: 'https://app.example.com',+ cursor: {+ createdAt: '2024-07-02T09:36:44.073Z',+ id: 'user_2igX4ULK7Q2tADwibFkEpng0xRc',+ },+ dryRun: true,+ },+ { extraHeaders: {} },+ );+ });+});diff --git a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts b/src/server/workflows-hono/memory-user-memory/workflows/hourly.tsindex 859d84461a8..fbc362de9dd 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/hourly.ts@@ -12,6 +12,8 @@ import {normalizeMemoryExtractionPayload,} from '@/server/services/memory/userMemory/extract';+import { serializeWorkflowCursor } from './utils';+const USER_PAGE_SIZE = 200;const USER_BATCH_SIZE = 20;@@ -48,10 +50,10 @@ export const hourlyWorkflowHandler = async (}const nextCursor = userBatch.cursor- ? {- createdAt: userBatch.cursor.createdAt.toISOString(),- id: userBatch.cursor.id,- }+ ? serializeWorkflowCursor(+ userBatch.cursor,+ 'Invalid cursor date for hourly memory extraction workflow',+ ): undefined;if (!dryRun) {diff --git a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.tsindex d85aded757d..ad666e7b2d9 100644--- a/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts+++ b/src/server/workflows-hono/memory-user-memory/workflows/processUsers.ts@@ -12,6 +12,8 @@ import {normalizeMemoryExtractionPayload,} from '@/server/services/memory/userMemory/extract';+import { serializeWorkflowCursor } from './utils';+const USER_PAGE_SIZE = 50;const USER_BATCH_SIZE = 10;@@ -86,7 +88,10 @@ export const processUsersHandler = async ({...buildWorkflowPayloadInput({...params,- userCursor: { createdAt: cursor.createdAt.toISOString(), id: cursor.id },+ userCursor: serializeWorkflowCursor(+ cursor,+ 'Invalid cursor date when scheduling next user page',+ ),}),},{ extraHeaders: upstashWorkflowExtraHeaders },diff --git a/src/server/workflows-hono/memory-user-memory/workflows/utils.ts b/src/server/workflows-hono/memory-user-memory/workflows/utils.tsnew file mode 100644index 00000000000..781e5c929bf--- /dev/null+++ b/src/server/workflows-hono/memory-user-memory/workflows/utils.ts@@ -0,0 +1,49 @@+/**+ * Cursor shape accepted by workflow pagination serializers.+ */+export interface WorkflowCursorLike {+ /**+ * Cursor timestamp from a live database row or a JSON-restored workflow step result.+ */+ createdAt: Date | string;+ /**+ * Stable cursor id used to break ties when timestamps are equal.+ */+ id: string;+}++/**+ * Serializes a workflow cursor into the JSON-safe cursor shape.+ *+ * Use when:+ * - Scheduling a child workflow with a pagination cursor+ * - Passing cursor data across Upstash Workflow JSON boundaries+ *+ * Expects:+ * - `createdAt` is either a valid Date or an ISO-compatible date string+ *+ * Returns:+ * - A cursor with `createdAt` normalized to an ISO string+ *+ * Before:+ * - { createdAt: Date("2024-07-02T09:36:44.073Z"), id: "user_1" }+ * - { createdAt: "2024-07-02T09:36:44.073Z", id: "user_1" }+ *+ * After:+ * - { createdAt: "2024-07-02T09:36:44.073Z", id: "user_1" }+ */+export const serializeWorkflowCursor = (+ cursor: WorkflowCursorLike,+ errorMessage = 'Invalid workflow cursor date',+) => {+ // NOTICE:+ // Upstash Workflow persists step results as JSON and restores Date values as strings.+ // This cursor can come from a live DB result or a restored context.run result.+ // Keep accepting both shapes until workflow step serialization preserves Date objects.+ const createdAt = new Date(cursor.createdAt);+ if (Number.isNaN(createdAt.getTime())) {+ throw new Error(errorMessage);+ }++ return { createdAt: createdAt.toISOString(), id: cursor.id };+};