π€― 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 step lock retries (#16821)
Arvin Xufe209c675274
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.tsindex ed282eb8b2e..39fac6ff4c1 100644--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -308,15 +308,28 @@ export class AgentRuntimeCoordinator {operationId: string,stepIndex: number,ttlSeconds?: number,+ ownerId?: string,): Promise<boolean> {- return this.stateManager.tryClaimStep(operationId, stepIndex, ttlSeconds);+ return this.stateManager.tryClaimStep(operationId, stepIndex, ttlSeconds, ownerId);}/*** Release the step execution lock.*/- async releaseStepLock(operationId: string, stepIndex: number): Promise<void> {- return this.stateManager.releaseStepLock(operationId, stepIndex);+ async releaseStepLock(operationId: string, stepIndex: number, ownerId?: string): Promise<void> {+ return this.stateManager.releaseStepLock(operationId, stepIndex, ownerId);+ }++ /**+ * Extend the step execution lock if it is still owned by this worker.+ */+ async refreshStepLock(+ operationId: string,+ stepIndex: number,+ ttlSeconds: number,+ ownerId?: string,+ ): Promise<boolean> {+ return this.stateManager.refreshStepLock(operationId, stepIndex, ttlSeconds, ownerId);}/**diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.tsindex 1775beb6b82..32c72d28e86 100644--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts@@ -12,6 +12,11 @@ import { stripFinalStateInEventData } from './StreamEventManager';const log = debug('lobe-server:agent-runtime:agent-state-manager');+const REFRESH_OWNED_LOCK_SCRIPT =+ "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end";+const RELEASE_OWNED_LOCK_SCRIPT =+ "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";+export interface StepResult {events?: AgentEvent[];executionTime: number;@@ -468,19 +473,20 @@ export class AgentStateManager {}}- private stepLockKey(operationId: string, stepIndex: number): string {- return `agent_runtime_step_lock:${operationId}:${stepIndex}`;+ private executionLockKey(operationId: string): string {+ return `agent_runtime_operation_lock:${operationId}`;}async tryClaimStep(operationId: string,- stepIndex: number,+ _stepIndex: number,ttlSeconds: number = 35,+ ownerId: string = Date.now().toString(),): Promise<boolean> {try {const result = await this.redis.set(- this.stepLockKey(operationId, stepIndex),- Date.now().toString(),+ this.executionLockKey(operationId),+ ownerId,'EX',ttlSeconds,'NX',@@ -494,9 +500,42 @@ export class AgentStateManager {}}- async releaseStepLock(operationId: string, stepIndex: number): Promise<void> {+ async refreshStepLock(+ operationId: string,+ _stepIndex: number,+ ttlSeconds: number,+ ownerId?: string,+ ): Promise<boolean> {+ try {+ const key = this.executionLockKey(operationId);+ if (!ownerId) {+ return (await this.redis.expire(key, ttlSeconds)) === 1;+ }++ const result = await this.redis.eval(+ REFRESH_OWNED_LOCK_SCRIPT,+ 1,+ key,+ ownerId,+ ttlSeconds.toString(),+ );++ return result === 1;+ } catch (error) {+ console.error('Failed to refresh step lock:', error);+ return false;+ }+ }++ async releaseStepLock(operationId: string, _stepIndex: number, ownerId?: string): Promise<void> {try {- await this.redis.del(this.stepLockKey(operationId, stepIndex));+ const key = this.executionLockKey(operationId);+ if (!ownerId) {+ await this.redis.del(key);+ return;+ }++ await this.redis.eval(RELEASE_OWNED_LOCK_SCRIPT, 1, key, ownerId);} catch (error) {console.error('Failed to release step lock:', error);}diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.tsindex 39021c4a142..59a37c96a8d 100644--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts@@ -15,6 +15,11 @@ export class InMemoryAgentStateManager implements IAgentStateManager {private steps: Map<string, any[]> = new Map();private metadata: Map<string, AgentOperationMetadata> = new Map();private events: Map<string, any[][]> = new Map();+ private stepLocks: Map<string, { expiresAt: number; ownerId: string }> = new Map();++ private executionLockKey(operationId: string): string {+ return `agent_runtime_operation_lock:${operationId}`;+ }async saveAgentState(operationId: string, state: AgentState): Promise<void> {// Deep clone to avoid reference issues@@ -220,15 +225,49 @@ export class InMemoryAgentStateManager implements IAgentStateManager {}async tryClaimStep(- _operationId: string,+ operationId: string,+ _stepIndex: number,+ ttlSeconds: number = 35,+ ownerId: string = Date.now().toString(),+ ): Promise<boolean> {+ const key = this.executionLockKey(operationId);+ const now = Date.now();+ const existing = this.stepLocks.get(key);++ if (existing && existing.expiresAt > now) {+ return false;+ }++ this.stepLocks.set(key, { expiresAt: now + ttlSeconds * 1000, ownerId });+ return true;+ }++ async refreshStepLock(+ operationId: string,_stepIndex: number,- _ttlSeconds?: number,+ ttlSeconds: number,+ ownerId?: string,): Promise<boolean> {+ const key = this.executionLockKey(operationId);+ const existing = this.stepLocks.get(key);++ if (!existing || (ownerId && existing.ownerId !== ownerId)) {+ return false;+ }++ existing.expiresAt = Date.now() + ttlSeconds * 1000;return true;}- async releaseStepLock(_operationId: string, _stepIndex: number): Promise<void> {- // noop+ async releaseStepLock(operationId: string, _stepIndex: number, ownerId?: string): Promise<void> {+ const key = this.executionLockKey(operationId);+ const existing = this.stepLocks.get(key);++ if (!existing || (ownerId && existing.ownerId !== ownerId)) {+ return;+ }++ this.stepLocks.delete(key);}async disconnect(): Promise<void> {@@ -244,6 +283,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {this.steps.clear();this.metadata.clear();this.events.clear();+ this.stepLocks.clear();log('All data cleared');}diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.tsindex 51e7f8ffcab..109e7f78200 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts@@ -15,6 +15,7 @@ const { redisMock, pipelineMock } = vi.hoisted(() => {};const redisMock = {del: vi.fn(),+ eval: vi.fn(),expire: vi.fn(),get: vi.fn(),hgetall: vi.fn(),@@ -22,6 +23,7 @@ const { redisMock, pipelineMock } = vi.hoisted(() => {keys: vi.fn(),multi: vi.fn(() => pipelineMock),quit: vi.fn(),+ set: vi.fn(),setex: vi.fn(),};return { pipelineMock, redisMock };@@ -182,4 +184,47 @@ describe('AgentStateManager', () => {expect(persistedEvents[0].finalState.status).toBe('done');});});++ describe('step execution lock', () => {+ it('claims an operation-scoped lock with the provided owner token', async () => {+ redisMock.set.mockResolvedValue('OK');++ await expect(stateManager.tryClaimStep('op-lock', 3, 120, 'owner-1')).resolves.toBe(true);++ expect(redisMock.set).toHaveBeenCalledWith(+ 'agent_runtime_operation_lock:op-lock',+ 'owner-1',+ 'EX',+ 120,+ 'NX',+ );+ });++ it('refreshes only the lock owned by the caller', async () => {+ redisMock.eval.mockResolvedValue(1);++ await expect(stateManager.refreshStepLock('op-lock', 4, 120, 'owner-1')).resolves.toBe(true);++ expect(redisMock.eval).toHaveBeenCalledWith(+ "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end",+ 1,+ 'agent_runtime_operation_lock:op-lock',+ 'owner-1',+ '120',+ );+ });++ it('releases only the lock owned by the caller', async () => {+ redisMock.eval.mockResolvedValue(1);++ await stateManager.releaseStepLock('op-lock', 5, 'owner-1');++ expect(redisMock.eval).toHaveBeenCalledWith(+ "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end",+ 1,+ 'agent_runtime_operation_lock:op-lock',+ 'owner-1',+ );+ });+ });});diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.tsindex c3e42cd60a9..9cdf31ff993 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts@@ -67,6 +67,26 @@ describe('InMemoryAgentStateManager', () => {});});+ describe('step execution lock', () => {+ it('serializes execution across all steps in the same operation', async () => {+ await expect(manager.tryClaimStep('op-lock', 1, 60, 'owner-a')).resolves.toBe(true);+ await expect(manager.tryClaimStep('op-lock', 2, 60, 'owner-b')).resolves.toBe(false);++ await manager.releaseStepLock('op-lock', 1, 'owner-b');+ await expect(manager.tryClaimStep('op-lock', 2, 60, 'owner-b')).resolves.toBe(false);++ await manager.releaseStepLock('op-lock', 1, 'owner-a');+ await expect(manager.tryClaimStep('op-lock', 2, 60, 'owner-b')).resolves.toBe(true);+ });++ it('refreshes only the caller-owned lock', async () => {+ await manager.tryClaimStep('op-refresh', 1, 60, 'owner-a');++ await expect(manager.refreshStepLock('op-refresh', 2, 60, 'owner-b')).resolves.toBe(false);+ await expect(manager.refreshStepLock('op-refresh', 2, 60, 'owner-a')).resolves.toBe(true);+ });+ });+// ------------------------------------------------------------------ //// saveAgentState / loadAgentState// ------------------------------------------------------------------ //diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.tsindex 9e45d56d445..c7556b51883 100644--- a/apps/server/src/modules/AgentRuntime/types.ts+++ b/apps/server/src/modules/AgentRuntime/types.ts@@ -83,10 +83,20 @@ export interface IAgentStateManager {*/loadAgentState: (operationId: string) => Promise<AgentState | null>;+ /**+ * Extend the step execution lock if it is still owned by the caller.+ */+ refreshStepLock: (+ operationId: string,+ stepIndex: number,+ ttlSeconds: number,+ ownerId?: string,+ ) => Promise<boolean>;+/*** Release the step execution lock.*/- releaseStepLock: (operationId: string, stepIndex: number) => Promise<void>;+ releaseStepLock: (operationId: string, stepIndex: number, ownerId?: string) => Promise<void>;/*** Save Agent state@@ -102,7 +112,12 @@ export interface IAgentStateManager {* Atomically try to claim a step for execution (distributed lock).* Returns true if the lock was acquired, false if another execution already holds it.*/- tryClaimStep: (operationId: string, stepIndex: number, ttlSeconds?: number) => Promise<boolean>;+ tryClaimStep: (+ operationId: string,+ stepIndex: number,+ ttlSeconds?: number,+ ownerId?: string,+ ) => Promise<boolean>;}/**diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 1ad55324c9e..7d47d0d5a4d 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import type {Agent,AgentRuntimeContext,@@ -112,6 +114,9 @@ const ASYNC_TOOL_VERIFY_MAX_ATTEMPTS = 5;/** Hard ceiling on a single backoff delay so late attempts don't overshoot. */const ASYNC_TOOL_VERIFY_MAX_DELAY_MS = 240_000;+const STEP_LOCK_TTL_SECONDS = 120;+const STEP_LOCK_HEARTBEAT_MS = 30_000;+/*** 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}.@@ -122,6 +127,9 @@ const asyncToolVerifyDelayMs = (attempt: number): number =>ASYNC_TOOL_VERIFY_MAX_DELAY_MS,);+const createStepLockOwner = (operationId: string, stepIndex: number): string =>+ `${operationId}:${stepIndex}:${process.pid}:${Date.now()}:${randomUUID()}`;+/*** Format error for storage in message pluginError metadata.* Handles Error objects which don't serialize properly with JSON.stringify.@@ -338,6 +346,34 @@ export class AgentRuntimeService {this.setupLocalExecutionCallback();}+ private startStepLockHeartbeat(+ operationId: string,+ stepIndex: number,+ ownerId: string,+ ): () => void {+ const timer = setInterval(() => {+ this.coordinator+ .refreshStepLock(operationId, stepIndex, STEP_LOCK_TTL_SECONDS, ownerId)+ .then((refreshed) => {+ if (!refreshed) {+ log(+ '[%s][%d] Step lock heartbeat did not refresh; ownership may have changed',+ operationId,+ stepIndex,+ );+ }+ })+ .catch((error) => {+ log('[%s][%d] Step lock heartbeat failed: %O', operationId, stepIndex, error);+ });+ }, STEP_LOCK_HEARTBEAT_MS);++ const timerWithUnref = timer as { unref?: () => void };+ timerWithUnref.unref?.();++ return () => clearInterval(timer);+ }+/*** Setup execution callback for LocalQueueServiceImpl* This breaks the circular dependency by using callback injection@@ -700,7 +736,13 @@ export class AgentRuntimeService {}// ===== Distributed lock: prevent duplicate execution from QStash retries =====- const claimed = await this.coordinator.tryClaimStep(operationId, stepIndex, 35);+ const stepLockOwner = createStepLockOwner(operationId, stepIndex);+ const claimed = await this.coordinator.tryClaimStep(+ operationId,+ stepIndex,+ STEP_LOCK_TTL_SECONDS,+ stepLockOwner,+ );if (!claimed) {log('[%s][%d] Step lock conflict β another instance is executing this step, returning locked',@@ -711,10 +753,16 @@ export class AgentRuntimeService {locked: true,nextStepScheduled: false,state: {},- success: false,+ success: true,};}+ const stopStepLockHeartbeat = this.startStepLockHeartbeat(+ operationId,+ stepIndex,+ stepLockOwner,+ );+// Hoisted so the error-path snapshot finalize can record an// approximate startedAt for the failing step. The inner `startAt` at the// runtime.step() call site stays as the authoritative start for the@@ -1381,10 +1429,8 @@ export class AgentRuntimeService {throw error;} finally {invokeAgentSpan.end();- // Release lock so legitimate retries or next operations can proceed.- // If Vercel force-kills the process, this won't execute β the lock- // auto-expires after TTL (35s), allowing QStash retries to self-heal.- await this.coordinator.releaseStepLock(operationId, stepIndex);+ stopStepLockHeartbeat();+ await this.coordinator.releaseStepLock(operationId, stepIndex, stepLockOwner);}}diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.tsindex d0cd8408821..f742bb66136 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts@@ -20,6 +20,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({getOperationMetadata: vi.fn(),tryClaimStep: vi.fn().mockResolvedValue(true),releaseStepLock: vi.fn().mockResolvedValue(undefined),+ refreshStepLock: vi.fn().mockResolvedValue(true),})),createStreamEventManager: vi.fn(() => ({publishStreamEvent: vi.fn(),@@ -257,7 +258,7 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'});expect(result.locked).toBe(true);- expect(result.success).toBe(false);+ expect(result.success).toBe(true);expect(result.nextStepScheduled).toBe(false);// Should NOT call loadAgentState since lock was not acquiredexpect(coordinator.loadAgentState).not.toHaveBeenCalled();@@ -282,7 +283,11 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'expect(result.stepResult).toBeNull();expect(result.nextStepScheduled).toBe(false);// Lock should still be released- expect(coordinator.releaseStepLock).toHaveBeenCalledWith('op-stale', 8);+ expect(coordinator.releaseStepLock).toHaveBeenCalledWith(+ 'op-stale',+ 8,+ expect.stringContaining('op-stale:8:'),+ );});it('should release lock after successful execution', async () => {@@ -300,7 +305,11 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'stepIndex: 6,});- expect(coordinator.releaseStepLock).toHaveBeenCalledWith('op-done', 6);+ expect(coordinator.releaseStepLock).toHaveBeenCalledWith(+ 'op-done',+ 6,+ expect.stringContaining('op-done:6:'),+ );});it('should release lock even when step execution encounters an error', async () => {@@ -324,7 +333,11 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'expect(result.state.status).toBe('error');// Lock must still be released via finally block- expect(coordinator.releaseStepLock).toHaveBeenCalledWith('op-error', 6);+ expect(coordinator.releaseStepLock).toHaveBeenCalledWith(+ 'op-error',+ 6,+ expect.stringContaining('op-error:6:'),+ );});it('should NOT release lock when tryClaimStep returns false', async () => {@@ -350,7 +363,32 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'stepIndex: 42,});- expect(coordinator.tryClaimStep).toHaveBeenCalledWith('op-args', 42, 35);+ expect(coordinator.tryClaimStep).toHaveBeenCalledWith(+ 'op-args',+ 42,+ 120,+ expect.stringContaining('op-args:42:'),+ );+ });++ it('should refresh the step lock while execution is still running', async () => {+ vi.useFakeTimers();+ const service = createService();+ const coordinator = (service as any).coordinator;++ try {+ const stopHeartbeat = (service as any).startStepLockHeartbeat('op-heartbeat', 7, 'owner-1');+ await vi.advanceTimersByTimeAsync(30_000);++ expect(coordinator.refreshStepLock).toHaveBeenCalledWith('op-heartbeat', 7, 120, 'owner-1');++ stopHeartbeat();+ await vi.advanceTimersByTimeAsync(30_000);++ expect(coordinator.refreshStepLock).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }});});diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 66dc3041437..42043c197a7 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -181,7 +181,7 @@ export interface AgentExecutionParams {export interface AgentExecutionResult {/*** When true, the step was already being executed by another instance (lock conflict).- * The caller should return 429 to force QStash to retry later.+ * The caller should ACK duplicate queue deliveries as a no-op.*/locked?: boolean;nextStepScheduled: boolean;diff --git a/src/server/agent-hono/handlers/__tests__/runStep.test.ts b/src/server/agent-hono/handlers/__tests__/runStep.test.tsindex 4cae3fa6837..bd82c1df332 100644--- a/src/server/agent-hono/handlers/__tests__/runStep.test.ts+++ b/src/server/agent-hono/handlers/__tests__/runStep.test.ts@@ -191,26 +191,28 @@ describe('runStep handler', () => {);});- it('returns 429 with Retry-After header when the step is locked', async () => {+ it('returns a no-op ACK when the step is locked', async () => {mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });mockExecuteStep.mockResolvedValue({locked: true,nextStepScheduled: false,state: {},- success: false,+ success: true,});const { ctx, getCaptures } = buildContext({ body: validBody });const res = await runStep(ctx);- expect(res.status).toBe(429);+ expect(res.status).toBe(200);const captured = getCaptures()[0];- expect(captured.body).toMatchObject({- error: 'Step is currently being executed, retry later',+ expect(captured.body).toEqual({+ locked: true,+ nextStepScheduled: false,operationId: 'op-1',stepIndex: 2,+ success: true,});- expect(captured.headers).toEqual({ 'Retry-After': '37' });+ expect(captured.headers).toBeUndefined();});it('forwards the upstash-retried header to executeStep as externalRetryCount', async () => {diff --git a/src/server/agent-hono/handlers/runStep.ts b/src/server/agent-hono/handlers/runStep.tsindex 2736ee6f163..feaeeb6e2e2 100644--- a/src/server/agent-hono/handlers/runStep.ts+++ b/src/server/agent-hono/handlers/runStep.ts@@ -150,14 +150,17 @@ export async function runStep(c: Context): Promise<Response> {verifyAsyncToolBarrier,});- // Step is currently being executed by another instance β tell QStash to retry later+ // Step is currently being executed by another instance. ACK duplicate+ // at-least-once deliveries so QStash does not amplify them into retries.if (result.locked) {- log(`[${operationId}] Step ${stepIndex} locked by another instance, returning 429`);- return c.json(- { error: 'Step is currently being executed, retry later', operationId, stepIndex },- 429,- { 'Retry-After': '37' },- );+ log(`[${operationId}] Step ${stepIndex} locked by another instance, returning no-op ACK`);+ return c.json({+ locked: true,+ nextStepScheduled: false,+ operationId,+ stepIndex,+ success: true,+ });}const executionTime = Date.now() - startTime;