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): stop persisting step events to the reader-less agent_runtime_events list (#19321)

Arvin Xu679380bf56a6
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 95271d96159..a7dc2ef9b80 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -8,7 +8,6 @@ import { type Redis } from 'ioredis';
import { hasNonPersistedMessage } from './messagePersistence';
import { getAgentRuntimeRedisClient } from './redis';
-import { stripFinalStateInEventData } from './StreamEventManager';
const log = debug('lobe-server:agent-runtime:agent-state-manager');
@@ -71,7 +70,6 @@ export class AgentStateManager {
private readonly STATE_PREFIX = 'agent_runtime_state';
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
@@ -212,21 +210,10 @@ export class AgentStateManager {
pipeline.ltrim(stepsKey, 0, 199); // Keep most recent 200 steps
pipeline.expire(stepsKey, this.DEFAULT_TTL);
- // Save step event sequence to agent_runtime_events
- if (stepResult.events && stepResult.events.length > 0) {
- const eventsKey = `${this.EVENTS_PREFIX}:${operationId}`;
-
- // A terminal `done` event carries the full `finalState` (incl. messages
- // + tool-set), so strip those reconstructible fields before persisting —
- // same chokepoint the stream path uses — otherwise this lpush is a
- // second route to Upstash's 10MB limit on long topics.
- pipeline.lpush(
- eventsKey,
- JSON.stringify(stepResult.events.map(stripFinalStateInEventData)),
- );
- pipeline.ltrim(eventsKey, 0, 199); // Keep events from most recent 200 steps
- pipeline.expire(eventsKey, this.DEFAULT_TTL);
- }
+ // `stepResult.events` is intentionally NOT persisted: nothing ever read
+ // the `agent_runtime_events` list back — the same events already reach
+ // clients through the live stream and land durably in the operation
+ // trace, so the list only duplicated every streamed byte into Redis.
// Update operation metadata
const metaKey = `${this.METADATA_PREFIX}:${operationId}`;
@@ -241,12 +228,7 @@ export class AgentStateManager {
await pipeline.exec();
- log(
- '[%s:%d] Saved step result with %d events',
- operationId,
- stepResult.stepIndex,
- stepResult.events?.length || 0,
- );
+ log('[%s:%d] Saved step result', operationId, stepResult.stepIndex);
} catch (error) {
console.error('Failed to save step result:', error);
throw error;
@@ -407,7 +389,6 @@ export class AgentStateManager {
`${this.STATE_PREFIX}:${operationId}`,
`${this.STEPS_PREFIX}:${operationId}`,
`${this.METADATA_PREFIX}:${operationId}`,
- `${this.EVENTS_PREFIX}:${operationId}`,
`${this.INTERRUPT_PREFIX}:${operationId}`,
];
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index 62dcffb9e4c..e437dbb74f4 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -14,7 +14,6 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
private states: Map<string, AgentState> = new Map();
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 interrupted: Set<string> = new Set();
@@ -78,19 +77,6 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
stepHistory.length = 200;
}
- // Save step event sequence
- if (stepResult.events && stepResult.events.length > 0) {
- let eventHistory = this.events.get(operationId);
- if (!eventHistory) {
- eventHistory = [];
- this.events.set(operationId, eventHistory);
- }
- eventHistory.unshift(stepResult.events);
- if (eventHistory.length > 200) {
- eventHistory.length = 200;
- }
- }
-
// Update operation metadata
const existingMeta = this.metadata.get(operationId);
if (existingMeta) {
@@ -100,12 +86,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
existingMeta.totalSteps = stepResult.newState.stepCount;
}
- log(
- '[%s:%d] Saved step result with %d events',
- operationId,
- stepResult.stepIndex,
- stepResult.events?.length || 0,
- );
+ log('[%s:%d] Saved step result', operationId, stepResult.stepIndex);
}
async getExecutionHistory(operationId: string, limit: number = 50): Promise<any[]> {
@@ -165,7 +146,6 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
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);
}
@@ -296,17 +276,9 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
this.states.clear();
this.steps.clear();
this.metadata.clear();
- this.events.clear();
this.stepLocks.clear();
log('All data cleared');
}
-
- /**
- * Get event history (for test verification)
- */
- getEventHistory(operationId: string): any[][] {
- return this.events.get(operationId) ?? [];
- }
}
/**
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index feb5881e3fd..970759cda2d 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -150,7 +150,7 @@ describe('AgentStateManager', () => {
).resolves.not.toThrow();
});
- it('strips messages from both the persisted state and the done-event finalState', async () => {
+ it('strips messages from the persisted state and never persists step events', async () => {
const stepResult = {
events: [
{
@@ -177,12 +177,10 @@ describe('AgentStateManager', () => {
const stateValue = pipelineMock.setex.mock.calls.at(-1)?.[2] as string;
expect(JSON.parse(stateValue).messages).toBeUndefined();
- const eventsValue = pipelineMock.lpush.mock.calls.at(-1)?.[1] as string;
- const persistedEvents = JSON.parse(eventsValue);
- expect(persistedEvents[0].finalState.messages).toBeUndefined();
- // The event envelope itself is preserved.
- expect(persistedEvents[0].type).toBe('done');
- expect(persistedEvents[0].finalState.status).toBe('done');
+ // Events reach clients via the live stream and land in the operation
+ // trace; the Redis list they used to fill had no readers.
+ const lpushKeys = pipelineMock.lpush.mock.calls.map((c) => c[0] as string);
+ expect(lpushKeys).toEqual(['agent_runtime_steps:op-strip-step']);
});
});
@@ -254,7 +252,6 @@ describe('AgentStateManager', () => {
'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 4d742c15227..deca2855112 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryAgentStateManager.test.ts
@@ -191,36 +191,6 @@ describe('InMemoryAgentStateManager', () => {
expect(history.length).toBeLessThanOrEqual(200);
});
- it('should save event history when events are provided', async () => {
- const events = [
- { type: 'text', data: 'hello' },
- { type: 'tool', data: 'run' },
- ];
- const stepResult = makeStepResult({ events });
-
- await manager.saveStepResult('op-ev', stepResult);
-
- const eventHistory = manager.getEventHistory('op-ev');
- expect(eventHistory).toHaveLength(1);
- expect(eventHistory[0]).toEqual(events);
- });
-
- it('should not add to event history when events array is empty', async () => {
- const stepResult = makeStepResult({ events: [] });
- await manager.saveStepResult('op-ev2', stepResult);
-
- const eventHistory = manager.getEventHistory('op-ev2');
- expect(eventHistory).toHaveLength(0);
- });
-
- it('should not add to event history when events is undefined', async () => {
- const stepResult = makeStepResult({ events: undefined });
- await manager.saveStepResult('op-ev3', stepResult);
-
- const eventHistory = manager.getEventHistory('op-ev3');
- expect(eventHistory).toHaveLength(0);
- });
-
it('should update metadata after saving step result', async () => {
await manager.createOperationMetadata('op-meta-update', {});
const stepResult = makeStepResult({
@@ -341,7 +311,6 @@ describe('InMemoryAgentStateManager', () => {
expect(await manager.loadAgentState('op-del')).toBeNull();
expect(await manager.getOperationMetadata('op-del')).toBeNull();
expect(await manager.getExecutionHistory('op-del')).toEqual([]);
- expect(manager.getEventHistory('op-del')).toEqual([]);
});
it('should not throw when deleting a non-existent operation', async () => {
@@ -506,30 +475,7 @@ describe('InMemoryAgentStateManager', () => {
expect(await manager.loadAgentState('op-clear')).toBeNull();
expect(await manager.getOperationMetadata('op-clear')).toBeNull();
expect(await manager.getExecutionHistory('op-clear')).toEqual([]);
- expect(manager.getEventHistory('op-clear')).toEqual([]);
expect(await manager.getActiveOperations()).toEqual([]);
});
});
-
- // ------------------------------------------------------------------ //
- // getEventHistory
- // ------------------------------------------------------------------ //
- describe('getEventHistory', () => {
- it('should return empty array for unknown operationId', () => {
- expect(manager.getEventHistory('no-such')).toEqual([]);
- });
-
- it('should accumulate event history in newest-first order', async () => {
- const events1 = [{ type: 'a' }];
- const events2 = [{ type: 'b' }];
-
- await manager.saveStepResult('op-evhist', makeStepResult({ events: events1 }));
- await manager.saveStepResult('op-evhist', makeStepResult({ events: events2 }));
-
- const history = manager.getEventHistory('op-evhist');
- // newest first (unshift order)
- expect(history[0]).toEqual(events2);
- expect(history[1]).toEqual(events1);
- });
- });
});