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): throttle server tools_calling stream chunks to 300ms (#19512)

Arvin Xuf92bf5678924
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmStreamSink.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmStreamSink.test.ts
new file mode 100644
index 00000000000..ad9a3895c45
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmStreamSink.test.ts
@@ -0,0 +1,122 @@
+import type { ChatToolPayload } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { RuntimeExecutorContext } from '../../context';
+import { ServerCallLlmStreamSink } from '../serverCallLlmStreamSink';
+
+const THROTTLE_INTERVAL = 300;
+
+const toolCall = (args: string): ChatToolPayload[] =>
+ [{ apiName: 'write', arguments: args, id: 'call_1', identifier: 'fs', type: 'default' }] as any;
+
+const createSink = () => {
+ const publishStreamChunk = vi.fn().mockResolvedValue('1-0');
+ const ctx = {
+ operationId: 'op-1',
+ stepIndex: 0,
+ streamManager: { publishStreamChunk },
+ } as unknown as RuntimeExecutorContext;
+
+ const sink = new ServerCallLlmStreamSink({ ctx, events: [], operationLogId: 'op-1:0' });
+
+ return { publishStreamChunk, sink };
+};
+
+/** The payload the Nth `publishStreamChunk` call carried. */
+const publishedArgs = (publishStreamChunk: ReturnType<typeof vi.fn>, index: number) =>
+ publishStreamChunk.mock.calls[index][2].toolsCalling[0].arguments;
+
+describe('ServerCallLlmStreamSink tools_calling throttle', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ // The core regression: providers stream tool arguments delta by delta and each
+ // callback carries the FULL accumulated call list, so publishing per delta sent
+ // one Redis XADD + Gateway POST per token with an ever-growing payload.
+ it('collapses a burst of snapshots into a single publish per window', async () => {
+ const { publishStreamChunk, sink } = createSink();
+
+ for (let i = 1; i <= 50; i += 1) sink.queueToolsCalling(toolCall('x'.repeat(i)));
+
+ expect(publishStreamChunk).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+
+ expect(publishStreamChunk).toHaveBeenCalledTimes(1);
+ // Only the newest snapshot matters: `tools_calling` is a full replace on the
+ // client, so the dropped intermediates are lossless.
+ expect(publishedArgs(publishStreamChunk, 0)).toBe('x'.repeat(50));
+ });
+
+ it('publishes at most once per window across a long stream', async () => {
+ const { publishStreamChunk, sink } = createSink();
+
+ // 5 windows' worth of deltas, 10ms apart.
+ for (let i = 1; i <= 150; i += 1) {
+ sink.queueToolsCalling(toolCall('x'.repeat(i)));
+ await vi.advanceTimersByTimeAsync(10);
+ }
+
+ // Unthrottled this would be 150 publishes.
+ expect(publishStreamChunk.mock.calls.length).toBeLessThanOrEqual(6);
+ expect(publishStreamChunk.mock.calls.length).toBeGreaterThan(0);
+ });
+
+ it('ships the final snapshot on the end-of-stream flush', async () => {
+ const { publishStreamChunk, sink } = createSink();
+
+ sink.queueToolsCalling(toolCall('partial'));
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+ sink.queueToolsCalling(toolCall('complete'));
+
+ // Stream ends inside the window — without the explicit flush the completed
+ // tool call would never reach the client.
+ await sink.flushToolsCallingBuffer();
+
+ expect(publishStreamChunk).toHaveBeenCalledTimes(2);
+ expect(publishedArgs(publishStreamChunk, 1)).toBe('complete');
+ });
+
+ it('does not publish twice when the flush races the pending timer', async () => {
+ const { publishStreamChunk, sink } = createSink();
+
+ sink.queueToolsCalling(toolCall('only-once'));
+ await sink.flushToolsCallingBuffer();
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+
+ expect(publishStreamChunk).toHaveBeenCalledTimes(1);
+ });
+
+ // `clearBuffers` runs when an attempt fails and is about to be retried; a
+ // pending snapshot from the dead attempt must not surface on the next one.
+ it('drops a pending snapshot when the buffers are cleared', async () => {
+ const { publishStreamChunk, sink } = createSink();
+
+ sink.queueToolsCalling(toolCall('aborted'));
+ sink.clearBuffers();
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL * 2);
+
+ expect(publishStreamChunk).not.toHaveBeenCalled();
+ });
+
+ it('republishes on the final flush when a throttled publish failed', async () => {
+ const { publishStreamChunk, sink } = createSink();
+ publishStreamChunk.mockRejectedValueOnce(new Error('redis down'));
+
+ sink.queueToolsCalling(toolCall('complete'));
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+
+ // The detached timer swallowed the failure rather than orphaning a rejection.
+ expect(publishStreamChunk).toHaveBeenCalledTimes(1);
+
+ await sink.flushToolsCallingBuffer();
+
+ expect(publishStreamChunk).toHaveBeenCalledTimes(2);
+ expect(publishedArgs(publishStreamChunk, 1)).toBe('complete');
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
index 7650cbbec58..ff496052408 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
@@ -299,14 +299,12 @@ export class ServerCallLlmAttempt {
this.toolCalls = raw;
await this.streamSink.flushTextBuffer();
- await this.ctx.streamManager.publishStreamChunk(
- this.ctx.operationId,
- this.ctx.stepIndex,
- {
- chunkType: 'tools_calling',
- toolsCalling: payload,
- },
- );
+ // Throttled, not published per delta: providers stream tool arguments
+ // token by token and each callback carries the full accumulated call
+ // list, so publishing every one floods Redis and the Gateway with
+ // ever-growing duplicate payloads. The sink coalesces them and always
+ // ships the final snapshot.
+ this.streamSink.queueToolsCalling(payload);
},
},
diagnostics: this.runtimeDiagnostics,
@@ -320,6 +318,10 @@ export class ServerCallLlmAttempt {
await this.streamSink.flushTextBuffer();
await this.streamSink.flushReasoningBuffer();
+ // Ships the final tool-call snapshot before the step's tool lifecycle events
+ // go out, so the client has the complete `tools` array by the time the first
+ // `tool_start` addresses it.
+ await this.streamSink.flushToolsCallingBuffer();
this.streamSink.clearBuffers();
await this.streamSink.waitForImageUploads();
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
index 8803c07e58c..2496f1bdb96 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
@@ -1,5 +1,6 @@
import type { AgentEvent, BlobStore, LLMAttemptContentPart } from '@lobechat/agent-runtime';
import type { Base64ImageData, ContentPartData } from '@lobechat/model-runtime';
+import type { ChatToolPayload } from '@lobechat/types';
import { fileEnv } from '@/envs/file';
import { nanoid } from '@/utils/uuid';
@@ -18,6 +19,26 @@ interface CreateServerCallLlmStreamSinkInput {
const BUFFER_INTERVAL = 300;
+/**
+ * Throttle window for `tools_calling` chunks.
+ *
+ * Providers stream tool-call arguments delta by delta (roughly one per token),
+ * and `parseToolCalls` re-emits the WHOLE accumulated call list every time — so
+ * an unthrottled publish costs one `XADD` + one `EXPIRE` round trip plus a
+ * Gateway POST per token, carrying a payload that grows with every delta. On a
+ * tool call with a few KB of arguments that is thousands of Redis commands and
+ * quadratic bytes, awaited inline in the provider stream: the visible symptom is
+ * a stalled, stuttering stream. Beyond the cost, the Gateway push lane drops
+ * events once `MAX_INFLIGHT` is reached, so flooding it also loses OTHER
+ * chunks (text deltas, which are NOT idempotent) off the live WebSocket path.
+ *
+ * Dropping intermediate frames is lossless here because `tools_calling` is a
+ * full SNAPSHOT, not a delta: the client replaces the message's `tools` array
+ * wholesale on every chunk. Only the newest snapshot matters, and the trailing
+ * flush always ships the final one.
+ */
+const TOOLS_CALLING_THROTTLE_INTERVAL = BUFFER_INTERVAL;
+
const appendTextPart = (parts: ServerCallLlmContentPart[], text: string) => {
const last = parts.at(-1);
if (last && last.type === 'text') {
@@ -47,6 +68,11 @@ export class ServerCallLlmStreamSink {
private readonly stepIndex: number;
private textBuffer = '';
private textBufferTimer: NodeJS.Timeout | null = null;
+ /** In-flight `tools_calling` publish; settles rather than rejects. */
+ private toolsCallingFlush: Promise<void> | null = null;
+ /** Latest un-published `tools_calling` snapshot; `undefined` once flushed. */
+ private toolsCallingSnapshot: ChatToolPayload[] | undefined;
+ private toolsCallingTimer: NodeJS.Timeout | null = null;
constructor({ blobStore, ctx, events, operationLogId }: CreateServerCallLlmStreamSinkInput) {
this.blobStore = blobStore;
@@ -118,6 +144,79 @@ export class ServerCallLlmStreamSink {
);
}
+ /**
+ * Queue a `tools_calling` snapshot for a throttled publish. Mirrors
+ * {@link queueText}: the timer stays armed across its own flush, so deltas
+ * arriving during a slow publish collapse into the snapshot instead of
+ * starting a second one. See {@link TOOLS_CALLING_THROTTLE_INTERVAL}.
+ */
+ queueToolsCalling(toolsCalling: ChatToolPayload[]) {
+ this.toolsCallingSnapshot = toolsCalling;
+
+ if (!this.toolsCallingTimer) {
+ this.toolsCallingTimer = setTimeout(async () => {
+ // The throttled publish runs detached from the provider stream, so a
+ // failure here has no caller to reject into. Swallow it: the snapshot is
+ // restored by the flush and the end-of-stream flush republishes it.
+ try {
+ await this.flushToolsCallingBuffer();
+ } catch (error) {
+ log(`[${this.operationLogId}] throttled tools_calling publish failed:`, error);
+ }
+ this.toolsCallingTimer = null;
+ }, TOOLS_CALLING_THROTTLE_INTERVAL);
+ }
+ }
+
+ async flushToolsCallingBuffer() {
+ // Join an in-flight publish before taking the snapshot. The throttle timer
+ // stays armed across its own flush, so the only possible overlap is with
+ // this method called directly (the attempt's end-of-stream flush); joining
+ // keeps snapshots strictly ordered and makes that final call a real barrier
+ // rather than a no-op that leaves a publish floating past the attempt.
+ if (this.toolsCallingFlush) await this.toolsCallingFlush;
+
+ const snapshot = this.toolsCallingSnapshot;
+ this.toolsCallingSnapshot = undefined;
+
+ if (!snapshot) return;
+
+ log(`[${this.operationLogId}] flushToolsCallingBuffer:`, snapshot.length);
+
+ const publishStart = Date.now();
+ const publish = this.streamManager.publishStreamChunk(this.operationId, this.stepIndex, {
+ chunkType: 'tools_calling',
+ toolsCalling: snapshot,
+ });
+ // Settle-only handle for joiners: never rejects, so awaiting it is safe and
+ // the failure is handled once, below, by the caller that owns the publish.
+ const joinable = publish.then(
+ () => {},
+ () => {},
+ );
+ this.toolsCallingFlush = joinable;
+
+ try {
+ await publish;
+ timing(
+ '[%s] flushToolsCallingBuffer published at %d, took %dms, calls: %d',
+ this.operationLogId,
+ publishStart,
+ Date.now() - publishStart,
+ snapshot.length,
+ );
+ } catch (error) {
+ // Put the snapshot back (unless a newer one landed) so the attempt's
+ // end-of-stream flush republishes it. Without this a failed throttled
+ // publish could silently drop the FINAL tool-call payload, which the
+ // unthrottled code path could never do.
+ if (!this.toolsCallingSnapshot) this.toolsCallingSnapshot = snapshot;
+ throw error;
+ } finally {
+ if (this.toolsCallingFlush === joinable) this.toolsCallingFlush = null;
+ }
+ }
+
clearBuffers() {
if (this.textBufferTimer) {
clearTimeout(this.textBufferTimer);
@@ -129,8 +228,14 @@ export class ServerCallLlmStreamSink {
this.reasoningBufferTimer = null;
}
+ if (this.toolsCallingTimer) {
+ clearTimeout(this.toolsCallingTimer);
+ this.toolsCallingTimer = null;
+ }
+
this.textBuffer = '';
this.reasoningBuffer = '';
+ this.toolsCallingSnapshot = undefined;
}
async flushReasoningBuffer() {