Skip to content

Commit 6327e0c

Browse files
committed
perf(sessions): speed up retained history reads
1 parent 83b6125 commit 6327e0c

4 files changed

Lines changed: 163 additions & 130 deletions

‎src/config/sessions/session-accessor.sqlite-active-events.ts‎

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ import type {
1616
} from "./session-accessor.sqlite-contract.js";
1717
import {
1818
readTranscriptProjectionGeneration,
19+
readVisibleMessageMetadata,
1920
readVisibleMessageRange,
2021
readVisibleTranscriptStats,
21-
resolveVisibleMessagePositionRange,
2222
resolveVisibleMessagePositions,
2323
} from "./session-accessor.sqlite-reset-window.js";
2424
import {
@@ -456,45 +456,28 @@ export function readSessionTranscriptBoundedMessageTailPage(
456456
);
457457
const endExclusive = Math.max(0, totalMessages - offset);
458458
const start = Math.max(0, endExclusive - maxMessages);
459-
const positions = resolveVisibleMessagePositionRange(projection, start, endExclusive);
460-
if (positions.length === 0 || maxBytes === 0) {
459+
const scannedMessages = endExclusive - start;
460+
if (scannedMessages === 0 || maxBytes === 0) {
461461
return {
462462
activeLeafEntryId: projection.state.leafEventId,
463463
events: [],
464464
newestContiguousEventCount: 0,
465-
scannedMessages: positions.length,
465+
scannedMessages,
466466
serializedBytes: 0,
467467
snapshot,
468468
totalMessages,
469469
};
470470
}
471471
const db = getActiveTranscriptKysely(projection.database);
472-
const metadata = executeSqliteQuerySync(
473-
projection.database.db,
474-
db
475-
.selectFrom("session_transcript_active_events as active")
476-
.innerJoin("transcript_events as event", (join) =>
477-
join
478-
.onRef("event.session_id", "=", "active.session_id")
479-
.onRef("event.seq", "=", "active.event_seq"),
480-
)
481-
.select([
482-
"active.message_position",
483-
/* kysely-allow-raw: byte budget covers the exact newline-terminated JSON event. */
484-
sql<number>`OCTET_LENGTH(event.event_json) + 1`.as("serialized_bytes"),
485-
])
486-
.where("active.session_id", "=", projection.resolved.sessionId)
487-
.where("active.message_position", "in", positions)
488-
.orderBy("active.message_position", "desc"),
489-
).rows;
490-
if (metadata.length !== positions.length) {
472+
const metadata = readVisibleMessageMetadata(projection, start, endExclusive).toReversed();
473+
if (metadata.length !== scannedMessages) {
491474
throw new Error("Active transcript bounded message page is incomplete");
492475
}
493476
const selectedPositions: number[] = [];
494477
let newestContiguousEventCount: number | undefined;
495478
let serializedBytes = 0;
496479
for (const row of metadata) {
497-
if (row.message_position === null || serializedBytes + row.serialized_bytes > maxBytes) {
480+
if (serializedBytes + row.serialized_bytes > maxBytes) {
498481
newestContiguousEventCount ??= selectedPositions.length;
499482
continue;
500483
}
@@ -522,7 +505,7 @@ export function readSessionTranscriptBoundedMessageTailPage(
522505
activeLeafEntryId: projection.state.leafEventId,
523506
events,
524507
newestContiguousEventCount: newestContiguousEventCount ?? selectedPositions.length,
525-
scannedMessages: positions.length,
508+
scannedMessages,
526509
serializedBytes,
527510
snapshot,
528511
totalMessages,

‎src/config/sessions/session-accessor.sqlite-history-events.test.ts‎

Lines changed: 74 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,14 @@ function historyEventId(entry: { event: unknown } | undefined): unknown {
2727
return event && typeof event === "object" && "id" in event ? event.id : undefined;
2828
}
2929

30-
function enforceSqliteVariableLimit(database: OpenClawAgentDatabase): void {
30+
function enforceSqliteVariableLimit(
31+
database: OpenClawAgentDatabase,
32+
limit = REGRESSION_SQLITE_VARIABLE_LIMIT,
33+
): void {
3134
const prepare = database.db.prepare.bind(database.db);
3235
vi.spyOn(database.db, "prepare").mockImplementation((source) => {
3336
const variableCount = source.match(/\?/gu)?.length ?? 0;
34-
if (variableCount > REGRESSION_SQLITE_VARIABLE_LIMIT) {
37+
if (variableCount > limit) {
3538
throw new Error("too many SQL variables");
3639
}
3740
return prepare(source);
@@ -318,30 +321,84 @@ describe("SQLite transcript history events", () => {
318321
expect(events.map(historyEventId)).toEqual(["seed", "active-boundary-2", "active-boundary-4"]);
319322
});
320323

321-
it("bounds metadata bindings when the raw history window exceeds SQLite's limit", async () => {
324+
it.each([REGRESSION_MAX_MESSAGES, REGRESSION_SQLITE_VARIABLE_LIMIT + 1])(
325+
"reads %s recent messages with bounded metadata bindings",
326+
async (maxMessages) => {
327+
await persistSessionTranscriptTurn(scope, {
328+
messages: [{ eventId: "seed", parentId: null, message: { role: "user", content: "seed" } }],
329+
touchSessionEntry: false,
330+
});
331+
const database = openOpenClawAgentDatabase({ agentId: scope.agentId, env: scope.env });
332+
const bindingCount = Math.max(REGRESSION_SQLITE_VARIABLE_LIMIT, maxMessages);
333+
insertSyntheticHistory(database, scope.sessionId, bindingCount);
334+
enforceSqliteVariableLimit(database);
335+
336+
const page = readRecentSessionTranscriptHistoryEvents(scope, {
337+
maxBytes: 1_000_000,
338+
maxLines: bindingCount + 1,
339+
maxMessages,
340+
});
341+
342+
expect(page.totalMessages).toBe(bindingCount + 1);
343+
expect(page.events).toHaveLength(maxMessages);
344+
expect(historyEventId(page.events[0])).toBe(
345+
`synthetic-message-${String(bindingCount - maxMessages + 2)}`,
346+
);
347+
expect(historyEventId(page.events.at(-1))).toBe(
348+
`synthetic-message-${String(bindingCount + 1)}`,
349+
);
350+
},
351+
);
352+
353+
it("batches sparse reset history without reviving discarded tool results", async () => {
354+
const keptIds = Array.from({ length: 1_001 }, (_, index) => `kept-${index}`);
322355
await persistSessionTranscriptTurn(scope, {
323-
messages: [{ eventId: "seed", parentId: null, message: { role: "user", content: "seed" } }],
356+
messages: keptIds.flatMap((eventId, index) => [
357+
{
358+
eventId,
359+
parentId: index === 0 ? null : `tool-${index - 1}`,
360+
message: { role: "user", content: eventId },
361+
},
362+
{
363+
eventId: `tool-${index}`,
364+
parentId: eventId,
365+
message: { role: "toolResult", content: "discarded orphan result" },
366+
},
367+
]),
368+
touchSessionEntry: false,
369+
});
370+
await appendTranscriptEvent(scope, {
371+
type: "reset",
372+
id: "reset",
373+
parentId: "tool-1000",
374+
timestamp: "2026-08-30T00:00:00.000Z",
375+
reason: "new",
376+
firstKeptEntryId: keptIds[0],
377+
});
378+
await persistSessionTranscriptTurn(scope, {
379+
messages: [
380+
{ eventId: "fresh", parentId: "reset", message: { role: "user", content: "fresh" } },
381+
],
324382
touchSessionEntry: false,
325383
});
326384
const database = openOpenClawAgentDatabase({ agentId: scope.agentId, env: scope.env });
327-
const bindingCount = REGRESSION_SQLITE_VARIABLE_LIMIT;
328-
insertSyntheticHistory(database, scope.sessionId, bindingCount);
329-
enforceSqliteVariableLimit(database);
385+
enforceSqliteVariableLimit(database, 999);
330386

331387
const page = readRecentSessionTranscriptHistoryEvents(scope, {
332388
maxBytes: 1_000_000,
333-
maxLines: bindingCount + 1,
334-
maxMessages: REGRESSION_MAX_MESSAGES,
389+
maxLines: 2_010,
390+
maxMessages: keptIds.length + 2,
335391
});
336-
337-
expect(page.totalMessages).toBe(bindingCount + 1);
338-
expect(page.events).toHaveLength(REGRESSION_MAX_MESSAGES);
339-
expect(historyEventId(page.events[0])).toBe(
340-
`synthetic-message-${String(bindingCount - REGRESSION_MAX_MESSAGES + 2)}`,
341-
);
342-
expect(historyEventId(page.events.at(-1))).toBe(
343-
`synthetic-message-${String(bindingCount + 1)}`,
392+
expect(page.totalMessages).toBe(keptIds.length + 2);
393+
expect(page.events.map(historyEventId)).toEqual([...keptIds, "reset", "fresh"]);
394+
expect(page.events.map(({ seq }) => seq)).toEqual(
395+
Array.from({ length: keptIds.length + 2 }, (_, index) => index + 1),
344396
);
397+
expect(
398+
readSessionTranscriptHistoryEventPage(scope, { offset: 500, maxMessages: 2 }).events.map(
399+
historyEventId,
400+
),
401+
).toEqual(["kept-501", "kept-502"]);
345402
});
346403

347404
it("reads more boundaries than SQLite permits as statement bindings", async () => {

‎src/config/sessions/session-accessor.sqlite-history-events.ts‎

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ import {
3030
} from "./session-accessor.sqlite-display-position.js";
3131
import {
3232
readTranscriptProjectionGeneration,
33+
readVisibleMessageMetadata,
3334
readVisibleMessageRange,
34-
resolveVisibleMessagePositionRange,
3535
resolveVisibleMessagePositions,
3636
} from "./session-accessor.sqlite-reset-window.js";
3737
import { MAX_VISIBLE_MESSAGE_MAX_MESSAGES } from "./session-accessor.sqlite-visible-cursor.js";
@@ -217,36 +217,15 @@ function resolveRecentHistoryStart(
217217
const { boundedEnd, boundedStart, boundaries, messageEnd, messageStart } =
218218
resolveVisibleHistoryRange(history, start, endExclusive);
219219
// No result can include more than maxMessages events, so older metadata would
220-
// only add SQLite bindings and synchronous work before the backward scan stops.
220+
// only add synchronous work before the backward scan stops.
221221
const metadataStart = Math.max(messageStart, messageEnd - maxMessages);
222-
const positions = resolveVisibleMessagePositionRange(projection, metadataStart, messageEnd);
223-
const db = getActiveTranscriptKysely(projection.database);
224222
const messageBytes = new Map(
225-
positions.length === 0
226-
? []
227-
: executeSqliteQuerySync(
228-
projection.database.db,
229-
db
230-
.selectFrom("session_transcript_active_events as active")
231-
.innerJoin("transcript_events as event", (join) =>
232-
join
233-
.onRef("event.session_id", "=", "active.session_id")
234-
.onRef("event.seq", "=", "active.event_seq"),
235-
)
236-
.select([
237-
"active.message_position",
238-
/* kysely-allow-raw: excluded history payloads must not be fetched or parsed. */
239-
sql<number>`OCTET_LENGTH(event.event_json) + 1`.as("serialized_bytes"),
240-
])
241-
.where("active.session_id", "=", projection.resolved.sessionId)
242-
.where("active.message_position", "in", positions),
243-
).rows.flatMap((row) =>
244-
row.message_position === null
245-
? []
246-
: [[row.message_position, row.serialized_bytes] as const],
247-
),
223+
readVisibleMessageMetadata(projection, metadataStart, messageEnd).map((row) => [
224+
row.logicalPosition,
225+
row.serialized_bytes,
226+
]),
248227
);
249-
let messageIndex = positions.length - 1;
228+
let messageIndex = messageEnd - 1;
250229
let selectedStart = boundedEnd;
251230
let selectedCount = 0;
252231
let bytes = 0;
@@ -259,10 +238,10 @@ function resolveRecentHistoryStart(
259238
break;
260239
}
261240
const boundary = boundaries.get(displayPosition);
262-
const messagePosition = boundary ? undefined : positions[messageIndex--];
241+
const logicalPosition = boundary ? undefined : messageIndex--;
263242
const serializedBytes =
264243
boundary?.serializedBytes ??
265-
(messagePosition === undefined ? undefined : messageBytes.get(messagePosition));
244+
(logicalPosition === undefined ? undefined : messageBytes.get(logicalPosition));
266245
if (serializedBytes === undefined) {
267246
continue;
268247
}

0 commit comments

Comments
 (0)