Skip to content

Commit 14ad804

Browse files
authored
perf(gateway): prewarm dashboard data caches after startup (#115710)
1 parent dd459ac commit 14ad804

9 files changed

Lines changed: 658 additions & 39 deletions
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { SessionCatalogProvider } from "../../plugins/session-catalog.js";
3+
4+
const hoisted = vi.hoisted(() => ({
5+
activeRegistry: { sessionCatalogs: [] as unknown[] },
6+
listSessionEntriesReadOnly: vi.fn(() => []),
7+
}));
8+
9+
vi.mock("../../plugins/runtime.js", () => ({
10+
getActivePluginSessionExtensionRegistry: () => hoisted.activeRegistry,
11+
}));
12+
13+
vi.mock("../../config/sessions/session-accessor.js", async (importOriginal) => ({
14+
...(await importOriginal<typeof import("../../config/sessions/session-accessor.js")>()),
15+
listSessionEntriesReadOnly: hoisted.listSessionEntriesReadOnly,
16+
}));
17+
18+
const { prewarmSessionCatalogList, sessionCatalogHandlers } = await import("./session-catalog.js");
19+
20+
function provider(
21+
id: string,
22+
overrides: Partial<SessionCatalogProvider> = {},
23+
): SessionCatalogProvider {
24+
return {
25+
id,
26+
label: id.toUpperCase(),
27+
list: vi.fn(async () => []),
28+
read: vi.fn(async ({ hostId, threadId }) => ({ hostId, threadId, items: [] })),
29+
...overrides,
30+
};
31+
}
32+
33+
function startList(params: {
34+
config: Record<string, unknown>;
35+
request: Record<string, unknown>;
36+
connId?: string;
37+
broadcastToConnIds?: ReturnType<typeof vi.fn>;
38+
}) {
39+
const respond = vi.fn();
40+
const completion = Promise.resolve(
41+
sessionCatalogHandlers["sessions.catalog.list"]?.({
42+
params: params.request,
43+
respond,
44+
client: params.connId ? { connId: params.connId } : undefined,
45+
context: {
46+
getRuntimeConfig: () => params.config,
47+
...(params.broadcastToConnIds ? { broadcastToConnIds: params.broadcastToConnIds } : {}),
48+
},
49+
} as never),
50+
);
51+
return { completion, respond };
52+
}
53+
54+
describe("session catalog prewarm", () => {
55+
beforeEach(() => {
56+
hoisted.activeRegistry.sessionCatalogs = [];
57+
hoisted.listSessionEntriesReadOnly.mockClear();
58+
});
59+
60+
it("serves the first handler call from the warmed list cache", async () => {
61+
const list = vi.fn(async () => []);
62+
hoisted.activeRegistry.sessionCatalogs = [{ provider: provider("codex", { list }) }];
63+
const config = { agents: { list: [{ id: "main", default: true }] } };
64+
65+
await prewarmSessionCatalogList({ config, agentId: "main", limitPerHost: 40 });
66+
const handler = startList({
67+
config,
68+
request: { agentId: "main", limitPerHost: 40 },
69+
});
70+
await handler.completion;
71+
72+
expect(list).toHaveBeenCalledOnce();
73+
expect(handler.respond).toHaveBeenCalledWith(true, {
74+
catalogs: [expect.objectContaining({ id: "codex", hosts: [] })],
75+
});
76+
});
77+
78+
it("fans out headless-leader progress without leaking subscriptions", async () => {
79+
let now = 1_000;
80+
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
81+
let release!: () => void;
82+
const gate = new Promise<void>((resolve) => {
83+
release = resolve;
84+
});
85+
const host = {
86+
hostId: "gateway:local",
87+
label: "Local",
88+
kind: "gateway" as const,
89+
connected: true,
90+
sessions: [],
91+
};
92+
const list = vi.fn(async ({ onHost }: { onHost?: (value: typeof host) => void }) => {
93+
await gate;
94+
onHost?.(host);
95+
return [host];
96+
});
97+
hoisted.activeRegistry.sessionCatalogs = [{ provider: provider("codex", { list }) }];
98+
const agentId = "prewarm";
99+
const config = { agents: { list: [{ id: agentId, default: true }] } };
100+
const followerBroadcast = vi.fn();
101+
102+
try {
103+
const prewarm = prewarmSessionCatalogList({
104+
config,
105+
agentId,
106+
limitPerHost: 40,
107+
});
108+
await vi.waitFor(() => expect(list).toHaveBeenCalledOnce());
109+
const follower = startList({
110+
config,
111+
request: {
112+
agentId,
113+
limitPerHost: 40,
114+
progressId: "follower-progress",
115+
},
116+
connId: "follower",
117+
broadcastToConnIds: followerBroadcast,
118+
});
119+
120+
expect(list).toHaveBeenCalledOnce();
121+
release();
122+
await Promise.all([prewarm, follower.completion]);
123+
124+
expect(followerBroadcast).toHaveBeenCalledOnce();
125+
expect(follower.respond).toHaveBeenCalledWith(true, {
126+
catalogs: [expect.objectContaining({ id: "codex", hosts: [host] })],
127+
});
128+
129+
now += 2_500;
130+
const settledFollowerBroadcast = vi.fn();
131+
const settledFollower = startList({
132+
config,
133+
request: { agentId, limitPerHost: 40, progressId: "settled-progress" },
134+
connId: "settled",
135+
broadcastToConnIds: settledFollowerBroadcast,
136+
});
137+
await settledFollower.completion;
138+
expect(settledFollowerBroadcast).not.toHaveBeenCalled();
139+
140+
now += 501;
141+
const nextBroadcast = vi.fn();
142+
const next = startList({
143+
config,
144+
request: { agentId, limitPerHost: 40, progressId: "next-progress" },
145+
connId: "next",
146+
broadcastToConnIds: nextBroadcast,
147+
});
148+
await next.completion;
149+
expect(list).toHaveBeenCalledTimes(2);
150+
expect(nextBroadcast).toHaveBeenCalledOnce();
151+
expect(followerBroadcast).toHaveBeenCalledOnce();
152+
} finally {
153+
release();
154+
nowSpy.mockRestore();
155+
}
156+
});
157+
});

‎src/gateway/server-methods/session-catalog.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ describe("session catalog Gateway methods", () => {
176176
});
177177
});
178178

179-
it("single-flights identical concurrent lists and gives followers only the final result", async () => {
179+
it("single-flights identical concurrent lists and fans progress to active followers", async () => {
180180
let release!: () => void;
181181
const gate = new Promise<void>((resolve) => {
182182
release = resolve;
@@ -189,8 +189,8 @@ describe("session catalog Gateway methods", () => {
189189
sessions: [],
190190
};
191191
const list = vi.fn(async ({ onHost }: { onHost?: (value: typeof host) => void }) => {
192-
onHost?.(host);
193192
await gate;
193+
onHost?.(host);
194194
return [host];
195195
});
196196
hoisted.activeRegistry.sessionCatalogs = [{ provider: provider("codex", { list }) }];
@@ -224,7 +224,7 @@ describe("session catalog Gateway methods", () => {
224224
]);
225225

226226
expect(leaderBroadcast).toHaveBeenCalledOnce();
227-
expect(followerBroadcast).not.toHaveBeenCalled();
227+
expect(followerBroadcast).toHaveBeenCalledOnce();
228228
for (const pending of [leader, follower, otherAgent, otherParams]) {
229229
expect(pending.respond).toHaveBeenCalledWith(true, {
230230
catalogs: [expect.objectContaining({ id: "codex", hosts: [host] })],

‎src/gateway/server-methods/session-catalog.ts‎

Lines changed: 88 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import { bindPluginSessionConversation } from "../../plugins/session-conversatio
2626
import { resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
2727
import { recordSessionStateEvent } from "../../sessions/session-state-events.js";
2828
import { upsertSessionUpstreamLink } from "../../sessions/session-upstream-links.js";
29+
import type { GatewayBroadcastToConnIdsFn } from "../server-broadcast-types.js";
2930
import { resolveAgentIdOrRespondError } from "./agent-id-shared.js";
3031
import { createSessionCatalogRequestEntrySnapshot } from "./session-catalog-entry-snapshot.js";
3132
import type { GatewayRequestHandlers, RespondFn } from "./types.js";
@@ -129,8 +130,15 @@ const providerCreateTargetsByConfig = new WeakMap<
129130

130131
type CatalogListResult = { catalogs: SessionCatalog[] };
131132

133+
type CatalogListProgressSubscriber = {
134+
broadcastToConnIds: GatewayBroadcastToConnIdsFn;
135+
connId: string;
136+
progressId: string;
137+
};
138+
132139
type CatalogListCacheEntry = {
133140
expiresAt?: number;
141+
progressSubscribers: Map<string, CatalogListProgressSubscriber>;
134142
result: Promise<CatalogListResult>;
135143
};
136144

@@ -350,8 +358,15 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
350358
const cache = catalogListCache(config, catalogRegistrations);
351359
const cached = cache.get(listKey);
352360
if (cached && (cached.expiresAt === undefined || cached.expiresAt > Date.now())) {
353-
// progressId is connection-owned and excluded from the work key. Followers skip progressive
354-
// frames and receive only the authoritative final result emitted for every caller below.
361+
// progressId is connection-owned and excluded from the work key. Active followers register
362+
// for the remaining host frames; settled followers receive only the authoritative result.
363+
if (cached.expiresAt === undefined && progressConnId && progressId) {
364+
cached.progressSubscribers.set(`${progressConnId}\0${progressId}`, {
365+
broadcastToConnIds: context.broadcastToConnIds,
366+
connId: progressConnId,
367+
progressId,
368+
});
369+
}
355370
cache.delete(listKey);
356371
cache.set(listKey, cached);
357372
respond(true, await cached.result);
@@ -360,6 +375,14 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
360375
if (cached) {
361376
cache.delete(listKey);
362377
}
378+
const progressSubscribers = new Map<string, CatalogListProgressSubscriber>();
379+
if (progressConnId && progressId) {
380+
progressSubscribers.set(`${progressConnId}\0${progressId}`, {
381+
broadcastToConnIds: context.broadcastToConnIds,
382+
connId: progressConnId,
383+
progressId,
384+
});
385+
}
363386
const operation = (async () => {
364387
const requestEntries = createSessionCatalogRequestEntrySnapshot({
365388
cfg: config,
@@ -370,27 +393,28 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
370393
selected.map(async (provider): Promise<SessionCatalog> => {
371394
const createTarget = resolveProviderCreateTarget(provider, resolvedAgent.agentId, config);
372395
const createSession = createTarget.ok ? { model: createTarget.target.model } : undefined;
373-
const onHost = progressConnId
374-
? (host: SessionCatalog["hosts"][number]) => {
375-
// Progressive frames are an optimization. The final RPC response remains
376-
// authoritative when a slow client drops an intermediate host update.
377-
context.broadcastToConnIds(
378-
"sessions.catalog.host",
379-
{
380-
progressId,
381-
agentId: resolvedAgent.agentId,
382-
catalog: catalogResult(
383-
provider,
384-
[requestEntries.projectHostCreatedActors(host)],
385-
undefined,
386-
createSession,
387-
),
388-
},
389-
new Set([progressConnId]),
390-
{ dropIfSlow: true },
391-
);
392-
}
393-
: undefined;
396+
const onHost = (host: SessionCatalog["hosts"][number]) => {
397+
const catalog = catalogResult(
398+
provider,
399+
[requestEntries.projectHostCreatedActors(host)],
400+
undefined,
401+
createSession,
402+
);
403+
// Progressive frames are an optimization. The final RPC response remains
404+
// authoritative when a slow client drops an intermediate host update.
405+
for (const subscriber of progressSubscribers.values()) {
406+
subscriber.broadcastToConnIds(
407+
"sessions.catalog.host",
408+
{
409+
progressId: subscriber.progressId,
410+
agentId: resolvedAgent.agentId,
411+
catalog,
412+
},
413+
new Set([subscriber.connId]),
414+
{ dropIfSlow: true },
415+
);
416+
}
417+
};
394418
try {
395419
const hosts = await provider.list({
396420
search,
@@ -399,7 +423,7 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
399423
...(request.cursors !== undefined ? { cursors: request.cursors } : {}),
400424
sessionEntries: requestEntries.sessionEntries,
401425
listNodes,
402-
...(onHost ? { onHost } : {}),
426+
onHost,
403427
});
404428
return catalogResult(
405429
provider,
@@ -414,7 +438,7 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
414438
);
415439
return { catalogs: catalogList };
416440
})();
417-
const entry: CatalogListCacheEntry = { result: operation };
441+
const entry: CatalogListCacheEntry = { progressSubscribers, result: operation };
418442
// Exact request/config/registration results remain shareable for 3s after settling. This catches
419443
// out-of-phase clients but expires before the UI's 5s fast follow, so changed rows surface there.
420444
// Expired and rejected work is removed; retaining it would mask provider recovery or new sessions.
@@ -437,6 +461,8 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
437461
cache.delete(listKey);
438462
}
439463
throw error;
464+
} finally {
465+
progressSubscribers.clear();
440466
}
441467
},
442468

@@ -581,3 +607,40 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
581607
}
582608
},
583609
};
610+
611+
/** Fill the same list single-flight and provider caches used by the Gateway RPC. */
612+
export async function prewarmSessionCatalogList(params: {
613+
config: OpenClawConfig;
614+
agentId: string;
615+
limitPerHost: number;
616+
}): Promise<void> {
617+
const handler = sessionCatalogHandlers["sessions.catalog.list"];
618+
if (!handler) {
619+
throw new Error("sessions.catalog.list handler is unavailable");
620+
}
621+
let responded = false;
622+
let responseError: string | undefined;
623+
const respond: RespondFn = (ok, _payload, error) => {
624+
responded = true;
625+
if (!ok) {
626+
responseError = error?.message || "sessions.catalog.list prewarm failed";
627+
}
628+
};
629+
await handler({
630+
params: {
631+
agentId: params.agentId,
632+
limitPerHost: params.limitPerHost,
633+
},
634+
client: null,
635+
// A headless leader intentionally has no progress id or connection subscription.
636+
// Concurrent clients still share its authoritative final result through the normal cache.
637+
context: { getRuntimeConfig: () => params.config },
638+
respond,
639+
} as never);
640+
if (!responded) {
641+
throw new Error("sessions.catalog.list prewarm returned no result");
642+
}
643+
if (responseError) {
644+
throw new Error(responseError);
645+
}
646+
}

0 commit comments

Comments
 (0)