🤯 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
⚡️ perf(agent): always inline agent steps in queue mode (#19531)
Arvin Xuf7f688bfa06a
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.tsindex b3eee1e2d41..13509ecdf48 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@@ -38,11 +38,6 @@ vi.mock('@/database/core/db-adaptor', () => ({getServerDB: mockGetServerDB,}));-const mockInlineStepsEnabled = vi.fn();-vi.mock('@/server/services/agentRuntime/inlineStepsGate', () => ({- isInlineAgentStepsEnabledForUser: (userId: string) => mockInlineStepsEnabled(userId),-}));-function buildOperationDiagnosticDB(row?: any) {return {select: vi.fn(function () {@@ -95,8 +90,6 @@ const validBody = {describe('runStep handler', () => {beforeEach(() => {mockGetOperationMetadata.mockReset();- mockInlineStepsEnabled.mockReset();- mockInlineStepsEnabled.mockResolvedValue(true);mockLoadInlineResume.mockReset();mockLoadInlineResume.mockResolvedValue(null);mockClearInlineResume.mockReset();@@ -435,8 +428,6 @@ describe('runStep inline step loop', () => {mockClearInlineResume.mockReset();mockLoadInlineResume.mockReset();mockLoadInlineResume.mockResolvedValue(null);- mockInlineStepsEnabled.mockReset();- mockInlineStepsEnabled.mockResolvedValue(true);mockGetServerDB.mockResolvedValue({} as any);mockGetOperationMetadata.mockResolvedValue(metadata);});@@ -722,48 +713,7 @@ describe('runStep inline step loop', () => {nowSpy.mockRestore();});- it('runs one step per delivery when the rollout flag is off', async () => {- mockInlineStepsEnabled.mockResolvedValue(false);- mockExecuteStep.mockResolvedValue({- nextStepScheduled: true,- state: { status: 'running', stepCount: 3 },- success: true,- });-- const { ctx, getCaptures } = buildContext({ body: validBody });- await runStep(ctx);-- expect(mockInlineStepsEnabled).toHaveBeenCalledWith('user-1');- expect(mockExecuteStep).toHaveBeenCalledTimes(1);- expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({ inlineContinuation: false });- expect(getCaptures()[0].body).toMatchObject({ inlinedSteps: 0, nextStepScheduled: true });- });-- it('still honours a parked envelope after the flag is switched off', async () => {- // Operations that were mid-loop when the flag flipped have an envelope and- // nothing queued behind them. Ignoring it would strand exactly the runs the- // rollback was meant to protect.- mockInlineStepsEnabled.mockResolvedValue(false);- mockLoadInlineResume.mockResolvedValue(continuationFor(7));- mockExecuteStep.mockResolvedValue({- nextStepScheduled: true,- state: { status: 'running', stepCount: 8 },- success: true,- });-- const { ctx } = buildContext({ body: validBody });- await runStep(ctx);-- expect(mockExecuteStep.mock.calls[0][0]).toMatchObject({- inlineContinuation: false,- stepIndex: 7,- });- // The queue owns the next step again, so the envelope must not linger.- expect(mockClearInlineResume).toHaveBeenCalledWith('op-1', 'op-1:owner');- });-it('leaves Redis alone when nothing was ever parked', async () => {- mockInlineStepsEnabled.mockResolvedValue(false);mockExecuteStep.mockResolvedValue({nextStepScheduled: true,state: { status: 'running', stepCount: 3 },diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex aaf1967f3e3..cf814206a8d 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -6,7 +6,6 @@ import { getServerDB } from '@/database/core/db-adaptor';import { agentOperations } from '@/database/schemas/agentOperations';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';import type { AgentExecutionResult, AgentStepContinuation } from '@/server/services/agentRuntime';-import { isInlineAgentStepsEnabledForUser } from '@/server/services/agentRuntime/inlineStepsGate';import { AiAgentService } from '@/server/services/aiAgent';const log = debug('lobe-server:agent:run-step');@@ -20,12 +19,20 @@ const log = debug('lobe-server:agent:run-step');* steps inside one invocation removes that cost; this deadline is what keeps* the invocation inside the platform's function timeout.*- * It must stay comfortably below the route's `maxDuration`, because a step that- * starts just under the deadline still runs to completion — production LLM- * steps are ~42s at p90 and ~125s at p99. The 450s default leaves ~150s of- * headroom under a 600s `maxDuration`, which covers p99. Raise it only- * alongside `maxDuration`. Once past the deadline the pending step goes back to- * the queue and a fresh invocation picks it up.+ * The deadline only decides whether a step may START; a step that starts just+ * under it still runs to completion, so what protects the invocation is the+ * headroom between this deadline and the route's `maxDuration`. That headroom+ * has to cover a long LLM step, and step length varies a lot by model: most+ * models finish LLM steps within ~40s at p99, but some run into several+ * minutes (one model family measured ~317s at p99, ~439s max). With 450s under+ * a 600s `maxDuration`, steps started before the deadline were observed ending+ * within seconds of the kill.+ *+ * 300s leaves 300s of headroom under 600s. A killed step is not lost — it+ * resumes from the parked envelope — but it is paid for twice, so keep this+ * conservative and raise it only alongside `maxDuration`. Once past the+ * deadline the pending step goes back to the queue and a fresh invocation+ * picks it up.*/const INLINE_STEP_START_DEADLINE_MS = Number(process.env.AGENT_INLINE_STEP_DEADLINE_MS ?? 450_000);@@ -166,10 +173,6 @@ export async function runStep(c: Context): Promise<Response> {// round-trip per step. One lock owner spans the whole loop: the operation// lock is re-entrant for its owner, so a redelivery from the queue still// loses the race the same way it does for a single step.- // Rollout switch, resolved once per invocation from RuntimeConfig (Redis,- // cached ~5s per instance). Off means exactly one step per delivery, which- // is what the worker has always done.- const inlineEnabled = await isInlineAgentStepsEnabledForUser(metadata.userId);const stepLockOwner = aiAgentService.createOperationLockOwner(operationId);let pendingContinuation: AgentStepContinuation | undefined;@@ -198,9 +201,6 @@ export async function runStep(c: Context): Promise<Response> {!verifyAsyncToolBarrier &&!groupMemberTimeout;- // Deliberately not gated on `inlineEnabled`: switching the flag off while- // operations are mid-loop must not strand the ones that already have an- // envelope parked and nothing queued behind them.// A previous invocation may have died part-way through its own inline loop.// It parks the envelope for each step before running it, so an envelope// ahead of the delivered index means exactly that: resume from there. Going@@ -234,7 +234,7 @@ export async function runStep(c: Context): Promise<Response> {? await aiAgentService.executeStep({context: resumeFrom.context,externalRetryCount,- inlineContinuation: inlineEnabled,+ inlineContinuation: true,operationId,retainStepLock: true,stepIndex: resumeFrom.stepIndex,@@ -248,7 +248,7 @@ export async function runStep(c: Context): Promise<Response> {finishAfterAsyncTool,groupMemberTimeout,humanInput,- inlineContinuation: inlineEnabled,+ inlineContinuation: true,lockRetryAttempt,operationId,rejectAndContinue,@@ -278,7 +278,7 @@ export async function runStep(c: Context): Promise<Response> {result = await aiAgentService.executeStep({context: next.context,- inlineContinuation: inlineEnabled,+ inlineContinuation: true,operationId,retainStepLock: true,stepIndex: next.stepIndex,diff --git a/apps/server/src/services/agentRuntime/inlineStepsGate.ts b/apps/server/src/services/agentRuntime/inlineStepsGate.tsdeleted file mode 100644index 9bc77220b40..00000000000--- a/apps/server/src/services/agentRuntime/inlineStepsGate.ts+++ /dev/null@@ -1,28 +0,0 @@-import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';--/**- * Resolves whether the queue worker may run consecutive steps of an operation- * inside a single invocation.- *- * Use when:- * - The QStash step worker is deciding how much of an operation to run- * - Rollout eligibility must come from RuntimeConfig rather than a deploy- *- * Expects:- * - `userId` is the owner of the operation being stepped- *- * Returns:- * - `true` only when the inline-step flag is enabled for that user- *- * Fails closed: any error resolving the flag falls back to the one-step-per-- * delivery behaviour the worker has always had.- */-export const isInlineAgentStepsEnabledForUser = async (userId: string): Promise<boolean> => {- try {- const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);-- return featureFlags.enableInlineAgentSteps === true;- } catch {- return false;- }-};diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex 645fba06792..fe7ed5bfcbd 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -44,12 +44,6 @@ export const FeatureFlagsSchema = z.object({agent_onboarding: FeatureFlagValue.optional(),dev_dock: FeatureFlagValue.optional(),dev_dock_workspaces: z.array(z.string()).optional(),- /**- * Rollout gate for the queue worker's inline step loop. Array values are user- * IDs, so the loop can be switched on for a slice of traffic before everyone.- * Off by default: the worker then runs one step per delivery, unchanged.- */- inline_agent_steps: FeatureFlagValue.optional(),// Cloud feature flag. Keep here until cloud owns a separate runtime flag domain.auth_captcha: FeatureFlagValue.optional(),cloud_promotion: FeatureFlagValue.optional(),@@ -111,7 +105,6 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {agent_self_iteration: isDev,agent_onboarding: isDev,dev_dock: isDev,- inline_agent_steps: false,auth_captcha: true,cloud_promotion: false,onboarding_v2: isDev,@@ -159,7 +152,6 @@ export const mapFeatureFlagsEnvToState = (enableAgentSelfIteration: evaluateFeatureFlag(config.agent_self_iteration, userId),enableAgentOnboarding: evaluateFeatureFlag(config.agent_onboarding, userId),enableDevDock: evaluateFeatureFlag(config.dev_dock, userId),- enableInlineAgentSteps: evaluateFeatureFlag(config.inline_agent_steps, userId),enableAuthCaptcha: evaluateFeatureFlag(config.auth_captcha, userId),enableOnboardingV2: evaluateFeatureFlag(config.onboarding_v2, userId),enableStorageOverage: evaluateFeatureFlag(config.storage_overage, userId),diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 21fee8bc574..f09cd58b712 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -28,12 +28,6 @@ export type IFeatureFlagsState = {enableAuthCaptcha: boolean | undefined;enableCheckUpdates: boolean | undefined;enableDevDock: boolean | undefined;- /**- * Lets the queue worker run consecutive agent steps inside one invocation- * instead of paying a queue round-trip per step. Rollout switch only — with it- * off the worker runs exactly one step per delivery, as it always has.- */- enableInlineAgentSteps: boolean | undefined;enableKnowledgeBase: boolean | undefined;enableOnboardingV2: boolean | undefined;enableRAGEval: boolean | undefined;