π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent-runtime): stop persisting messages in Redis state so large ops aren't dropped (#16112)
Arvin Xu2e404e234b39
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.tsindex 360d29ca82c..1775beb6b82 100644--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts@@ -6,7 +6,9 @@ import {import debug from 'debug';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');@@ -60,6 +62,37 @@ export class AgentStateManager {this.redis = redisClient;}+ /**+ * Serialize an AgentState for Redis persistence, dropping the `messages`+ * array first.+ *+ * `messages` is the dominant size driver of the serialized state β long+ * topics inline tool results and base64 media, pushing the blob past+ * Upstash's 10MB single-request limit, which throws and drops the op+ * outright (StateStorePersistError). It is also fully reconstructible: the+ * canonical rows live in the DB and every step rehydrates `state.messages`+ * from there on entry (`AgentRuntimeService.rehydrateStateMessagesFromDB`),+ * while the few out-of-band readers fall back to a DB query. So we never+ * serialize it into the persisted blob.+ *+ * Keep this in sync with the stream-event strip in `StreamEventManager`+ * (`stripStateForStream`) and the `done`-event strip in+ * `OperationTraceRecorder` β all drop the same reconstructible payload.+ *+ * Exception: when the working set carries a non-persisted (ephemeral /+ * suppressed) message β one with no DB row β the array is NOT reconstructible+ * from a query, so persist it in full. These ops are rare and short-lived+ * (group-member supervisor turns); the size win is forgone to avoid losing+ * the prompt.+ */+ private serializeStateForPersist(state: AgentState): string {+ if (hasNonPersistedMessage((state as { messages?: unknown }).messages)) {+ return JSON.stringify(state);+ }+ const { messages: _messages, ...rest } = state as AgentState & { messages?: unknown };+ return JSON.stringify(rest);+ }+/*** Save Agent state*/@@ -67,7 +100,7 @@ export class AgentStateManager {const stateKey = `${this.STATE_PREFIX}:${operationId}`;try {- const serializedState = JSON.stringify(state);+ const serializedState = this.serializeStateForPersist(state);await this.redis.setex(stateKey, this.DEFAULT_TTL, serializedState);// Update metadata@@ -119,7 +152,11 @@ export class AgentStateManager {try {// Save latest stateconst stateKey = `${this.STATE_PREFIX}:${operationId}`;- pipeline.setex(stateKey, this.DEFAULT_TTL, JSON.stringify(stepResult.newState));+ pipeline.setex(+ stateKey,+ this.DEFAULT_TTL,+ this.serializeStateForPersist(stepResult.newState),+ );// Save step historyconst stepsKey = `${this.STEPS_PREFIX}:${operationId}`;@@ -140,7 +177,14 @@ export class AgentStateManager {if (stepResult.events && stepResult.events.length > 0) {const eventsKey = `${this.EVENTS_PREFIX}:${operationId}`;- pipeline.lpush(eventsKey, JSON.stringify(stepResult.events));+ // 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 stepspipeline.expire(eventsKey, this.DEFAULT_TTL);}diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.tsindex dfb0ee8dd2b..51e7f8ffcab 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts@@ -2,26 +2,33 @@ import { describe, expect, it, vi } from 'vitest';import { AgentStateManager } from '../AgentStateManager';-// Mock Redis client-vi.mock('../redis', () => ({- getAgentRuntimeRedisClient: () => ({+// Mock Redis client. Hoisted so individual tests can assert on the exact+// payloads handed to `setex` / `lpush`.+const { redisMock, pipelineMock } = vi.hoisted(() => {+ const pipelineMock = {+ exec: vi.fn(),+ expire: vi.fn(),+ hmset: vi.fn(),+ lpush: vi.fn(),+ ltrim: vi.fn(),+ setex: vi.fn(),+ };+ const redisMock = {del: vi.fn(),expire: vi.fn(),get: vi.fn(),hgetall: vi.fn(),hmset: vi.fn(),keys: vi.fn(),- multi: vi.fn(() => ({- exec: vi.fn(),- expire: vi.fn(),- hmset: vi.fn(),- lpush: vi.fn(),- ltrim: vi.fn(),- setex: vi.fn(),- })),+ multi: vi.fn(() => pipelineMock),quit: vi.fn(),setex: vi.fn(),- }),+ };+ return { pipelineMock, redisMock };+});++vi.mock('../redis', () => ({+ getAgentRuntimeRedisClient: () => redisMock,}));describe('AgentStateManager', () => {@@ -67,6 +74,42 @@ describe('AgentStateManager', () => {await expect(stateManager.saveAgentState(operationId, state as any)).resolves.not.toThrow();});++ it('omits the messages array from the persisted state blob', async () => {+ const state = {+ cost: { total: 1 },+ messages: [{ content: 'x'.repeat(1000), id: 'msg-1', role: 'user' }],+ status: 'running' as const,+ stepCount: 1,+ };++ await stateManager.saveAgentState('op-strip', state as any);++ const serialized = redisMock.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');+ });++ it('keeps the full messages array when an ephemeral (id-less) message is present', async () => {+ const state = {+ cost: { total: 1 },+ messages: [+ { content: 'persisted history', id: 'msg-1', role: 'user' },+ // ephemeral supervisor instruction β never written to the DB (no id)+ { content: 'respond to the group', role: 'user' },+ ],+ status: 'running' as const,+ stepCount: 1,+ };++ await stateManager.saveAgentState('op-ephemeral', state as any);++ const serialized = redisMock.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('saveStepResult', () => {@@ -103,5 +146,40 @@ describe('AgentStateManager', () => {stateManager.saveStepResult(operationId, stepResult as any),).resolves.not.toThrow();});++ it('strips messages from both the persisted state and the done-event finalState', async () => {+ const stepResult = {+ events: [+ {+ finalState: {+ messages: [{ content: 'big assistant answer', role: 'assistant' }],+ status: 'done',+ },+ reason: 'completed',+ type: 'done',+ },+ ],+ executionTime: 1,+ newState: {+ cost: { total: 1 },+ messages: [{ content: 'x'.repeat(1000), id: 'msg-1', role: 'user' }],+ status: 'done' as const,+ stepCount: 1,+ },+ stepIndex: 1,+ };++ await stateManager.saveStepResult('op-strip-step', stepResult as any);++ 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');+ });});});diff --git a/apps/server/src/modules/AgentRuntime/__tests__/messagePersistence.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/messagePersistence.test.tsnew file mode 100644index 00000000000..4b31a385247--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/__tests__/messagePersistence.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { hasNonPersistedMessage } from '../messagePersistence';++describe('hasNonPersistedMessage', () => {+ it('is false when every message has a DB id', () => {+ expect(+ hasNonPersistedMessage([+ { content: 'hi', id: 'm1', role: 'user' },+ { content: 'yo', id: 'm2', role: 'assistant' },+ ]),+ ).toBe(false);+ });++ it('is true when a message has no id (ephemeral / suppressed)', () => {+ expect(+ hasNonPersistedMessage([+ { content: 'persisted', id: 'm1', role: 'user' },+ // group-member supervisor instruction β never written to the DB+ { content: 'respond to the group', role: 'user' },+ ]),+ ).toBe(true);+ });++ it('is false for non-array / empty / nullish inputs', () => {+ expect(hasNonPersistedMessage(undefined)).toBe(false);+ expect(hasNonPersistedMessage(null)).toBe(false);+ expect(hasNonPersistedMessage([])).toBe(false);+ expect(hasNonPersistedMessage('nope')).toBe(false);+ });++ it('ignores malformed entries without a role', () => {+ expect(hasNonPersistedMessage([{ content: 'x' }, null, undefined])).toBe(false);+ });+});diff --git a/apps/server/src/modules/AgentRuntime/messagePersistence.ts b/apps/server/src/modules/AgentRuntime/messagePersistence.tsnew file mode 100644index 00000000000..ee33a64a78d--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/messagePersistence.ts@@ -0,0 +1,15 @@+/**+ * True when `messages` contains an entry with no DB id β a non-persisted+ * (ephemeral / suppressed) message that cannot be reconstructed from a query.+ *+ * The group-member supervisor instruction is the canonical case: it's injected+ * via `suppressUserMessage` + `ephemeralUserMessage`, drives the member's turn,+ * but is deliberately never written as a `role: 'user'` row (so it has a falsy+ * `id`). Ops carrying such a message keep their full working set in Redis+ * instead of being stripped + rehydrated from the DB, which would silently drop+ * the prompt β see `AgentStateManager.serializeStateForPersist` and+ * `AgentRuntimeService.rehydrateStateMessagesFromDB`.+ */+export const hasNonPersistedMessage = (messages: unknown): boolean =>+ Array.isArray(messages) &&+ messages.some((m) => m && typeof m === 'object' && (m as any).role && !(m as any).id);diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.tsindex 27e8bdf89c3..84b7945300e 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts@@ -389,11 +389,15 @@ describe('Multi-Round Tool Execution', () => {expect(assistantGroupMessages).toHaveLength(1);// The assistantGroup children are assistant messages, each with a tools array- // containing the tool calls for that round+ // containing the tool calls for that round. `state.messages` is now rehydrated+ // from the DB on every step (DB is the single source of truth), so the final+ // state reflects the complete conversation: the two tool-call rounds plus the+ // final text answer β all consecutive assistant messages fold into one group.const group = assistantGroupMessages[0] as any;- expect(group.children).toHaveLength(2); // 2 rounds of tool calls+ expect(group.children).toHaveLength(3); // 2 tool-call rounds + final text answer- // Each child should have 2 tools (search + crawl per round)+ // Each child should have 2 tools (search + crawl per round); the final text+ // answer carries none, so the total across all rounds is still 4.const totalToolCalls = group.children.reduce((sum: number, child: any) => sum + (child.tools?.length ?? 0),0,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 34d30b8a006..1ad55324c9e 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -42,6 +42,7 @@ import { appEnv } from '@/envs/app';import { type AgentRuntimeCoordinatorOptions } from '@/server/modules/AgentRuntime';import { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modules/AgentRuntime';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';+import { hasNonPersistedMessage } from '@/server/modules/AgentRuntime/messagePersistence';import {createRuntimeExecutors,type RuntimeExecutorContext,@@ -759,6 +760,15 @@ export class AgentRuntimeService {externalRetryCount,};+ // Rehydrate `messages` from the DB at every step entry. Each step is a+ // separate invocation that loads state fresh from Redis, so this makes+ // the DB the single source of truth for the conversation on every path+ // β not just the async-tool / human-intervention resumes that already+ // refresh below. With this in place the Redis-persisted state no longer+ // needs to carry the (potentially multi-MB) `messages` array, which is+ // what trips Upstash's 10MB single-request limit and drops the op.+ await this.rehydrateStateMessagesFromDB(agentState);+// Enrich invoke_agent span with agent identity now that state is loaded.const stateAgentConfig = agentState.metadata?.agentConfig as{ description?: string | null; title?: string | null } | undefined;@@ -1970,6 +1980,23 @@ export class AgentRuntimeService {// `updateToolMessage` swallows transaction errors into `success: false`,// so the flag must be checked β an unfulfilled message would hold the// parent's barrier forever while the callback acked with 200.+ //+ // A state loaded via the fallback above arrives without `messages` (the+ // persisted Redis blob no longer carries them β see+ // AgentStateManager.serializeStateForPersist), so rehydrate from the DB+ // before reading the sub-agent's final answer. An in-process+ // params.finalState already carries them and skips this.+ if (!failed && finalState && !Array.isArray(finalState.messages)) {+ try {+ finalState.messages = await this.refreshMessagesFromDB(finalState);+ } catch (error) {+ console.error(+ '[%s] sub-agent bridge: failed to refresh messages from DB: %O',+ operationId,+ error,+ );+ }+ }const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];const lastAssistant = [...messages].reverse()@@ -2140,6 +2167,22 @@ export class AgentRuntimeService {);// 1. Backfill this member's anchor.+ // The member's textual answer is only read in delegate mode below; a state+ // loaded via the fallback above arrives without `messages` (dropped from+ // the persisted Redis blob β see AgentStateManager.serializeStateForPersist),+ // so rehydrate from the DB when we actually need them. An in-process+ // params.finalState already carries them and skips this.+ if (!failed && mode !== 'in_group' && finalState && !Array.isArray(finalState.messages)) {+ try {+ finalState.messages = await this.refreshMessagesFromDB(finalState);+ } catch (error) {+ console.error(+ '[%s] group-member bridge: failed to refresh messages from DB: %O',+ operationId,+ error,+ );+ }+ }const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];const lastAssistant = [...messages].reverse()@@ -2324,6 +2367,40 @@ export class AgentRuntimeService {return flatList as AgentState['messages'];}+ /**+ * Overwrite `state.messages` in place with the canonical DB conversation at+ * step entry, making the DB the single source of truth for messages.+ *+ * Guarded against regressions:+ * - Ops carrying a non-persisted (ephemeral / suppressed) message β e.g. the+ * group-member supervisor instruction, which has no DB row β keep their+ * full working set in Redis (see `AgentStateManager.serializeStateForPersist`),+ * so leave the loaded array intact instead of clobbering it with a DB-only+ * view that would drop the prompt.+ * - `state.messages` is guaranteed to end up an array, so a missing-identifier+ * early return or an empty/failed read never hands `undefined` to downstream+ * consumers (e.g. `shouldCompress(state.messages)`).+ * - A populated working set is never replaced with an empty one or on a DB+ * error, so a transient read miss can't blank the conversation mid-op.+ */+ private async rehydrateStateMessagesFromDB(state: AgentState): Promise<void> {+ if (hasNonPersistedMessage(state.messages)) return;++ if (!Array.isArray(state.messages)) state.messages = [];++ if (!state.metadata?.agentId || !state.metadata?.topicId) return;++ try {+ const refreshed = await this.refreshMessagesFromDB(state);+ if (refreshed.length > 0) state.messages = refreshed;+ } catch (error) {+ console.error(+ '[rehydrateStateMessagesFromDB] failed, keeping Redis state snapshot: %O',+ error,+ );+ }+ }+private resolveAsyncToolResumeParentMessageId(messages: AgentState['messages'],pendingTools: ChatToolPayload[],