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): refuse to commit a step after its lock is lost (#22524)

Mocha1928b68bb482
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts
index 6556e725897..33b07f1f1d6 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts
@@ -8,6 +8,7 @@ import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorFo
import { CriticalAgentInterventionPersistenceError } from '../../CompletionLifecycle';
import { logToolCallPc } from '../../formalObservation';
+import { StepOwnershipLostError } from '../executionErrors';
import type { AgentRuntimeServiceContext } from '../types';
const log = debug('lobe-server:agent-runtime-service');
@@ -20,7 +21,8 @@ export type StepFailureDeps = Pick<
/**
* A step threw. Record it on the span, persist the error state, settle the
* completion lifecycle and finalize the trace, then rethrow β€” except a failed
- * intervention Review publication, which keeps the run parked for the retry.
+ * intervention Review publication, which keeps the run parked for the retry,
+ * and a lost step lock, which leaves the run to whoever owns it now.
*/
export async function failStep(
deps: StepFailureDeps,
@@ -40,6 +42,14 @@ export async function failStep(
stepStartAt: number;
},
): Promise<never> {
+ // Losing the lock says nothing about the run, only that this attempt may not
+ // commit. Settling it as an error here would end it under its new owner; the
+ // queue redelivers the step instead and the claim decides who runs it.
+ if (error instanceof StepOwnershipLostError) {
+ log('[%s][%d] Step lock lost before commit; leaving the run as it is', operationId, stepIndex);
+ throw error;
+ }
+
const isInterventionPersistenceFailure =
error instanceof CriticalAgentInterventionPersistenceError;
invokeAgentSpan.recordException(error as Error);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
index a277421748a..3035c1a96e1 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts
@@ -8,12 +8,15 @@ import {
} from '@lobechat/observability-otel/modules/agent-runtime';
import debug from 'debug';
+import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
+
import {
type AgentExecutionParams,
type AgentExecutionResult,
type AgentStepContinuation,
} from '../../types';
import { STEP_LOCK_TTL_SECONDS } from '../constants';
+import { StepOwnershipLostError } from '../executionErrors';
import { isShareRunRevoked } from '../shareRunGate';
import type { AgentRuntimeServiceContext } from '../types';
import { createStepLockOwner } from '../utils';
@@ -75,6 +78,42 @@ export type ExecuteStepDeps = Pick<
| 'workspaceId'
>;
+/**
+ * Commit only while this attempt still owns the operation: a step whose LLM
+ * call outlived the lock TTL may have been claimed by a redelivery meanwhile,
+ * and both attempts committing would run two chains of the same operation. A
+ * refresh that cannot reach Redis refuses too.
+ *
+ * Not atomic with the save: a lock that expires between this refresh and the
+ * write can still let a second owner commit. Nor are LLM or tool calls already
+ * in flight interrupted; losing the lock only stops the commit.
+ */
+async function assertStepOwnership(
+ deps: ExecuteStepDeps,
+ operationId: string,
+ stepIndex: number,
+ stepLockOwner: string,
+): Promise<void> {
+ let refreshed: boolean;
+ let cause: unknown;
+ try {
+ refreshed = await deps.coordinator.refreshStepLock(
+ operationId,
+ stepIndex,
+ STEP_LOCK_TTL_SECONDS,
+ stepLockOwner,
+ );
+ } catch (error) {
+ refreshed = false;
+ cause = error;
+ }
+ if (refreshed) return;
+
+ // The new owner records the trace from here; our partial would roll it back.
+ deps.traceRecorder.discardPartial();
+ throw new StepOwnershipLostError(operationId, stepIndex, { cause });
+}
+
/**
* Execute Agent step
*/
@@ -109,6 +148,15 @@ export async function executeStep(
log('[%s][%d] Operation lease refresh failed: %O', operationId, stepIndex, error);
});
const stopStepLockHeartbeat = deps.startStepLockHeartbeat(operationId, stepIndex, stepLockOwner);
+ // Only a queue that redelivers a failed step can retry a refused commit, and
+ // only there can a second delivery own the step at all. The local queue drops
+ // a failed callback and the sync path has no queue: fencing them would strand
+ // the run on a Redis blip.
+ const commitFenced =
+ !!deps.queueService && !(deps.queueService.getImpl() instanceof LocalQueueServiceImpl);
+ const assertOwnership = commitFenced
+ ? () => assertStepOwnership(deps, operationId, stepIndex, stepLockOwner)
+ : undefined;
// Hoisted so the shared `finally` can stop it on every exit path β€” an
// orphaned poll would keep reading Redis for a step that is long gone.
@@ -275,6 +323,7 @@ export async function executeStep(
const { startAt, stepResult } = await runAndReconcileStep(deps, {
...input,
+ assertOwnership,
operationId,
runtime,
stepIndex,
@@ -282,6 +331,7 @@ export async function executeStep(
const { content, shouldContinue, stepPresentationData, toolsCalling } =
await saveAndPublishStep(deps, {
+ assertOwnership,
gatewayMessagePatchEnabled,
operationId,
startAt,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
index 4d3469345cd..3daf44a3364 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
@@ -39,6 +39,7 @@ export type StepPresentation = ReturnType<typeof buildStepPresentation>['present
export async function runAndReconcileStep(
deps: StepRunStepDeps,
{
+ assertOwnership,
currentContext,
currentState,
forcedFinishState,
@@ -46,7 +47,13 @@ export async function runAndReconcileStep(
resumedClientLlmWait,
runtime,
stepIndex,
- }: PreparedStepInput & { operationId: string; runtime: AgentRuntime; stepIndex: number },
+ }: PreparedStepInput & {
+ /** Throws once this attempt no longer owns the operation; absent when commits are not fenced. */
+ assertOwnership?: () => Promise<void>;
+ operationId: string;
+ runtime: AgentRuntime;
+ stepIndex: number;
+ },
): Promise<{ startAt: number; stepResult: StepRunResult }> {
// Execute step (skipped when force-finishing a parked supervisor op).
const startAt = Date.now();
@@ -58,6 +65,10 @@ export async function runAndReconcileStep(
? { events: [], newState: forcedFinishState, nextContext: undefined }
: await runtime.step(currentState, currentContext);
+ // The LLM call is where a step can outlive its lock. Check before anything
+ // below writes on the step's behalf (the client park saves state).
+ await assertOwnership?.();
+
// Inner runtime.step() catches model-runtime exceptions and stuffs the
// raw error into newState.error without re-throwing β€” so the outer
// catch at the bottom of this method never sees them. Normalize +
@@ -145,6 +156,7 @@ export async function runAndReconcileStep(
export async function saveAndPublishStep(
deps: StepRunStepDeps,
{
+ assertOwnership,
gatewayMessagePatchEnabled,
operationId,
startAt,
@@ -152,6 +164,8 @@ export async function saveAndPublishStep(
stepResult,
stepStartUiMessages,
}: {
+ /** Throws once this attempt no longer owns the operation; absent when commits are not fenced. */
+ assertOwnership?: () => Promise<void>;
gatewayMessagePatchEnabled: boolean;
operationId: string;
startAt: number;
@@ -233,7 +247,10 @@ export async function saveAndPublishStep(
log('[%s][%d] Credentials changed in-run; dropped the snapshot', operationId, stepIndex);
}
- // Save state, coordinator will handle event sending automatically
+ // Save state, coordinator will handle event sending automatically. This is
+ // the commit: a redelivery of this step is skipped as already done once it
+ // lands, so only the lock owner may write it.
+ await assertOwnership?.();
await deps.coordinator.saveStepResult(operationId, {
...stepResult,
executionTime: Date.now() - startAt,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executionErrors.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executionErrors.ts
new file mode 100644
index 00000000000..8b1a1686c4c
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executionErrors.ts
@@ -0,0 +1,16 @@
+/**
+ * The step lock was lost, or could not be confirmed, before this attempt
+ * committed the step. It says nothing about the run, only that this attempt
+ * must not commit: `failStep` rethrows it untouched, so the queue redelivers
+ * the step and its claim decides who runs it.
+ */
+export class StepOwnershipLostError extends Error {
+ constructor(
+ public readonly operationId: string,
+ public readonly stepIndex: number,
+ options?: { cause?: unknown },
+ ) {
+ super(`Step ${stepIndex} of operation ${operationId} lost its lock before commit`, options);
+ this.name = 'StepOwnershipLostError';
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
index 119bf308c74..6ba54ce05d5 100644
--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
@@ -46,6 +46,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
saveAgentState: vi.fn(),
saveStepResult: vi.fn(),
tryClaimStep: vi.fn().mockResolvedValue(true),
+ refreshStepLock: vi.fn().mockResolvedValue(true),
};
}),
createStreamEventManager: vi.fn(function () {
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts
new file mode 100644
index 00000000000..85e0e5d1050
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts
@@ -0,0 +1,206 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
+
+import { AgentRuntimeService } from '../AgentRuntimeService';
+import { StepOwnershipLostError } from '../AgentRuntimeService/executionErrors';
+
+// Mock all heavy dependencies to isolate executeStep logic
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return { query: vi.fn().mockResolvedValue([]) };
+ }),
+}));
+vi.mock('@/server/modules/AgentRuntime', () => ({
+ AgentRuntimeCoordinator: vi.fn().mockImplementation(function () {
+ return {
+ loadAgentState: vi.fn(),
+ saveAgentState: vi.fn(),
+ saveStepResult: vi.fn(),
+ createAgentOperation: vi.fn(),
+ getOperationMetadata: vi.fn(),
+ isInterrupted: vi.fn().mockResolvedValue(false),
+ hasQueuedMessages: vi.fn().mockResolvedValue(false),
+ tryClaimStep: vi.fn().mockResolvedValue(true),
+ releaseStepLock: vi.fn().mockResolvedValue(undefined),
+ refreshStepLock: vi.fn().mockResolvedValue(true),
+ };
+ }),
+ createStreamEventManager: vi.fn(function () {
+ return {
+ publishStreamEvent: vi.fn(),
+ publishAgentRuntimeEnd: vi.fn(),
+ publishAgentRuntimeInit: vi.fn(),
+ cleanupOperation: vi.fn(),
+ };
+ }),
+}));
+vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({
+ createRuntimeExecutors: vi.fn(function () {
+ return {};
+ }),
+}));
+vi.mock('@/server/services/mcp', () => ({ mcpService: {} }));
+vi.mock('@/server/services/queue', () => ({
+ QueueService: vi.fn().mockImplementation(function () {
+ return {
+ getImpl: vi.fn(function () {
+ return {};
+ }),
+ scheduleMessage: vi.fn(),
+ };
+ }),
+}));
+vi.mock('@/server/services/queue/impls', () => ({
+ LocalQueueServiceImpl: class {
+ setExecutionCallback() {}
+ },
+}));
+vi.mock('@/server/services/toolExecution', () => ({
+ ToolExecutionService: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+vi.mock('@/server/services/toolExecution/builtin', () => ({
+ BuiltinToolsExecutor: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({
+ dynamicInterventionAudits: [],
+}));
+
+describe('AgentRuntimeService.executeStep - step ownership', () => {
+ // A step whose LLM call outlives the lock TTL can be claimed by a redelivery
+ // while it still runs. Whichever attempt no longer owns the lock must not
+ // commit, or two chains continue the same operation.
+ const runContinuingStep = async (
+ lockStillOwned: () => Promise<boolean>,
+ queue: 'local' | 'none' | 'redelivering' = 'redelivering',
+ ) => {
+ const scheduleMessage = vi.fn().mockResolvedValue('msg-next');
+ const impl = queue === 'local' ? new LocalQueueServiceImpl() : {};
+ const service = new AgentRuntimeService({} as any, 'user-1', {
+ queueService: queue === 'none' ? null : ({ getImpl: () => impl, scheduleMessage } as any),
+ });
+ const coordinator = (service as any).coordinator;
+ const completionLifecycle = (service as any).completionLifecycle;
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({
+ lastModified: new Date().toISOString(),
+ messages: [],
+ metadata: {},
+ status: 'running',
+ stepCount: 3,
+ });
+ coordinator.refreshStepLock = vi.fn(lockStillOwned);
+ vi.spyOn(completionLifecycle, 'emitSignalEvents').mockResolvedValue([]);
+ const dispatchHooks = vi
+ .spyOn(completionLifecycle, 'dispatchHooks')
+ .mockResolvedValue(undefined);
+ const discardPartial = vi.spyOn((service as any).traceRecorder, 'discardPartial');
+ (service as any).createAgentRuntime = vi.fn().mockResolvedValue({
+ runtime: {
+ step: vi.fn().mockResolvedValue({
+ events: [],
+ newState: {
+ lastModified: new Date().toISOString(),
+ messages: [],
+ metadata: {},
+ status: 'running',
+ stepCount: 4,
+ },
+ nextContext: { payload: {}, phase: 'llm_result' },
+ }),
+ },
+ });
+
+ const run = service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-owner',
+ stepIndex: 3,
+ });
+
+ return { coordinator, discardPartial, dispatchHooks, run, scheduleMessage };
+ };
+
+ it('commits and queues the next step while the attempt still owns the lock', async () => {
+ const { coordinator, run, scheduleMessage } = await runContinuingStep(async () => true);
+
+ await expect(run).resolves.toMatchObject({ nextStepScheduled: true, success: true });
+
+ expect(coordinator.saveStepResult).toHaveBeenCalledTimes(1);
+ expect(coordinator.refreshStepLock).toHaveBeenCalledWith(
+ 'op-owner',
+ 3,
+ 120,
+ expect.stringContaining('op-owner:3:'),
+ );
+ // Checked before the commit, not after it.
+ expect(coordinator.refreshStepLock.mock.invocationCallOrder[0]).toBeLessThan(
+ coordinator.saveStepResult.mock.invocationCallOrder[0],
+ );
+ expect(scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ stepIndex: 4 }));
+ });
+
+ it('drops the step when another attempt took the lock during the LLM call', async () => {
+ const { coordinator, discardPartial, dispatchHooks, run, scheduleMessage } =
+ await runContinuingStep(async () => false);
+
+ await expect(run).rejects.toBeInstanceOf(StepOwnershipLostError);
+
+ expect(coordinator.saveStepResult).not.toHaveBeenCalled();
+ expect(scheduleMessage).not.toHaveBeenCalled();
+ // The run belongs to the new owner: no error state, no completion hooks.
+ expect(coordinator.saveAgentState).not.toHaveBeenCalled();
+ expect(dispatchHooks).not.toHaveBeenCalled();
+ // Its trace partial would roll back the steps the new owner records.
+ expect(discardPartial).toHaveBeenCalled();
+ });
+
+ it('drops the step when the lock is lost between the LLM call and the commit', async () => {
+ const owned = [true, false];
+ const { coordinator, run, scheduleMessage } = await runContinuingStep(
+ async () => owned.shift() ?? false,
+ );
+
+ await expect(run).rejects.toBeInstanceOf(StepOwnershipLostError);
+
+ expect(coordinator.saveStepResult).not.toHaveBeenCalled();
+ expect(scheduleMessage).not.toHaveBeenCalled();
+ });
+
+ it('treats a lock that cannot be confirmed as lost', async () => {
+ const { coordinator, run } = await runContinuingStep(async () => {
+ throw new Error('redis down');
+ });
+
+ await expect(run).rejects.toBeInstanceOf(StepOwnershipLostError);
+
+ expect(coordinator.saveStepResult).not.toHaveBeenCalled();
+ expect(coordinator.saveAgentState).not.toHaveBeenCalled();
+ });
+
+ // Without redelivery a refused commit is never retried, and no second
+ // delivery can own the step: fencing would only strand the run.
+ it('keeps committing on a queue that does not redeliver a failed step', async () => {
+ const { coordinator, run, scheduleMessage } = await runContinuingStep(
+ async () => false,
+ 'local',
+ );
+
+ await expect(run).resolves.toMatchObject({ nextStepScheduled: true, success: true });
+
+ expect(coordinator.saveStepResult).toHaveBeenCalledTimes(1);
+ expect(scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({ stepIndex: 4 }));
+ });
+
+ it('keeps committing when steps run without a queue', async () => {
+ const { coordinator, run } = await runContinuingStep(async () => false, 'none');
+
+ await expect(run).resolves.toMatchObject({ success: true });
+
+ expect(coordinator.saveStepResult).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
index 0f57bed99e2..bb500485829 100644
--- a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
@@ -34,6 +34,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
saveAgentState: vi.fn(),
saveStepResult: vi.fn(),
tryClaimStep: vi.fn().mockResolvedValue(true),
+ refreshStepLock: vi.fn().mockResolvedValue(true),
};
}),
createStreamEventManager: vi.fn(function () {