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(userMemories): incorrect hourly cron schedule for memory analysis (#12568)

Neko01606208c57e
diff --git a/packages/database/src/models/__tests__/user.test.ts b/packages/database/src/models/__tests__/user.test.ts
index 403d60bd0f6..c738575b3c4 100644
--- a/packages/database/src/models/__tests__/user.test.ts
+++ b/packages/database/src/models/__tests__/user.test.ts
@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { nextauthAccounts, users, userSettings } from '../../schemas';
+import { messages, nextauthAccounts, topics, users, userSettings } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import type { ListUsersForMemoryExtractorCursor } from '../user';
import { UserModel, UserNotFoundError } from '../user';
@@ -441,6 +441,73 @@ describe('UserModel', () => {
});
});
+ describe('listUsersForHourlyMemoryExtractor', () => {
+ it('should return only users with memory enabled and at least one chatted topic', async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([
+ { id: 'u1', createdAt: new Date('2024-01-01T00:00:00Z') }, // no settings => enabled
+ { id: 'u2', createdAt: new Date('2024-01-02T00:00:00Z') }, // memory disabled
+ { id: 'u3', createdAt: new Date('2024-01-03T00:00:00Z') }, // no messages
+ { id: 'u4', createdAt: new Date('2024-01-04T00:00:00Z') }, // assistant-only messages
+ { id: 'u5', createdAt: new Date('2024-01-05T00:00:00Z') }, // enabled + chatted
+ ]);
+
+ await serverDB.insert(userSettings).values([
+ { id: 'u2', memory: { enabled: false } },
+ { id: 'u3', memory: { enabled: true } },
+ { id: 'u4', memory: { enabled: true } },
+ { id: 'u5', memory: { enabled: true } },
+ ]);
+
+ await serverDB.insert(topics).values([
+ { id: 't1', userId: 'u1' },
+ { id: 't2', userId: 'u2' },
+ { id: 't3', userId: 'u3' },
+ { id: 't4', userId: 'u4' },
+ { id: 't5', userId: 'u5' },
+ ]);
+
+ await serverDB.insert(messages).values([
+ { id: 'm1', role: 'user', topicId: 't1', userId: 'u1' },
+ { id: 'm2', role: 'user', topicId: 't2', userId: 'u2' },
+ { id: 'm4', role: 'assistant', topicId: 't4', userId: 'u4' },
+ { id: 'm5', role: 'user', topicId: 't5', userId: 'u5' },
+ ]);
+
+ const result = await UserModel.listUsersForHourlyMemoryExtractor(serverDB);
+
+ expect(result.map((u) => u.id)).toEqual(['u1', 'u5']);
+ });
+
+ it('should support whitelist and cursor pagination', async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([
+ { id: 'user-a', createdAt: new Date('2024-01-01T00:00:00Z') },
+ { id: 'user-b', createdAt: new Date('2024-01-02T00:00:00Z') },
+ { id: 'user-c', createdAt: new Date('2024-01-03T00:00:00Z') },
+ ]);
+
+ await serverDB.insert(topics).values([
+ { id: 'topic-a', userId: 'user-a' },
+ { id: 'topic-b', userId: 'user-b' },
+ { id: 'topic-c', userId: 'user-c' },
+ ]);
+
+ await serverDB.insert(messages).values([
+ { id: 'msg-a', role: 'user', topicId: 'topic-a', userId: 'user-a' },
+ { id: 'msg-b', role: 'user', topicId: 'topic-b', userId: 'user-b' },
+ { id: 'msg-c', role: 'user', topicId: 'topic-c', userId: 'user-c' },
+ ]);
+
+ const result = await UserModel.listUsersForHourlyMemoryExtractor(serverDB, {
+ cursor: { createdAt: new Date('2024-01-02T00:00:00Z'), id: 'user-b' },
+ whitelist: ['user-a', 'user-c'],
+ });
+
+ expect(result.map((u) => u.id)).toEqual(['user-c']);
+ });
+ });
+
describe('getInfoForAIGeneration', () => {
it('should return user info with language preference', async () => {
await serverDB.insert(userSettings).values({
diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.ts
index e52ed58c515..9915458ea31 100644
--- a/packages/database/src/models/user.ts
+++ b/packages/database/src/models/user.ts
@@ -8,14 +8,14 @@ import type {
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import dayjs from 'dayjs';
-import { and, eq, gt, inArray, or } from 'drizzle-orm';
+import { and, asc, eq, gt, inArray, or, sql } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
import { merge } from '@/utils/merge';
import { today } from '@/utils/time';
import type { NewUser, UserItem, UserSettingsItem } from '../schemas';
-import { nextauthAccounts, users, userSettings } from '../schemas';
+import { messages, nextauthAccounts, topics, users, userSettings } from '../schemas';
import type { LobeChatDatabase } from '../type';
type DecryptUserKeyVaults = (
@@ -40,6 +40,8 @@ export type ListUsersForMemoryExtractorOptions = {
whitelist?: string[];
};
+export type ListUsersForHourlyMemoryExtractorOptions = ListUsersForMemoryExtractorOptions;
+
export interface UserInfoForAIGeneration {
responseLanguage: string;
userName: string;
@@ -340,6 +342,52 @@ export class UserModel {
});
};
+ static listUsersForHourlyMemoryExtractor = (
+ db: LobeChatDatabase,
+ options: ListUsersForHourlyMemoryExtractorOptions = {},
+ ) => {
+ const cursorCondition = options.cursor
+ ? or(
+ gt(users.createdAt, options.cursor.createdAt),
+ and(eq(users.createdAt, options.cursor.createdAt), gt(users.id, options.cursor.id)),
+ )
+ : undefined;
+
+ const whitelistCondition =
+ options.whitelist && options.whitelist.length > 0
+ ? inArray(users.id, options.whitelist)
+ : undefined;
+
+ // User memory defaults to enabled=true when user settings are missing.
+ const memoryEnabledCondition = sql`COALESCE((${userSettings.memory} ->> 'enabled')::boolean, true) = true`;
+ // Eligible users must have at least one topic with at least one user message.
+ const hasChattedTopicCondition = sql`
+ EXISTS (
+ SELECT 1
+ FROM ${topics}
+ INNER JOIN ${messages}
+ ON ${messages.topicId} = ${topics.id}
+ AND ${messages.userId} = ${users.id}
+ AND ${messages.role} = 'user'
+ WHERE ${topics.userId} = ${users.id}
+ )
+ `;
+
+ const query = db
+ .select({
+ createdAt: users.createdAt,
+ id: users.id,
+ })
+ .from(users)
+ .leftJoin(userSettings, eq(users.id, userSettings.id))
+ .where(
+ and(cursorCondition, whitelistCondition, memoryEnabledCondition, hasChattedTopicCondition),
+ )
+ .orderBy(asc(users.createdAt), asc(users.id));
+
+ return options.limit !== undefined ? query.limit(options.limit) : query;
+ };
+
/**
* Get user info for AI generation (name and language preference)
*/
diff --git a/src/app/(backend)/api/workflows/memory-user-memory/call-cron-hourly-analysis/route.ts b/src/app/(backend)/api/workflows/memory-user-memory/call-cron-hourly-analysis/route.ts
new file mode 100644
index 00000000000..1bf2fac5f7a
--- /dev/null
+++ b/src/app/(backend)/api/workflows/memory-user-memory/call-cron-hourly-analysis/route.ts
@@ -0,0 +1,117 @@
+import { MemorySourceType } from '@lobechat/types';
+import { Client } from '@upstash/qstash';
+import { serve } from '@upstash/workflow/nextjs';
+import { chunk } from 'es-toolkit/compat';
+
+import { appEnv } from '@/envs/app';
+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';
+import {
+ buildWorkflowPayloadInput,
+ MemoryExtractionExecutor,
+ type MemoryExtractionHourlyWorkflowPayload,
+ MemoryExtractionWorkflowService,
+ normalizeMemoryExtractionPayload,
+} from '@/server/services/memory/userMemory/extract';
+
+const USER_PAGE_SIZE = 200;
+const USER_BATCH_SIZE = 20;
+
+const { webhook, upstashWorkflowExtraHeaders } = parseMemoryExtractionConfig();
+
+const resolveBaseUrl = () => webhook.baseUrl || appEnv.INTERNAL_APP_URL || appEnv.APP_URL;
+
+export const { POST } = serve<MemoryExtractionHourlyWorkflowPayload>(
+ async (context) => {
+ const { cursor, dryRun } = context.requestPayload || {};
+
+ const baseUrl = resolveBaseUrl();
+ if (!baseUrl) {
+ throw new Error('Missing baseUrl for hourly memory extraction workflow');
+ }
+
+ const parsedCursor = cursor
+ ? { createdAt: new Date(cursor.createdAt), id: cursor.id }
+ : undefined;
+ if (parsedCursor && Number.isNaN(parsedCursor.createdAt.getTime())) {
+ throw new Error('Invalid cursor date for hourly memory extraction workflow');
+ }
+
+ 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 userIds = userBatch.ids;
+ if (userIds.length === 0) {
+ return { message: 'No eligible users for hourly memory extraction.', processedUsers: 0 };
+ }
+
+ const nextCursor = userBatch.cursor
+ ? {
+ createdAt: userBatch.cursor.createdAt.toISOString(),
+ id: userBatch.cursor.id,
+ }
+ : undefined;
+
+ 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}`, () =>
+ MemoryExtractionWorkflowService.triggerProcessUsers(
+ buildWorkflowPayloadInput(
+ normalizeMemoryExtractionPayload({
+ baseUrl,
+ mode: 'workflow',
+ sources: [MemorySourceType.ChatTopic],
+ userIds: batchUserIds,
+ }),
+ ),
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ ),
+ ),
+ ),
+ );
+ }
+
+ if (nextCursor) {
+ await context.run('memory:user-memory:hourly:schedule-next-page', () =>
+ MemoryExtractionWorkflowService.triggerHourly(
+ {
+ baseUrl,
+ cursor: nextCursor,
+ dryRun,
+ },
+ { extraHeaders: upstashWorkflowExtraHeaders },
+ ),
+ );
+ }
+
+ return {
+ dryRun: !!dryRun,
+ hasNextPage: !!nextCursor,
+ processedUsers: userIds.length,
+ scheduledBatches: dryRun ? 0 : chunk(userIds, USER_BATCH_SIZE).length,
+ };
+ },
+ {
+ flowControl: {
+ key: 'memory-user-memory.call-cron-hourly-analysis',
+ parallelism: 1,
+ ratePerSecond: 1,
+ },
+ // NOTICE(@nekomeowww): Here as scenarios like Vercel Deployment Protection,
+ // intermediate context.run(...) won't offer customizable headers like context.trigger(...) / client.trigger(...)
+ // for passing additional headers, we have to provide a custom QStash client with the required headers here.
+ //
+ // Refer to the doc for more details:
+ // https://upstash.com/docs/workflow/troubleshooting/vercel#step-2-pass-header-when-triggering
+ qstashClient: new Client({
+ headers: {
+ ...upstashWorkflowExtraHeaders,
+ },
+ token: process.env.QSTASH_TOKEN!,
+ }),
+ },
+);
diff --git a/src/server/services/memory/userMemory/extract.ts b/src/server/services/memory/userMemory/extract.ts
index 80144fd4d53..ff0dabc05c2 100644
--- a/src/server/services/memory/userMemory/extract.ts
+++ b/src/server/services/memory/userMemory/extract.ts
@@ -106,6 +106,12 @@ export interface TopicWorkflowCursor extends MemoryExtractionWorkflowCursor {
userId: string;
}
+export interface MemoryExtractionHourlyWorkflowPayload {
+ baseUrl?: string;
+ cursor?: MemoryExtractionWorkflowCursor;
+ dryRun?: boolean;
+}
+
export interface MemoryExtractionNormalizedPayload {
asyncTaskId?: string;
baseUrl: string;
@@ -1651,6 +1657,35 @@ export class MemoryExtractionExecutor {
};
}
+ async getUsersForHourlyExtraction(
+ limit: number,
+ cursor?: ListUsersForMemoryExtractorCursor,
+ ): Promise<UserPaginationResult> {
+ const db = await this.db;
+
+ const rows = await UserModel.listUsersForHourlyMemoryExtractor(db, {
+ cursor,
+ limit,
+ whitelist: this.privateConfig.whitelistUsers,
+ });
+ if (!rows?.length) {
+ return { ids: [] };
+ }
+
+ const last = rows.at(-1);
+ const nextCursor = last
+ ? {
+ createdAt: last.createdAt,
+ id: last.id,
+ }
+ : undefined;
+
+ return {
+ cursor: nextCursor,
+ ids: rows.map((row) => row.id),
+ };
+ }
+
async filterTopicIdsForUser(userId: string, topicIds: string[]) {
if (!topicIds.length) return [];
@@ -2170,6 +2205,7 @@ export class MemoryExtractionExecutor {
}
const WORKFLOW_PATHS = {
+ hourly: '/api/workflows/memory-user-memory/call-cron-hourly-analysis',
personaUpdate: '/api/workflows/memory-user-memory/pipelines/persona/update-writing',
topicBatch: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-topics',
userTopics: '/api/workflows/memory-user-memory/pipelines/chat-topic/process-user-topics',
@@ -2218,6 +2254,18 @@ export class MemoryExtractionWorkflowService {
return this.getClient().trigger({ body: payload, headers: options?.extraHeaders, url });
}
+ static triggerHourly(
+ payload: MemoryExtractionHourlyWorkflowPayload,
+ options?: { extraHeaders?: Record<string, string> },
+ ) {
+ if (!payload.baseUrl) {
+ throw new Error('Missing baseUrl for workflow trigger');
+ }
+
+ const url = getWorkflowUrl(WORKFLOW_PATHS.hourly, payload.baseUrl);
+ return this.getClient().trigger({ body: payload, headers: options?.extraHeaders, url });
+ }
+
static triggerProcessUserTopics(
payload: UserTopicWorkflowPayload,
options?: { extraHeaders?: Record<string, string> },