Skip to content

Commit 1a22189

Browse files
authored
perf(gateway): resolve labels without hydrating session rows (#133001)
1 parent 6c9954c commit 1a22189

10 files changed

Lines changed: 207 additions & 288 deletions

‎src/gateway/session-utils-list.ts‎

Lines changed: 5 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ const SESSIONS_LIST_YIELD_BATCH_SIZE = 10;
8282

8383
const SESSIONS_LIST_DEFAULT_LIMIT = 100;
8484
const SESSIONS_LIST_TRANSCRIPT_FIELD_ROWS = 100;
85-
const SESSIONS_LIST_TRANSCRIPT_USAGE_MAX_BYTES = 64 * 1024;
8685

8786
type ListSessionsFromStoreParams = {
8887
cfg: OpenClawConfig;
@@ -91,7 +90,6 @@ type ListSessionsFromStoreParams = {
9190
storePath: string;
9291
store: Record<string, SessionEntry>;
9392
modelCatalog?: SessionListModelCatalog | ModelCatalogEntry[];
94-
lightweightListRows?: boolean;
9593
opts: SessionsListParams;
9694
involvingActorId?: string;
9795
ownerFirstActorId?: string;
@@ -535,7 +533,7 @@ function buildSessionsListResult(params: {
535533
const { list, sessions } = params;
536534
// The defaults projection uses the same agent identity as getSessionDefaults:
537535
// the requested agent when scoped, otherwise the legacy compatibility agent.
538-
// Legacy plain-array catalogs (direct listSessionsFromStore callers) pass through
536+
// Legacy plain-array catalogs (direct list callers) pass through
539537
// unchanged; per-agent maps resolve by the same identity.
540538
const preparedDefaultsCatalog =
541539
params.modelCatalog instanceof Map
@@ -578,69 +576,17 @@ function buildSessionsListResult(params: {
578576

579577
export function filterAndSortSessionEntries(params: {
580578
cfg: OpenClawConfig;
579+
entryFilter?: (key: string, entry: SessionEntry) => boolean;
581580
store: Record<string, SessionEntry>;
582581
opts: SessionsListParams;
583582
now: number;
583+
getRowContext?: SessionListRowContextProvider;
584584
involvingActorId?: string;
585585
}): [string, SessionEntry][] {
586586
return selectSessionEntries(params).entries;
587587
}
588588

589-
export function listSessionsFromStore(params: ListSessionsFromStoreParams): SessionsListResult {
590-
const { cfg, store, opts } = params;
591-
const list = prepareSessionList(params);
592-
const sessions = list.entries.map(([key, entry], index) => {
593-
const includeTranscriptFields = index < list.transcriptFieldRows;
594-
const rowAgentId =
595-
!parseAgentSessionKey(key) && typeof opts.agentId === "string"
596-
? normalizeAgentId(opts.agentId)
597-
: undefined;
598-
const storeChildSessionsByKey =
599-
list.storeChildSessionsByKey ??
600-
buildSingleRowStoreChildSessionsByKey({
601-
store,
602-
storePath: list.storePath,
603-
key,
604-
now: list.now,
605-
});
606-
return buildGatewaySessionRow({
607-
cfg,
608-
storePath: list.storePath,
609-
store,
610-
key,
611-
entry,
612-
agentId: rowAgentId,
613-
modelCatalog: params.modelCatalog,
614-
now: list.now,
615-
includeDerivedTitles: includeTranscriptFields && list.includeDerivedTitles,
616-
includeLastMessage: includeTranscriptFields && list.includeLastMessage,
617-
transcriptUsageMaxBytes: SESSIONS_LIST_TRANSCRIPT_USAGE_MAX_BYTES,
618-
storeChildSessionsByKey,
619-
rowContext: list.rowContext,
620-
configuredAgentIds: list.configuredAgentIds,
621-
skipTranscriptUsageFallback: params.lightweightListRows === true,
622-
lightweightListRow: params.lightweightListRows === true,
623-
});
624-
});
625-
return buildSessionsListResult({
626-
cfg,
627-
list,
628-
modelCatalog: params.modelCatalog,
629-
sessions,
630-
agentId: opts.agentId,
631-
});
632-
}
633-
634-
/**
635-
* Async version of listSessionsFromStore that yields to the event loop between
636-
* batches of session row builds. This prevents large session stores from
637-
* blocking the event loop during sessions.list requests.
638-
*
639-
* The synchronous file I/O in readSessionTitleFieldsFromTranscript (head/tail
640-
* reads for derived titles and last-message previews) is the dominant blocker.
641-
* By yielding every SESSIONS_LIST_YIELD_BATCH_SIZE rows, we keep the event
642-
* loop responsive for WebSocket heartbeats, channel I/O, and concurrent RPC.
643-
*/
589+
/** Build rows in batches so session lists do not starve other Gateway work. */
644590
export async function listSessionsFromStoreAsync(
645591
params: ListSessionsFromStoreParams,
646592
): Promise<SessionsListResult> {
@@ -701,9 +647,9 @@ export async function listSessionsFromStoreAsync(
701647
now: list.now,
702648
includeDerivedTitles: false,
703649
includeLastMessage: false,
704-
transcriptUsageMaxBytes: SESSIONS_LIST_TRANSCRIPT_USAGE_MAX_BYTES,
705650
storeChildSessionsByKey,
706651
rowContext: list.rowContext,
652+
configuredAgentIds: list.configuredAgentIds,
707653
skipTranscriptUsageFallback: true,
708654
lightweightListRow: true,
709655
});

‎src/gateway/session-utils-owners.test.ts‎

Lines changed: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,14 @@ const getUserProfileDisplay = vi.hoisted(() =>
3434

3535
vi.mock("../state/user-profiles.js", () => ({ getUserProfileDisplay }));
3636

37-
import { listSessionsFromStore, listSessionsFromStoreAsync } from "./session-utils.js";
37+
import { listSessionsFromStoreAsync } from "./session-utils.js";
3838

3939
afterEach(() => {
4040
vi.restoreAllMocks();
4141
getUserProfileDisplay.mockClear();
4242
});
4343

44-
it("lets configured agents win id-only owner facet collisions", () => {
44+
it("lets configured agents win id-only owner facet collisions", async () => {
4545
const actorOrders = [
4646
["human", "agent"],
4747
["agent", "human"],
@@ -61,7 +61,7 @@ it("lets configured agents win id-only owner facet collisions", () => {
6161
} satisfies SessionEntry,
6262
]),
6363
);
64-
const result = listSessionsFromStore({
64+
const result = await listSessionsFromStoreAsync({
6565
cfg: {
6666
agents: { list: [{ id: "shared-id", identity: { name: "Shared agent" } }] },
6767
} as OpenClawConfig,
@@ -81,7 +81,7 @@ it("lets configured agents win id-only owner facet collisions", () => {
8181
}
8282
});
8383

84-
it("returns the complete deterministic owner facet independently of pagination", () => {
84+
it("returns the complete deterministic owner facet independently of pagination", async () => {
8585
const store: Record<string, SessionEntry> = {
8686
"agent:main:ada": {
8787
archivedAt: 3,
@@ -99,7 +99,7 @@ it("returns the complete deterministic owner facet independently of pagination",
9999
},
100100
};
101101

102-
const result = listSessionsFromStore({
102+
const result = await listSessionsFromStoreAsync({
103103
cfg: {} as OpenClawConfig,
104104
storePath: "/tmp/openclaw-session-owners",
105105
store,
@@ -138,7 +138,7 @@ it("returns the complete deterministic owner facet independently of pagination",
138138
});
139139
expect(getUserProfileDisplay).toHaveBeenCalledTimes(2);
140140

141-
const filtered = listSessionsFromStore({
141+
const filtered = await listSessionsFromStoreAsync({
142142
cfg: {} as OpenClawConfig,
143143
storePath: "/tmp/openclaw-session-owners",
144144
store,
@@ -148,7 +148,7 @@ it("returns the complete deterministic owner facet independently of pagination",
148148
expect(filtered.owners).toEqual(result.owners);
149149
});
150150

151-
it("prepends an owner window without advancing shared-page pagination", () => {
151+
it("prepends an owner window without advancing shared-page pagination", async () => {
152152
const store: Record<string, SessionEntry> = {
153153
"agent:main:foreign-newest": {
154154
createdActor: { type: "human", source: "profile", id: "profile-ada" },
@@ -164,7 +164,7 @@ it("prepends an owner window without advancing shared-page pagination", () => {
164164
},
165165
};
166166

167-
const result = listSessionsFromStore({
167+
const result = await listSessionsFromStoreAsync({
168168
cfg: {} as OpenClawConfig,
169169
storePath: "/tmp/openclaw-session-owner-first",
170170
store,
@@ -179,7 +179,7 @@ it("prepends an owner window without advancing shared-page pagination", () => {
179179
expect(result).toMatchObject({ count: 2, totalCount: 2, nextOffset: 1, hasMore: true });
180180
});
181181

182-
it("projects only durable profiles and configured agents as effective owners", () => {
182+
it("projects only durable profiles and configured agents as effective owners", async () => {
183183
const cases = [
184184
{
185185
createdActor: { type: "human" as const, source: "profile" as const, id: "profile-ada" },
@@ -222,7 +222,7 @@ it("projects only durable profiles and configured agents as effective owners", (
222222
} satisfies SessionEntry,
223223
]),
224224
);
225-
const result = listSessionsFromStore({
225+
const result = await listSessionsFromStoreAsync({
226226
cfg: {
227227
agents: {
228228
list: [
@@ -305,7 +305,7 @@ it("filters immutable creator and effective owner separately while preserving pr
305305
updatedAt: 0,
306306
},
307307
} satisfies Record<string, SessionEntry>;
308-
const result = listSessionsFromStore({
308+
const result = await listSessionsFromStoreAsync({
309309
cfg: {} as OpenClawConfig,
310310
storePath: "/tmp/openclaw-session-owners",
311311
store,
@@ -339,7 +339,7 @@ it("filters immutable creator and effective owner separately while preserving pr
339339
label: "Bob",
340340
},
341341
]);
342-
const creatorFiltered = listSessionsFromStore({
342+
const creatorFiltered = await listSessionsFromStoreAsync({
343343
cfg: {} as OpenClawConfig,
344344
storePath: "/tmp/openclaw-session-owners",
345345
store,
@@ -355,7 +355,7 @@ it("filters immutable creator and effective owner separately while preserving pr
355355
owner: { actor: { id: "profile-bob", label: "Bob" } },
356356
},
357357
);
358-
const ownerFiltered = listSessionsFromStore({
358+
const ownerFiltered = await listSessionsFromStoreAsync({
359359
cfg: {} as OpenClawConfig,
360360
storePath: "/tmp/openclaw-session-owners",
361361
store,
@@ -403,7 +403,7 @@ it("filters immutable creator and effective owner separately while preserving pr
403403
opts: { creatorId: "profile-ada" },
404404
};
405405
expect
406-
.soft(listSessionsFromStore(query).sessions.map((row) => row.key))
406+
.soft((await listSessionsFromStoreAsync(query)).sessions.map((row) => row.key))
407407
.toEqual(["agent:main:shared", "agent:main:draft"]);
408408
const authorized = await listSessionsFromStoreAsync({ ...query, entryFilter });
409409
expect
@@ -416,7 +416,7 @@ it("filters immutable creator and effective owner separately while preserving pr
416416
}
417417
});
418418

419-
it("deduplicates participants in order, excludes the owner, and filters sessions involving the viewer", () => {
419+
it("deduplicates participants in order, excludes the owner, and filters sessions involving the viewer", async () => {
420420
const store: Record<string, SessionEntry> = {
421421
"agent:main:owned": {
422422
createdActor: { type: "human", source: "profile", id: "profile-ada" },
@@ -480,7 +480,7 @@ it("deduplicates participants in order, excludes the owner, and filters sessions
480480
const cfg: OpenClawConfig = {
481481
agents: { list: [{ id: "research", identity: { name: "Research" } }] },
482482
};
483-
const result = listSessionsFromStore({
483+
const result = await listSessionsFromStoreAsync({
484484
cfg,
485485
storePath: "/tmp/openclaw-session-participants",
486486
store,
@@ -502,7 +502,7 @@ it("deduplicates participants in order, excludes the owner, and filters sessions
502502
participantCount: 5,
503503
});
504504

505-
const unfiltered = listSessionsFromStore({
505+
const unfiltered = await listSessionsFromStoreAsync({
506506
cfg,
507507
storePath: "/tmp/openclaw-session-participants",
508508
store,
@@ -520,7 +520,7 @@ it("deduplicates participants in order, excludes the owner, and filters sessions
520520
expect(participant).not.toHaveProperty("label");
521521
expect(participant).not.toHaveProperty("avatarUrl");
522522
}
523-
const selected = listSessionsFromStore({
523+
const selected = await listSessionsFromStoreAsync({
524524
cfg,
525525
storePath: "/tmp/openclaw-session-participants",
526526
store,
@@ -535,7 +535,7 @@ it("deduplicates participants in order, excludes the owner, and filters sessions
535535

536536
it.each(["spawn", "talk", "cron"] as const)(
537537
"associates a required %s creator without inventing profile contributions or promoting unqualified creators",
538-
(via) => {
538+
async (via) => {
539539
getUserProfileDisplay.mockImplementation((id) => ({
540540
id: id === "former" ? "current" : id,
541541
displayName: "Current",
@@ -593,7 +593,7 @@ it.each(["spawn", "talk", "cron"] as const)(
593593
store,
594594
opts: { archived: "all" as const, includePeople: true },
595595
};
596-
const all = listSessionsFromStore(query);
596+
const all = await listSessionsFromStoreAsync(query);
597597
const creator = {
598598
type: "human",
599599
id: "former",
@@ -615,15 +615,15 @@ it.each(["spawn", "talk", "cron"] as const)(
615615
});
616616
expect(row.owner).toBeUndefined();
617617
}
618-
const involving = listSessionsFromStore({ ...query, involvingActorId: "current" });
618+
const involving = await listSessionsFromStoreAsync({ ...query, involvingActorId: "current" });
619619
expect(involving.sessions.map((row) => row.key)).toEqual(["agent:main:historical", childKey]);
620620
expect(involving.sessions[0]?.participants).toEqual([
621621
{ identity: { type: "profile", id: "current" }, label: "Current" },
622622
]);
623623
expect(involving.people).toEqual([
624624
{ identity: { type: "profile", id: "current" }, label: "Current", sessionCount: 2 },
625625
]);
626-
const ownerFirst = listSessionsFromStore({
626+
const ownerFirst = await listSessionsFromStoreAsync({
627627
...query,
628628
opts: { archived: "all", limit: 1 },
629629
ownerFirstActorId: "current",
@@ -632,7 +632,7 @@ it.each(["spawn", "talk", "cron"] as const)(
632632

633633
// Reassignment must not erase the creator's Activity association or fabricate their input.
634634
child.owner = { actor: { type: "agent", id: "main" } };
635-
const associated = listSessionsFromStore({
635+
const associated = await listSessionsFromStoreAsync({
636636
...query,
637637
opts: { ...query.opts, involvingProfileId: "former" },
638638
});
@@ -646,7 +646,7 @@ it.each(["spawn", "talk", "cron"] as const)(
646646
},
647647
);
648648

649-
it("returns a canonical selected person and orders merged owners without borrowing remote identities", () => {
649+
it("returns a canonical selected person and orders merged owners without borrowing remote identities", async () => {
650650
getUserProfileDisplay.mockImplementation((id) => ({
651651
id: id === "former" ? "current" : id,
652652
displayName: id,
@@ -674,29 +674,29 @@ it("returns a canonical selected person and orders merged owners without borrowi
674674
store,
675675
opts: { archived: "all" as const, includePeople: true, involvingProfileId: "former", limit: 1 },
676676
};
677-
const result = listSessionsFromStore(query);
677+
const result = await listSessionsFromStoreAsync(query);
678678
expect(result).toMatchObject({
679679
involvingProfileId: "current",
680680
totalCount: 1,
681681
peopleIncomplete: true,
682682
});
683683
expect(result.people?.some((person) => person.identity.id === "current")).toBe(true);
684-
const ordered = listSessionsFromStore({
684+
const ordered = await listSessionsFromStoreAsync({
685685
...query,
686686
opts: { archived: "all", limit: 1 },
687687
ownerFirstActorId: "current",
688688
});
689689
expect(ordered.sessions[0]?.key).toBe("agent:main:owned");
690-
const involved = listSessionsFromStore({
690+
const involved = await listSessionsFromStoreAsync({
691691
...query,
692692
opts: { archived: "all" },
693693
involvingActorId: "current",
694694
});
695695
expect(involved.sessions.map((row) => row.key)).toEqual(["agent:main:owned"]);
696696
});
697697

698-
it("reports the authoritative admission bound even when the visible participant list is smaller", () => {
699-
const result = listSessionsFromStore({
698+
it("reports the authoritative admission bound even when the visible participant list is smaller", async () => {
699+
const result = await listSessionsFromStoreAsync({
700700
cfg: {},
701701
storePath: "/tmp/openclaw-session-bound",
702702
store: {
@@ -811,7 +811,7 @@ it("preserves list output across visibility, scope, owner, and search filters",
811811
} as GatewayClient;
812812
const entryFilter = createSessionListEntryFilter({ client: viewer });
813813

814-
const project = async (opts: Parameters<typeof listSessionsFromStore>[0]["opts"]) => {
814+
const project = async (opts: Parameters<typeof listSessionsFromStoreAsync>[0]["opts"]) => {
815815
const result = await listSessionsFromStoreAsync({
816816
cfg,
817817
...(entryFilter ? { entryFilter } : {}),
@@ -898,9 +898,9 @@ it("preserves list output across visibility, scope, owner, and search filters",
898898
);
899899
});
900900

901-
it("keeps the serialized list response deterministic for the current filter path", () => {
901+
it("keeps the serialized list response deterministic for the current filter path", async () => {
902902
vi.spyOn(Date, "now").mockReturnValue(1_000_000);
903-
const result = listSessionsFromStore({
903+
const result = await listSessionsFromStoreAsync({
904904
cfg: {
905905
agents: {
906906
defaults: { model: { primary: "openai/gpt-5.4" } },
@@ -930,7 +930,7 @@ it("keeps the serialized list response deterministic for the current filter path
930930
const expectedSerializedResponse = [
931931
'{"ts":1000000,"path":"/tmp/openclaw-session-byte-parity","count":1,"totalCount":1,"limitApplied":100,"nextOffset":null,"hasMore":false,"owners":[]',
932932
',"defaults":{"modelProvider":"openai","model":"gpt-5.4","contextTokens":200000,"agentRuntime":{"id":"codex","cloudPlacementSupported":false,"devicePlacementSupported":false,"source":"implicit"},"thinkingLevels":[{"id":"off","label":"off"},{"id":"minimal","label":"minimal"},{"id":"low","label":"low"},{"id":"medium","label":"medium"},{"id":"high","label":"high"},{"id":"xhigh","label":"xhigh"}],"thinkingOptions":["off","minimal","low","medium","high","xhigh"],"thinkingDefault":"off"}',
933-
',"sessions":[{"key":"global","visibility":"shared","createdActor":{"type":"system","id":"creator-b","identity":{"type":"legacy","actorType":"system","source":null,"id":"creator-b"}},"kind":"global","classification":"global","agentId":"main","isMain":false,"isBackground":false,"subject":"needle global","updatedAt":999999,"archived":false,"pinned":false,"unread":false,"sessionId":"session-global","thinkingLevels":[{"id":"off","label":"off"},{"id":"minimal","label":"minimal"},{"id":"low","label":"low"},{"id":"medium","label":"medium"},{"id":"high","label":"high"},{"id":"xhigh","label":"xhigh"}],"thinkingOptions":["off","minimal","low","medium","high","xhigh"],"thinkingDefault":"off","effectiveFastMode":false,"effectiveFastModeSource":"default","fastAutoOnSeconds":60,"totalTokens":1,"totalTokensFresh":true,"estimatedCostUsd":0,"effectiveResponseUsage":"off","effectiveQueueMode":"steer","modelProvider":"openai","model":"gpt-5.4","modelOverrideSource":null,"agentRuntime":{"id":"codex","cloudPlacementSupported":false,"devicePlacementSupported":false,"source":"implicit"},"contextTokens":100}]}',
933+
',"sessions":[{"key":"global","visibility":"shared","createdActor":{"type":"system","id":"creator-b","identity":{"type":"legacy","actorType":"system","source":null,"id":"creator-b"}},"kind":"global","classification":"global","agentId":"main","isMain":false,"isBackground":false,"subject":"needle global","updatedAt":999999,"archived":false,"pinned":false,"unread":false,"sessionId":"session-global","thinkingLevels":[{"id":"off","label":"off"},{"id":"minimal","label":"minimal"},{"id":"low","label":"low"},{"id":"medium","label":"medium"},{"id":"high","label":"high"}],"thinkingOptions":["off","minimal","low","medium","high"],"thinkingDefault":"off","effectiveFastMode":false,"effectiveFastModeSource":"default","fastAutoOnSeconds":60,"totalTokens":1,"totalTokensFresh":true,"estimatedCostUsd":0,"effectiveResponseUsage":"off","effectiveQueueMode":"steer","modelProvider":"openai","model":"gpt-5.4","modelOverrideSource":null,"agentRuntime":{"id":"codex","cloudPlacementSupported":false,"devicePlacementSupported":false,"source":"implicit"},"contextTokens":100}]}',
934934
].join("");
935935

936936
expect(JSON.stringify(result)).toBe(expectedSerializedResponse);

0 commit comments

Comments
 (0)