🤯 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): run blocking XREAD on a dedicated Redis connection (#17876)
Mark-star-dot0a04d21dc313
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.tsindex 0e2c98ae49a..1d0a2b10fd3 100644--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts@@ -147,6 +147,30 @@ export class StreamEventManager {this.redis = redisClient;}+ /**+ * Run blocking reads on a short-lived duplicated connection. ioredis+ * executes commands on one connection strictly in order, so an+ * `XREAD BLOCK` issued on the shared client parks the connection for up to+ * the block timeout and every concurrent command (XADD / EXPIRE, plus any+ * other module sharing the client) queues behind it — with an SSE+ * subscriber attached, each publish paid up to ~1s, serializing streaming+ * into a chunk-per-second drip.+ *+ * The connection is scoped to the read rather than the instance: managers+ * are constructed per request (`createStreamEventManager()`) and most+ * callers never `disconnect()`, so an instance-held duplicate would leak a+ * socket per request. Scoping also lets concurrent blocking readers block+ * independently instead of queueing on one shared blocking connection.+ */+ private async withBlockingConnection<T>(fn: (conn: Redis) => Promise<T>): Promise<T> {+ const conn = this.redis.duplicate();+ try {+ return await fn(conn);+ } finally {+ conn.disconnect();+ }+ }+/*** Publish stream event to Redis Stream*/@@ -283,78 +307,81 @@ export class StreamEventManager {log('Starting subscription for operation %s from %s', operationId, lastEventId);- while (!signal?.aborted) {- try {- const xreadStart = Date.now();- const results = await this.redis.xread(- 'BLOCK',- 1000, // 1 second timeout- 'STREAMS',- streamKey,- currentLastId,- );- const xreadEnd = Date.now();-- if (results && results.length > 0) {- const [, messages] = results[0];- const events: StreamEvent[] = [];-- for (const [id, fields] of messages) {- const eventData: any = {};-- // Parse Redis Stream fields- for (let i = 0; i < fields.length; i += 2) {- const key = fields[i];- const value = fields[i + 1];-- if (key === 'data') {- eventData[key] = JSON.parse(value);- } else if (key === 'stepIndex' || key === 'timestamp') {- eventData[key] = parseInt(value);- } else {- eventData[key] = value;+ // One dedicated connection for the whole subscription loop.+ await this.withBlockingConnection(async (conn) => {+ while (!signal?.aborted) {+ try {+ const xreadStart = Date.now();+ const results = await conn.xread(+ 'BLOCK',+ 1000, // 1 second timeout+ 'STREAMS',+ streamKey,+ currentLastId,+ );+ const xreadEnd = Date.now();++ if (results && results.length > 0) {+ const [, messages] = results[0];+ const events: StreamEvent[] = [];++ for (const [id, fields] of messages) {+ const eventData: any = {};++ // Parse Redis Stream fields+ for (let i = 0; i < fields.length; i += 2) {+ const key = fields[i];+ const value = fields[i + 1];++ if (key === 'data') {+ eventData[key] = JSON.parse(value);+ } else if (key === 'stepIndex' || key === 'timestamp') {+ eventData[key] = parseInt(value);+ } else {+ eventData[key] = value;+ }}- }- events.push({- ...eventData,- id, // Redis Stream event ID- } as StreamEvent);+ events.push({+ ...eventData,+ id, // Redis Stream event ID+ } as StreamEvent);- currentLastId = id;- }+ currentLastId = id;+ }- if (events.length > 0) {- const now = Date.now();- // Calculate latency from event publication to read- for (const event of events) {- const latency = now - event.timestamp;- timing(- '[%s:%d] XREAD %s, published at %d, read at %d, latency %dms, xread took %dms',- operationId,- event.stepIndex,- event.type,- event.timestamp,- now,- latency,- xreadEnd - xreadStart,- );+ if (events.length > 0) {+ const now = Date.now();+ // Calculate latency from event publication to read+ for (const event of events) {+ const latency = now - event.timestamp;+ timing(+ '[%s:%d] XREAD %s, published at %d, read at %d, latency %dms, xread took %dms',+ operationId,+ event.stepIndex,+ event.type,+ event.timestamp,+ now,+ latency,+ xreadEnd - xreadStart,+ );+ }+ onEvents(events);}- onEvents(events);}- }- } catch (error) {- if (signal?.aborted) {- break;- }+ } catch (error) {+ if (signal?.aborted) {+ break;+ }- console.error('[StreamEventManager] Stream subscription error:', error);- // Retry after brief delay- await new Promise((resolve) => {- setTimeout(resolve, 1000);- });+ console.error('[StreamEventManager] Stream subscription error:', error);+ // Retry after brief delay+ await new Promise((resolve) => {+ setTimeout(resolve, 1000);+ });+ }}- }+ });log('Subscription ended for operation %s', operationId);}@@ -391,7 +418,9 @@ export class StreamEventManager {fromId = tail.length > 0 ? tail[0][0] : '0';}- const results = await this.redis.xread('BLOCK', blockMs, 'STREAMS', streamKey, fromId);+ const results = await this.withBlockingConnection((conn) =>+ conn.xread('BLOCK', blockMs, 'STREAMS', streamKey, fromId),+ );if (!results || results.length === 0) return { events: [], lastEventId: fromId };const [, messages] = results[0];diff --git a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.tsindex 3c801a475a5..acc004963c9 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts@@ -6,9 +6,21 @@ import {stripFinalStateInEventData,} from '../StreamEventManager';-// Mock Redis client+// Mock Redis clients. Blocking reads (`XREAD BLOCK`) must run on a dedicated+// short-lived duplicated connection: ioredis executes commands on one+// connection strictly in order, so a blocking read on the shared client would+// stall every concurrent XADD/EXPIRE behind the block timeout. The duplicate+// is scoped to the read (managers are constructed per request and rarely+// disconnected, so an instance-held duplicate would leak a socket).+const mockBlockingRedis = {+ disconnect: vi.fn(),+ quit: vi.fn(),+ xread: vi.fn(),+};+const mockRedis = {del: vi.fn(),+ duplicate: vi.fn(() => mockBlockingRedis),expire: vi.fn(),keys: vi.fn(),quit: vi.fn(),@@ -302,7 +314,7 @@ describe('StreamEventManager', () => {it("resolves '$' to the current tail and returns it (not '$') on timeout", async () => {// Stream has a tail entry; xread then times out (no newer events).mockRedis.xrevrange.mockResolvedValue([['7-0', ['type', 'stream_chunk']]]);- mockRedis.xread.mockResolvedValue(null);+ mockBlockingRedis.xread.mockResolvedValue(null);const res = await streamManager.readEventsOnce('op-1', '$', 25_000);@@ -314,7 +326,7 @@ describe('StreamEventManager', () => {'COUNT',1,);- expect(mockRedis.xread).toHaveBeenCalledWith(+ expect(mockBlockingRedis.xread).toHaveBeenCalledWith('BLOCK',25_000,'STREAMS',@@ -327,11 +339,11 @@ describe('StreamEventManager', () => {it("resolves '$' on an empty stream to '0'", async () => {mockRedis.xrevrange.mockResolvedValue([]);- mockRedis.xread.mockResolvedValue(null);+ mockBlockingRedis.xread.mockResolvedValue(null);const res = await streamManager.readEventsOnce('op-1', '$');- expect(mockRedis.xread).toHaveBeenCalledWith(+ expect(mockBlockingRedis.xread).toHaveBeenCalledWith('BLOCK',expect.any(Number),'STREAMS',@@ -342,12 +354,12 @@ describe('StreamEventManager', () => {});it('does not resolve an explicit cursor and blocks from it directly', async () => {- mockRedis.xread.mockResolvedValue(null);+ mockBlockingRedis.xread.mockResolvedValue(null);const res = await streamManager.readEventsOnce('op-1', '5-0');expect(mockRedis.xrevrange).not.toHaveBeenCalled();- expect(mockRedis.xread).toHaveBeenCalledWith(+ expect(mockBlockingRedis.xread).toHaveBeenCalledWith('BLOCK',expect.any(Number),'STREAMS',@@ -358,7 +370,7 @@ describe('StreamEventManager', () => {});it('parses events and advances the cursor to the last id', async () => {- mockRedis.xread.mockResolvedValue([+ mockBlockingRedis.xread.mockResolvedValue([['agent_runtime_stream:op-1',[@@ -394,6 +406,60 @@ describe('StreamEventManager', () => {});});+ // Regression: publishes used to share one connection with `XREAD BLOCK`+ // subscribers, so every XADD/EXPIRE queued behind the 1s block timeout and+ // streaming degraded to one chunk per second while any SSE client was+ // attached.+ describe('blocking reads use a dedicated scoped connection', () => {+ it('does not open extra connections at construction (managers are per-request)', () => {+ expect(mockRedis.duplicate).not.toHaveBeenCalled();+ });++ it('keeps writes on the shared client and blocking reads on a scoped duplicate', async () => {+ mockRedis.xadd.mockResolvedValue('event-id-1');+ mockBlockingRedis.xread.mockResolvedValue(null);++ await streamManager.publishStreamChunk('op-1', 0, { chunkType: 'text', content: 'hi' });+ await streamManager.readEventsOnce('op-1', '5-0');++ expect(mockRedis.xadd).toHaveBeenCalledTimes(1);+ expect(mockRedis.duplicate).toHaveBeenCalledTimes(1);+ expect(mockBlockingRedis.xread).toHaveBeenCalledTimes(1);+ expect(mockRedis.xread).not.toHaveBeenCalled();+ });++ it('closes the scoped connection after the read completes', async () => {+ mockBlockingRedis.xread.mockResolvedValue(null);++ await streamManager.readEventsOnce('op-1', '5-0');++ expect(mockBlockingRedis.disconnect).toHaveBeenCalledTimes(1);+ });++ it('closes the scoped connection when the read throws', async () => {+ mockBlockingRedis.xread.mockRejectedValue(new Error('boom'));++ await expect(streamManager.readEventsOnce('op-1', '5-0')).rejects.toThrow('boom');++ expect(mockBlockingRedis.disconnect).toHaveBeenCalledTimes(1);+ });++ it('runs a whole subscription loop on one scoped connection and closes it', async () => {+ const abort = new AbortController();+ mockBlockingRedis.xread.mockImplementation(async () => {+ abort.abort();+ return null;+ });++ await streamManager.subscribeStreamEvents('op-1', '0', () => {}, abort.signal);++ expect(mockRedis.duplicate).toHaveBeenCalledTimes(1);+ expect(mockBlockingRedis.xread).toHaveBeenCalledTimes(1);+ expect(mockRedis.xread).not.toHaveBeenCalled();+ expect(mockBlockingRedis.disconnect).toHaveBeenCalledTimes(1);+ });+ });+describe('stripFinalStateInEventData', () => {it('returns data unchanged when finalState is absent', () => {const data = { phase: 'execution_complete', reason: 'done' };