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(agent-signal): narrow the nightly review candidate scan (#18547)

Arvin Xu6b177535da30
diff --git a/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts b/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts
index 972d2363688..bc9416916c0 100644
--- a/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts
+++ b/apps/server/src/router-hono/workflows/agent-signal/workflows/nightlyReview.ts
@@ -126,6 +126,7 @@ export const paginateNightlyReviewUsers = async (
return service.listEligibleUsersPage({
cursor,
limit: pageSize,
+ requestedAt: parseWorkflowDate(payload.requestedAt, 'Invalid nightly review requestedAt'),
whitelist: payload.whitelist,
});
},
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts
index d8cd7db51c1..4a5d855d546 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/schedule.test.ts
@@ -205,6 +205,48 @@ describe('nightlyReviewScheduleService', () => {
expect(deps.listActiveAgentTargets).not.toHaveBeenCalled();
expect(deps.enqueueSource).not.toHaveBeenCalled();
});
+
+ /**
+ * ROOT CAUSE:
+ *
+ * The candidate scan had no predicate, so every cron fire walked all 321k users to reach
+ * the handful actually inside their 02:00-04:00 window β€” ~18h of flow-controlled work per
+ * hourly fire, which drifted every user's review later each day. The local window itself
+ * stays here rather than in SQL; only the activity floor is pushed down.
+ *
+ * @example
+ * expect(deps.listEligibleUsers).toHaveBeenCalledWith(
+ * expect.objectContaining({ activeSince: new Date('2026-05-02T12:05:00.000Z') }),
+ * );
+ */
+ it('narrows the candidate scan to recently active users', async () => {
+ const deps = createDeps();
+ deps.listEligibleUsers.mockResolvedValue([]);
+ const service = createSelfReviewScheduleService(deps);
+ const requestedAt = new Date('2026-05-03T18:05:00.000Z');
+
+ await service.listEligibleUsersPage({ limit: 50, requestedAt });
+
+ expect(deps.listEligibleUsers).toHaveBeenCalledWith({
+ activeSince: new Date('2026-05-02T12:05:00.000Z'),
+ limit: 50,
+ requestedAt,
+ });
+ });
+
+ /**
+ * @example
+ * expect(deps.listEligibleUsers).toHaveBeenCalledWith({ limit: 50 });
+ */
+ it('leaves the scan unnarrowed when no schedule instant is supplied', async () => {
+ const deps = createDeps();
+ deps.listEligibleUsers.mockResolvedValue([]);
+ const service = createSelfReviewScheduleService(deps);
+
+ await service.listEligibleUsersPage({ limit: 50 });
+
+ expect(deps.listEligibleUsers).toHaveBeenCalledWith({ limit: 50 });
+ });
});
describe('buildNightlyReviewSourceId', () => {
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts
index d79c610ecf9..4f24253a84c 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/schedule.ts
@@ -19,6 +19,17 @@ const FALLBACK_TIMEZONE = 'UTC';
const NIGHT_WINDOW_START_HOUR = 2;
const NIGHT_WINDOW_END_HOUR_EXCLUSIVE = 4;
+/**
+ * How far back the candidate scan looks for user activity.
+ *
+ * A user is dispatched only if their local previous day had activity, and that day can start
+ * at most `NIGHT_WINDOW_END_HOUR_EXCLUSIVE + 24` hours before the cron instant. Rounding up
+ * keeps the floor a strict superset of every per-user window regardless of timezone.
+ */
+const ACTIVITY_LOOKBACK_HOURS = 30;
+
+const HOUR_IN_MS = 60 * 60 * 1000;
+
/** Active agent target returned by the nightly review scheduler data boundary. */
export interface NightlyReviewAgentTarget {
/** Agent id that should receive one nightly review source event. */
@@ -45,6 +56,8 @@ export interface NightlyReviewScheduleCursor {
/** Options for listing users during one nightly review dispatch pass. */
export interface ListNightlyReviewEligibleUsersInput {
+ /** Activity floor below which a user cannot have anything to review. */
+ activeSince?: Date;
/** Cursor returned by the previous scheduler page. */
cursor?: NightlyReviewScheduleCursor;
/** Maximum eligible users to return. */
@@ -89,6 +102,8 @@ export interface NightlyReviewScheduleAdapters {
export interface ListNightlyReviewEligibleUsersPageOptions extends ListNightlyReviewEligibleUsersInput {
/** Maximum eligible users returned by this page. */
limit: number;
+ /** UTC instant shared by the whole pagination tree, used to narrow the candidate scan. */
+ requestedAt?: Date;
}
/** One cursor-paginated page of nightly review user candidates. */
@@ -147,6 +162,8 @@ export interface NightlyReviewScheduleService {
* Expects:
* - `limit` is a positive, externally bounded page size
* - The adapter sorts users by `createdAt, id`
+ * - `requestedAt` narrows the scan to users with recent activity;
+ * {@link dispatchNightlyReviewForUser} remains the only authority on the local window
*
* Returns:
* - The current users and a next cursor only when the page is full
@@ -299,7 +316,18 @@ export const createSelfReviewScheduleService = (
},
async (span) => {
try {
- const users = await adapters.listEligibleUsers(options);
+ const users = await adapters.listEligibleUsers({
+ ...options,
+ // Without `requestedAt` the caller is a test or a legacy path; fall back to the
+ // unnarrowed scan rather than inventing a floor from wall-clock time.
+ ...(options.requestedAt
+ ? {
+ activeSince: new Date(
+ options.requestedAt.getTime() - ACTIVITY_LOOKBACK_HOURS * HOUR_IN_MS,
+ ),
+ }
+ : {}),
+ });
const lastUser = users.at(-1);
const nextCursor =
users.length === options.limit && lastUser
@@ -361,6 +389,12 @@ export const createServerNightlyReviewScheduleService = (
windowEnd,
windowStart,
}),
- listEligibleUsers: (input) => model.listEligibleUsers(input),
+ listEligibleUsers: (input) =>
+ model.listEligibleUsers({
+ activeSince: input?.activeSince,
+ cursor: input?.cursor,
+ limit: input?.limit,
+ whitelist: input?.whitelist,
+ }),
});
};
diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts
index 2217abf78c4..7e157d42e40 100644
--- a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts
+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts
@@ -4,7 +4,15 @@ import { sql } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import { agents, messagePlugins, messages, topics, users, userSettings } from '../../../schemas';
+import {
+ agents,
+ messagePlugins,
+ messages,
+ topics,
+ users,
+ userSettings,
+ workspaces,
+} from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { AgentSignalNightlyReviewModel } from '../nightlyReview';
@@ -125,6 +133,150 @@ describe('AgentSignalNightlyReviewModel', () => {
});
});
+ describe('listEligibleUsers narrowing', () => {
+ /**
+ * ROOT CAUSE:
+ *
+ * `listEligibleUsers` had no predicate at all, so the hourly cron fanned one workflow run
+ * out per row of a 321k-row `users` table to reach the handful of users whose local clock
+ * was actually inside the 02:00-04:00 review window. At a 5/s flow-control ceiling one pass
+ * needed ~18h while the cron fired every hour, so the backlog β€” and every user's effective
+ * review time β€” drifted later every day.
+ *
+ * The activity floor is a strict superset of every per-user review window, so narrowing on
+ * it can only skip a dispatch the local-window check would have skipped anyway. The window
+ * itself stays in the service layer, which resolves timezones through `Intl`; pushing it
+ * into SQL would make the scan depend on the database's tzdata build agreeing with `Intl`,
+ * and it buys little at the busiest hour anyway.
+ */
+ const seedActivity = async () => {
+ await serverDB.insert(users).values([
+ { createdAt: new Date('2026-05-01T00:00:00.000Z'), id: enabledUserId },
+ { createdAt: new Date('2026-05-02T00:00:00.000Z'), id: otherUserId },
+ ]);
+ await serverDB.insert(userSettings).values([
+ { general: { timezone: 'Asia/Shanghai' }, id: enabledUserId },
+ { general: { timezone: 'America/New_York' }, id: otherUserId },
+ ]);
+ await serverDB.insert(agents).values([
+ { id: 'nightly-active-agent', slug: INBOX_SESSION_ID, userId: enabledUserId },
+ { id: 'nightly-stale-agent', slug: INBOX_SESSION_ID, userId: otherUserId },
+ ]);
+ await serverDB.insert(topics).values([
+ { agentId: 'nightly-active-agent', id: 'nightly-active-topic', userId: enabledUserId },
+ { agentId: 'nightly-stale-agent', id: 'nightly-stale-topic', userId: otherUserId },
+ ]);
+ await serverDB.insert(messages).values([
+ {
+ agentId: 'nightly-active-agent',
+ createdAt: new Date('2026-05-03T09:00:00.000Z'),
+ id: 'nightly-active-message',
+ role: 'user',
+ topicId: 'nightly-active-topic',
+ userId: enabledUserId,
+ },
+ {
+ agentId: 'nightly-stale-agent',
+ createdAt: new Date('2026-04-01T09:00:00.000Z'),
+ id: 'nightly-stale-message',
+ role: 'user',
+ topicId: 'nightly-stale-topic',
+ userId: otherUserId,
+ },
+ ]);
+ };
+
+ /**
+ * @example
+ * expect(result.map((item) => item.id)).toEqual([enabledUserId]);
+ */
+ it('drops users with no message activity since the floor', async () => {
+ await seedActivity();
+ const model = new AgentSignalNightlyReviewModel(serverDB);
+
+ const result = await model.listEligibleUsers({
+ activeSince: new Date('2026-05-02T12:05:00.000Z'),
+ });
+
+ expect(result).toEqual([
+ {
+ createdAt: new Date('2026-05-01T00:00:00.000Z'),
+ id: enabledUserId,
+ timezone: 'Asia/Shanghai',
+ },
+ ]);
+ });
+
+ /**
+ * Workspace messages belong to a different review surface, so they must not keep a user in
+ * the personal nightly scan.
+ *
+ * @example
+ * expect(result).toEqual([]);
+ */
+ it('ignores workspace activity when deciding who is a candidate', async () => {
+ await serverDB.insert(users).values({
+ createdAt: new Date('2026-05-01T00:00:00.000Z'),
+ id: enabledUserId,
+ });
+ const [workspace] = await serverDB
+ .insert(workspaces)
+ .values({
+ name: 'nightly-review-workspace',
+ primaryOwnerId: enabledUserId,
+ slug: 'nightly-review-workspace',
+ })
+ .returning();
+ await serverDB.insert(agents).values({
+ id: 'nightly-workspace-agent',
+ slug: INBOX_SESSION_ID,
+ userId: enabledUserId,
+ workspaceId: workspace!.id,
+ });
+ await serverDB.insert(topics).values({
+ agentId: 'nightly-workspace-agent',
+ id: 'nightly-workspace-topic',
+ userId: enabledUserId,
+ workspaceId: workspace!.id,
+ });
+ await serverDB.insert(messages).values({
+ agentId: 'nightly-workspace-agent',
+ createdAt: new Date('2026-05-03T09:00:00.000Z'),
+ id: 'nightly-workspace-message',
+ role: 'user',
+ topicId: 'nightly-workspace-topic',
+ userId: enabledUserId,
+ workspaceId: workspace!.id,
+ });
+ const model = new AgentSignalNightlyReviewModel(serverDB);
+
+ const result = await model.listEligibleUsers({
+ activeSince: new Date('2026-05-02T12:05:00.000Z'),
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ /**
+ * A whitelist is an explicit target list for backfills; narrowing it would drop the very
+ * rows the caller named.
+ *
+ * @example
+ * expect(result.map((item) => item.id)).toEqual([otherUserId]);
+ */
+ it('ignores activity narrowing for whitelist runs', async () => {
+ await seedActivity();
+ const model = new AgentSignalNightlyReviewModel(serverDB);
+
+ const result = await model.listEligibleUsers({
+ activeSince: new Date('2026-05-02T12:05:00.000Z'),
+ whitelist: [otherUserId],
+ });
+
+ expect(result.map((item) => item.id)).toEqual([otherUserId]);
+ });
+ });
+
describe('listActiveAgentTargets', () => {
const chatConfigForSelfIteration = (enabled?: boolean) =>
enabled === undefined ? {} : { selfIteration: { enabled } };
diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.ts
index dd7633d495a..7f431aac78e 100644
--- a/packages/database/src/models/agentSignal/nightlyReview.ts
+++ b/packages/database/src/models/agentSignal/nightlyReview.ts
@@ -43,6 +43,15 @@ export interface ListAgentSignalNightlyReviewUsersCursor {
/** Options for listing users eligible for AgentSignal nightly review scheduling. */
export interface ListAgentSignalNightlyReviewUsersOptions {
+ /**
+ * Coarse activity floor. Only users with at least one non-workspace message at or after
+ * this instant are candidates.
+ *
+ * This is deliberately a superset of every per-user review window: the precise window is
+ * still applied by {@link AgentSignalNightlyReviewModel.listActiveAgentTargets}, so a
+ * generous floor here can only cost a skipped dispatch, never a missed review.
+ */
+ activeSince?: Date;
/** Cursor returned by the previous page. */
cursor?: ListAgentSignalNightlyReviewUsersCursor;
/** Maximum users to return. */
@@ -124,6 +133,8 @@ export class AgentSignalNightlyReviewModel {
* Expects:
* - Global feature gates are checked by the service layer
* - Missing user timezone falls back to UTC
+ * - `activeSince` is supplied by the scheduler; it is a superset of the per-user review
+ * window re-applied downstream, and it is skipped for whitelist runs
*
* Returns:
* - Users sorted by `createdAt, id` for deterministic pagination
@@ -145,13 +156,36 @@ export class AgentSignalNightlyReviewModel {
? inArray(users.id, options.whitelist)
: undefined;
- const query = this.db
+ // A whitelist is an explicit, already-bounded target list for backfills and manual runs;
+ // narrowing it further would silently drop the very rows the caller asked for.
+ const narrow = !whitelistCondition;
+
+ // Driving the activity filter from a `created_at` range keeps this on
+ // `messages_created_at_idx`; a per-user `EXISTS` would fall back to `messages_user_id_idx`
+ // and re-scan a heavy user's entire history on every page.
+ const activeUsers =
+ narrow && options.activeSince
+ ? this.db
+ .selectDistinct({ userId: messages.userId })
+ .from(messages)
+ .where(and(gte(messages.createdAt, options.activeSince), isNull(messages.workspaceId)))
+ .as('nightly_review_active_users')
+ : undefined;
+
+ let query = this.db
.select({
createdAt: users.createdAt,
id: users.id,
timezone: sql<string>`COALESCE(${userSettings.general}->>'timezone', 'UTC')`,
})
.from(users)
+ .$dynamic();
+
+ if (activeUsers) {
+ query = query.innerJoin(activeUsers, eq(activeUsers.userId, users.id));
+ }
+
+ query = query
.leftJoin(userSettings, eq(users.id, userSettings.id))
.where(and(cursorCondition, whitelistCondition))
.orderBy(asc(users.createdAt), asc(users.id));