Skip to content

Commit ad1a2cd

Browse files
authored
perf(gateway): per-transcript broadcast lanes (#121104)
* perf(gateway): per-transcript broadcast lanes Transcript-update broadcasts were serialized behind one global promise queue, so one session's pending async seq read head-of-line blocked every other session's session.message and sessions.changed delivery. Ordering is a per-transcript contract, so key the queue by transcript identity and drop drained lanes. Per-message transcript usage stays derived: session.message payloads carry live totalTokens/estimatedCostUsd as a dashboard API contract (#50101). * fix(ui): target the Cloud Worker Desktop labs row in its toggle test The row added in #120727 reused index 6, which belongs to Message audit metadata, so the case toggled the audit row and asserted its patch. Labs features render in registry order, and workerDesktop is the eighth entry.
1 parent af73dbc commit ad1a2cd

3 files changed

Lines changed: 116 additions & 7 deletions

File tree

‎src/gateway/server-session-events.test.ts‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const sessionRow = vi.hoisted(() => ({
1414
agentRuntime: { id: "openclaw", source: "model" },
1515
}));
1616
const isEmbeddedAgentRunInProgressMock = vi.hoisted(() => vi.fn());
17+
const loadGatewaySessionRowMock = vi.hoisted(() => vi.fn());
1718
const projectChatDisplayMessageMock = vi.hoisted(() => vi.fn((message: unknown) => message));
1819
const loadAccessorSessionEntryReadOnlyMock = vi.hoisted(() => vi.fn());
1920
const loadGatewaySessionEntryReadOnlyMock = vi.hoisted(() => vi.fn());
@@ -32,7 +33,7 @@ vi.mock("./chat-display-projection.js", () => ({
3233
}));
3334
vi.mock("./session-utils.js", () => ({
3435
attachOpenClawTranscriptMeta: (message: unknown) => message,
35-
loadGatewaySessionRow: () => sessionRow,
36+
loadGatewaySessionRow: loadGatewaySessionRowMock,
3637
loadSessionEntry: () => ({ entry: undefined, storePath: "" }),
3738
loadSessionEntryReadOnly: loadGatewaySessionEntryReadOnlyMock,
3839
}));
@@ -102,6 +103,7 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
102103
isEmbeddedAgentRunInProgressMock.mockReturnValue(false);
103104
loadAccessorSessionEntryReadOnlyMock.mockReturnValue(undefined);
104105
loadGatewaySessionEntryReadOnlyMock.mockReturnValue({ entry: undefined, storePath: "" });
106+
loadGatewaySessionRowMock.mockReturnValue(sessionRow);
105107
readSessionMessageCountAsyncMock.mockResolvedValue(undefined);
106108
sessionRow.thinkingLevel = "ultra";
107109
});
@@ -550,9 +552,95 @@ describe("createTranscriptUpdateBroadcastHandler", () => {
550552
});
551553
expect(broadcastToConnIds.mock.calls[0]?.[1]).toMatchObject({ messageSeq: 7 });
552554
});
555+
556+
it("does not stall one session's broadcasts behind another session's pending seq read", async () => {
557+
let releaseSlowCount: (value: number | undefined) => void = () => undefined;
558+
readSessionMessageCountAsyncMock.mockImplementation((params: { sessionKey?: string }) =>
559+
params.sessionKey === "agent:main:slow"
560+
? new Promise<number | undefined>((resolve) => {
561+
releaseSlowCount = resolve;
562+
})
563+
: Promise.resolve(3),
564+
);
565+
loadAccessorSessionEntryReadOnlyMock.mockReturnValue({ sessionId: "sess-main" });
566+
const { broadcastToConnIds, handler } = createHandler(false);
567+
568+
// No messageSeq: the slow lane blocks on its async transcript count.
569+
const slowTask = handler({
570+
message: { role: "assistant", content: [{ type: "text", text: "slow" }] },
571+
messageId: "slow-1",
572+
target: {
573+
agentId: "main",
574+
sessionId: "sess-slow",
575+
sessionKey: "agent:main:slow",
576+
storePath: "/tmp/slow-sessions.json",
577+
},
578+
});
579+
580+
await handler({
581+
sessionFile: "/tmp/sess-main.jsonl",
582+
sessionKey: "agent:main:main",
583+
message: { role: "assistant", content: [{ type: "text", text: "fast" }] },
584+
messageId: "fast-1",
585+
messageSeq: 1,
586+
});
587+
588+
// The independent lane broadcast completed while the slow lane is parked.
589+
expect(broadcastToConnIds).toHaveBeenCalledTimes(1);
590+
expect(broadcastToConnIds.mock.calls[0]?.[1]).toMatchObject({ messageId: "fast-1" });
591+
592+
releaseSlowCount(5);
593+
await slowTask;
594+
expect(broadcastToConnIds).toHaveBeenCalledTimes(2);
595+
expect(broadcastToConnIds.mock.calls[1]?.[1]).toMatchObject({ messageId: "slow-1" });
596+
});
597+
598+
it("preserves message order within one session lane", async () => {
599+
let releaseFirstCount: (value: number | undefined) => void = () => undefined;
600+
readSessionMessageCountAsyncMock.mockImplementationOnce(
601+
() =>
602+
new Promise<number | undefined>((resolve) => {
603+
releaseFirstCount = resolve;
604+
}),
605+
);
606+
loadAccessorSessionEntryReadOnlyMock.mockReturnValue({ sessionId: "sess-main" });
607+
const { broadcastToConnIds, handler } = createHandler(false);
608+
609+
const firstTask = handler({
610+
message: { role: "assistant", content: [{ type: "text", text: "first" }] },
611+
messageId: "ordered-1",
612+
target: {
613+
agentId: "main",
614+
sessionId: "sess-main",
615+
sessionKey: "agent:main:main",
616+
storePath: "/tmp/explicit-sessions.json",
617+
},
618+
});
619+
const secondTask = handler({
620+
sessionFile: "/tmp/sess-main.jsonl",
621+
sessionKey: "agent:main:main",
622+
message: { role: "assistant", content: [{ type: "text", text: "second" }] },
623+
messageId: "ordered-2",
624+
messageSeq: 2,
625+
});
626+
627+
await Promise.resolve();
628+
expect(broadcastToConnIds).not.toHaveBeenCalled();
629+
630+
releaseFirstCount(1);
631+
await Promise.all([firstTask, secondTask]);
632+
expect(broadcastToConnIds.mock.calls.map((call) => call[1]?.messageId)).toEqual([
633+
"ordered-1",
634+
"ordered-2",
635+
]);
636+
});
553637
});
554638

555639
describe("createLifecycleEventBroadcastHandler", () => {
640+
beforeEach(() => {
641+
loadGatewaySessionRowMock.mockReturnValue(sessionRow);
642+
});
643+
556644
it("projects swarm phase and log payload fields", () => {
557645
const broadcastToConnIds = vi.fn();
558646
const handler = createLifecycleEventBroadcastHandler({

‎src/gateway/server-session-events.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,10 @@ export function createTranscriptUpdateBroadcastHandler(params: {
164164
sessionMessageSubscribers: SessionMessageSubscribers;
165165
chatAbortControllers: Map<string, ChatAbortControllerEntry>;
166166
}) {
167-
let broadcastQueue = Promise.resolve();
167+
// Ordering is a per-transcript contract: subscribers merge each session's
168+
// updates independently, so lanes keyed by transcript identity keep message
169+
// order without one session's async seq reads stalling every other session.
170+
const broadcastQueues = new Map<string, Promise<void>>();
168171
return (update: InternalSessionTranscriptUpdate): Promise<void> => {
169172
// Capture legacy ownership before the async queue can cross a same-id reset;
170173
// committed producer ownership always wins over a later session-store read.
@@ -174,10 +177,26 @@ export function createTranscriptUpdateBroadcastHandler(params: {
174177
? readTranscriptUpdateLifecycleOwner(update)?.lifecycleRevision
175178
: undefined);
176179
const queuedUpdate = lifecycleRevision ? { ...update, lifecycleRevision } : update;
177-
// Preserve transcript update order even when counting messages requires an
178-
// async read from the session file.
179-
const task = broadcastQueue.then(() => handleTranscriptUpdateBroadcast(params, queuedUpdate));
180-
broadcastQueue = task.catch(() => undefined);
180+
const laneKey =
181+
normalizeOptionalString(update.target?.sessionKey) ??
182+
normalizeOptionalString(update.sessionKey) ??
183+
normalizeOptionalString(update.sessionFile) ??
184+
"";
185+
// Preserve transcript update order within the lane even when counting
186+
// messages requires an async read from the session file.
187+
const tail = broadcastQueues.get(laneKey) ?? Promise.resolve();
188+
const task = tail.then(() => handleTranscriptUpdateBroadcast(params, queuedUpdate));
189+
const settled = task.then(
190+
() => undefined,
191+
() => undefined,
192+
);
193+
broadcastQueues.set(laneKey, settled);
194+
void settled.then(() => {
195+
// Drop drained lanes so idle sessions do not accumulate map entries.
196+
if (broadcastQueues.get(laneKey) === settled) {
197+
broadcastQueues.delete(laneKey);
198+
}
199+
});
181200
return task;
182201
};
183202
}
@@ -320,6 +339,8 @@ async function handleTranscriptUpdateBroadcast(
320339
return;
321340
}
322341
}
342+
// Message frames must keep transcript-derived live usage (dashboard API
343+
// contract from #50101); the 64KB cap bounds the per-message tail read.
323344
const sessionRow = loadGatewaySessionRow(sessionKey, {
324345
agentId: routingAgentId,
325346
transcriptUsageMaxBytes: 64 * 1024,

‎ui/src/pages/labs/labs-page.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ describe("LabsPage", () => {
201201
},
202202
{
203203
label: "Cloud Worker Desktop",
204-
index: 6,
204+
index: 7,
205205
sourceConfig: { cloudWorkers: { desktop: false } },
206206
expectedPatch: { cloudWorkers: { desktop: true } },
207207
note: "labs: update workerDesktop",

0 commit comments

Comments
 (0)