Skip to content

Commit 3600db9

Browse files
committed
perf(gateway): bound sessions.preview and chat.message.get transcript reads
sessions.preview reads a bounded recent tail (64-256 events/1MiB, one 8MiB escalation when filtered messages starve the 12-item preview) and yields between batch keys instead of synchronously materializing every transcript in a 64-key loop. chat.message.get resolves visibility via the message-ID-anchored reader instead of loading the full projected transcript per request.
1 parent bb43e08 commit 3600db9

5 files changed

Lines changed: 134 additions & 18 deletions

File tree

‎src/gateway/server-methods/chat-message-get-handler.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,8 @@ import {
1313
} from "../chat-display-projection.js";
1414
import { resolveCurrentUserProfileDisplay } from "../current-user-profile-display.js";
1515
import { MAX_PAYLOAD_BYTES } from "../server-constants.js";
16-
import {
17-
readSessionMessageByIdAsync,
18-
readSessionMessagesAsync,
19-
} from "../session-transcript-readers.js";
16+
import { readSessionMessagesAroundIdWithStatsAsync } from "../session-transcript-anchor-reader.js";
17+
import { readSessionMessageByIdAsync } from "../session-transcript-readers.js";
2018
import { loadGatewaySessionEntryReadOnly } from "../session-utils.js";
2119
import { readChatHistoryMessageId } from "./chat-history-pages.js";
2220
import { resolveRequestedChatAgentId, validateChatSelectedAgent } from "./chat-origin-routing.js";
@@ -37,7 +35,9 @@ async function isChatMessageIdVisibleAfterHistoryFilters(params: {
3735
if (params.sessionStartedAt === undefined) {
3836
return true;
3937
}
40-
const messages = await readSessionMessagesAsync(
38+
// The anchored reader includes the immediately preceding row, which is the
39+
// complete context needed to hide a stale announce and its paired reply.
40+
const { messages } = await readSessionMessagesAroundIdWithStatsAsync(
4141
{
4242
agentId: params.agentId,
4343
sessionEntry: params.sessionEntry,
@@ -46,8 +46,8 @@ async function isChatMessageIdVisibleAfterHistoryFilters(params: {
4646
storePath: params.storePath,
4747
},
4848
{
49-
mode: "full",
50-
reason: "chat.message.get visibility",
49+
maxMessages: 1,
50+
messageId: params.messageId,
5151
...(params.allowResetArchiveFallback === true ? { allowResetArchiveFallback: true } : {}),
5252
},
5353
);

‎src/gateway/server-methods/sessions-read.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Read-only session queries.
2+
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
23
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
34
import {
45
ErrorCodes,
@@ -536,21 +537,16 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
536537
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, formatErrorMessage(error)));
537538
}
538539
},
539-
"sessions.preview": ({ params, respond, context, client }) => {
540+
"sessions.preview": async ({ params, respond, context, client }) => {
540541
if (!assertValidParams(params, validateSessionsPreviewParams, "sessions.preview", respond)) {
541542
return;
542543
}
543-
const p = params;
544-
const keys = (Array.isArray(p.keys) ? p.keys : [])
544+
const keys = (Array.isArray(params.keys) ? params.keys : [])
545545
.map((key) => normalizeOptionalString(key ?? ""))
546546
.filter((key): key is string => Boolean(key))
547547
.slice(0, 64);
548-
const limit =
549-
typeof p.limit === "number" && Number.isFinite(p.limit) ? Math.max(1, p.limit) : 12;
550-
const maxChars =
551-
typeof p.maxChars === "number" && Number.isFinite(p.maxChars)
552-
? Math.max(20, p.maxChars)
553-
: 240;
548+
const limit = params.limit ?? 12;
549+
const maxChars = params.maxChars ?? 240;
554550

555551
if (keys.length === 0) {
556552
respond(true, { ts: Date.now(), previews: [] } satisfies SessionsPreviewResult, undefined);
@@ -565,6 +561,9 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
565561
const previews: SessionsPreviewEntry[] = [];
566562

567563
for (const key of keys) {
564+
if (previews.length > 0) {
565+
await yieldToEventLoop();
566+
}
568567
const requestedAgent = resolveRequestedGlobalAgentId(cfg, key);
569568
if (!requestedAgent.ok) {
570569
respond(false, undefined, requestedAgent.error);

‎src/gateway/server.chat.gateway-server-chat-b.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6608,6 +6608,10 @@ describe("gateway server chat", () => {
66086608
expect(hidden.ok).toBe(false);
66096609
expect(hidden.unavailableReason).toBe("not_found");
66106610

6611+
const announce = await fetchChatMessage(ws, makeMainMessageParams("msg-announce"));
6612+
expect(announce.ok).toBe(false);
6613+
expect(announce.unavailableReason).toBe("not_found");
6614+
66116615
const visible = await fetchChatMessage(ws, makeMainMessageParams("msg-visible-assistant"));
66126616
expect(visible.ok).toBe(true);
66136617
expect(JSON.stringify(visible.message)).toContain("visible reply");

‎src/gateway/server.sessions.preview-resolve.test.ts‎

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
/**
22
* Gateway session preview resolve tests.
33
*/
4-
import { expect, test } from "vitest";
4+
import { expect, test, vi } from "vitest";
5+
import * as sessionAccessor from "../config/sessions/session-accessor.js";
6+
import * as sessionHistoryEvents from "../config/sessions/session-accessor.sqlite-history-events.js";
57
import type { GatewayClient } from "./server-methods/types.js";
68
import { createToolSummaryPreviewTranscriptLines } from "./session-preview.test-helpers.js";
79
import { rpcReq, writeSessionStore } from "./test-helpers.js";
@@ -14,6 +16,23 @@ import {
1416

1517
const { createSessionStoreDir, openClient } = setupGatewaySessionsTestHarness();
1618

19+
async function seedPreviewTail(
20+
sessionId: string,
21+
messages: Array<{ role: string; content: string }>,
22+
): Promise<void> {
23+
const { storePath } = await createSessionStoreDir();
24+
await writeSessionStore({
25+
entries: { "agent:main:main": sessionStoreEntry(sessionId) },
26+
});
27+
await sessionAccessor.persistSessionTranscriptTurn(
28+
{ agentId: "main", sessionId, sessionKey: "agent:main:main", storePath },
29+
{
30+
messages: messages.map((message) => ({ message })),
31+
touchSessionEntry: false,
32+
},
33+
);
34+
}
35+
1736
function identifiedClient(profileId: string, scopes: string[] = ["operator.read"]): GatewayClient {
1837
return {
1938
connect: {
@@ -113,6 +132,74 @@ test("sessions.preview honors maxChars up to the shared cap", async () => {
113132
]);
114133
});
115134

135+
test("sessions.preview reads only a bounded tail from a large transcript", async () => {
136+
await seedPreviewTail(
137+
"sess-preview-bounded-tail",
138+
Array.from({ length: 1024 }, (_, index) => ({
139+
role: "assistant",
140+
content: `message ${String(index)}`,
141+
})),
142+
);
143+
const fullRead = vi.spyOn(sessionAccessor, "readSessionTranscriptMessageEvents");
144+
const tailRead = vi.spyOn(sessionHistoryEvents, "readRecentSessionTranscriptHistoryEvents");
145+
146+
try {
147+
const preview = await directSessionReq<{
148+
previews: Array<{ items: Array<{ role: string; text: string }> }>;
149+
}>("sessions.preview", { keys: ["main"], limit: 12, maxChars: 120 });
150+
151+
expect(preview.ok).toBe(true);
152+
expect(preview.payload?.previews[0]?.items).toEqual(
153+
Array.from({ length: 12 }, (_, index) => ({
154+
role: "assistant",
155+
text: `message ${String(1012 + index)}`,
156+
})),
157+
);
158+
expect(fullRead).not.toHaveBeenCalled();
159+
expect(tailRead).toHaveBeenCalledOnce();
160+
expect(tailRead.mock.results[0]).toMatchObject({
161+
type: "return",
162+
value: { events: { length: 64 }, totalMessages: 1024 },
163+
});
164+
} finally {
165+
fullRead.mockRestore();
166+
tailRead.mockRestore();
167+
}
168+
});
169+
170+
test("sessions.preview widens its bounded tail past filtered tool-result rows", async () => {
171+
await seedPreviewTail("sess-preview-sparse-tail", [
172+
...Array.from({ length: 12 }, (_, index) => ({
173+
role: "assistant",
174+
content: `visible ${String(index)}`,
175+
})),
176+
...Array.from({ length: 320 }, (_, index) => ({
177+
role: "toolResult",
178+
content: `tool ${String(index)}`,
179+
})),
180+
]);
181+
const tailRead = vi.spyOn(sessionHistoryEvents, "readRecentSessionTranscriptHistoryEvents");
182+
183+
try {
184+
const preview = await directSessionReq<{
185+
previews: Array<{ items: Array<{ role: string; text: string }> }>;
186+
}>("sessions.preview", { keys: ["main"], limit: 12, maxChars: 120 });
187+
188+
expect(preview.payload?.previews[0]?.items).toEqual(
189+
Array.from({ length: 12 }, (_, index) => ({
190+
role: "assistant",
191+
text: `visible ${String(index)}`,
192+
})),
193+
);
194+
expect(tailRead.mock.calls.map(([, options]) => options)).toEqual([
195+
{ maxBytes: 1024 * 1024, maxLines: 64, maxMessages: 64 },
196+
{ maxBytes: 8 * 1024 * 1024, maxLines: 1024, maxMessages: 1024 },
197+
]);
198+
} finally {
199+
tailRead.mockRestore();
200+
}
201+
});
202+
116203
test("sessions.resolve by sessionId ignores fuzzy-search list limits and returns the exact match", async () => {
117204
await createSessionStoreDir();
118205
const now = Date.now();

‎src/gateway/session-transcript-readers.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,33 @@ function buildSqlitePreviewItems(
252252
maxItems: number,
253253
maxChars: number,
254254
): SessionPreviewItem[] {
255-
return buildSessionPreviewItems(readSqliteMessagesSync(target), maxItems, maxChars);
255+
// Tool-only and suppressed rows need headroom; cap even the recovery scan so previews
256+
// never materialize an entire large transcript or monopolize the Gateway thread.
257+
const initialMaxEvents = Math.min(256, Math.max(64, Math.ceil(maxItems) * 4));
258+
const readPreviewPage = (maxEvents: number, maxBytes: number) => {
259+
const page = readRecentSessionTranscriptHistoryEvents(toTranscriptReadScope(target), {
260+
maxBytes,
261+
maxLines: maxEvents,
262+
maxMessages: maxEvents,
263+
});
264+
return {
265+
items: buildSessionPreviewItems(
266+
extractMessageRecordsFromEventEntries(page.events).map(sqliteRecordMessageWithSeq),
267+
maxItems,
268+
maxChars,
269+
),
270+
hasOlderEvents: page.totalMessages > page.events.length,
271+
};
272+
};
273+
const preview = readPreviewPage(initialMaxEvents, 1024 * 1024);
274+
if (preview.items.length >= maxItems || !preview.hasOlderEvents) {
275+
return preview.items;
276+
}
277+
const recoveryMaxEvents = Math.min(
278+
2048,
279+
Math.max(1024, initialMaxEvents * 8, Math.ceil(maxItems)),
280+
);
281+
return readPreviewPage(recoveryMaxEvents, 8 * 1024 * 1024).items;
256282
}
257283

258284
/** Reads display messages asynchronously through the reader seam. */

0 commit comments

Comments
 (0)