π€― 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
π fix(agent-runtime): re-queue step-lock conflicts instead of dead-lettering them (#18458)
Arvin Xu89779f5aaa24
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 4cae3fa6837..70b5a7dd8d6 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@@ -191,6 +191,31 @@ describe('runStep handler', () => {);});+ it('acks without retry when the runtime already re-queued the locked step', async () => {+ mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });+ mockExecuteStep.mockResolvedValue({+ locked: true,+ lockRescheduled: true,+ nextStepScheduled: true,+ state: {},+ success: true,+ });++ const { ctx, getCaptures } = buildContext({ body: validBody });+ const res = await runStep(ctx);++ // Must not be retryable: a re-delivery is already scheduled, and letting+ // QStash retry on top of it is what dead-letters the step.+ expect(res.status).toBe(200);+ expect(getCaptures()[0].body).toMatchObject({+ locked: true,+ nextStepScheduled: true,+ operationId: 'op-1',+ stepIndex: 2,+ success: true,+ });+ });+it('returns 429 with Retry-After header when the step is locked', async () => {mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });mockExecuteStep.mockResolvedValue({diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex 1657fc8a5ae..2fccc59fefe 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -90,6 +90,7 @@ export async function runStep(c: Context): Promise<Response> {toolMessageId,verifyAsyncToolBarrier,asyncToolVerifyAttempt,+ lockRetryAttempt,} = { ...body, ...body.payload };if (!operationId) {@@ -141,6 +142,7 @@ export async function runStep(c: Context): Promise<Response> {humanInput,finishAfterAsyncTool,groupMemberTimeout,+ lockRetryAttempt,operationId,rejectAndContinue,rejectionReason,@@ -151,8 +153,25 @@ export async function runStep(c: Context): Promise<Response> {});// A non-stale lock conflict means another delivery is still executing this- // operation. Keep the response retryable so QStash redelivers this step.+ // operation.if (result.locked) {+ // The runtime already re-queued this step on its own backoff, which can+ // outlast a step that holds the lock for minutes. ACK so QStash doesn't+ // retry on top of that and dead-letter the delivery once its (much+ // shorter) retry budget runs out.+ if (result.lockRescheduled) {+ log(`[${operationId}] Step ${stepIndex} locked by another instance, re-queued`);+ return c.json({+ locked: true,+ nextStepScheduled: true,+ operationId,+ stepIndex,+ success: true,+ });+ }++ // Backoff exhausted (or re-queueing failed) β fall back to a retryable+ // response so the delivery still gets whatever retries the queue offers.log(`[${operationId}] Step ${stepIndex} locked by another instance, returning 429`);return c.json({ error: 'Step is currently being executed, retry later', operationId, stepIndex },diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex e3a14f3598b..f6a953afb16 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -128,6 +128,31 @@ const ASYNC_TOOL_VERIFY_MAX_DELAY_MS = 240_000;const STEP_LOCK_TTL_SECONDS = 120;const STEP_LOCK_HEARTBEAT_MS = 30_000;+/**+ * How many times a delivery that lost the operation lock re-queues itself+ * before giving up and falling back to a retryable response.+ */+const STEP_LOCK_RETRY_MAX_ATTEMPTS = 12;+/** Base delay for the first lock-conflict re-delivery. */+const STEP_LOCK_RETRY_BASE_DELAY_MS = 15_000;+/**+ * Ceiling on a single lock-conflict backoff. Together with the base delay,+ * {@link STEP_LOCK_RETRY_MAX_ATTEMPTS} attempts span ~20 minutes β comfortably+ * longer than the platform's hard step ceiling, so a step that legitimately+ * holds the lock for minutes no longer strands the delivery waiting behind it.+ */+const STEP_LOCK_RETRY_MAX_DELAY_MS = 120_000;++/**+ * Exponential backoff for the Nth (1-based) lock-conflict re-delivery:+ * 15s, 30s, 60s, 120s, then capped at {@link STEP_LOCK_RETRY_MAX_DELAY_MS}.+ */+const stepLockRetryDelayMs = (attempt: number): number =>+ Math.min(+ STEP_LOCK_RETRY_BASE_DELAY_MS * 2 ** (Math.max(1, attempt) - 1),+ STEP_LOCK_RETRY_MAX_DELAY_MS,+ );+/*** Exponential backoff delay for the Nth (1-based) watchdog re-check:* 15s, 30s, 60s, 120s, 240s, capped at {@link ASYNC_TOOL_VERIFY_MAX_DELAY_MS}.@@ -750,6 +775,7 @@ export class AgentRuntimeService {verifyAsyncToolBarrier,asyncToolVerifyAttempt,externalRetryCount = 0,+ lockRetryAttempt = 0,} = params;// Group member timeout watchdog: enforce a member's deadline without claiming@@ -822,6 +848,81 @@ export class AgentRuntimeService {};}+ // The lock is held by a live step of this operation, and this delivery is+ // not a stale duplicate β it still has to run once the holder is done.+ //+ // Don't lean on the queue's own retry budget for that wait: the lock is+ // heartbeat-refreshed for as long as the holding step runs (unbounded),+ // while the budget is a handful of fixed-delay retries. A step that runs+ // longer than the budget therefore exhausts it and the delivery is+ // dead-lettered β the step it carried is then never executed. Re-queue a+ // fresh delivery on our own bounded backoff instead, and ACK this one.+ //+ // The re-delivery has to carry this delivery's own resume/intervention+ // payload: a human-intervention resume (`processHumanIntervention`) or an+ // async-tool resume (`tryResumeParentFromAsyncTool`) can lose the lock+ // race too, and re-queueing only the retry counter would run a plain step+ // once the lock clears β silently dropping the approval / human input, or+ // leaving a parked operation parked forever. Undefined fields drop out of+ // the JSON body, so unrelated deliveries still send just the counter.+ const nextLockRetryAttempt = lockRetryAttempt + 1;+ if (this.queueService && nextLockRetryAttempt <= STEP_LOCK_RETRY_MAX_ATTEMPTS) {+ const delay = stepLockRetryDelayMs(nextLockRetryAttempt);+ log(+ '[%s][%d] Step lock conflict β re-queueing attempt %d/%d in %dms',+ operationId,+ stepIndex,+ nextLockRetryAttempt,+ STEP_LOCK_RETRY_MAX_ATTEMPTS,+ delay,+ );++ try {+ await this.queueService.scheduleMessage({+ context,+ delay,+ endpoint: `${this.baseURL}/run`,+ operationId,+ payload: {+ approvedToolCall,+ finishAfterAsyncTool,+ humanInput,+ lockRetryAttempt: nextLockRetryAttempt,+ rejectAndContinue,+ rejectionReason,+ resumeAsyncTool,+ toolMessageId,+ },+ priority: 'high',+ retryDelay:+ typeof currentState?.metadata?.queueRetryDelay === 'string'+ ? currentState.metadata.queueRetryDelay+ : undefined,+ retries:+ typeof currentState?.metadata?.queueRetries === 'number'+ ? currentState.metadata.queueRetries+ : undefined,+ stepIndex,+ });++ return {+ locked: true,+ lockRescheduled: true,+ nextStepScheduled: true,+ state: {},+ success: true,+ };+ } catch (error) {+ // Fall through to the retryable response so the delivery isn't lost.+ log(+ '[%s][%d] Failed to re-queue after step lock conflict: %O',+ operationId,+ stepIndex,+ error,+ );+ }+ }+log('[%s][%d] Step lock conflict β another instance is executing this step, returning locked',operationId,diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.tsindex 250318b73e3..f2171a5519c 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts@@ -383,6 +383,146 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'expect(coordinator.releaseStepLock).not.toHaveBeenCalled();});+ it('should re-queue the same step on its own backoff for a non-stale lock conflict', async () => {+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({+ status: 'running',+ stepCount: 5,+ metadata: { queueRetries: 5, queueRetryDelay: '10000' },+ });++ const result = await service.executeStep({ operationId: 'op-requeue', stepIndex: 5 });++ expect(result.locked).toBe(true);+ expect(result.lockRescheduled).toBe(true);+ // ACK so the queue doesn't retry on top of the re-delivery we just scheduled.+ expect(result.success).toBe(true);+ expect(scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: 'op-requeue',+ payload: { lockRetryAttempt: 1 },+ retries: 5,+ retryDelay: '10000',+ stepIndex: 5,+ }),+ );+ expect(coordinator.releaseStepLock).not.toHaveBeenCalled();+ });++ it('should carry the delivery resume payload into the re-queued lock-conflict message', async () => {+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });++ // A human-intervention resume that lost the lock race. Re-queueing only the+ // retry counter would run a plain step and drop the approval entirely.+ await service.executeStep({+ approvedToolCall: { id: 'call-1' },+ humanInput: 'approved',+ operationId: 'op-resume',+ rejectAndContinue: false,+ stepIndex: 5,+ toolMessageId: 'msg-tool-1',+ });++ expect(scheduleMessage.mock.calls[0][0].payload).toMatchObject({+ approvedToolCall: { id: 'call-1' },+ humanInput: 'approved',+ lockRetryAttempt: 1,+ rejectAndContinue: false,+ toolMessageId: 'msg-tool-1',+ });+ });++ it('should carry an async-tool resume flag into the re-queued lock-conflict message', async () => {+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });++ await service.executeStep({+ operationId: 'op-async-resume',+ resumeAsyncTool: true,+ stepIndex: 5,+ });++ expect(scheduleMessage.mock.calls[0][0].payload).toMatchObject({+ lockRetryAttempt: 1,+ resumeAsyncTool: true,+ });+ });++ it('should back off exponentially across successive lock-conflict re-deliveries', async () => {+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });++ await service.executeStep({ lockRetryAttempt: 0, operationId: 'op-b', stepIndex: 5 });+ await service.executeStep({ lockRetryAttempt: 2, operationId: 'op-b', stepIndex: 5 });++ expect(scheduleMessage.mock.calls[0][0]).toMatchObject({+ delay: 15_000,+ payload: { lockRetryAttempt: 1 },+ });+ expect(scheduleMessage.mock.calls[1][0]).toMatchObject({+ delay: 60_000,+ payload: { lockRetryAttempt: 3 },+ });+ });++ it('should fall back to a retryable response once the lock-conflict backoff is exhausted', async () => {+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });++ const result = await service.executeStep({+ lockRetryAttempt: 12,+ operationId: 'op-exhausted',+ stepIndex: 5,+ });++ expect(scheduleMessage).not.toHaveBeenCalled();+ expect(result.locked).toBe(true);+ expect(result.lockRescheduled).toBeUndefined();+ expect(result.success).toBe(false);+ });++ it('should stay retryable when re-queueing after a lock conflict fails', async () => {+ const scheduleMessage = vi.fn().mockRejectedValue(new Error('qstash down'));+ const service = new AgentRuntimeService({} as any, 'user-1', {+ queueService: { getImpl: () => ({}), scheduleMessage } as any,+ });+ const coordinator = (service as any).coordinator;+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);+ coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });++ const result = await service.executeStep({ operationId: 'op-schedule-fail', stepIndex: 5 });++ expect(result.locked).toBe(true);+ expect(result.lockRescheduled).toBeUndefined();+ expect(result.success).toBe(false);+ });+it('should ack stale duplicate deliveries even when the stale step lock is held', async () => {const service = createService();const coordinator = (service as any).coordinator;diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 7e48e039d29..7b920e3f9de 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -154,6 +154,13 @@ export interface AgentExecutionParams {*/groupMemberTimeout?: GroupMemberTimeoutParams;humanInput?: any;+ /**+ * 1-based attempt number carried by a re-delivery that a previous attempt+ * re-queued after losing the operation lock. Lets the bounded backoff stop+ * after a fixed number of tries instead of re-queueing forever. Absent+ * (treated as attempt 0) on the original delivery.+ */+ lockRetryAttempt?: number;operationId: string;/*** Whether a rejection should resume execution by treating the rejected tool@@ -192,6 +199,13 @@ export interface AgentExecutionResult {* this response retryable so fresh deliveries can run after the lock clears.*/locked?: boolean;+ /**+ * Set alongside `locked` when this delivery re-queued itself for a later+ * attempt. The caller should ACK (2xx) rather than returning a retryable+ * status: the redelivery is already scheduled, so letting the queue retry on+ * top of it only amplifies the conflict and burns the retry budget.+ */+ lockRescheduled?: boolean;nextStepScheduled: boolean;state: any;stepResult?: any;