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): poll a tiny interrupt sentinel instead of the full state blob (#18995)

Arvin Xu4a560271be53
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index ad5d7ec83a0..51e1b07edf7 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -247,6 +247,21 @@ export class AgentRuntimeCoordinator {
return this.stateManager.loadAgentState(operationId);
}
+ /**
+ * Set the interrupt sentinel so pollers can observe the stop request
+ * without loading the full state blob.
+ */
+ async markInterrupted(operationId: string): Promise<void> {
+ return this.stateManager.markInterrupted(operationId);
+ }
+
+ /**
+ * Check the interrupt sentinel.
+ */
+ async isInterrupted(operationId: string): Promise<boolean> {
+ return this.stateManager.isInterrupted(operationId);
+ }
+
/**
* Get operation metadata
*/
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 99b6a10edbc..95271d96159 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -72,6 +72,7 @@ export class AgentStateManager {
private readonly STEPS_PREFIX = 'agent_runtime_steps';
private readonly METADATA_PREFIX = 'agent_runtime_meta';
private readonly EVENTS_PREFIX = 'agent_runtime_events';
+ private readonly INTERRUPT_PREFIX = 'agent_runtime_interrupt';
private readonly DEFAULT_TTL = 2 * 3600; // 2h
constructor() {
@@ -163,6 +164,24 @@ export class AgentStateManager {
}
}
+ /**
+ * Set the interrupt sentinel. The full state blob can run to hundreds of
+ * KB (tool manifests, user memory, …), so the step-abort poller checks
+ * this tiny key instead of re-downloading the blob every interval β€” the
+ * blob's `status: 'interrupted'` stays the authoritative record.
+ */
+ async markInterrupted(operationId: string): Promise<void> {
+ await this.redis.setex(`${this.INTERRUPT_PREFIX}:${operationId}`, this.DEFAULT_TTL, '1');
+ }
+
+ /**
+ * Check the interrupt sentinel without loading the state blob.
+ */
+ async isInterrupted(operationId: string): Promise<boolean> {
+ const exists = await this.redis.exists(`${this.INTERRUPT_PREFIX}:${operationId}`);
+ return exists === 1;
+ }
+
/**
* Save step execution result
*/
@@ -389,6 +408,7 @@ export class AgentStateManager {
`${this.STEPS_PREFIX}:${operationId}`,
`${this.METADATA_PREFIX}:${operationId}`,
`${this.EVENTS_PREFIX}:${operationId}`,
+ `${this.INTERRUPT_PREFIX}:${operationId}`,
];
try {
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index 44b6b7e8316..62dcffb9e4c 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -16,6 +16,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
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 interrupted: Set<string> = new Set();
private executionLockKey(operationId: string): string {
return `agent_runtime_operation_lock:${operationId}`;
@@ -152,11 +153,20 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
log('[%s] Created operation metadata', operationId);
}
+ async markInterrupted(operationId: string): Promise<void> {
+ this.interrupted.add(operationId);
+ }
+
+ async isInterrupted(operationId: string): Promise<boolean> {
+ return this.interrupted.has(operationId);
+ }
+
async deleteAgentOperation(operationId: string): Promise<void> {
this.states.delete(operationId);
this.steps.delete(operationId);
this.metadata.delete(operationId);
this.events.delete(operationId);
+ this.interrupted.delete(operationId);
log('Deleted operation %s', operationId);
}
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index 415aeb15dee..52df665aa5a 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -28,7 +28,9 @@ describe('AgentRuntimeCoordinator', () => {
getExecutionHistory: vi.fn(),
getOperationMetadata: vi.fn(),
getStats: vi.fn(),
+ isInterrupted: vi.fn(),
loadAgentState: vi.fn(),
+ markInterrupted: vi.fn(),
saveAgentState: vi.fn(),
saveStepResult: vi.fn(),
};
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index 109e7f78200..feb5881e3fd 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -16,6 +16,7 @@ const { redisMock, pipelineMock } = vi.hoisted(() => {
const redisMock = {
del: vi.fn(),
eval: vi.fn(),
+ exists: vi.fn(),
expire: vi.fn(),
get: vi.fn(),
hgetall: vi.fn(),
@@ -227,4 +228,35 @@ describe('AgentStateManager', () => {
);
});
});
+
+ describe('interrupt sentinel', () => {
+ it('markInterrupted writes a small sentinel key with the state TTL', async () => {
+ await stateManager.markInterrupted('op-int');
+
+ expect(redisMock.setex).toHaveBeenCalledWith('agent_runtime_interrupt:op-int', 2 * 3600, '1');
+ });
+
+ it('isInterrupted checks key existence instead of loading the state blob', async () => {
+ redisMock.exists.mockResolvedValueOnce(1);
+ expect(await stateManager.isInterrupted('op-int')).toBe(true);
+
+ redisMock.exists.mockResolvedValueOnce(0);
+ expect(await stateManager.isInterrupted('op-int')).toBe(false);
+
+ expect(redisMock.exists).toHaveBeenCalledWith('agent_runtime_interrupt:op-int');
+ expect(redisMock.get).not.toHaveBeenCalled();
+ });
+
+ it('deleteAgentOperation removes the sentinel with the other keys', async () => {
+ await stateManager.deleteAgentOperation('op-del');
+
+ expect(redisMock.del).toHaveBeenCalledWith(
+ 'agent_runtime_state:op-del',
+ 'agent_runtime_steps:op-del',
+ 'agent_runtime_meta:op-del',
+ 'agent_runtime_events:op-del',
+ 'agent_runtime_interrupt:op-del',
+ );
+ });
+ });
});
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
index 9cdf31ff993..4d742c15227 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
@@ -310,6 +310,23 @@ describe('InMemoryAgentStateManager', () => {
// ------------------------------------------------------------------ //
// deleteAgentOperation
// ------------------------------------------------------------------ //
+ describe('interrupt sentinel', () => {
+ it('should report false before markInterrupted and true after', async () => {
+ expect(await manager.isInterrupted('op-int')).toBe(false);
+
+ await manager.markInterrupted('op-int');
+
+ expect(await manager.isInterrupted('op-int')).toBe(true);
+ });
+
+ it('should clear the sentinel when the operation is deleted', async () => {
+ await manager.markInterrupted('op-int');
+ await manager.deleteAgentOperation('op-int');
+
+ expect(await manager.isInterrupted('op-int')).toBe(false);
+ });
+ });
+
describe('deleteAgentOperation', () => {
it('should remove all data for an operation', async () => {
await manager.createOperationMetadata('op-del', { userId: 'u1' });
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 7dda84b0d9a..86a88c0c1a0 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -86,11 +86,23 @@ export interface IAgentStateManager {
totalOperations: number;
}>;
+ /**
+ * Check the interrupt sentinel written by `markInterrupted`. Cheap enough
+ * to poll, unlike `loadAgentState` which pulls the whole state blob.
+ */
+ isInterrupted: (operationId: string) => Promise<boolean>;
+
/**
* Load Agent state
*/
loadAgentState: (operationId: string) => Promise<AgentState | null>;
+ /**
+ * Set the interrupt sentinel for the operation, alongside the
+ * authoritative `status: 'interrupted'` in the persisted state.
+ */
+ markInterrupted: (operationId: string) => Promise<void>;
+
/**
* Extend the step execution lock if it is still owned by the caller.
*/
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 774f1301b81..e081823553f 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -1042,11 +1042,10 @@ describe('AgentRuntimeService', () => {
const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };
vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
- // First call returns running state (for executeStep's initial load),
- // second call returns interrupted state (checked after runtime.step completes)
- mockCoordinator.loadAgentState
- .mockResolvedValueOnce(mockState) // initial load
- .mockResolvedValueOnce({ ...mockState, status: 'interrupted' }); // post-step check
+ // Initial load returns running state; the post-step interrupt check
+ // reads the sentinel instead of the state blob
+ mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);
+ mockCoordinator.isInterrupted.mockResolvedValueOnce(true);
const result = await service.executeStep(mockParams);
@@ -1062,6 +1061,74 @@ describe('AgentRuntimeService', () => {
);
});
+ it('should detect an interruption written by an old worker without a sentinel', async () => {
+ const mockStepResult = {
+ events: [],
+ newState: { ...mockState, status: 'running', stepCount: 2 },
+ nextContext: mockParams.context,
+ };
+
+ 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.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);
+ expect(mockCoordinator.saveStepResult).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({
+ newState: expect.objectContaining({ status: 'interrupted' }),
+ }),
+ );
+ });
+
+ it('should abort a long step when an old worker writes only interrupted state', async () => {
+ vi.useFakeTimers();
+ const mockStepResult = {
+ events: [],
+ newState: { ...mockState, status: 'running', stepCount: 2 },
+ nextContext: mockParams.context,
+ };
+
+ try {
+ vi.spyOn(service as any, 'createAgentRuntime').mockImplementation((...args: unknown[]) => {
+ const { abortSignal } = args[0] as { abortSignal: AbortSignal };
+ return {
+ runtime: {
+ step: vi.fn(
+ () =>
+ new Promise((resolve) => {
+ abortSignal.addEventListener('abort', () => resolve(mockStepResult), {
+ once: true,
+ });
+ }),
+ ),
+ },
+ };
+ });
+ mockCoordinator.loadAgentState
+ .mockResolvedValueOnce(mockState)
+ .mockResolvedValue({ ...mockState, status: 'interrupted' });
+ mockCoordinator.isInterrupted.mockResolvedValue(false);
+
+ const execution = service.executeStep(mockParams);
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(30_000);
+ const result = await execution;
+
+ expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));
+ expect(result.nextStepScheduled).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('should resolve pending client tools when interruption races the parked result', async () => {
const completedTool = {
apiName: 'calculate',
@@ -1113,9 +1180,8 @@ describe('AgentRuntimeService', () => {
step: vi.fn().mockResolvedValueOnce(parkedResult).mockResolvedValueOnce(resolvedResult),
};
vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });
- mockCoordinator.loadAgentState
- .mockResolvedValueOnce(mockState)
- .mockResolvedValueOnce({ ...mockState, status: 'interrupted' });
+ mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);
+ mockCoordinator.isInterrupted.mockResolvedValueOnce(true);
const mixedBatchContext = {
...mockParams.context!,
@@ -1677,6 +1743,19 @@ describe('AgentRuntimeService', () => {
'Operation test-operation-1 is in error state',
);
});
+
+ it('should reject restarting an interrupted operation', async () => {
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ ...mockState,
+ status: 'interrupted',
+ });
+
+ await expect(service.startExecution(mockParams)).rejects.toThrow(
+ 'Operation test-operation-1 is interrupted',
+ );
+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();
+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();
+ });
});
describe('processHumanIntervention', () => {
@@ -1885,6 +1964,13 @@ describe('AgentRuntimeService', () => {
lastModified: expect.any(String),
}),
);
+ expect(mockCoordinator.markInterrupted).toHaveBeenCalledWith('op-1');
+ // Sentinel must land before the state save: the step-boundary check
+ // reads only the sentinel, so state-first ordering would let a check
+ // between the two writes miss the interrupt and clobber it.
+ expect(mockCoordinator.markInterrupted.mock.invocationCallOrder[0]).toBeLessThan(
+ mockCoordinator.saveAgentState.mock.invocationCallOrder[0],
+ );
});
it('should interrupt a waiting_for_human operation', async () => {
@@ -1910,6 +1996,7 @@ describe('AgentRuntimeService', () => {
expect(result).toBe(false);
expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();
+ expect(mockCoordinator.markInterrupted).not.toHaveBeenCalled();
});
it('should return false when operation already done', async () => {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index d3f4452b4a2..845ad488f4b 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -145,6 +145,13 @@ const STEP_LOCK_TTL_SECONDS = 120;
* is the only way a running tool learns it should stop.
*/
const STEP_ABORT_POLL_INTERVAL_MS = 2_000;
+/**
+ * Temporary compatibility cadence for interrupts written by pre-sentinel
+ * workers during a rolling deployment. Remove after every worker writes the
+ * sentinel; keeping this much slower than the sentinel poll preserves most of
+ * the Redis bandwidth reduction in the meantime.
+ */
+const LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS = 30_000;
/** Cap on the exponential backoff multiplier after consecutive poll failures. */
const STEP_ABORT_POLL_MAX_BACKOFF = 8;
const STEP_LOCK_HEARTBEAT_MS = 30_000;
@@ -584,6 +591,17 @@ export class AgentRuntimeService {
return false;
}
+ // Sentinel FIRST: the poller and the step-boundary check read only the
+ // sentinel, so it must become visible no later than the interrupted
+ // state β€” otherwise a boundary check landing between the two writes
+ // reads false and the following saveStepResult clobbers the
+ // interruption. Writing it first also keeps failure atomic: if the
+ // sentinel write throws, the state below is never marked either, so the
+ // two never diverge. A sentinel that lands without the state save
+ // (crash between the writes) only stops the op earlier than the record
+ // shows β€” the step-boundary check then persists the interrupted state.
+ await this.coordinator.markInterrupted(operationId);
+
await this.coordinator.saveAgentState(operationId, {
...state,
lastModified: new Date().toISOString(),
@@ -1745,9 +1763,9 @@ export class AgentRuntimeService {
// Create Agent and Runtime instances
// Use agentState.metadata which contains the full app context (topicId, agentId, etc.)
// operationMetadata only contains basic fields (agentConfig, modelRuntimeConfig, userId)
- // Interrupts arrive as a flag on the persisted state β€” the request that
- // asked for the stop runs in a different invocation, so there is no
- // in-process controller to share. Poll for it while the step is alive
+ // Interrupts arrive as a sentinel key beside the persisted state β€” the
+ // request that asked for the stop runs in a different invocation, so
+ // there is no in-process controller to share. Poll while the step is alive
// and cancel locally, otherwise a multi-minute tool would keep running
// long after the user asked it to stop.
const stepAbortController = new AbortController();
@@ -1757,11 +1775,25 @@ export class AgentRuntimeService {
// spikes exactly when the store is already struggling. Each read is
// scheduled only after the previous one settles, and failures back off.
let abortPollFailures = 0;
+ let lastLegacyInterruptStatePollAt = Date.now();
const pollForAbort = async () => {
try {
- const latest = await this.coordinator.loadAgentState(operationId);
+ // 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.
+ let interrupted = await this.coordinator.isInterrupted(operationId);
+ const now = Date.now();
+ if (
+ !interrupted &&
+ now - lastLegacyInterruptStatePollAt >= LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS
+ ) {
+ lastLegacyInterruptStatePollAt = now;
+ interrupted =
+ (await this.coordinator.loadAgentState(operationId))?.status === 'interrupted';
+ }
abortPollFailures = 0;
- if (latest?.status === 'interrupted') {
+ if (interrupted) {
stepAbortController.abort();
return;
}
@@ -1903,12 +1935,18 @@ export class AgentRuntimeService {
}));
// Check if the operation was interrupted while the step was executing
- // (e.g., user clicked abort during a long LLM call)
- const latestState = await this.coordinator.loadAgentState(operationId);
+ // (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.
+ const sentinelInterrupted = await this.coordinator.isInterrupted(operationId);
+ const wasInterrupted = sentinelInterrupted
+ ? true
+ : (await this.coordinator.loadAgentState(operationId))?.status === 'interrupted';
logToolCallPc(operationId, stepIndex, 'post.latest_state_loaded', () => ({
- interrupted: latestState?.status === 'interrupted',
+ interrupted: wasInterrupted,
}));
- if (latestState?.status === 'interrupted') {
+ if (wasInterrupted) {
// Stop can be persisted after a client-tool executor's last local
// signal check but before this reconciliation read. If that executor
// just returned a parked state, run the agent's existing abort path
@@ -2628,6 +2666,10 @@ export class AgentRuntimeService {
throw new Error(`Operation ${operationId} is in error state`);
}
+ if (currentState.status === 'interrupted') {
+ throw new Error(`Operation ${operationId} is interrupted`);
+ }
+
// Build execution context
let executionContext = context;
if (!executionContext) {
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 92e373eb98f..bd65d368530 100644
--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
@@ -36,6 +36,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({
createAgentOperation: vi.fn(),
getOperationMetadata: vi.fn(),
+ isInterrupted: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
saveAgentState: 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 280d57056ed..c610590fd1a 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -25,6 +25,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
saveStepResult: vi.fn(),
createAgentOperation: vi.fn(),
getOperationMetadata: vi.fn(),
+ isInterrupted: vi.fn().mockResolvedValue(false),
tryClaimStep: vi.fn().mockResolvedValue(true),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
refreshStepLock: vi.fn().mockResolvedValue(true),
diff --git a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
index 0be42ece635..528497dc9dd 100644
--- a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts
@@ -24,6 +24,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({
AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({
createAgentOperation: vi.fn(),
getOperationMetadata: vi.fn(),
+ isInterrupted: vi.fn().mockResolvedValue(false),
loadAgentState: vi.fn(),
releaseStepLock: vi.fn().mockResolvedValue(undefined),
saveAgentState: vi.fn(),