Skip to content

Commit d1003d7

Browse files
committed
fix(gateway): project subagent topology for session lists
1 parent 21c533e commit d1003d7

11 files changed

Lines changed: 485 additions & 57 deletions

‎src/agents/subagent-delivery-state.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ export function clearDeliveryState(entry: SubagentRunRecord): void {
8484
}
8585

8686
/** Returns true when delivery is suspended with a durable timestamp. */
87-
export function isDeliverySuspended(entry: SubagentRunRecord): boolean {
87+
export function isDeliverySuspended(entry: Pick<SubagentRunRecord, "delivery">): boolean {
8888
return entry.delivery?.status === "suspended" && typeof entry.delivery.suspendedAt === "number";
8989
}
9090

‎src/agents/subagent-registry-queries.ts‎

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,13 @@
55
*/
66
import type { DeliveryContext } from "../utils/delivery-context.types.js";
77
import { isDeliverySuspended } from "./subagent-delivery-state.js";
8-
import type { SubagentRunRecord } from "./subagent-registry.types.js";
8+
import type { SubagentRunReadRecord, SubagentRunRecord } from "./subagent-registry.types.js";
99
import { compareSubagentRunGeneration } from "./subagent-run-generation.js";
1010
import { hasSubagentRunEnded, isLiveUnendedSubagentRun } from "./subagent-run-liveness.js";
1111

12-
function resolveControllerSessionKey(entry: SubagentRunRecord): string {
12+
function resolveControllerSessionKey(
13+
entry: Pick<SubagentRunRecord, "controllerSessionKey" | "requesterSessionKey">,
14+
): string {
1315
return entry.controllerSessionKey?.trim() || entry.requesterSessionKey;
1416
}
1517

@@ -74,31 +76,31 @@ export function listRunsForControllerFromRuns(
7476
return results;
7577
}
7678

77-
type LatestRunPair = {
79+
type LatestRunPair<T extends SubagentRunReadRecord = SubagentRunRecord> = {
7880
runId: string;
79-
entry: SubagentRunRecord;
81+
entry: T;
8082
};
8183

8284
/** Cached read index for display, controller grouping, and descendant queries. */
83-
export type SubagentRunReadIndex = {
84-
getDisplaySubagentRun(childSessionKey: string): SubagentRunRecord | null;
85-
latestRunsByChildSessionKey: ReadonlyMap<string, SubagentRunRecord>;
85+
export type SubagentRunReadIndex<T extends SubagentRunReadRecord = SubagentRunRecord> = {
86+
getDisplaySubagentRun(childSessionKey: string): T | null;
87+
latestRunsByChildSessionKey: ReadonlyMap<string, T>;
8688
countActiveDescendantRuns(rootSessionKey: string): number;
8789
countPendingDescendantRuns(rootSessionKey: string): number;
8890
countPendingDescendantRunsExcludingRun(rootSessionKey: string, excludeRunId: string): number;
8991
hasDescendantRunAwaitingSettle(rootSessionKey: string, excludeRunId?: string): boolean;
90-
listDescendantRunsForRequester(rootSessionKey: string): SubagentRunRecord[];
91-
runsByControllerSessionKey: ReadonlyMap<string, readonly SubagentRunRecord[]>;
92+
listDescendantRunsForRequester(rootSessionKey: string): T[];
93+
runsByControllerSessionKey: ReadonlyMap<string, readonly T[]>;
9294
};
9395

9496
export type LatestSubagentRunReadIndex = {
9597
getLatestSubagentRun(childSessionKey: string): SubagentRunRecord | null;
9698
};
9799

98-
function rememberLatestRunEntry(
99-
map: Map<string, SubagentRunRecord>,
100+
function rememberLatestRunEntry<T extends SubagentRunReadRecord>(
101+
map: Map<string, T>,
100102
key: string,
101-
entry: SubagentRunRecord,
103+
entry: T,
102104
): void {
103105
const existing = map.get(key);
104106
if (!existing || compareSubagentRunGeneration(entry, existing) > 0) {
@@ -124,11 +126,11 @@ export function buildLatestSubagentRunReadIndexFromRuns(
124126
};
125127
}
126128

127-
function rememberLatestRunPair(
128-
map: Map<string, LatestRunPair>,
129+
function rememberLatestRunPair<T extends SubagentRunReadRecord>(
130+
map: Map<string, LatestRunPair<T>>,
129131
key: string,
130132
runId: string,
131-
entry: SubagentRunRecord,
133+
entry: T,
132134
): void {
133135
const existing = map.get(key);
134136
if (!existing || compareSubagentRunGeneration(entry, existing.entry) > 0) {
@@ -137,19 +139,19 @@ function rememberLatestRunPair(
137139
}
138140

139141
/** Builds a read index from snapshot and optional in-memory runs. */
140-
export function buildSubagentRunReadIndexFromRuns(params: {
141-
runs: Map<string, SubagentRunRecord>;
142-
inMemoryRuns?: Iterable<SubagentRunRecord>;
142+
export function buildSubagentRunReadIndexFromRuns<T extends SubagentRunReadRecord>(params: {
143+
runs: Map<string, T>;
144+
inMemoryRuns?: Iterable<T>;
143145
now?: number;
144-
}): SubagentRunReadIndex {
146+
}): SubagentRunReadIndex<T> {
145147
const { runs } = params;
146148
const now = params.now ?? Date.now();
147-
const inMemoryDisplayByChildSessionKey = new Map<string, SubagentRunRecord>();
148-
const latestSnapshotActiveByChildSessionKey = new Map<string, SubagentRunRecord>();
149-
const latestSnapshotEndedByChildSessionKey = new Map<string, SubagentRunRecord>();
150-
const latestRunByChildSessionKey = new Map<string, LatestRunPair>();
151-
const runsByControllerSessionKey = new Map<string, SubagentRunRecord[]>();
152-
const latestRunByRequesterAndChildSessionKey = new Map<string, Map<string, LatestRunPair>>();
149+
const inMemoryDisplayByChildSessionKey = new Map<string, T>();
150+
const latestSnapshotActiveByChildSessionKey = new Map<string, T>();
151+
const latestSnapshotEndedByChildSessionKey = new Map<string, T>();
152+
const latestRunByChildSessionKey = new Map<string, LatestRunPair<T>>();
153+
const runsByControllerSessionKey = new Map<string, T[]>();
154+
const latestRunByRequesterAndChildSessionKey = new Map<string, Map<string, LatestRunPair<T>>>();
153155
const activeDescendantCountBySessionKey = new Map<string, number>();
154156
const pendingDescendantCountBySessionKey = new Map<string, number>();
155157

@@ -188,18 +190,18 @@ export function buildSubagentRunReadIndexFromRuns(params: {
188190
}
189191
let latestByChild = latestRunByRequesterAndChildSessionKey.get(requesterSessionKey);
190192
if (!latestByChild) {
191-
latestByChild = new Map<string, LatestRunPair>();
193+
latestByChild = new Map<string, LatestRunPair<T>>();
192194
latestRunByRequesterAndChildSessionKey.set(requesterSessionKey, latestByChild);
193195
}
194196
rememberLatestRunPair(latestByChild, childSessionKey, runId, entry);
195197
}
196198

197-
const latestRunsByChildSessionKey = new Map<string, SubagentRunRecord>();
199+
const latestRunsByChildSessionKey = new Map<string, T>();
198200
for (const [childSessionKey, pair] of latestRunByChildSessionKey) {
199201
latestRunsByChildSessionKey.set(childSessionKey, pair.entry);
200202
}
201203

202-
const getDisplaySubagentRun = (childSessionKey: string): SubagentRunRecord | null => {
204+
const getDisplaySubagentRun = (childSessionKey: string): T | null => {
203205
const key = childSessionKey.trim();
204206
if (!key) {
205207
return null;
@@ -214,7 +216,7 @@ export function buildSubagentRunReadIndexFromRuns(params: {
214216

215217
const forEachDescendantRun = (
216218
rootSessionKey: string,
217-
visitor: (runId: string, entry: SubagentRunRecord) => void | boolean,
219+
visitor: (runId: string, entry: T) => void | boolean,
218220
): void => {
219221
const root = rootSessionKey.trim();
220222
if (!root) {
@@ -327,8 +329,8 @@ export function buildSubagentRunReadIndexFromRuns(params: {
327329
stopAtFirst: true,
328330
}) > 0;
329331

330-
const listDescendantRunsForRequester = (rootSessionKey: string): SubagentRunRecord[] => {
331-
const descendants: SubagentRunRecord[] = [];
332+
const listDescendantRunsForRequester = (rootSessionKey: string): T[] => {
333+
const descendants: T[] = [];
332334
forEachDescendantRun(rootSessionKey, (_runId, entry) => {
333335
descendants.push(entry);
334336
});

‎src/agents/subagent-registry-read.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,12 @@ import {
1717
type SubagentRunReadIndex,
1818
} from "./subagent-registry-queries.js";
1919
import {
20+
getSubagentSessionListRunsSnapshotForRead,
2021
getSubagentRunsSnapshotForChildSession,
2122
getSubagentRunsSnapshotForController,
2223
getSubagentRunsSnapshotForRead,
2324
} from "./subagent-registry-state.js";
24-
import type { SubagentRunRecord } from "./subagent-registry.types.js";
25+
import type { SubagentRunReadRecord, SubagentRunRecord } from "./subagent-registry.types.js";
2526
import { compareSubagentRunGeneration } from "./subagent-run-generation.js";
2627

2728
export {
@@ -30,10 +31,12 @@ export {
3031
resolveSubagentSessionStatus,
3132
} from "./subagent-session-metrics.js";
3233

33-
/** Builds a reusable read index from the current persisted and in-memory run state. */
34-
export function buildSubagentRunReadIndex(now = Date.now()): SubagentRunReadIndex {
34+
/** Builds the session-list index without hydrating full retained registry payloads. */
35+
export function buildSubagentSessionListReadIndex(
36+
now = Date.now(),
37+
): SubagentRunReadIndex<SubagentRunReadRecord> {
3538
return buildSubagentRunReadIndexFromRuns({
36-
runs: getSubagentRunsSnapshotForRead(subagentRuns),
39+
runs: getSubagentSessionListRunsSnapshotForRead(subagentRuns),
3740
inMemoryRuns: subagentRuns.values(),
3841
now,
3942
});

‎src/agents/subagent-registry-state.test.ts‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,22 @@
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import {
44
clearSubagentRunsReadCacheForTest,
5+
getSubagentSessionListRunsSnapshotForRead,
56
getSubagentRunsSnapshotForChildSession,
67
getSubagentRunsSnapshotForController,
78
getSubagentRunsSnapshotForRead,
89
onSubagentRegistryPersisted,
910
persistSubagentRunsToDisk,
1011
} from "./subagent-registry-state.js";
11-
import type { SubagentRunRecord } from "./subagent-registry.types.js";
12+
import type { SubagentRunReadRecord, SubagentRunRecord } from "./subagent-registry.types.js";
1213

1314
const mocks = vi.hoisted(() => ({
1415
loadSubagentRunsForChildSessionFromSqlite:
1516
vi.fn<(childSessionKey: string) => SubagentRunRecord[]>(),
1617
loadSubagentRunsForControllerFromSqlite:
1718
vi.fn<(controllerSessionKey: string) => SubagentRunRecord[]>(),
1819
loadSubagentRegistryFromSqlite: vi.fn<() => Map<string, SubagentRunRecord>>(),
20+
loadSubagentSessionListRunsFromSqlite: vi.fn<() => Map<string, SubagentRunReadRecord>>(),
1921
saveSubagentRegistryChangesToSqlite:
2022
vi.fn<(runs: Map<string, SubagentRunRecord>, changedRunIds: readonly string[]) => void>(),
2123
saveSubagentRegistryToSqlite: vi.fn<(runs: Map<string, SubagentRunRecord>) => void>(),
@@ -25,6 +27,7 @@ vi.mock("./subagent-registry.store.sqlite.js", () => ({
2527
loadSubagentRunsForChildSessionFromSqlite: mocks.loadSubagentRunsForChildSessionFromSqlite,
2628
loadSubagentRunsForControllerFromSqlite: mocks.loadSubagentRunsForControllerFromSqlite,
2729
loadSubagentRegistryFromSqlite: mocks.loadSubagentRegistryFromSqlite,
30+
loadSubagentSessionListRunsFromSqlite: mocks.loadSubagentSessionListRunsFromSqlite,
2831
saveSubagentRegistryChangesToSqlite: mocks.saveSubagentRegistryChangesToSqlite,
2932
saveSubagentRegistryToSqlite: mocks.saveSubagentRegistryToSqlite,
3033
}));
@@ -53,6 +56,7 @@ describe("subagent registry state read cache", () => {
5356
mocks.loadSubagentRunsForChildSessionFromSqlite.mockReset();
5457
mocks.loadSubagentRunsForControllerFromSqlite.mockReset();
5558
mocks.loadSubagentRegistryFromSqlite.mockReset();
59+
mocks.loadSubagentSessionListRunsFromSqlite.mockReset();
5660
mocks.saveSubagentRegistryChangesToSqlite.mockReset();
5761
mocks.saveSubagentRegistryToSqlite.mockReset();
5862
});
@@ -98,6 +102,70 @@ describe("subagent registry state read cache", () => {
98102
expect(mocks.loadSubagentRegistryFromSqlite).toHaveBeenCalledTimes(1);
99103
});
100104

105+
it("uses the projected sqlite snapshot for session-list reads", () => {
106+
const firstRun = createRun("run-first");
107+
firstRun.model = "openai/gpt-5.6";
108+
const secondRun = createRun("run-second");
109+
mocks.loadSubagentSessionListRunsFromSqlite
110+
.mockReturnValueOnce(new Map([[firstRun.runId, firstRun]]))
111+
.mockReturnValueOnce(new Map([[secondRun.runId, secondRun]]));
112+
113+
expect([...getSubagentSessionListRunsSnapshotForRead(new Map()).keys()]).toEqual(["run-first"]);
114+
expect([...getSubagentSessionListRunsSnapshotForRead(new Map()).keys()]).toEqual(["run-first"]);
115+
expect(mocks.loadSubagentSessionListRunsFromSqlite).toHaveBeenCalledTimes(1);
116+
expect(mocks.loadSubagentRegistryFromSqlite).not.toHaveBeenCalled();
117+
118+
vi.advanceTimersByTime(500);
119+
120+
expect([...getSubagentSessionListRunsSnapshotForRead(new Map()).keys()]).toEqual([
121+
"run-second",
122+
]);
123+
expect(mocks.loadSubagentSessionListRunsFromSqlite).toHaveBeenCalledTimes(2);
124+
});
125+
126+
it("refreshes session-list projections from authoritative writes", () => {
127+
const savedRun = createRun("run-saved");
128+
savedRun.model = "openai/gpt-5.6";
129+
savedRun.outcome = { status: "ok", error: "not projected" };
130+
mocks.saveSubagentRegistryToSqlite.mockImplementationOnce(() => {
131+
throw new Error("disk unavailable");
132+
});
133+
134+
persistSubagentRunsToDisk(new Map([[savedRun.runId, savedRun]]));
135+
136+
const projected = getSubagentSessionListRunsSnapshotForRead(new Map()).get(savedRun.runId);
137+
expect(projected).toMatchObject({
138+
runId: savedRun.runId,
139+
model: savedRun.model,
140+
outcome: { status: "ok" },
141+
});
142+
expect(projected?.outcome).not.toHaveProperty("error");
143+
expect(mocks.loadSubagentSessionListRunsFromSqlite).not.toHaveBeenCalled();
144+
});
145+
146+
it("preserves unrelated projected rows across incremental writes", () => {
147+
const retained = createRun("retained");
148+
const changed = createRun("changed");
149+
mocks.loadSubagentSessionListRunsFromSqlite.mockReturnValue(
150+
new Map([
151+
[retained.runId, retained],
152+
[changed.runId, changed],
153+
]),
154+
);
155+
expect([...getSubagentSessionListRunsSnapshotForRead(new Map()).keys()]).toEqual([
156+
"retained",
157+
"changed",
158+
]);
159+
160+
changed.model = "openai/gpt-5.6";
161+
persistSubagentRunsToDisk(new Map([[changed.runId, changed]]), [changed.runId]);
162+
163+
const projected = getSubagentSessionListRunsSnapshotForRead(new Map());
164+
expect([...projected.keys()]).toEqual(["retained", "changed"]);
165+
expect(projected.get(changed.runId)?.model).toBe("openai/gpt-5.6");
166+
expect(mocks.loadSubagentSessionListRunsFromSqlite).toHaveBeenCalledOnce();
167+
});
168+
101169
it("updates only named runs in the local read cache", () => {
102170
const changed = createRun("changed");
103171
const untouched = createRun("untouched");

0 commit comments

Comments
 (0)