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): settle deferred step work between inline steps (#19541)

Arvin Xu1488baa3fba4
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
index 13509ecdf48..f2c84fc47d5 100644
--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
@@ -2,6 +2,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AiAgentService } from '@/server/services/aiAgent';
+import type * as ScheduleAfterResponseModule from '@/server/utils/scheduleAfterResponse';
+import { after } from '@/server/utils/scheduleAfterResponse';
import { runStep, runStepHealth } from '../runStep';
@@ -12,6 +14,20 @@ const mockExecuteStep = vi.fn();
const mockScheduleContinuation = vi.fn();
const mockReleaseOperationLock = vi.fn();
const mockGetServerDB = vi.hoisted(() => vi.fn());
+// Lets a test force the step-boundary flush to report a timeout; undefined
+// means use the real implementation.
+const flushOverride = vi.hoisted(() => ({ settled: undefined as boolean | undefined }));
+
+vi.mock('@/server/utils/scheduleAfterResponse', async (importOriginal) => {
+ const actual = await importOriginal<typeof ScheduleAfterResponseModule>();
+ return {
+ ...actual,
+ flushScheduledWork: (options?: { timeoutMs?: number }) =>
+ flushOverride.settled === undefined
+ ? actual.flushScheduledWork(options)
+ : Promise.resolve(flushOverride.settled),
+ };
+});
vi.mock('@/server/modules/AgentRuntime', () => ({
AgentRuntimeCoordinator: vi.fn().mockImplementation(function () {
@@ -671,6 +687,68 @@ describe('runStep inline step loop', () => {
expect(mockClearInlineResume).toHaveBeenCalledWith('op-1', 'op-1:owner');
});
+ it('hands the next step to the queue when deferred work does not settle in time', async () => {
+ // A timed-out flush may be a budget settlement that has not released its
+ // hold yet. Starting the next step anyway would reserve on top of it and
+ // bring back the false "over budget" rejection.
+ flushOverride.settled = false;
+ const pending = continuationFor(3);
+ mockExecuteStep.mockResolvedValueOnce({
+ continuation: pending,
+ nextStepScheduled: false,
+ state: { status: 'running', stepCount: 3 },
+ success: true,
+ });
+
+ try {
+ const { ctx, getCaptures } = buildContext({ body: validBody });
+ const res = await runStep(ctx);
+
+ expect(res.status).toBe(200);
+ expect(mockExecuteStep).toHaveBeenCalledTimes(1);
+ expect(mockScheduleContinuation).toHaveBeenCalledWith(pending);
+ expect(getCaptures()[0].body).toMatchObject({
+ inlinedSteps: 0,
+ nextStepIndex: 3,
+ nextStepScheduled: true,
+ });
+ expect(mockReleaseOperationLock).toHaveBeenCalledWith('op-1', 'op-1:owner');
+ } finally {
+ flushOverride.settled = undefined;
+ }
+ });
+
+ it('settles work a step deferred before the next inline step starts', async () => {
+ // Budget holds are released in work deferred with `after()`. If that work
+ // waited for the end of the invocation, every earlier step's hold would
+ // still be reserved when the next step reserves, and users with enough
+ // credit get rejected as over budget.
+ const events: string[] = [];
+ mockExecuteStep
+ .mockImplementationOnce(async () => {
+ after(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ events.push('step 2 settled');
+ });
+ events.push('step 2 done');
+ return {
+ continuation: continuationFor(3),
+ nextStepScheduled: false,
+ state: { status: 'running', stepCount: 3 },
+ success: true,
+ };
+ })
+ .mockImplementationOnce(async () => {
+ events.push('step 3 started');
+ return { nextStepScheduled: false, state: doneState, success: true };
+ });
+
+ const { ctx } = buildContext({ body: validBody });
+ await runStep(ctx);
+
+ expect(events).toEqual(['step 2 done', 'step 2 settled', 'step 3 started']);
+ });
+
it('ignores a parked envelope that is not ahead of the delivered step', async () => {
// After a deadline hand-off the queued message carries the same index the
// envelope named. That delivery is authoritative, payload and all.
diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.ts
index cf814206a8d..1221f3e72c9 100644
--- a/apps/server/src/router-hono/agent/handlers/runStep.ts
+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts
@@ -7,6 +7,10 @@ import { agentOperations } from '@/database/schemas/agentOperations';
import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
import type { AgentExecutionResult, AgentStepContinuation } from '@/server/services/agentRuntime';
import { AiAgentService } from '@/server/services/aiAgent';
+import {
+ flushScheduledWork,
+ runWithScheduledWorkScope,
+} from '@/server/utils/scheduleAfterResponse';
const log = debug('lobe-server:agent:run-step');
@@ -36,6 +40,17 @@ const log = debug('lobe-server:agent:run-step');
*/
const INLINE_STEP_START_DEADLINE_MS = Number(process.env.AGENT_INLINE_STEP_DEADLINE_MS ?? 450_000);
+/**
+ * Longest the loop waits at a step boundary for work the previous step
+ * deferred with `after()`.
+ *
+ * That work includes settling the step's budget hold, which has to finish
+ * before the next step reserves again. It normally takes well under a second.
+ * The cap only stops one stuck telemetry call from stalling the operation;
+ * anything still running keeps going.
+ */
+const STEP_BOUNDARY_FLUSH_TIMEOUT_MS = 10_000;
+
const toIsoString = (value: Date | string | null | undefined): null | string => {
if (!value) return null;
if (value instanceof Date) return value.toISOString();
@@ -178,7 +193,7 @@ export async function runStep(c: Context): Promise<Response> {
let pendingContinuation: AgentStepContinuation | undefined;
let currentStepIndex = stepIndex;
let inlinedSteps = 0;
- let result: AgentExecutionResult;
+ let result!: AgentExecutionResult;
// True once this invocation has an envelope to account for: either it
// resumed from one, or a step handed back a continuation (which parks one).
let touchedEnvelope = false;
@@ -220,99 +235,122 @@ export async function runStep(c: Context): Promise<Response> {
}
try {
- // The first iteration carries this delivery's one-shot payload (human
- // input, approvals, resume flags). Later iterations are plain steps, so
- // they must not replay any of it, and neither must a resumed run β€” it
- // stands in for a later iteration of a dead loop, not for the original
- // message.
- //
- // `externalRetryCount` is the exception, because it describes this
- // delivery rather than the step's payload. A parked approval whose Review
- // failed to persist is only replayed when the count is nonzero, so
- // dropping it here would leave that approval permanently unavailable.
- result = resumeFrom
- ? await aiAgentService.executeStep({
- context: resumeFrom.context,
- externalRetryCount,
- inlineContinuation: true,
- operationId,
- retainStepLock: true,
- stepIndex: resumeFrom.stepIndex,
- stepLockOwner,
- })
- : await aiAgentService.executeStep({
- approvedToolCall,
- asyncToolVerifyAttempt,
- context,
- externalRetryCount,
- finishAfterAsyncTool,
- groupMemberTimeout,
- humanInput,
+ // Work a step defers with `after()` (budget settlement, trace flushes,
+ // telemetry) normally waits for the HTTP response. One invocation now
+ // spans many steps, so every earlier step's budget hold would stay
+ // reserved until the loop ends and squeeze the next reservation. Scoping
+ // it to the loop starts that work immediately and lets each boundary wait
+ // for it, which is how it behaved when every step was its own request.
+ await runWithScheduledWorkScope(async () => {
+ // The first iteration carries this delivery's one-shot payload (human
+ // input, approvals, resume flags). Later iterations are plain steps, so
+ // they must not replay any of it, and neither must a resumed run β€” it
+ // stands in for a later iteration of a dead loop, not for the original
+ // message.
+ //
+ // `externalRetryCount` is the exception, because it describes this
+ // delivery rather than the step's payload. A parked approval whose Review
+ // failed to persist is only replayed when the count is nonzero, so
+ // dropping it here would leave that approval permanently unavailable.
+ result = resumeFrom
+ ? await aiAgentService.executeStep({
+ context: resumeFrom.context,
+ externalRetryCount,
+ inlineContinuation: true,
+ operationId,
+ retainStepLock: true,
+ stepIndex: resumeFrom.stepIndex,
+ stepLockOwner,
+ })
+ : await aiAgentService.executeStep({
+ approvedToolCall,
+ asyncToolVerifyAttempt,
+ context,
+ externalRetryCount,
+ finishAfterAsyncTool,
+ groupMemberTimeout,
+ humanInput,
+ inlineContinuation: true,
+ lockRetryAttempt,
+ operationId,
+ rejectAndContinue,
+ rejectionReason,
+ resumeAsyncTool,
+ retainStepLock: true,
+ stepIndex,
+ stepLockOwner,
+ toolMessageId,
+ verifyAsyncToolBarrier,
+ });
+ pendingContinuation = result.continuation;
+ touchedEnvelope ||= Boolean(pendingContinuation);
+
+ while (pendingContinuation) {
+ // Let the previous step's deferred work finish first. Its budget
+ // hold is released there, and the next step reserves again.
+ const settled = await flushScheduledWork({ timeoutMs: STEP_BOUNDARY_FLUSH_TIMEOUT_MS });
+ if (!settled) {
+ // The deferred work cannot be told apart, so a slow telemetry call
+ // and a slow budget settlement look the same. Reserving again on
+ // top of an unreleased hold is exactly the false "over budget"
+ // this wait exists to prevent, so stop inlining and hand the step
+ // to the queue, the way it ran before steps were inlined.
+ log(
+ `[${operationId}] Deferred work still running after ${STEP_BOUNDARY_FLUSH_TIMEOUT_MS}ms, handing step ${pendingContinuation.stepIndex} back to the queue`,
+ );
+ break;
+ }
+
+ const elapsed = Date.now() - startTime;
+ if (elapsed >= INLINE_STEP_START_DEADLINE_MS) {
+ log(
+ `[${operationId}] Inline budget spent after ${inlinedSteps} extra step(s) (${elapsed}ms), handing step ${pendingContinuation.stepIndex} back to the queue`,
+ );
+ break;
+ }
+
+ const next = pendingContinuation;
+ pendingContinuation = undefined;
+ currentStepIndex = next.stepIndex;
+
+ result = await aiAgentService.executeStep({
+ context: next.context,
inlineContinuation: true,
- lockRetryAttempt,
operationId,
- rejectAndContinue,
- rejectionReason,
- resumeAsyncTool,
retainStepLock: true,
- stepIndex,
+ stepIndex: next.stepIndex,
stepLockOwner,
- toolMessageId,
- verifyAsyncToolBarrier,
});
- pendingContinuation = result.continuation;
- touchedEnvelope ||= Boolean(pendingContinuation);
-
- while (pendingContinuation) {
- const elapsed = Date.now() - startTime;
- if (elapsed >= INLINE_STEP_START_DEADLINE_MS) {
- log(
- `[${operationId}] Inline budget spent after ${inlinedSteps} extra step(s) (${elapsed}ms), handing step ${pendingContinuation.stepIndex} back to the queue`,
- );
- break;
- }
+ inlinedSteps += 1;
+ pendingContinuation = result.continuation;
+ touchedEnvelope ||= Boolean(pendingContinuation);
- const next = pendingContinuation;
- pendingContinuation = undefined;
- currentStepIndex = next.stepIndex;
-
- result = await aiAgentService.executeStep({
- context: next.context,
- inlineContinuation: true,
- operationId,
- retainStepLock: true,
- stepIndex: next.stepIndex,
- stepLockOwner,
- });
- inlinedSteps += 1;
- pendingContinuation = result.continuation;
- touchedEnvelope ||= Boolean(pendingContinuation);
-
- // A lock conflict mid-loop means another worker took over this
- // operation. Stop rather than fight it β€” that worker owns the rest.
- if (result.locked) break;
- }
+ // A lock conflict mid-loop means another worker took over this
+ // operation. Stop rather than fight it β€” that worker owns the rest.
+ if (result.locked) break;
+ }
- // Whatever is still pending goes back to the queue so the operation
- // resumes in a fresh invocation.
- if (pendingContinuation) {
- await aiAgentService.scheduleContinuation(pendingContinuation);
- result = { ...result, nextStepScheduled: true };
- pendingContinuation = undefined;
- }
+ // Whatever is still pending goes back to the queue so the operation
+ // resumes in a fresh invocation.
+ if (pendingContinuation) {
+ await aiAgentService.scheduleContinuation(pendingContinuation);
+ result = { ...result, nextStepScheduled: true };
+ pendingContinuation = undefined;
+ }
- // Drop the envelope once this invocation is done with it: either the queue
- // owns the next step again, or the operation stopped. Leaving it behind
- // would let a late redelivery re-run a step someone else already owns.
- // Skipped when nothing was ever parked, to keep the flag-off path free of
- // an extra Redis round-trip.
- //
- // Scoped to our lock owner, because "done with it" is only true while we
- // still hold the operation. A delivery that read an envelope and then lost
- // the lock race must not delete the newer one the live worker parked.
- if (touchedEnvelope) {
- await coordinator.clearInlineResume(operationId, stepLockOwner);
- }
+ // Drop the envelope once this invocation is done with it: either the queue
+ // owns the next step again, or the operation stopped. Leaving it behind
+ // would let a late redelivery re-run a step someone else already owns.
+ // Skipped when nothing was ever parked, to keep the flag-off path free of
+ // an extra Redis round-trip.
+ //
+ // Scoped to our lock owner, because "done with it" is only true while we
+ // still hold the operation. A delivery that read an envelope and then lost
+ // the lock race must not delete the newer one the live worker parked.
+ if (touchedEnvelope) {
+ await coordinator.clearInlineResume(operationId, stepLockOwner);
+ }
+ });
} finally {
// Owner-scoped, so this is a no-op when the first step never claimed the
// lock (a conflicting delivery, a terminal operation, a watchdog probe).
diff --git a/apps/server/src/utils/scheduleAfterResponse.test.ts b/apps/server/src/utils/scheduleAfterResponse.test.ts
new file mode 100644
index 00000000000..f384f9769d2
--- /dev/null
+++ b/apps/server/src/utils/scheduleAfterResponse.test.ts
@@ -0,0 +1,139 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { after, flushScheduledWork, runWithScheduledWorkScope } from './scheduleAfterResponse';
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+describe('scheduled work scope', () => {
+ it('starts deferred work immediately and waits for it on flush', async () => {
+ const events: string[] = [];
+
+ await runWithScheduledWorkScope(async () => {
+ after(async () => {
+ events.push('work started');
+ await sleep(20);
+ events.push('work finished');
+ });
+ events.push('scheduled');
+
+ await flushScheduledWork();
+ events.push('flushed');
+ });
+
+ expect(events).toEqual(['work started', 'scheduled', 'work finished', 'flushed']);
+ });
+
+ it('drains work that deferred work schedules in turn', async () => {
+ const events: string[] = [];
+
+ await runWithScheduledWorkScope(async () => {
+ after(async () => {
+ await sleep(5);
+ after(async () => {
+ await sleep(5);
+ events.push('nested finished');
+ });
+ });
+
+ await flushScheduledWork();
+ events.push('flushed');
+ });
+
+ expect(events).toEqual(['nested finished', 'flushed']);
+ });
+
+ it('stops waiting at the timeout and leaves the work running', async () => {
+ let finished = false;
+
+ await runWithScheduledWorkScope(async () => {
+ after(async () => {
+ await sleep(80);
+ finished = true;
+ });
+
+ const startedAt = Date.now();
+ await expect(flushScheduledWork({ timeoutMs: 10 })).resolves.toBe(false);
+ expect(Date.now() - startedAt).toBeLessThan(60);
+ expect(finished).toBe(false);
+ });
+
+ await sleep(100);
+ expect(finished).toBe(true);
+ });
+
+ it('does not let a failing task reject the flush', async () => {
+ await runWithScheduledWorkScope(async () => {
+ after(async () => {
+ throw new Error('boom');
+ });
+
+ await expect(flushScheduledWork()).resolves.toBe(true);
+ });
+ });
+
+ it('reports a drained flush within the timeout as settled', async () => {
+ await runWithScheduledWorkScope(async () => {
+ after(async () => {
+ await sleep(5);
+ });
+
+ await expect(flushScheduledWork({ timeoutMs: 1000 })).resolves.toBe(true);
+ });
+ });
+
+ it('does not wait for unfinished work when the scope ends', async () => {
+ let finished = false;
+
+ const startedAt = Date.now();
+ await runWithScheduledWorkScope(async () => {
+ after(async () => {
+ await sleep(80);
+ finished = true;
+ });
+ });
+
+ expect(Date.now() - startedAt).toBeLessThan(60);
+ expect(finished).toBe(false);
+ await sleep(100);
+ expect(finished).toBe(true);
+ });
+
+ it('captures work deferred from a stream callback created inside the scope', async () => {
+ // Model responses settle their budget hold from a TransformStream flush()
+ // callback. The fix for inline agent steps depends on that work still being
+ // tied to the scope by the time the stream finishes.
+ const events: string[] = [];
+
+ await runWithScheduledWorkScope(async () => {
+ const stream = new Response('data: 1\n\ndata: 2\n\n').body!.pipeThrough(
+ new TransformStream<Uint8Array, Uint8Array>({
+ async flush() {
+ after(async () => {
+ await sleep(20);
+ events.push('settled');
+ });
+ },
+ transform(chunk, controller) {
+ controller.enqueue(chunk);
+ },
+ }),
+ );
+
+ const reader = stream.getReader();
+ while (!(await reader.read()).done) {
+ // drain the stream so flush() runs
+ }
+ events.push('stream done');
+
+ await flushScheduledWork();
+ events.push('flushed');
+ });
+
+ expect(events).toEqual(['stream done', 'settled', 'flushed']);
+ });
+
+ it('is a no-op outside a scope', async () => {
+ await expect(flushScheduledWork()).resolves.toBe(true);
+ });
+});
diff --git a/apps/server/src/utils/scheduleAfterResponse.ts b/apps/server/src/utils/scheduleAfterResponse.ts
index 0a8681f5776..316d28ce284 100644
--- a/apps/server/src/utils/scheduleAfterResponse.ts
+++ b/apps/server/src/utils/scheduleAfterResponse.ts
@@ -1,3 +1,5 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+
import debug from 'debug';
const log = debug('lobe-server:schedule-after-response');
@@ -12,7 +14,11 @@ const runWork = async (work: ScheduleAfterResponseWork) => {
}
};
-export const after = (work: ScheduleAfterResponseWork): void => {
+/**
+ * Hand work to the host so it runs after the HTTP response is sent. Falls back
+ * to running it immediately when there is no host that supports this.
+ */
+const scheduleOnHost = (work: () => Promise<void>): void => {
try {
const nextServer = require('next/server') as {
after?: (work: () => Promise<void>) => void;
@@ -20,7 +26,7 @@ export const after = (work: ScheduleAfterResponseWork): void => {
if (typeof nextServer.after === 'function') {
try {
- nextServer.after(() => runWork(work));
+ nextServer.after(work);
return;
} catch (error) {
log('next/server after() unavailable, falling back: %O', error);
@@ -30,5 +36,99 @@ export const after = (work: ScheduleAfterResponseWork): void => {
// next/server is not available in standalone Hono.
}
- void runWork(work);
+ void work();
+};
+
+interface ScheduledWorkScope {
+ pending: Set<Promise<void>>;
+}
+
+const scopeStorage = new AsyncLocalStorage<ScheduledWorkScope>();
+
+const drain = async (scope: ScheduledWorkScope) => {
+ // Loop, because finished work may have scheduled more.
+ while (scope.pending.size > 0) {
+ await Promise.allSettled(scope.pending);
+ }
+};
+
+export const after = (work: ScheduleAfterResponseWork): void => {
+ const scope = scopeStorage.getStore();
+
+ if (scope) {
+ const task = runWork(work);
+ scope.pending.add(task);
+ void task.finally(() => scope.pending.delete(task));
+ return;
+ }
+
+ scheduleOnHost(() => runWork(work));
+};
+
+/**
+ * Run `fn` so that work it defers with {@link after} starts immediately and can
+ * be awaited with {@link flushScheduledWork}, instead of waiting for the HTTP
+ * response.
+ *
+ * Use when:
+ * - One request performs several independent units of work back to back, and
+ * what one unit defers must be done before the next unit starts β€” e.g. the
+ * agent step loop, where each step's budget settlement has to release its
+ * hold before the next step reserves again.
+ *
+ * Deferred work is only captured while the async context propagates from
+ * `fn`. Anything scheduled outside it keeps the ordinary post-response
+ * behaviour. Node binds that context where a stream is created, so work
+ * deferred from a stream callback (for example a model response's `onFinal`)
+ * is captured only when the stream itself is created inside the scope. Work still running when `fn` settles is handed to the host, so
+ * returning from the scope never waits for it.
+ */
+export const runWithScheduledWorkScope = async <T>(fn: () => Promise<T>): Promise<T> => {
+ const scope: ScheduledWorkScope = { pending: new Set() };
+
+ try {
+ return await scopeStorage.run(scope, fn);
+ } finally {
+ if (scope.pending.size > 0) scheduleOnHost(() => drain(scope));
+ }
+};
+
+/**
+ * Wait for work deferred inside the current {@link runWithScheduledWorkScope}.
+ * A no-op outside a scope.
+ *
+ * With `timeoutMs`, stops waiting after that long and lets the remaining work
+ * keep running, so one stuck telemetry call cannot stall the caller.
+ *
+ * Resolves `true` when nothing is left pending, and `false` when it gave up at
+ * the timeout. Callers that need the work done before they continue must treat
+ * `false` as "not settled": the captured set does not tell telemetry apart from
+ * work that has to finish, such as releasing a budget hold.
+ */
+export const flushScheduledWork = async ({
+ timeoutMs,
+}: { timeoutMs?: number } = {}): Promise<boolean> => {
+ const scope = scopeStorage.getStore();
+ if (!scope || scope.pending.size === 0) return true;
+
+ const drained = drain(scope);
+ if (timeoutMs === undefined) {
+ await drained;
+ return true;
+ }
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timedOut = new Promise<'timeout'>((resolve) => {
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
+ });
+
+ const outcome = await Promise.race([drained.then(() => 'drained' as const), timedOut]);
+ clearTimeout(timer);
+
+ if (outcome === 'timeout') {
+ log('Stopped waiting for %d scheduled task(s) after %dms', scope.pending.size, timeoutMs);
+ return false;
+ }
+
+ return true;
};