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): order gateway pushes instead of waiting for them (#19797)

Arvin Xubc90375d8141
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index e4597a3904e..0fb7acc2af4 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -130,9 +130,41 @@ export const pickGatewayInitMeta = (initialState: unknown): GatewayInitMeta | un
* Redis SSE remains the primary event storage / subscription mechanism.
* The Gateway is an additional push channel for WebSocket delivery.
*/
+export interface GatewayStreamNotifierOptions {
+ /**
+ * Let `publishStreamEvent` return before its ordering-barrier pushes
+ * (`stream_end`, `message_patch`) reach the gateway. Only for a caller that
+ * calls `drainPushes` at every point its invocation can be frozen or handed
+ * over β€” otherwise an unawaited push can be lost with the invocation.
+ */
+ deferPushes?: boolean;
+}
+
export class GatewayStreamNotifier implements IStreamEventManager {
private inflight = 0;
+ /**
+ * Gateway pushes issued for an operation that have not settled yet, and the
+ * last ordering barrier among them.
+ *
+ * The step used to await the push of `stream_end` and `message_patch` so the
+ * client could not apply a later event first. That put a gateway round trip
+ * (~250ms, twice per step in production traces) on the path between two
+ * steps. Ordering does not actually need the step to wait β€” it needs the
+ * pushes to leave in order, which these two maps arrange:
+ *
+ * - an ordinary push queues behind the last barrier, and otherwise runs
+ * concurrently with its neighbours, exactly as stream chunks always have;
+ * - a barrier push additionally waits for everything already in flight, so
+ * nothing issued before it can land after it.
+ *
+ * This is strictly stronger than the previous arrangement, where every push
+ * that was not awaited β€” chunks included β€” could overtake one that was.
+ */
+ private pendingPushes = new Map<string, Set<Promise<void>>>();
+
+ private pushBarriers = new Map<string, Promise<void>>();
+
/**
* `operationId β†’ mirrorOperationId`. When an operation declares a
* `mirrorToOperationId` (an in-group broadcast/speak member pointing at its
@@ -198,6 +230,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
private resolvePersistedShareVisitor?: (
operationId: string,
) => Promise<GatewayVisitorRedaction>,
+ private options: GatewayStreamNotifierOptions = {},
) {
log('Gateway notifier initialized: %s', gatewayUrl);
}
@@ -210,15 +243,15 @@ export class GatewayStreamNotifier implements IStreamEventManager {
): Promise<string> {
const result = await this.inner.publishStreamEvent(operationId, event);
const gatewayEvent = { ...event, operationId, timestamp: Date.now() };
- if (event.type === 'stream_end' || event.type === 'message_patch') {
- // `visible_output_end` may be published immediately after `stream_end`.
- // Await ordering boundaries so the client applies stream_end.finalContent
- // before visible_output_end, and its canonical message patch before the
- // following step_start / agent_runtime_end revision check.
- await this.pushEvent(operationId, gatewayEvent);
- } else {
- void this.pushEvent(operationId, gatewayEvent);
- }
+ // `visible_output_end` may be published immediately after `stream_end`.
+ // These two are ordering barriers so the client applies
+ // stream_end.finalContent before visible_output_end, and the canonical
+ // message patch before the following step_start / agent_runtime_end
+ // revision check. Ordering comes from `issuePush`; waiting is only
+ // skipped for a caller that drains before its invocation ends.
+ const barrier = event.type === 'stream_end' || event.type === 'message_patch';
+ const push = this.issuePush(operationId, gatewayEvent, { barrier });
+ if (barrier && !this.options.deferPushes) await push;
return result;
}
@@ -228,7 +261,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
chunkData: StreamChunkData,
): Promise<string> {
const result = await this.inner.publishStreamChunk(operationId, stepIndex, chunkData);
- void this.pushEvent(operationId, {
+ void this.issuePush(operationId, {
data: chunkData,
operationId,
stepIndex,
@@ -290,16 +323,21 @@ export class GatewayStreamNotifier implements IStreamEventManager {
log('Gateway /api/operations/init failed: %O', error);
}
- void this.pushEvent(operationId, {
- // Every run, not just share visitors: nothing on the other end reads this
- // event's data, while the raw `initialState` is the whole `AgentState` β€”
- // the LLM context plus the tool-set maps. See `buildPublicInitEventData`.
- data: buildPublicInitEventData(initialState),
+ void this.issuePush(
operationId,
- stepIndex: 0,
- timestamp: Date.now(),
- type: 'agent_runtime_init',
- });
+ {
+ // Every run, not just share visitors: nothing on the other end reads this
+ // event's data, while the raw `initialState` is the whole `AgentState` β€”
+ // the LLM context plus the tool-set maps. See `buildPublicInitEventData`.
+ data: buildPublicInitEventData(initialState),
+ operationId,
+ stepIndex: 0,
+ timestamp: Date.now(),
+ type: 'agent_runtime_init',
+ },
+ // The run's first event: everything else for this op queues behind it.
+ { barrier: true },
+ );
return result;
}
@@ -361,17 +399,24 @@ export class GatewayStreamNotifier implements IStreamEventManager {
...(uiMessages !== undefined && { uiMessages }),
};
- void this.pushEvent(operationId, {
- // Share-visitor runs must not receive the creator's raw AgentState
- // (world.userMemory / world.agent, systemRole,
- // userInterventionConfig, ...) over their WS channel β€” see
- // `buildPublicEndEventData`.
- data: endRedaction ? buildPublicEndEventData(endEventData) : endEventData,
+ // Terminal, so it is worth waiting for: the run is over and nothing else
+ // will carry this event if the invocation is frozen before the push lands.
+ // As a barrier it also flushes everything the run issued before it.
+ await this.issuePush(
operationId,
- stepIndex,
- timestamp: Date.now(),
- type: 'agent_runtime_end',
- });
+ {
+ // Share-visitor runs must not receive the creator's raw AgentState
+ // (world.userMemory / world.agent, systemRole,
+ // userInterventionConfig, ...) over their WS channel β€” see
+ // `buildPublicEndEventData`.
+ data: endRedaction ? buildPublicEndEventData(endEventData) : endEventData,
+ operationId,
+ stepIndex,
+ timestamp: Date.now(),
+ type: 'agent_runtime_end',
+ },
+ { barrier: true },
+ );
// Terminal event has been forwarded (including any mirror); drop the mapping
// so it can't leak across a reused operationId.
@@ -495,6 +540,58 @@ export class GatewayStreamNotifier implements IStreamEventManager {
await Promise.all(pushes);
}
+ /**
+ * Hand a push to the gateway without making the caller wait for it. Returns a
+ * promise that never rejects, so a failed push cannot poison the order it was
+ * issued in.
+ */
+ private issuePush(
+ operationId: string,
+ event: Record<string, unknown>,
+ options?: { barrier?: boolean },
+ ): Promise<void> {
+ const barrier = this.pushBarriers.get(operationId);
+ const pending = this.pendingPushes.get(operationId) ?? new Set<Promise<void>>();
+ const waitFor = options?.barrier
+ ? Promise.allSettled([...pending, ...(barrier ? [barrier] : [])]).then(() => {})
+ : (barrier ?? Promise.resolve());
+
+ const settled = waitFor.then(() =>
+ this.pushEvent(operationId, event).catch((error) => {
+ log('Gateway push failed for %s (%s): %O', operationId, event.type, error);
+ }),
+ );
+
+ pending.add(settled);
+ this.pendingPushes.set(operationId, pending);
+ void settled.then(() => {
+ pending.delete(settled);
+ if (pending.size === 0 && this.pendingPushes.get(operationId) === pending) {
+ this.pendingPushes.delete(operationId);
+ }
+ if (this.pushBarriers.get(operationId) === settled) this.pushBarriers.delete(operationId);
+ });
+
+ if (options?.barrier) this.pushBarriers.set(operationId, settled);
+
+ return settled;
+ }
+
+ /**
+ * Wait for an operation's issued pushes to reach the gateway. The invocation
+ * that produced them calls this before it can be frozen or handed over β€”
+ * nothing else guarantees an unawaited push survives the end of a request.
+ */
+ async drainPushes(operationId: string): Promise<void> {
+ // A settling barrier releases pushes queued behind it, so draining takes a
+ // few rounds; bounded so a pathological producer cannot spin here.
+ for (let round = 0; round < 5; round += 1) {
+ const pending = this.pendingPushes.get(operationId);
+ if (!pending?.size) return;
+ await Promise.allSettled(pending);
+ }
+ }
+
private mirrorPush(mirrorTo: string, event: Record<string, unknown>): Promise<void> {
return this.httpPost('/api/operations/push-event', {
event,
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 5905fd42bbc..15ae248c97f 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -43,6 +43,9 @@ describe('GatewayStreamNotifier', () => {
beforeEach(() => {
vi.clearAllMocks();
+ // `clearAllMocks` keeps implementations, so a test that installs a fetch
+ // that never resolves would otherwise hang whichever test runs next.
+ mockFetch.mockReset().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });
inner = createMockInner();
notifier = new GatewayStreamNotifier(inner, gatewayUrl, serviceToken);
});
@@ -170,6 +173,7 @@ describe('GatewayStreamNotifier', () => {
};
await notifier.publishStreamEvent('op-1', { data, stepIndex: 1, type: 'stream_end' });
+ await notifier.drainPushes('op-1');
const pushed = JSON.parse(mockFetch.mock.calls[0][1].body).event.data;
expect(pushed).toEqual({ finalContent: 'the answer', stepLabel: 'Step 2' });
@@ -181,6 +185,7 @@ describe('GatewayStreamNotifier', () => {
const data = { reasoning: 'dropped', toolsCalling: [] };
await notifier.publishStreamEvent('op-1', { data, stepIndex: 1, type: 'stream_end' });
+ await notifier.drainPushes('op-1');
expect(JSON.parse(mockFetch.mock.calls[0][1].body).event.data).toEqual({});
});
@@ -214,7 +219,9 @@ describe('GatewayStreamNotifier', () => {
});
});
- it('awaits stream_end gateway push before resolving', async () => {
+ it('waits for the stream_end gateway push unless the caller defers pushes', async () => {
+ // Request-scoped callers (hetero ingest, routers) never drain, so the
+ // push must land before publishStreamEvent resolves.
let resolveFetch!: () => void;
mockFetch.mockImplementationOnce(
() =>
@@ -223,28 +230,103 @@ describe('GatewayStreamNotifier', () => {
}),
);
- const result = notifier.publishStreamEvent('op-1', {
- data: { finalContent: 'final answer' },
- stepIndex: 0,
- type: 'stream_end' as const,
- });
- let resolved = false;
- void result.then(() => {
- resolved = true;
- });
+ let published = false;
+ const publish = notifier
+ .publishStreamEvent('op-1', {
+ data: { finalContent: 'final answer' },
+ stepIndex: 0,
+ type: 'stream_end' as const,
+ })
+ .then(() => {
+ published = true;
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(published).toBe(false);
- await Promise.resolve();
+ resolveFetch();
+ await publish;
+ expect(published).toBe(true);
+ });
- expect(mockFetch).toHaveBeenCalledWith(
- `${gatewayUrl}/api/operations/push-event`,
- expect.objectContaining({ method: 'POST' }),
+ it('does not wait for the stream_end gateway push when deferred, but drainPushes does', async () => {
+ const notifier = new GatewayStreamNotifier(
+ inner,
+ gatewayUrl,
+ serviceToken,
+ undefined,
+ undefined,
+ { deferPushes: true },
+ );
+ let resolveFetch!: () => void;
+ mockFetch.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveFetch = () => resolve({ ok: true, text: () => Promise.resolve('') });
+ }),
);
- expect(resolved).toBe(false);
+
+ // The step publishes and moves on: the push is ordered, not awaited.
+ await expect(
+ notifier.publishStreamEvent('op-1', {
+ data: { finalContent: 'final answer' },
+ stepIndex: 0,
+ type: 'stream_end' as const,
+ }),
+ ).resolves.toBe('publishStreamEvent-result');
+
+ let drained = false;
+ const drain = notifier.drainPushes('op-1').then(() => {
+ drained = true;
+ });
+ await Promise.resolve();
+ expect(drained).toBe(false);
resolveFetch();
+ await drain;
+ expect(drained).toBe(true);
+ });
- await expect(result).resolves.toBe('publishStreamEvent-result');
- expect(resolved).toBe(true);
+ it('keeps a barrier behind the pushes issued before it, and ahead of later ones', async () => {
+ const notifier = new GatewayStreamNotifier(
+ inner,
+ gatewayUrl,
+ serviceToken,
+ undefined,
+ undefined,
+ { deferPushes: true },
+ );
+ const order: string[] = [];
+ let releaseChunk!: () => void;
+ mockFetch.mockImplementation((_url: string, init: { body: string }) => {
+ const { type } = JSON.parse(init.body).event;
+ if (type === 'stream_chunk') {
+ return new Promise((resolve) => {
+ releaseChunk = () => {
+ order.push('stream_chunk');
+ resolve({ ok: true, text: () => Promise.resolve('') });
+ };
+ });
+ }
+ order.push(type);
+ return Promise.resolve({ ok: true, text: () => Promise.resolve('') });
+ });
+
+ await notifier.publishStreamChunk('op-1', 0, { chunkType: 'text' } as StreamChunkData);
+ await notifier.publishStreamEvent('op-1', {
+ data: { finalContent: 'done' },
+ stepIndex: 0,
+ type: 'stream_end',
+ });
+ await notifier.publishStreamEvent('op-1', { data: {}, stepIndex: 1, type: 'step_start' });
+
+ // Nothing may pass the barrier while the chunk it waits for is in flight.
+ await Promise.resolve();
+ expect(order).toEqual([]);
+
+ releaseChunk();
+ await notifier.drainPushes('op-1');
+
+ expect(order).toEqual(['stream_chunk', 'stream_end', 'step_start']);
});
it('still returns inner result even if gateway fails', async () => {
diff --git a/apps/server/src/modules/AgentRuntime/factory.ts b/apps/server/src/modules/AgentRuntime/factory.ts
index 757d732dede..57422230890 100644
--- a/apps/server/src/modules/AgentRuntime/factory.ts
+++ b/apps/server/src/modules/AgentRuntime/factory.ts
@@ -3,7 +3,7 @@ import debug from 'debug';
import { appEnv } from '@/envs/app';
import { AgentStateManager } from './AgentStateManager';
-import { GatewayStreamNotifier } from './GatewayStreamNotifier';
+import { GatewayStreamNotifier, type GatewayStreamNotifierOptions } from './GatewayStreamNotifier';
import { FULL_STRIP_REDACTION } from './gatewayVisitorRedaction';
import { inMemoryAgentStateManager } from './InMemoryAgentStateManager';
import { inMemoryStreamEventManager } from './InMemoryStreamEventManager';
@@ -55,7 +55,9 @@ export const createAgentStateManager = (): IAgentStateManager => {
* - If Redis is unavailable and enableQueueAgentRuntime=false (default): InMemoryStreamEventManager
* - If Redis is unavailable and enableQueueAgentRuntime=true: throw
*/
-export const createStreamEventManager = (): IStreamEventManager => {
+export const createStreamEventManager = (
+ options?: GatewayStreamNotifierOptions,
+): IStreamEventManager => {
let manager: IStreamEventManager;
// Prefer Redis whenever it is available so the runtime worker and SSE route
@@ -99,6 +101,7 @@ export const createStreamEventManager = (): IStreamEventManager => {
if (!meta?.streamOwnerUserId) return null;
return meta.visitorRedaction ?? FULL_STRIP_REDACTION;
},
+ options,
);
}
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index ec76d9e60a7..8d7542083c9 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -185,6 +185,13 @@ export interface IStreamEventManager {
*/
disconnect: () => Promise<void>;
+ /**
+ * Wait for the gateway pushes this process issued for an operation to land.
+ * Only the gateway-backed manager has anything to drain; the invocation that
+ * produced the pushes calls it before it can be frozen or handed over.
+ */
+ drainPushes?: (operationId: string) => Promise<void>;
+
/**
* Get count of active operations
*/
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 6aea7ff8225..08a1b58f424 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -496,11 +496,13 @@ export class AgentRuntimeService {
new UserModel(db, userId)
.getUserPreference()
.then((preference) => preference?.lab?.enableGatewayMux === true));
- // Use factory function to auto-select Redis or InMemory implementation
+ // Use factory function to auto-select Redis or InMemory implementation.
+ // Gateway pushes are deferred off the step path: every point where this
+ // invocation can stop or hand the run over calls `drainPushes` first.
this.streamManager =
options?.streamEventManager ??
options?.coordinatorOptions?.streamEventManager ??
- createStreamEventManager();
+ createStreamEventManager({ deferPushes: true });
this.coordinator = new AgentRuntimeCoordinator({
...options?.coordinatorOptions,
messagePatchModeResolver: (state) => this.usesGatewayMessagePatch(state),
@@ -2475,8 +2477,11 @@ export class AgentRuntimeService {
log('[%s][%d] Next step %d deferred to caller', operationId, stepIndex, nextStepIndex);
} else {
// The next step runs in another invocation, which rebuilds the
- // partial from the store β€” it has to see this step.
+ // partial from the store β€” it has to see this step. The gateway
+ // pushes this invocation issued have to land for the same reason:
+ // nothing carries them once it stops running.
await this.traceRecorder.flushPartial();
+ await this.streamManager.drainPushes?.(operationId);
await this.queueService.scheduleMessage({ ...next, endpoint: `${this.baseURL}/run` });
nextStepScheduled = true;
logToolCallPc(operationId, stepIndex, 'post.next_step_scheduled', () => ({
@@ -2718,7 +2723,12 @@ export class AgentRuntimeService {
// Parked runs (human input, async tools) and finished ones are read back
// by a different invocation, so the partial cannot stay in memory only.
// An inline hand-off keeps it: the next step runs on this recorder.
- if (!handedOffInline) await this.traceRecorder.flushPartial();
+ if (!handedOffInline) {
+ await this.traceRecorder.flushPartial();
+ // Same boundary for the stream: an issued push is only guaranteed to
+ // reach the gateway while this invocation is still running.
+ await this.streamManager.drainPushes?.(operationId);
+ }
// The inline step loop keeps the lock across step boundaries β€” releasing
// here would open a window for a stale redelivery to claim it mid-run.
// Its caller releases once, in a `finally`, for the whole invocation.
@@ -2741,8 +2751,10 @@ export class AgentRuntimeService {
}
// The steps this invocation inlined are still only in memory β€” the
- // invocation that picks the run up reads the partial from the store.
+ // invocation that picks the run up reads the partial from the store, and
+ // the gateway pushes it issued have nothing else to carry them.
await this.traceRecorder.flushPartial();
+ await this.streamManager.drainPushes?.(continuation.operationId);
await this.queueService.scheduleMessage({
...continuation,