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): stop the nightly self-review cron from hanging into a silent 524 (#18494)

Arvin Xu6635b3ecc665
diff --git a/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts b/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts
index a55c162aec3..8522570f448 100644
--- a/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts
+++ b/apps/server/src/router-hono/workflows/agent-signal/handlers/__tests__/scheduleNightlyReview.test.ts
@@ -4,12 +4,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { scheduleNightlyReview } from '../scheduleNightlyReview';
const mocks = vi.hoisted(() => ({
- triggerPaginateUsers: vi.fn(),
+ publishPaginateUsersEntry: vi.fn(),
}));
vi.mock('@/server/workflows/agentSignal/nightlyReview', () => ({
AgentSignalNightlyReviewWorkflow: {
- triggerPaginateUsers: mocks.triggerPaginateUsers,
+ publishPaginateUsersEntry: mocks.publishPaginateUsersEntry,
},
}));
@@ -26,7 +26,7 @@ describe('scheduleNightlyReview', () => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-05-03T18:30:00.000Z'));
- mocks.triggerPaginateUsers.mockResolvedValue({ workflowRunId: 'nightly-page-1' });
+ mocks.publishPaginateUsersEntry.mockResolvedValue({ messageId: 'nightly-message-1' });
});
afterEach(() => {
@@ -46,9 +46,9 @@ describe('scheduleNightlyReview', () => {
await expect(response.json()).resolves.toEqual({
scheduled: true,
success: true,
- workflowRunId: 'nightly-page-1',
+ messageId: 'nightly-message-1',
});
- expect(mocks.triggerPaginateUsers).toHaveBeenCalledWith({
+ expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledWith({
cursor: undefined,
pageSize: 50,
requestedAt: '2026-05-03T18:30:00.000Z',
@@ -77,9 +77,9 @@ describe('scheduleNightlyReview', () => {
await expect(response.json()).resolves.toEqual({
scheduled: true,
success: true,
- workflowRunId: 'nightly-page-1',
+ messageId: 'nightly-message-1',
});
- expect(mocks.triggerPaginateUsers).toHaveBeenCalledWith({
+ expect(mocks.publishPaginateUsersEntry).toHaveBeenCalledWith({
cursor: { createdAt: '2026-05-04T00:00:00.000Z', id: 'user-1' },
pageSize: 100,
requestedAt: '2026-05-03T18:30:00.000Z',
@@ -87,4 +87,26 @@ describe('scheduleNightlyReview', () => {
whitelist: ['user-1'],
});
});
+
+ it('reports a failed publish as 500 so the error reaches the DLQ', async () => {
+ /**
+ * Regression: the publish used to stall until Cloudflare returned 524 with an empty body, so
+ * every failed tick landed in the DLQ carrying no diagnosis at all.
+ *
+ * @example
+ * expect(response.status).toBe(500);
+ */
+ mocks.publishPaginateUsersEntry.mockRejectedValue(
+ new Error('nightly review cron publish timed out after 10000ms'),
+ );
+
+ const response = await createApp().request('/cron-hourly-nightly-self-review', {
+ method: 'POST',
+ });
+
+ expect(response.status).toBe(500);
+ await expect(response.json()).resolves.toEqual({
+ error: 'nightly review cron publish timed out after 10000ms',
+ });
+ });
});
diff --git a/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts b/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts
index 91537a7c65d..b1981e84211 100644
--- a/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts
+++ b/apps/server/src/router-hono/workflows/agent-signal/handlers/scheduleNightlyReview.ts
@@ -127,16 +127,20 @@ export async function scheduleNightlyReview(c: Context) {
: {}),
});
- const result = await AgentSignalNightlyReviewWorkflow.triggerPaginateUsers(options);
+ const startedAt = Date.now();
+ const result = await AgentSignalNightlyReviewWorkflow.publishPaginateUsersEntry(options);
span.setAttributes({
+ 'agent.signal.cron.publish_duration_ms': Date.now() - startedAt,
'agent.signal.cron.success': true,
- 'agent.signal.cron.workflow_run_id': result.workflowRunId,
+ 'agent.signal.cron.message_id': result.messageId,
});
span.setStatus({ code: SpanStatusCode.OK });
- return c.json({ scheduled: true, success: true, workflowRunId: result.workflowRunId }, 202);
+ return c.json({ messageId: result.messageId, scheduled: true, success: true }, 202);
} catch (error) {
+ // This log is the only trace a failed tick leaves behind: a stalled publish used to be
+ // killed by Cloudflare at 100s, which produced a 524 with no body and nothing on the server.
console.error('[agent-signal/cron-hourly-nightly-self-review] Error:', error);
span.setAttribute('agent.signal.cron.success', false);
span.setStatus({
diff --git a/apps/server/src/workflows/agentSignal/__tests__/nightlyReview.test.ts b/apps/server/src/workflows/agentSignal/__tests__/nightlyReview.test.ts
index 7306d135caa..2a886f0baa2 100644
--- a/apps/server/src/workflows/agentSignal/__tests__/nightlyReview.test.ts
+++ b/apps/server/src/workflows/agentSignal/__tests__/nightlyReview.test.ts
@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({
injectActiveTraceHeaders: vi.fn((headers: Headers) => {
headers.set('traceparent', '00-trace-parent');
}),
+ publishJSON: vi.fn(),
trigger: vi.fn(),
}));
@@ -22,6 +23,9 @@ vi.mock('@/libs/observability/traceparent', () => ({
}));
vi.mock('@/libs/qstash', () => ({
+ qstashClient: {
+ publishJSON: mocks.publishJSON,
+ },
workflowClient: {
trigger: mocks.trigger,
},
@@ -30,6 +34,96 @@ vi.mock('@/libs/qstash', () => ({
beforeEach(() => {
vi.clearAllMocks();
mocks.trigger.mockResolvedValue({ workflowRunId: 'workflow-1' });
+ mocks.publishJSON.mockResolvedValue({ messageId: 'message-1' });
+});
+
+describe('AgentSignalNightlyReviewWorkflow cron entry', () => {
+ const payload = {
+ pageSize: 50,
+ requestedAt: '2026-05-03T18:30:00.000Z',
+ targetLimit: 20,
+ };
+
+ it('publishes the cron entry through the qstash client', async () => {
+ /**
+ * @example
+ * expect(publishJSON).toHaveBeenCalledWith(expect.objectContaining({ flowControl }));
+ */
+ await expect(
+ AgentSignalNightlyReviewWorkflow.publishPaginateUsersEntry(payload),
+ ).resolves.toEqual({ messageId: 'message-1' });
+
+ expect(mocks.publishJSON).toHaveBeenCalledWith({
+ body: payload,
+ flowControl: {
+ key: 'agent-signal.nightly-review.paginate-users',
+ parallelism: 1,
+ },
+ headers: { traceparent: '00-trace-parent' },
+ url: 'https://internal.example.com/api/workflows/agent-signal/paginate-nightly-review-users',
+ });
+ });
+
+ it('fails fast instead of hanging when the outbound publish stalls', async () => {
+ /**
+ * Regression: a stalled publish used to keep the handler open until Cloudflare returned 524,
+ * which left no error anywhere and silently killed nightly review for months.
+ *
+ * @example
+ * await expect(publishPaginateUsersEntry(payload)).rejects.toThrow('timed out');
+ */
+ vi.useFakeTimers();
+ mocks.publishJSON.mockReturnValue(new Promise(() => {}));
+
+ try {
+ const assertion = expect(
+ AgentSignalNightlyReviewWorkflow.publishPaginateUsersEntry(payload),
+ ).rejects.toThrow('nightly review cron publish timed out after 10000ms');
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ await assertion;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps a late failure on the abandoned publish from going unhandled', async () => {
+ /**
+ * `Promise.race` cannot cancel the publish, so the orphan needs its own rejection handler.
+ *
+ * @example
+ * expect(unhandled).not.toHaveBeenCalled();
+ */
+ vi.useFakeTimers();
+
+ let rejectPublish: ((error: Error) => void) | undefined;
+ mocks.publishJSON.mockReturnValue(
+ new Promise((_, reject) => {
+ rejectPublish = reject;
+ }),
+ );
+
+ const unhandled = vi.fn();
+ process.on('unhandledRejection', unhandled);
+
+ try {
+ const assertion = expect(
+ AgentSignalNightlyReviewWorkflow.publishPaginateUsersEntry(payload),
+ ).rejects.toThrow('timed out');
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ await assertion;
+
+ rejectPublish?.(new Error('late qstash failure'));
+ await vi.advanceTimersByTimeAsync(0);
+ await Promise.resolve();
+
+ expect(unhandled).not.toHaveBeenCalled();
+ } finally {
+ process.off('unhandledRejection', unhandled);
+ vi.useRealTimers();
+ }
+ });
});
describe('AgentSignalNightlyReviewWorkflow', () => {
diff --git a/apps/server/src/workflows/agentSignal/nightlyReview.ts b/apps/server/src/workflows/agentSignal/nightlyReview.ts
index 628f99247c9..20b4488ca72 100644
--- a/apps/server/src/workflows/agentSignal/nightlyReview.ts
+++ b/apps/server/src/workflows/agentSignal/nightlyReview.ts
@@ -3,10 +3,21 @@ import debug from 'debug';
import { appEnv } from '@/envs/app';
import { injectActiveTraceHeaders } from '@/libs/observability/traceparent';
-import { workflowClient } from '@/libs/qstash';
+import { qstashClient, workflowClient } from '@/libs/qstash';
const log = debug('lobe-server:workflows:agent-signal:nightly-review');
+/**
+ * Hard ceiling for every outbound publish in the nightly review chain.
+ *
+ * The QStash SDK retries five times with `exp(n) * 50ms` backoff and the underlying `fetch` has
+ * no timeout of its own, so a stalled outbound connection keeps the cron handler open until
+ * Cloudflare cuts the origin off at 100s β€” which surfaces as a 524 with an empty body and no
+ * server-side log at all. Failing fast here turns that silent black hole into a 500 whose error
+ * message reaches the QStash DLQ.
+ */
+export const NIGHTLY_REVIEW_PUBLISH_TIMEOUT_MS = 10_000;
+
const WORKFLOW_PATHS = {
executeUser: '/api/workflows/agent-signal/execute-nightly-review-user',
paginateUsers: '/api/workflows/agent-signal/paginate-nightly-review-users',
@@ -105,6 +116,34 @@ const getTriggerHeaders = (): Record<string, string> => {
return Object.fromEntries(headers.entries());
};
+/**
+ * Races an outbound publish against {@link NIGHTLY_REVIEW_PUBLISH_TIMEOUT_MS}.
+ *
+ * The abandoned publish keeps running β€” `Promise.race` cannot cancel it β€” so it gets its own
+ * no-op rejection handler: without one, a late failure on the orphaned promise surfaces as an
+ * unhandled rejection and can take the worker down.
+ */
+const withPublishTimeout = async <T>(publish: Promise<T>, label: string): Promise<T> => {
+ publish.catch(() => undefined);
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ try {
+ return await Promise.race([
+ publish,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () =>
+ reject(new Error(`${label} timed out after ${NIGHTLY_REVIEW_PUBLISH_TIMEOUT_MS}ms`)),
+ NIGHTLY_REVIEW_PUBLISH_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
/**
* Triggers the cursor-pagination and single-user layers of nightly review scheduling.
*
@@ -128,6 +167,34 @@ const getTriggerHeaders = (): Record<string, string> => {
* -> executeNightlyReviewUser
*/
export class AgentSignalNightlyReviewWorkflow {
+ /**
+ * Starts the pagination tree from the hourly cron entry.
+ *
+ * Publishes through `@upstash/qstash` rather than the workflow client's `trigger()`: `serve()`
+ * treats a plain POST as a first invocation, and this is the publish path the task crons have
+ * been running in production without ever landing in the DLQ. The timeout keeps the cron
+ * handler inside Cloudflare's 100s origin budget no matter how the outbound call behaves.
+ */
+ static publishPaginateUsersEntry(payload: PaginateNightlyReviewUsersPayload) {
+ log('Publishing nightly review cron entry payload=%O', {
+ pageSize: payload.pageSize,
+ whitelist: payload.whitelist?.length ?? 0,
+ });
+
+ return withPublishTimeout(
+ qstashClient.publishJSON({
+ body: payload,
+ flowControl: {
+ key: NIGHTLY_REVIEW_PAGINATE_FLOW_CONTROL_KEY,
+ parallelism: 1,
+ } satisfies FlowControl,
+ headers: getTriggerHeaders(),
+ url: getWorkflowUrl(WORKFLOW_PATHS.paginateUsers),
+ }),
+ 'nightly review cron publish',
+ );
+ }
+
/** Triggers one database page or one bounded fan-out chunk. */
static triggerPaginateUsers(payload: PaginateNightlyReviewUsersPayload) {
log('Triggering nightly review user pagination payload=%O', {
@@ -136,29 +203,35 @@ export class AgentSignalNightlyReviewWorkflow {
users: payload.users?.length ?? 0,
});
- return workflowClient.trigger({
- body: payload,
- flowControl: {
- key: NIGHTLY_REVIEW_PAGINATE_FLOW_CONTROL_KEY,
- parallelism: 1,
- } satisfies FlowControl,
- headers: getTriggerHeaders(),
- url: getWorkflowUrl(WORKFLOW_PATHS.paginateUsers),
- });
+ return withPublishTimeout(
+ workflowClient.trigger({
+ body: payload,
+ flowControl: {
+ key: NIGHTLY_REVIEW_PAGINATE_FLOW_CONTROL_KEY,
+ parallelism: 1,
+ } satisfies FlowControl,
+ headers: getTriggerHeaders(),
+ url: getWorkflowUrl(WORKFLOW_PATHS.paginateUsers),
+ }),
+ 'nightly review pagination trigger',
+ );
}
/** Triggers one workflow that processes exactly one user. */
static triggerExecuteUser(payload: ExecuteNightlyReviewUserPayload) {
log('Triggering nightly review execution userId=%s', payload.user.id);
- return workflowClient.trigger({
- body: payload,
- flowControl: {
- key: NIGHTLY_REVIEW_EXECUTE_FLOW_CONTROL_KEY,
- parallelism: 5,
- } satisfies FlowControl,
- headers: getTriggerHeaders(),
- url: getWorkflowUrl(WORKFLOW_PATHS.executeUser),
- });
+ return withPublishTimeout(
+ workflowClient.trigger({
+ body: payload,
+ flowControl: {
+ key: NIGHTLY_REVIEW_EXECUTE_FLOW_CONTROL_KEY,
+ parallelism: 5,
+ } satisfies FlowControl,
+ headers: getTriggerHeaders(),
+ url: getWorkflowUrl(WORKFLOW_PATHS.executeUser),
+ }),
+ 'nightly review execution trigger',
+ );
}
}