Skip to content

Commit 0991fad

Browse files
zilokki-botprobefuller-stack-dev
authored
fix(gateway): bound session catalog refresh pressure (#113171)
* fix(gateway): bound session catalog refresh pressure * fix(gateway): keep session catalog coordinator types internal * chore: rerun ci * test(secrets): allow migration isolation shard headroom * test(secrets): lock migration isolation profile * chore: keep session catalog note out of changelog * test(gateway): cover saturated session catalog admission * fix(gateway): queue saturated session catalog loads * test(gateway): cover session catalog pressure over rpc * test(gateway): cover session catalog pressure over rpc * test(gateway): keep catalog pressure proof isolated * test(gateway): satisfy catalog pressure proof types * fix(gateway): keep catalog admission internals private * fix(gateway): preserve raw catalog host filters * test(gateway): preserve session catalog host filter order --------- Co-authored-by: probe <[email protected]> Co-authored-by: fuller-stack-dev <[email protected]>
1 parent 78486e2 commit 0991fad

4 files changed

Lines changed: 174 additions & 9 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { SessionCatalogListAdmission } from "./session-catalog-list-admission.js";
3+
4+
function deferred<T>() {
5+
let resolve!: (value: T) => void;
6+
let reject!: (reason: unknown) => void;
7+
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
8+
resolve = resolvePromise;
9+
reject = rejectPromise;
10+
});
11+
return { promise, reject, resolve };
12+
}
13+
14+
describe("SessionCatalogListAdmission", () => {
15+
it("starts at most the configured number of provider lists", async () => {
16+
const admission = new SessionCatalogListAdmission(2, 2);
17+
const gates = Array.from({ length: 4 }, () => deferred<number>());
18+
const tasks = gates.map((gate) => vi.fn(() => gate.promise));
19+
const pending = tasks.map((task) => admission.run(task));
20+
21+
expect(tasks.map((task) => task.mock.calls.length)).toEqual([1, 1, 0, 0]);
22+
gates[0]?.resolve(0);
23+
await expect(pending[0]).resolves.toBe(0);
24+
expect(tasks.map((task) => task.mock.calls.length)).toEqual([1, 1, 1, 0]);
25+
26+
gates[1]?.resolve(1);
27+
gates[2]?.resolve(2);
28+
gates[3]?.resolve(3);
29+
await expect(Promise.all(pending)).resolves.toEqual([0, 1, 2, 3]);
30+
});
31+
32+
it("releases a slot after rejection and preserves FIFO order", async () => {
33+
const admission = new SessionCatalogListAdmission(1, 2);
34+
const active = deferred<void>();
35+
const order: string[] = [];
36+
const first = admission.run(() => active.promise);
37+
const second = admission.run(async () => {
38+
order.push("second");
39+
return 2;
40+
});
41+
const third = admission.run(async () => {
42+
order.push("third");
43+
return 3;
44+
});
45+
46+
active.reject(new Error("provider failed"));
47+
await expect(first).rejects.toThrow("provider failed");
48+
await expect(Promise.all([second, third])).resolves.toEqual([2, 3]);
49+
expect(order).toEqual(["second", "third"]);
50+
});
51+
52+
it("rejects overflow without starting the provider", async () => {
53+
const admission = new SessionCatalogListAdmission(1, 1);
54+
const active = deferred<void>();
55+
const first = admission.run(() => active.promise);
56+
const queued = admission.run(async () => undefined);
57+
const overflowTask = vi.fn(async () => undefined);
58+
59+
await expect(admission.run(overflowTask)).rejects.toMatchObject({ code: "catalog_busy" });
60+
expect(overflowTask).not.toHaveBeenCalled();
61+
62+
active.resolve();
63+
await Promise.all([first, queued]);
64+
});
65+
});
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
type QueuedProviderList = {
2+
start: () => void;
3+
};
4+
5+
class SessionCatalogListBusyError extends Error {
6+
readonly code = "catalog_busy";
7+
8+
constructor(maxConcurrent: number, maxQueued: number) {
9+
super(`session catalog is busy (${maxConcurrent} active, ${maxQueued} queued); retry shortly`);
10+
this.name = "SessionCatalogListBusyError";
11+
}
12+
}
13+
14+
export class SessionCatalogListAdmission {
15+
private active = 0;
16+
private readonly queue: QueuedProviderList[] = [];
17+
18+
constructor(
19+
private readonly maxConcurrent: number,
20+
private readonly maxQueued: number,
21+
) {
22+
if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) {
23+
throw new Error("maxConcurrent must be a positive integer");
24+
}
25+
if (!Number.isInteger(maxQueued) || maxQueued < 0) {
26+
throw new Error("maxQueued must be a non-negative integer");
27+
}
28+
}
29+
30+
run<T>(task: () => Promise<T>): Promise<T> {
31+
if (this.active < this.maxConcurrent) {
32+
return this.start(task);
33+
}
34+
if (this.queue.length >= this.maxQueued) {
35+
return Promise.reject(new SessionCatalogListBusyError(this.maxConcurrent, this.maxQueued));
36+
}
37+
return new Promise<T>((resolve, reject) => {
38+
this.queue.push({
39+
start: () => {
40+
void this.start(task).then(resolve, reject);
41+
},
42+
});
43+
});
44+
}
45+
46+
private async start<T>(task: () => Promise<T>): Promise<T> {
47+
this.active += 1;
48+
try {
49+
return await task();
50+
} finally {
51+
// Release before draining so every settlement, including rejection, hands
52+
// exactly one slot to the oldest waiter instead of leaking capacity.
53+
this.active -= 1;
54+
this.drain();
55+
}
56+
}
57+
58+
private drain(): void {
59+
while (this.active < this.maxConcurrent) {
60+
const next = this.queue.shift();
61+
if (!next) {
62+
return;
63+
}
64+
next.start();
65+
}
66+
}
67+
}

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,27 @@ describe("session catalog Gateway methods", () => {
232232
}
233233
});
234234

235+
it("keeps differently ordered host filters distinct when sharing lists", async () => {
236+
const observedHostIds: Array<string[] | undefined> = [];
237+
const list = vi.fn(async ({ hostIds }: { hostIds?: string[] }) => {
238+
observedHostIds.push(hostIds ? [...hostIds] : undefined);
239+
return [];
240+
});
241+
hoisted.activeRegistry.sessionCatalogs = [{ provider: provider("codex", { list }) }];
242+
const config = {};
243+
244+
await Promise.all([
245+
call("sessions.catalog.list", { hostIds: ["host-a", "host-b"] }, config),
246+
call("sessions.catalog.list", { hostIds: ["host-b", "host-a"] }, config),
247+
]);
248+
249+
expect(list).toHaveBeenCalledTimes(2);
250+
expect(observedHostIds).toEqual([
251+
["host-a", "host-b"],
252+
["host-b", "host-a"],
253+
]);
254+
});
255+
235256
it("shares settled identical lists across out-of-phase clients until the window expires", async () => {
236257
let now = 1_000;
237258
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);

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

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,22 @@ import { upsertSessionUpstreamLink } from "../../sessions/session-upstream-links
2929
import type { GatewayBroadcastToConnIdsFn } from "../server-broadcast-types.js";
3030
import { resolveAgentIdOrRespondError } from "./agent-id-shared.js";
3131
import { createSessionCatalogRequestEntrySnapshot } from "./session-catalog-entry-snapshot.js";
32+
import { SessionCatalogListAdmission } from "./session-catalog-list-admission.js";
3233
import type { GatewayRequestHandlers, RespondFn } from "./types.js";
3334
import { assertValidParams } from "./validation.js";
3435

3536
const SESSION_CATALOG_SEARCH_MAX_UTF16_UNITS = 500;
3637
const SESSION_CATALOG_SHARE_WINDOW_MS = 3_000;
3738
const SESSION_CATALOG_LIST_CACHE_MAX_ENTRIES = 128;
39+
const MAX_CONCURRENT_SESSION_CATALOG_LISTS = 4;
40+
const MAX_QUEUED_SESSION_CATALOG_LISTS = 32;
41+
42+
// Catalog adapters may scan local databases or invoke external CLIs. Bound the
43+
// expensive provider operation itself so adding providers cannot multiply the cap.
44+
const sessionCatalogListAdmission = new SessionCatalogListAdmission(
45+
MAX_CONCURRENT_SESSION_CATALOG_LISTS,
46+
MAX_QUEUED_SESSION_CATALOG_LISTS,
47+
);
3848

3949
function createSessionCatalogRequestNodeSnapshot(): NonNullable<
4050
SessionCatalogListProviderParams["listNodes"]
@@ -416,15 +426,17 @@ export const sessionCatalogHandlers: GatewayRequestHandlers = {
416426
}
417427
};
418428
try {
419-
const hosts = await provider.list({
420-
search,
421-
limitPerHost: request.limitPerHost,
422-
hostIds: request.hostIds,
423-
...(request.cursors !== undefined ? { cursors: request.cursors } : {}),
424-
sessionEntries: requestEntries.sessionEntries,
425-
listNodes,
426-
onHost,
427-
});
429+
const hosts = await sessionCatalogListAdmission.run(() =>
430+
provider.list({
431+
search,
432+
limitPerHost: request.limitPerHost,
433+
hostIds: request.hostIds,
434+
...(request.cursors !== undefined ? { cursors: request.cursors } : {}),
435+
sessionEntries: requestEntries.sessionEntries,
436+
listNodes,
437+
onHost,
438+
}),
439+
);
428440
return catalogResult(
429441
provider,
430442
hosts.map(requestEntries.projectHostCreatedActors),

0 commit comments

Comments
 (0)