Skip to content

Commit d75164c

Browse files
perf(ui): stop long-lived request and session caches from growing forever (#127818)
* perf(ui): bound long-lived request and session state * fix(gateway-client): prevent request id collisions * fix(ui): preserve ordering across agent caches * fix(ui): preserve session order after pruning * fix(ui): retain cached session order during loading * fix(ui): evict removed agent session caches * test(ui): cover canonical session cache pruning
1 parent 6ed8954 commit d75164c

10 files changed

Lines changed: 356 additions & 79 deletions
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { describe, expect, it } from "vitest";
2+
import { GatewayPendingRequests } from "./pending-request.js";
3+
4+
describe("GatewayPendingRequests", () => {
5+
it("does not retain settled IDs for the socket generation", async () => {
6+
let requestId = 0;
7+
const requests = new GatewayPendingRequests({
8+
createRequestId: () => `request-${requestId++}`,
9+
nowMs: () => 0,
10+
});
11+
const sender = {
12+
send: () => {
13+
throw new Error("synthetic send failure");
14+
},
15+
};
16+
17+
for (let index = 0; index < 100; index += 1) {
18+
await requests.request(sender, "bounded", {}, { timeoutMs: null }).catch(() => undefined);
19+
}
20+
21+
const retained = (requests as unknown as { retiredIds?: ReadonlySet<string> }).retiredIds;
22+
expect(retained?.size ?? 0).toBe(0);
23+
});
24+
});

‎packages/gateway-client/src/pending-request.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,7 @@ type GatewayPendingRequestsOptions = {
4646
/** Owns request deadlines, correlation, settlement, and generation-scoped IDs. */
4747
export class GatewayPendingRequests {
4848
private readonly pending = new Map<string, GatewayPendingRequest>();
49-
private readonly retiredIds = new Set<string>();
50-
private collisionSuffix = 0;
49+
private requestSequence = 0;
5150

5251
constructor(private readonly opts: GatewayPendingRequestsOptions) {}
5352

@@ -101,7 +100,6 @@ export class GatewayPendingRequests {
101100
return false;
102101
}
103102
this.pending.delete(id);
104-
this.retiredIds.add(id);
105103
cleanup();
106104
this.finishTiming(id, pending, false, errorCode);
107105
return true;
@@ -186,23 +184,14 @@ export class GatewayPendingRequests {
186184
pending.reject(error);
187185
}
188186
this.pending.clear();
189-
// IDs are tombstoned only for one socket generation. Retired socket frames
190-
// are fenced by GatewayProtocolClient before a replacement generation runs.
191-
this.retiredIds.clear();
192-
this.collisionSuffix = 0;
187+
// Request sequences belong to one socket generation. Retired socket frames
188+
// are fenced by GatewayProtocolClient before the sequence restarts.
189+
this.requestSequence = 0;
193190
}
194191

195192
private allocateRequestId(): string {
196-
const id = this.opts.createRequestId();
197-
if (!this.pending.has(id) && !this.retiredIds.has(id)) {
198-
return id;
199-
}
200-
let uniqueId: string;
201-
do {
202-
this.collisionSuffix += 1;
203-
uniqueId = `${id}:${this.collisionSuffix}`;
204-
} while (this.pending.has(uniqueId) || this.retiredIds.has(uniqueId));
205-
return uniqueId;
193+
this.requestSequence += 1;
194+
return `${this.requestSequence}:${this.opts.createRequestId()}`;
206195
}
207196

208197
private finishTiming(

‎packages/gateway-client/src/protocol-client.request.test.ts‎

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -210,20 +210,45 @@ describe("GatewayProtocolClient requests", () => {
210210
await expect(aborted).rejects.toThrow("gateway request aborted for aborted");
211211

212212
const replacement = client.request("replacement", {}, { timeoutMs: null });
213-
expect(latestFrame(connection)).toMatchObject({ id: "same-id:1", method: "replacement" });
214-
respond(connection, "same-id", { stale: true });
213+
expect(latestFrame(connection)).toMatchObject({ id: "2:same-id", method: "replacement" });
214+
respond(connection, "1:same-id", { stale: true });
215215
expect(client.hasPendingRequests).toBe(true);
216-
respond(connection, "same-id:1", { current: true });
216+
respond(connection, "2:same-id", { current: true });
217217
await expect(replacement).resolves.toEqual({ current: true });
218218

219219
await expect(client.request("send.failure", {}, { timeoutMs: null })).rejects.toThrow(
220220
"synthetic send failure",
221221
);
222-
expect(latestFrame(connection)).toMatchObject({ id: "same-id:2", method: "send.failure" });
222+
expect(latestFrame(connection)).toMatchObject({ id: "3:same-id", method: "send.failure" });
223223
expect(client.hasPendingRequests).toBe(false);
224224
client.stop();
225225
});
226226

227+
it("keeps concurrent requests distinct when generated IDs contain sequence suffixes", async () => {
228+
const generatedIds = ["same-id:1", "same-id"];
229+
const { client, connections } = createRequestHarness({
230+
createRequestId: () => generatedIds.shift() ?? "same-id",
231+
});
232+
const connection = connections[0];
233+
if (!connection) {
234+
throw new Error("expected request connection");
235+
}
236+
237+
const first = client.request("first", {}, { timeoutMs: null });
238+
const second = client.request("second", {}, { timeoutMs: null });
239+
const [firstFrame, secondFrame] = connection.frames;
240+
if (!firstFrame || !secondFrame) {
241+
throw new Error("expected concurrent request frames");
242+
}
243+
expect(firstFrame.id).not.toBe(secondFrame.id);
244+
245+
respond(connection, firstFrame.id, { request: "first" });
246+
respond(connection, secondFrame.id, { request: "second" });
247+
await expect(first).resolves.toEqual({ request: "first" });
248+
await expect(second).resolves.toEqual({ request: "second" });
249+
client.stop();
250+
});
251+
227252
it("ignores late accepted and final replies after a timeout collision", async () => {
228253
vi.useFakeTimers();
229254
const onAccepted = vi.fn();
@@ -242,14 +267,14 @@ describe("GatewayProtocolClient requests", () => {
242267
{},
243268
{ timeoutMs: null, expectFinal: true, onAccepted },
244269
);
245-
expect(latestFrame(connection)).toMatchObject({ id: "same-id:1", method: "agent" });
246-
respond(connection, "same-id", { status: "accepted", runId: "old" });
247-
respond(connection, "same-id", { status: "ok", runId: "old" });
270+
expect(latestFrame(connection)).toMatchObject({ id: "2:same-id", method: "agent" });
271+
respond(connection, "1:same-id", { status: "accepted", runId: "old" });
272+
respond(connection, "1:same-id", { status: "ok", runId: "old" });
248273
expect(onAccepted).not.toHaveBeenCalled();
249274
expect(client.hasPendingRequests).toBe(true);
250275

251-
respond(connection, "same-id:1", { status: "accepted", runId: "new" });
252-
respond(connection, "same-id:1", { status: "ok", runId: "new" });
276+
respond(connection, "2:same-id", { status: "accepted", runId: "new" });
277+
respond(connection, "2:same-id", { status: "ok", runId: "new" });
253278
await expect(replacement).resolves.toEqual({ status: "ok", runId: "new" });
254279
expect(onAccepted).toHaveBeenCalledExactlyOnceWith({ status: "accepted", runId: "new" });
255280
client.stop();
@@ -463,7 +488,7 @@ describe("GatewayProtocolClient requests", () => {
463488
client.stop();
464489
});
465490

466-
it("clears generation tombstones when the socket flushes", async () => {
491+
it("restarts the request sequence when the socket flushes", async () => {
467492
vi.useFakeTimers();
468493
const { client, connections } = createRequestHarness({ createRequestId: () => "same-id" });
469494
const firstConnection = connections[0];
@@ -482,8 +507,8 @@ describe("GatewayProtocolClient requests", () => {
482507
throw new Error("expected replacement request connection");
483508
}
484509
const replacement = client.request("second", {}, { timeoutMs: null });
485-
expect(latestFrame(secondConnection)).toMatchObject({ id: "same-id", method: "second" });
486-
respond(secondConnection, "same-id", { ok: true });
510+
expect(latestFrame(secondConnection)).toMatchObject({ id: "1:same-id", method: "second" });
511+
respond(secondConnection, "1:same-id", { ok: true });
487512
await expect(replacement).resolves.toEqual({ ok: true });
488513
client.stop();
489514
});

‎ui/src/api/gateway.node.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ type ConnectFrame = {
205205
};
206206
};
207207

208-
const REQUEST_FRAME_ID = "00000000-0000-4000-8000-000000000000";
208+
const REQUEST_FRAME_ID = "2:00000000-0000-4000-8000-000000000000";
209209

210210
function requestFrameBytes(method: string, params?: unknown): number {
211211
const frame =
@@ -1679,7 +1679,7 @@ describe("GatewayBrowserClient", () => {
16791679

16801680
const { connectFrame } = await startConnect(client);
16811681

1682-
expect(connectFrame.id).toBe("req-insecure");
1682+
expect(connectFrame.id).toBe("1:req-insecure");
16831683
expect(connectFrame.method).toBe("connect");
16841684
expect(connectFrame.params?.auth).toEqual({
16851685
token: "shared-auth-token",
@@ -1699,7 +1699,7 @@ describe("GatewayBrowserClient", () => {
16991699

17001700
const { connectFrame } = await startConnect(client);
17011701

1702-
expect(connectFrame.id).toBe("req-insecure");
1702+
expect(connectFrame.id).toBe("1:req-insecure");
17031703
expect(connectFrame.method).toBe("connect");
17041704
expect(connectFrame.params?.auth).toEqual({
17051705
token: undefined,

‎ui/src/api/gateway.ts‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,24 @@ export class GatewayBrowserClient {
296296

297297
constructor(private opts: GatewayBrowserClientOptions) {
298298
this.client = new GatewayProtocolClient<ConnectPlan>({
299-
createSocket: (handlers) => createBrowserGatewaySocket(this.opts.url, handlers),
299+
createSocket: (handlers) => {
300+
this.maxPayloadBytes = undefined;
301+
const socket = createBrowserGatewaySocket(this.opts.url, handlers);
302+
return {
303+
...socket,
304+
send: (data) => {
305+
if (
306+
this.maxPayloadBytes !== undefined &&
307+
new TextEncoder().encode(data).byteLength > this.maxPayloadBytes
308+
) {
309+
throw new Error(
310+
"Request exceeds the Gateway payload limit. Shorten the message or remove one or more attachments and retry.",
311+
);
312+
}
313+
socket.send(data);
314+
},
315+
};
316+
},
300317
createRequestId: generateUUID,
301318
createRequestError: (error) =>
302319
new GatewayRequestError({
@@ -654,15 +671,6 @@ export class GatewayBrowserClient {
654671
params?: unknown,
655672
options?: GatewayProtocolRequestOptions,
656673
): Promise<T> {
657-
// The UUID request envelope adds 75 bytes with params, 61 when params is omitted.
658-
const requestBytes =
659-
new TextEncoder().encode(JSON.stringify([method, params])).byteLength +
660-
(params === undefined ? 61 : 75);
661-
if (this.maxPayloadBytes !== undefined && requestBytes > this.maxPayloadBytes) {
662-
throw new Error(
663-
"Request exceeds the Gateway payload limit. Shorten the message or remove one or more attachments and retry.",
664-
);
665-
}
666674
return await this.client.request<T>(method, params, options);
667675
}
668676

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// @vitest-environment node
2+
import { describe, expect, it } from "vitest";
3+
import type { SessionsListResult } from "../api/types.ts";
4+
import { compareSidebarSessionRowsByMode } from "./app-sidebar-session-navigation-logic.ts";
5+
import { publishSidebarSessionList } from "./session-data-controller-events.ts";
6+
7+
describe("publishSidebarSessionList", () => {
8+
const createOwner = () => ({
9+
context: undefined,
10+
sessionCreatedOrder: new Map<string, number>(),
11+
sessionResultsByAgent: {} as Record<string, SessionsListResult>,
12+
sessionsResult: null as SessionsListResult | null,
13+
sessionsAgentId: null as string | null,
14+
sessionsLoading: false,
15+
sessionMutationError: null,
16+
expandedAgentId: () => "main",
17+
requestSessionDataUpdate: () => undefined,
18+
});
19+
20+
const publish = (owner: ReturnType<typeof createOwner>, agentId: string | null, keys: string[]) =>
21+
publishSidebarSessionList(owner, {
22+
result: {
23+
sessions: keys.map((key, index) => ({ key, kind: "direct", updatedAt: index })),
24+
count: keys.length,
25+
} as SessionsListResult,
26+
agentId,
27+
loading: false,
28+
error: null,
29+
});
30+
31+
it("keeps observed creation order only for rows in the current accumulated result", () => {
32+
const owner = createOwner();
33+
34+
publish(owner, "main", ["first", "second"]);
35+
publish(owner, "main", ["second", "third"]);
36+
37+
expect([...owner.sessionCreatedOrder.keys()]).toEqual(["second", "third"]);
38+
});
39+
40+
it("keeps observed order after pruning and adding a session", () => {
41+
const owner = createOwner();
42+
43+
publish(owner, "main", ["removed", "z-retained"]);
44+
publish(owner, "main", ["z-retained"]);
45+
publish(owner, "main", ["z-retained", "a-added"]);
46+
47+
const ordered = owner.sessionResultsByAgent.main?.sessions.toSorted((a, b) =>
48+
compareSidebarSessionRowsByMode({
49+
a,
50+
b,
51+
sortMode: "created",
52+
owners: undefined,
53+
createdOrder: owner.sessionCreatedOrder,
54+
}),
55+
);
56+
expect(ordered?.map((row) => row.key)).toEqual(["z-retained", "a-added"]);
57+
});
58+
59+
it("keeps creation order for every retained agent result", () => {
60+
const owner = createOwner();
61+
62+
publish(owner, "alpha", ["alpha-first", "alpha-second"]);
63+
publish(owner, "beta", ["beta-first"]);
64+
publish(owner, "alpha", ["alpha-first", "alpha-second"]);
65+
66+
expect([...owner.sessionCreatedOrder.keys()]).toEqual([
67+
"alpha-first",
68+
"alpha-second",
69+
"beta-first",
70+
]);
71+
});
72+
73+
it("keeps cached agent order while an uncached agent has no result", () => {
74+
const owner = createOwner();
75+
76+
publish(owner, "alpha", ["alpha-first", "alpha-second"]);
77+
publishSidebarSessionList(owner, {
78+
result: null,
79+
agentId: "beta",
80+
loading: true,
81+
error: null,
82+
});
83+
84+
expect([...owner.sessionCreatedOrder.keys()]).toEqual(["alpha-first", "alpha-second"]);
85+
});
86+
87+
it("preserves promoted order for an unscoped canonical result", () => {
88+
const owner = createOwner();
89+
owner.sessionCreatedOrder.set("first", 1);
90+
owner.sessionCreatedOrder.set("second", 0);
91+
92+
publish(owner, null, ["first", "second"]);
93+
94+
expect([...owner.sessionCreatedOrder]).toEqual([
95+
["first", 1],
96+
["second", 0],
97+
]);
98+
});
99+
});

0 commit comments

Comments
 (0)