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.

⚡️ perf(agent-runtime): read status without loading the state blob (#23210)

YuTengjing4a6961585f21
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index 5bafad7de40..fbe2c2d6c87 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -199,14 +199,21 @@ export class AgentRuntimeCoordinator {
*/
async saveAgentState(operationId: string, state: AgentState): Promise<void> {
try {
- const previousState = await this.stateManager.loadAgentState(operationId);
+ // Only the status is compared, so read it without the state blob. A
+ // state saved without `stepCount` still takes the step index from the
+ // previous blob; that rare case is the only one that downloads it.
+ const previousStatus = await this.stateManager.loadAgentStatus(operationId);
+ const previousStepCount =
+ state.stepCount === undefined
+ ? (await this.stateManager.loadAgentState(operationId))?.stepCount
+ : undefined;
// Save state
await this.stateManager.saveAgentState(operationId, state);
// Send a terminal event once the operation first enters a terminal state.
- if (hasEnteredStreamEndState(previousState?.status, state.status)) {
- const stepIndex = state.stepCount ?? previousState?.stepCount ?? 0;
+ if (hasEnteredStreamEndState(previousStatus ?? undefined, state.status)) {
+ const stepIndex = state.stepCount ?? previousStepCount ?? 0;
const messagePatchMode = this.resolveMessagePatchMode(state);
if (!hasVisibleOutputEndPublished(state)) {
await this.publishVisibleOutputEnd(operationId, state, stepIndex);
@@ -232,19 +239,18 @@ export class AgentRuntimeCoordinator {
*/
async saveStepResult(operationId: string, stepResult: StepResult): Promise<void> {
try {
- // Get previous state for detecting state changes
- const previousState = await this.stateManager.loadAgentState(operationId);
+ // Only the previous status is needed to detect the terminal transition.
+ const previousStatus = await this.stateManager.loadAgentStatus(operationId);
// Save step result
await this.stateManager.saveStepResult(operationId, stepResult);
// This ensures agent_runtime_end is sent after all step events.
- if (hasEnteredStreamEndState(previousState?.status, stepResult.newState.status)) {
+ if (hasEnteredStreamEndState(previousStatus ?? undefined, stepResult.newState.status)) {
// Example: call_llm step 3 can early-publish visible_output_end, then
// finish step 4 enters done. Keep terminal stepIndex for end payloads,
// but suppress visible_output_end once the operation marker exists.
- const stepIndex =
- stepResult.stepIndex ?? stepResult.newState.stepCount ?? previousState?.stepCount ?? 0;
+ const stepIndex = stepResult.stepIndex ?? stepResult.newState.stepCount ?? 0;
const messagePatchMode = this.resolveMessagePatchMode(stepResult.newState);
if (!hasVisibleOutputEndPublished(stepResult.newState)) {
await this.publishVisibleOutputEnd(operationId, stepResult.newState, stepIndex);
@@ -276,6 +282,13 @@ export class AgentRuntimeCoordinator {
return this.stateManager.loadAgentState(operationId);
}
+ /**
+ * Get only the persisted status, without loading the state blob.
+ */
+ async loadAgentStatus(operationId: string): Promise<AgentState['status'] | null> {
+ return this.stateManager.loadAgentStatus(operationId);
+ }
+
/**
* Set the interrupt sentinel so pollers can observe the stop request
* without loading the full state blob.
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 8f9e1cc9116..a3e095b8c06 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -394,18 +394,23 @@ export class AgentStateManager {
const { stripToolSet } = persistOptions;
if (stripToolSet) await this.externalizeToolSet(operationId, state);
const serializedState = this.serializeStateForPersist(state, persistOptions);
- await this.redis.setex(stateKey, this.DEFAULT_TTL, serializedState);
+ // One MULTI, like `saveStepResult`: `loadAgentStatus` reads the status
+ // from the metadata hash, so it must never disagree with the blob.
+ const pipeline = this.redis.multi();
+ pipeline.setex(stateKey, this.DEFAULT_TTL, serializedState);
// Keep the externalized tool set alive in lockstep with the blob so a
// long run never loads a stripped blob whose tool set has expired.
- if (stripToolSet) await this.redis.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
-
- // Update metadata
- await this.updateOperationMetadata(operationId, {
+ if (stripToolSet) pipeline.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
+ const metaKey = `${this.METADATA_PREFIX}:${operationId}`;
+ const metadata: Partial<AgentOperationMetadata> = {
lastActiveAt: new Date().toISOString(),
status: state.status,
totalCost: state.cost?.total || 0,
totalSteps: getLlmCallCount(state),
- });
+ };
+ pipeline.hmset(metaKey, metadata as any);
+ pipeline.expire(metaKey, this.DEFAULT_TTL);
+ await pipeline.exec();
// State change events are recorded through the events array in saveStepResult
@@ -445,6 +450,18 @@ export class AgentStateManager {
}
}
+ /**
+ * Read only the persisted status. Both save paths write it to the metadata
+ * hash in the same MULTI as the blob, so this is the blob's status without
+ * downloading the blob, which can run to hundreds of KB. Falls back to the blob
+ * only when the hash has no status field.
+ */
+ async loadAgentStatus(operationId: string): Promise<AgentState['status'] | null> {
+ const status = await this.redis.hget(`${this.METADATA_PREFIX}:${operationId}`, 'status');
+ if (status) return status as AgentState['status'];
+ return (await this.loadAgentState(operationId))?.status ?? null;
+ }
+
/**
* Set the interrupt sentinel. The full state blob can run to hundreds of
* KB (tool manifests, user memory, …), so the step-abort poller checks
@@ -661,37 +678,6 @@ export class AgentStateManager {
}
}
- /**
- * Update operation metadata
- */
- private async updateOperationMetadata(
- operationId: string,
- updates: Partial<AgentOperationMetadata>,
- ): Promise<void> {
- const metaKey = `${this.METADATA_PREFIX}:${operationId}`;
-
- try {
- const redisUpdates: Record<string, string> = {};
-
- Object.entries(updates).forEach(([key, value]) => {
- if (value !== undefined) {
- if (typeof value === 'object') {
- redisUpdates[key] = JSON.stringify(value);
- } else {
- redisUpdates[key] = value.toString();
- }
- }
- });
-
- if (Object.keys(redisUpdates).length > 0) {
- await this.redis.hmset(metaKey, redisUpdates);
- await this.redis.expire(metaKey, this.DEFAULT_TTL);
- }
- } catch (error) {
- console.error('Failed to update session metadata:', error);
- }
- }
-
/**
* Delete all data for Agent operation
*/
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index 8468743a28a..a446a48d573 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -50,6 +50,10 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
return normalizeAgentState(structuredClone(state));
}
+ async loadAgentStatus(operationId: string): Promise<AgentState['status'] | null> {
+ return this.states.get(operationId)?.status ?? null;
+ }
+
async saveStepResult(operationId: string, stepResult: StepResult): Promise<void> {
// Save latest state
// Use JSON round-trip instead of structuredClone to safely handle
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index fd797c749e7..c7a030ced22 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -41,6 +41,7 @@ describe('AgentRuntimeCoordinator', () => {
getStats: vi.fn(),
isInterrupted: vi.fn(),
loadAgentState: vi.fn(),
+ loadAgentStatus: vi.fn(),
markInterrupted: vi.fn(),
hasQueuedMessages: vi.fn(),
setQueuedMessages: vi.fn(),
@@ -125,10 +126,11 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'done', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState(operationId, newState as any);
+ expect(mockStateManager.loadAgentState).not.toHaveBeenCalled();
expect(mockStateManager.saveAgentState).toHaveBeenCalledWith(operationId, newState);
expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({
finalState: newState,
@@ -146,7 +148,7 @@ describe('AgentRuntimeCoordinator', () => {
const error = new Error('redis down');
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
mockStreamManager.publishStreamEvent.mockRejectedValueOnce(error);
try {
@@ -169,7 +171,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { error: { message: 'boom' }, status: 'error', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState(operationId, newState as any);
@@ -187,6 +189,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { error: { message: 'boom' }, status: 'error' };
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
mockStateManager.loadAgentState.mockResolvedValue(previousState);
await coordinator.saveAgentState(operationId, newState as any);
@@ -205,7 +208,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'interrupted', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState(operationId, newState as any);
@@ -223,7 +226,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'waiting_for_human', stepCount: 4 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState(operationId, newState as any);
@@ -241,7 +244,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'waiting_for_async_tool', stepCount: 4 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState(operationId, newState as any);
@@ -254,7 +257,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'done', stepCount: 5 };
const newState = { status: 'error', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState(operationId, newState as any);
@@ -267,7 +270,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'idle', stepCount: 0 };
const newState = { status: 'running', stepCount: 1 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState(operationId, newState as any);
@@ -286,11 +289,13 @@ describe('AgentRuntimeCoordinator', () => {
};
// Mock previous state as running
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
- expect(mockStateManager.loadAgentState).toHaveBeenCalledWith(operationId);
+ // Only the previous status is read; the state blob is not downloaded.
+ expect(mockStateManager.loadAgentStatus).toHaveBeenCalledWith(operationId);
+ expect(mockStateManager.loadAgentState).not.toHaveBeenCalled();
expect(mockStateManager.saveStepResult).toHaveBeenCalledWith(operationId, stepResult);
expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith({
finalState: stepResult.newState,
@@ -311,7 +316,7 @@ describe('AgentRuntimeCoordinator', () => {
const error = new Error('redis down');
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
mockStreamManager.publishStreamEvent.mockRejectedValueOnce(error);
try {
@@ -341,7 +346,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 5,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -370,7 +375,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 0,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 0 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -399,7 +404,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 5,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -424,7 +429,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 5,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -445,7 +450,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 5,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -466,7 +471,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 4,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 3 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -487,7 +492,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 4,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 3 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -503,7 +508,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 5,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -524,7 +529,7 @@ describe('AgentRuntimeCoordinator', () => {
stepIndex: 3,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 2 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -541,7 +546,7 @@ describe('AgentRuntimeCoordinator', () => {
};
// Mock previous state as already done
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'done', stepCount: 5 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('done');
await coordinator.saveStepResult(operationId, stepResult as any);
@@ -628,7 +633,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'done', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
const savePromise = coordinatorWithResolver.saveAgentState('op-1', newState as any);
@@ -656,7 +661,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'done', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinatorWithResolver.saveAgentState('op-1', newState as any);
@@ -682,7 +687,7 @@ describe('AgentRuntimeCoordinator', () => {
newState: { status: 'done', stepCount: 4 },
stepIndex: 4,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 3 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinatorWithResolver.saveStepResult('op-2', stepResult as any);
@@ -708,7 +713,7 @@ describe('AgentRuntimeCoordinator', () => {
newState: { status: 'done', stepCount: 4 },
stepIndex: 4,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 3 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinatorWithResolver.saveStepResult('op-patch', stepResult as any);
@@ -731,7 +736,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'error', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinatorWithResolver.saveAgentState('op-3', newState as any);
@@ -751,7 +756,7 @@ describe('AgentRuntimeCoordinator', () => {
// legacy call sites stay unaffected.
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'done', stepCount: 5 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinator.saveAgentState('op-4', newState as any);
@@ -777,7 +782,7 @@ describe('AgentRuntimeCoordinator', () => {
const previousState = { status: 'running', stepCount: 3 };
const newState = { status: 'interrupted', stepCount: 3 };
- mockStateManager.loadAgentState.mockResolvedValue(previousState);
+ mockStateManager.loadAgentStatus.mockResolvedValue(previousState.status);
await coordinatorWithResolver.saveAgentState('op-int-1', newState as any);
@@ -804,7 +809,7 @@ describe('AgentRuntimeCoordinator', () => {
newState: { status: 'interrupted', stepCount: 2 },
stepIndex: 2,
};
- mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 1 });
+ mockStateManager.loadAgentStatus.mockResolvedValue('running');
await coordinatorWithResolver.saveStepResult('op-int-2', stepResult as any);
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index 2474f47e1ad..10d0964c057 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -21,6 +21,7 @@ const { redisMock, pipelineMock } = vi.hoisted(() => {
exists: vi.fn(),
expire: vi.fn(),
get: vi.fn(),
+ hget: vi.fn(),
hgetall: vi.fn(),
hmset: vi.fn(),
keys: vi.fn(),
@@ -109,6 +110,28 @@ describe('AgentStateManager', () => {
await expect(stateManager.saveAgentState(operationId, state as any)).resolves.not.toThrow();
});
+ it('writes the status to the metadata hash in the same MULTI as the blob', async () => {
+ await stateManager.saveAgentState('op-meta', {
+ cost: { total: 2 },
+ status: 'interrupted',
+ stepCount: 3,
+ } as any);
+
+ expect(redisMock.multi).toHaveBeenCalledTimes(1);
+ expect(pipelineMock.setex).toHaveBeenCalledWith(
+ 'agent_runtime_state:op-meta',
+ 2 * 3600,
+ expect.any(String),
+ );
+ expect(pipelineMock.hmset).toHaveBeenCalledWith(
+ 'agent_runtime_meta:op-meta',
+ expect.objectContaining({ status: 'interrupted', totalCost: 2 }),
+ );
+ expect(pipelineMock.exec).toHaveBeenCalledTimes(1);
+ expect(redisMock.setex).not.toHaveBeenCalled();
+ expect(redisMock.hmset).not.toHaveBeenCalled();
+ });
+
it('omits the messages array from the persisted state blob', async () => {
const state = {
cost: { total: 1 },
@@ -120,7 +143,7 @@ describe('AgentStateManager', () => {
await stateManager.saveAgentState('op-strip', state as any);
- const serialized = redisMock.setex.mock.calls.at(-1)?.[2] as string;
+ const serialized = pipelineMock.setex.mock.calls.at(-1)?.[2] as string;
expect(JSON.parse(serialized).messages).toBeUndefined();
// Other fields are retained.
expect(JSON.parse(serialized).status).toBe('running');
@@ -132,7 +155,7 @@ describe('AgentStateManager', () => {
const messages = [{ content: 'private transcript', id: 'private-1', role: 'user' }];
const state = { messages, origin, status: 'running', stepCount: 1 };
await stateManager.saveAgentState('private-op', state as any);
- const serialized = redisMock.setex.mock.calls.at(-1)?.[2] as string;
+ const serialized = pipelineMock.setex.mock.calls.at(-1)?.[2] as string;
expect(JSON.parse(serialized).messages).toEqual(messages);
await stateManager.saveStepResult('private-op', {
@@ -159,13 +182,38 @@ describe('AgentStateManager', () => {
await stateManager.saveAgentState('op-ephemeral', state as any);
- const serialized = redisMock.setex.mock.calls.at(-1)?.[2] as string;
+ const serialized = pipelineMock.setex.mock.calls.at(-1)?.[2] as string;
const persisted = JSON.parse(serialized);
expect(persisted.messages).toHaveLength(2);
expect(persisted.messages[1].content).toBe('respond to the group');
});
});
+ describe('loadAgentStatus', () => {
+ it('reads the status from the metadata hash without loading the blob', async () => {
+ redisMock.hget.mockResolvedValueOnce('interrupted');
+
+ await expect(stateManager.loadAgentStatus('op-status')).resolves.toBe('interrupted');
+ expect(redisMock.hget).toHaveBeenCalledWith('agent_runtime_meta:op-status', 'status');
+ expect(redisMock.get).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the blob when the hash has no status', async () => {
+ redisMock.hget.mockResolvedValueOnce(null);
+ redisMock.get.mockResolvedValueOnce(JSON.stringify({ status: 'done', stepCount: 2 }));
+
+ await expect(stateManager.loadAgentStatus('op-legacy')).resolves.toBe('done');
+ expect(redisMock.get).toHaveBeenCalledWith('agent_runtime_state:op-legacy');
+ });
+
+ it('returns null when neither the hash nor the blob exists', async () => {
+ redisMock.hget.mockResolvedValueOnce(null);
+ redisMock.get.mockResolvedValueOnce(null);
+
+ await expect(stateManager.loadAgentStatus('op-missing')).resolves.toBeNull();
+ });
+ });
+
describe('saveStepResult', () => {
it('should save step result successfully when status is done', async () => {
const operationId = 'test-operation-id';
@@ -269,7 +317,7 @@ describe('AgentStateManager', () => {
2 * 3600,
JSON.stringify(toolSet),
);
- const blob = redisMock.setex.mock.calls.find(
+ const blob = pipelineMock.setex.mock.calls.find(
(c) => c[0] === 'agent_runtime_state:op-ots-strip',
);
expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
@@ -287,7 +335,7 @@ describe('AgentStateManager', () => {
(c) => c[0] === `agent_runtime_toolset:${op}`,
);
expect(writes).toHaveLength(1);
- expect(redisMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
+ expect(pipelineMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
});
it('refreshes the tool-set TTL inside the step pipeline and strips the blob', async () => {
@@ -364,11 +412,11 @@ describe('AgentStateManager', () => {
expect(redisMock.setex.mock.calls.some((c) => c[0] === `agent_runtime_toolset:${op}`)).toBe(
false,
);
- expect(redisMock.expire).not.toHaveBeenCalledWith(
+ expect(pipelineMock.expire).not.toHaveBeenCalledWith(
`agent_runtime_toolset:${op}`,
expect.anything(),
);
- const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
expect(JSON.parse(blob![2] as string).operationToolSet).toEqual(toolSet);
});
@@ -428,8 +476,8 @@ describe('AgentStateManager', () => {
2 * 3600,
JSON.stringify(toolSet),
);
- expect(redisMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
- const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(pipelineMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
+ const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
});
@@ -466,8 +514,8 @@ describe('AgentStateManager', () => {
stepIndex: 1,
} as any);
- const saveBlob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
- const stepBlob = pipelineMock.setex.mock.calls.find(
+ // Both saves write the blob through a MULTI: saveAgentState first.
+ const [saveBlob, stepBlob] = pipelineMock.setex.mock.calls.filter(
(c) => c[0] === `agent_runtime_state:${op}`,
);
expect(saveBlob![2]).toBe(JSON.stringify(state));
@@ -475,10 +523,6 @@ describe('AgentStateManager', () => {
expect(redisMock.setex.mock.calls.some((c) => c[0] === `agent_runtime_toolset:${op}`)).toBe(
false,
);
- expect(redisMock.expire).not.toHaveBeenCalledWith(
- `agent_runtime_toolset:${op}`,
- expect.anything(),
- );
expect(pipelineMock.expire).not.toHaveBeenCalledWith(
`agent_runtime_toolset:${op}`,
expect.anything(),
@@ -506,8 +550,7 @@ describe('AgentStateManager', () => {
expect(redisMock.setex.mock.calls.some((c) => c[0] === `agent_runtime_toolset:${op}`)).toBe(
false,
);
- const saveBlob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
- const stepBlob = pipelineMock.setex.mock.calls.find(
+ const [saveBlob, stepBlob] = pipelineMock.setex.mock.calls.filter(
(c) => c[0] === `agent_runtime_state:${op}`,
);
expect(JSON.parse(saveBlob![2] as string).operationToolSet).toEqual(toolSet);
@@ -527,7 +570,7 @@ describe('AgentStateManager', () => {
} as any);
expect(getServerFeatureFlagsStateFromRuntimeConfig).not.toHaveBeenCalled();
- const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
});
@@ -542,7 +585,7 @@ describe('AgentStateManager', () => {
stepCount: 1,
} as any);
- const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
expect(JSON.parse(blob![2] as string).operationToolSet).toEqual(toolSet);
});
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index a2dc5de168d..bf2aae68a2e 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -120,6 +120,13 @@ export interface IAgentStateManager {
*/
loadAgentState: (operationId: string) => Promise<AgentState | null>;
+ /**
+ * Read only the persisted state's `status`. Use it instead of
+ * `loadAgentState` when the status is all the caller needs: the Redis
+ * implementation reads one hash field rather than the whole state blob.
+ */
+ loadAgentStatus: (operationId: string) => Promise<AgentState['status'] | null>;
+
/** Read the inline step loop's parked envelope, if any. */
loadInlineResume: (operationId: string) => Promise<null | string>;
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.credentials.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.credentials.test.ts
index de205f76ab9..d27bee401a0 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.credentials.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.credentials.test.ts
@@ -532,16 +532,17 @@ describe('AgentRuntimeService', () => {
const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };
vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
- mockCoordinator.loadAgentState
- .mockResolvedValueOnce(mockState)
- .mockResolvedValueOnce({ ...mockState, status: 'interrupted' });
+ mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);
+ mockCoordinator.loadAgentStatus.mockResolvedValueOnce('interrupted');
mockCoordinator.isInterrupted.mockResolvedValueOnce(false);
const result = await service.executeStep(mockParams);
expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));
expect(result.nextStepScheduled).toBe(false);
- expect(mockCoordinator.loadAgentState).toHaveBeenCalledTimes(2);
+ // The fallback reads only the status, not a second copy of the blob.
+ expect(mockCoordinator.loadAgentState).toHaveBeenCalledTimes(1);
+ expect(mockCoordinator.loadAgentStatus).toHaveBeenCalledWith('test-operation-1');
expect(mockCoordinator.saveStepResult).toHaveBeenCalledWith(
'test-operation-1',
expect.objectContaining({
@@ -575,9 +576,8 @@ describe('AgentRuntimeService', () => {
},
};
});
- mockCoordinator.loadAgentState
- .mockResolvedValueOnce(mockState)
- .mockResolvedValue({ ...mockState, status: 'interrupted' });
+ mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);
+ mockCoordinator.loadAgentStatus.mockResolvedValue('interrupted');
mockCoordinator.isInterrupted.mockResolvedValue(false);
const execution = service.executeStep(mockParams);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/abortPoll.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/abortPoll.ts
index dd250660a96..1e2fd1d91f5 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/abortPoll.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/abortPoll.ts
@@ -46,10 +46,10 @@ export function startStepAbortPoll(
let lastLegacyInterruptStatePollAt = Date.now();
const pollForAbort = async () => {
try {
- // Prefer the sentinel. During the first rolling deployment, an old
- // worker can still write only the authoritative state, so sample
- // that large blob at a much lower cadence until all writers have
- // sentinel support.
+ // Prefer the sentinel. Some stops (share-run gate, client LLM wait,
+ // intervention) persist `status: 'interrupted'` without it, so also
+ // sample the persisted status at a lower cadence. Only the status is
+ // read, not the whole state blob.
let interrupted = await deps.coordinator.isInterrupted(operationId);
const now = Date.now();
if (
@@ -57,8 +57,7 @@ export function startStepAbortPoll(
now - lastLegacyInterruptStatePollAt >= LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS
) {
lastLegacyInterruptStatePollAt = now;
- interrupted =
- (await deps.coordinator.loadAgentState(operationId))?.status === 'interrupted';
+ interrupted = (await deps.coordinator.loadAgentStatus(operationId)) === 'interrupted';
}
abortPollFailures = 0;
if (interrupted) {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/deferredInit.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/deferredInit.ts
index ad2465b1a1c..e3aea90d8d3 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/deferredInit.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/deferredInit.ts
@@ -60,8 +60,7 @@ const persistStopBeforeInit = async (
operationId: string,
state: AgentState,
): Promise<void> => {
- const alreadyPersisted =
- (await coordinator.loadAgentState(operationId))?.status === 'interrupted';
+ const alreadyPersisted = (await coordinator.loadAgentStatus(operationId)) === 'interrupted';
state.status = 'interrupted';
if (alreadyPersisted) return;
await coordinator.saveAgentState(operationId, {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
index 3daf44a3364..563ef3f0965 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts
@@ -86,13 +86,13 @@ export async function runAndReconcileStep(
// Check if the operation was interrupted while the step was executing
// (e.g., user clicked abort during a long LLM call). Prefer the tiny
- // sentinel, but fall back to the state once at the step boundary while
- // old workers that only write `status: 'interrupted'` may still be
- // running during a rolling deployment.
+ // sentinel, then check the persisted status: some stops (share-run gate,
+ // client LLM wait, intervention) persist `status: 'interrupted'` without
+ // the sentinel. Only the status is read, not the whole state blob.
const sentinelInterrupted = await deps.coordinator.isInterrupted(operationId);
const wasInterrupted = sentinelInterrupted
? true
- : (await deps.coordinator.loadAgentState(operationId))?.status === 'interrupted';
+ : (await deps.coordinator.loadAgentStatus(operationId)) === 'interrupted';
logToolCallPc(operationId, stepIndex, 'post.latest_state_loaded', () => ({
interrupted: wasInterrupted,
}));
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 d9ff01a5c07..918f7856d04 100644
--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
@@ -54,6 +54,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
isInterrupted: vi.fn().mockResolvedValue(false),
hasQueuedMessages: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
+ loadAgentStatus: vi.fn().mockResolvedValue(null),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
saveAgentState: vi.fn(),
saveStepResult: vi.fn(),
diff --git a/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts b/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts
index 2df7000150f..af863d9aeb8 100644
--- a/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/clientLlmWait.test.ts
@@ -25,6 +25,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
hasQueuedMessages: vi.fn().mockResolvedValue(false),
isInterrupted: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
+ loadAgentStatus: vi.fn().mockResolvedValue(null),
markInterrupted: vi.fn().mockResolvedValue(undefined),
refreshStepLock: vi.fn().mockResolvedValue(true),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
index 76ac448b26a..a8cc200faa2 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.agentDocumentIndex.test.ts
@@ -19,6 +19,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
hasQueuedMessages: vi.fn().mockResolvedValue(false),
isInterrupted: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
+ loadAgentStatus: vi.fn().mockResolvedValue(null),
refreshStepLock: vi.fn().mockResolvedValue(true),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
saveAgentState: vi.fn(),
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts
index 4482158cb33..6b86a2e4840 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.ownership.test.ts
@@ -18,6 +18,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
AgentRuntimeCoordinator: vi.fn().mockImplementation(function () {
return {
loadAgentState: vi.fn(),
+ loadAgentStatus: vi.fn().mockResolvedValue(null),
saveAgentState: vi.fn(),
saveStepResult: vi.fn(),
createAgentOperation: vi.fn(),
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 6094754ccaf..6baf2c102f5 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -42,30 +42,9 @@ vi.mock('@/database/models/message', () => ({
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', () =>
+ import('./testUtils').then((m) => m.executeStepAgentRuntimeModule()),
+);
vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({
createRuntimeExecutors: vi.fn(function () {
return {};
diff --git a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
index ea736f5c1ba..ac6b414bfeb 100644
--- a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
@@ -31,6 +31,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
isInterrupted: vi.fn().mockResolvedValue(false),
hasQueuedMessages: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
+ loadAgentStatus: vi.fn().mockResolvedValue(null),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
saveAgentState: vi.fn(),
saveStepResult: vi.fn(),
diff --git a/apps/server/src/services/agentRuntime/__tests__/testUtils.ts b/apps/server/src/services/agentRuntime/__tests__/testUtils.ts
new file mode 100644
index 00000000000..5dbb1eaadab
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/__tests__/testUtils.ts
@@ -0,0 +1,33 @@
+import { vi } from 'vitest';
+
+/**
+ * `@/server/modules/AgentRuntime` replacement for executeStep tests: a stub
+ * coordinator whose step lock always succeeds and whose interrupt checks report
+ * a running operation, plus a no-op stream event manager. Tests override
+ * individual methods on `(service as any).coordinator`.
+ */
+export const executeStepAgentRuntimeModule = () => ({
+ AgentRuntimeCoordinator: vi.fn().mockImplementation(function () {
+ return {
+ createAgentOperation: vi.fn(),
+ getOperationMetadata: vi.fn(),
+ hasQueuedMessages: vi.fn().mockResolvedValue(false),
+ isInterrupted: vi.fn().mockResolvedValue(false),
+ loadAgentState: vi.fn(),
+ loadAgentStatus: vi.fn().mockResolvedValue(null),
+ refreshStepLock: vi.fn().mockResolvedValue(true),
+ releaseStepLock: vi.fn().mockResolvedValue(undefined),
+ saveAgentState: vi.fn(),
+ saveStepResult: vi.fn(),
+ tryClaimStep: vi.fn().mockResolvedValue(true),
+ };
+ }),
+ createStreamEventManager: vi.fn(function () {
+ return {
+ cleanupOperation: vi.fn(),
+ publishAgentRuntimeEnd: vi.fn(),
+ publishAgentRuntimeInit: vi.fn(),
+ publishStreamEvent: vi.fn(),
+ };
+ }),
+});