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-runtime): retry non-stale lock conflicts (#16832)

Arvin Xu9caeac5bb6c4
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 7d47d0d5a4d..37605d06bd5 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -744,6 +744,34 @@ export class AgentRuntimeService {
stepLockOwner,
);
if (!claimed) {
+ let currentState: AgentState | null | undefined = null;
+ try {
+ currentState = await this.coordinator.loadAgentState(operationId);
+ } catch (error) {
+ log(
+ '[%s][%d] Failed to load state while handling step lock conflict: %O',
+ operationId,
+ stepIndex,
+ error,
+ );
+ }
+
+ const currentStepCount = currentState?.stepCount;
+ if (currentState && typeof currentStepCount === 'number' && currentStepCount > stepIndex) {
+ log(
+ '[%s][%d] Step lock conflict is stale (stepCount=%d), skipping',
+ operationId,
+ stepIndex,
+ currentStepCount,
+ );
+ return {
+ nextStepScheduled: false,
+ state: currentState,
+ stepResult: null,
+ success: true,
+ };
+ }
+
log(
'[%s][%d] Step lock conflict — another instance is executing this step, returning locked',
operationId,
@@ -753,7 +781,7 @@ export class AgentRuntimeService {
locked: true,
nextStepScheduled: false,
state: {},
- success: true,
+ success: false,
};
}
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index f742bb66136..7cf45687fa4 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -247,10 +247,15 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
return service;
};
- it('should return locked=true when tryClaimStep returns false', async () => {
+ it('should return locked=true for a non-stale lock conflict', async () => {
const service = createService();
const coordinator = (service as any).coordinator;
coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({
+ status: 'running',
+ stepCount: 5,
+ lastModified: new Date().toISOString(),
+ });
const result = await service.executeStep({
operationId: 'op-locked',
@@ -258,10 +263,32 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
});
expect(result.locked).toBe(true);
+ expect(result.success).toBe(false);
+ expect(result.nextStepScheduled).toBe(false);
+ expect(coordinator.loadAgentState).toHaveBeenCalledWith('op-locked');
+ expect(coordinator.releaseStepLock).not.toHaveBeenCalled();
+ });
+
+ it('should ack stale duplicate deliveries even when the stale step lock is held', async () => {
+ const service = createService();
+ const coordinator = (service as any).coordinator;
+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({
+ status: 'running',
+ stepCount: 10,
+ lastModified: new Date().toISOString(),
+ });
+
+ const result = await service.executeStep({
+ operationId: 'op-stale-locked',
+ stepIndex: 8,
+ });
+
expect(result.success).toBe(true);
+ expect(result.locked).toBeUndefined();
+ expect(result.stepResult).toBeNull();
expect(result.nextStepScheduled).toBe(false);
- // Should NOT call loadAgentState since lock was not acquired
- expect(coordinator.loadAgentState).not.toHaveBeenCalled();
+ expect(coordinator.releaseStepLock).not.toHaveBeenCalled();
});
it('should skip execution when stepCount > stepIndex (delayed retry after lock TTL)', async () => {
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 42043c197a7..c4141dce98b 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -181,7 +181,8 @@ export interface AgentExecutionParams {
export interface AgentExecutionResult {
/**
* When true, the step was already being executed by another instance (lock conflict).
- * The caller should ACK duplicate queue deliveries as a no-op.
+ * Stale duplicates are handled before returning this; callers should keep
+ * this response retryable so fresh deliveries can run after the lock clears.
*/
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.ts
index bd82c1df332..4cae3fa6837 100644
--- a/src/server/agent-hono/handlers/__tests__/runStep.test.ts
+++ b/src/server/agent-hono/handlers/__tests__/runStep.test.ts
@@ -191,28 +191,26 @@ describe('runStep handler', () => {
);
});
- it('returns a no-op ACK when the step is locked', async () => {
+ it('returns 429 with Retry-After header when the step is locked', async () => {
mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
mockExecuteStep.mockResolvedValue({
locked: true,
nextStepScheduled: false,
state: {},
- success: true,
+ success: false,
});
const { ctx, getCaptures } = buildContext({ body: validBody });
const res = await runStep(ctx);
- expect(res.status).toBe(200);
+ expect(res.status).toBe(429);
const captured = getCaptures()[0];
- expect(captured.body).toEqual({
- locked: true,
- nextStepScheduled: false,
+ expect(captured.body).toMatchObject({
+ error: 'Step is currently being executed, retry later',
operationId: 'op-1',
stepIndex: 2,
- success: true,
});
- expect(captured.headers).toBeUndefined();
+ expect(captured.headers).toEqual({ 'Retry-After': '37' });
});
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.ts
index feaeeb6e2e2..1657fc8a5ae 100644
--- a/src/server/agent-hono/handlers/runStep.ts
+++ b/src/server/agent-hono/handlers/runStep.ts
@@ -150,17 +150,15 @@ export async function runStep(c: Context): Promise<Response> {
verifyAsyncToolBarrier,
});
- // Step is currently being executed by another instance. ACK duplicate
- // at-least-once deliveries so QStash does not amplify them into retries.
+ // A non-stale lock conflict means another delivery is still executing this
+ // operation. Keep the response retryable so QStash redelivers this step.
if (result.locked) {
- log(`[${operationId}] Step ${stepIndex} locked by another instance, returning no-op ACK`);
- return c.json({
- locked: true,
- nextStepScheduled: false,
- operationId,
- stepIndex,
- success: true,
- });
+ 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' },
+ );
}
const executionTime = Date.now() - startTime;