Skip to content

Commit d2b0f80

Browse files
committed
perf(sessions): cache branch summaries behind a transcript watermark
1 parent b34c196 commit d2b0f80

2 files changed

Lines changed: 268 additions & 7 deletions

File tree

‎src/config/sessions/session-accessor.sqlite-message-cut.test.ts‎

Lines changed: 175 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1-
import { afterEach, describe, expect, it } from "vitest";
1+
import { afterEach, describe, expect, it, vi } from "vitest";
22
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
3-
import { closeOpenClawAgentDatabasesForTest } from "../../state/openclaw-agent-db.js";
3+
import {
4+
closeOpenClawAgentDatabasesForTest,
5+
openOpenClawAgentDatabase,
6+
} from "../../state/openclaw-agent-db.js";
47
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
58
import {
69
deliveryContextFromSession,
@@ -19,16 +22,52 @@ import {
1922
switchSessionBranch,
2023
upsertSessionEntry,
2124
} from "./session-accessor.js";
25+
import { listSqliteSessionBranches } from "./session-accessor.sqlite.js";
2226

2327
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
2428
const agentId = "main";
2529
const sessionKey = "agent:main:message-cut";
2630

2731
afterEach(() => {
32+
vi.restoreAllMocks();
2833
closeOpenClawAgentDatabasesForTest();
2934
closeOpenClawStateDatabaseForTest();
3035
});
3136

37+
function trackFullTranscriptLoads(env: NodeJS.ProcessEnv): () => number {
38+
const database = openOpenClawAgentDatabase({ agentId, env });
39+
const prepare = vi.spyOn(database.db, "prepare");
40+
return () =>
41+
prepare.mock.calls.filter(
42+
([sql]) =>
43+
sql.includes('select "event_json" from "transcript_events"') &&
44+
sql.includes('order by "seq" asc'),
45+
).length;
46+
}
47+
48+
async function createSiblingSession(params: {
49+
env: NodeJS.ProcessEnv;
50+
headline: string;
51+
sessionId: string;
52+
sessionKey: string;
53+
}) {
54+
const scope = { agentId, ...params };
55+
await upsertSessionEntry(scope, { sessionId: params.sessionId, updatedAt: Date.now() });
56+
await appendTranscriptEvent(scope, {
57+
type: "session",
58+
id: params.sessionId,
59+
version: 3,
60+
timestamp: "2026-07-18T01:00:00.000Z",
61+
});
62+
await appendTranscriptMessage(scope, {
63+
eventId: `${params.sessionId}-user`,
64+
message: { role: "user", content: params.headline },
65+
now: Date.parse("2026-07-18T01:00:01.000Z"),
66+
parentId: null,
67+
});
68+
return scope;
69+
}
70+
3271
async function createSession(options: { activeLeafTarget?: string } = {}) {
3372
const stateDir = tempDirs.make("openclaw-message-cut-");
3473
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
@@ -127,6 +166,140 @@ async function createSession(options: { activeLeafTarget?: string } = {}) {
127166
}
128167

129168
describe("SQLite session message cuts", () => {
169+
it("reuses branch summaries while the transcript watermark is unchanged", async () => {
170+
const { env } = await createSession();
171+
const fullTranscriptLoads = trackFullTranscriptLoads(env);
172+
173+
const first = await listSqliteSessionBranches({ agentId, env, sessionKey });
174+
expect(fullTranscriptLoads()).toBe(1);
175+
176+
const second = await listSqliteSessionBranches({ agentId, env, sessionKey });
177+
expect(second).toEqual(first);
178+
expect(fullTranscriptLoads()).toBe(1);
179+
if (second.status !== "ok" || !second.branches[0]) {
180+
throw new Error("expected cached branch list result");
181+
}
182+
second.branches[0].headline = "caller mutation";
183+
184+
await expect(listSqliteSessionBranches({ agentId, env, sessionKey })).resolves.toEqual(first);
185+
expect(fullTranscriptLoads()).toBe(1);
186+
});
187+
188+
it("recomputes branch summaries after an append advances the watermark", async () => {
189+
const { env, scope } = await createSession();
190+
const fullTranscriptLoads = trackFullTranscriptLoads(env);
191+
192+
const before = await listSqliteSessionBranches({ agentId, env, sessionKey });
193+
expect(fullTranscriptLoads()).toBe(1);
194+
await appendTranscriptMessage(scope, {
195+
eventId: "assistant-3",
196+
message: { role: "assistant", content: "third answer" },
197+
now: Date.parse("2026-07-18T00:00:07.000Z"),
198+
parentId: "assistant-2",
199+
});
200+
201+
const after = await listSqliteSessionBranches({ agentId, env, sessionKey });
202+
expect(fullTranscriptLoads()).toBe(2);
203+
expect(after).not.toEqual(before);
204+
expect(after.status).toBe("ok");
205+
if (after.status !== "ok") {
206+
throw new Error("expected branch list result");
207+
}
208+
expect(after.branches.find((branch) => branch.active)).toMatchObject({
209+
leafEntryId: "assistant-3",
210+
headline: "third answer",
211+
});
212+
});
213+
214+
it.each(["rewind", "switch", "fork"] as const)(
215+
"%s invalidates the source cache and lists the resulting branch",
216+
async (mode) => {
217+
const { env, scope } = await createSession();
218+
const aliasKey = `${sessionKey}:alias`;
219+
const targetKey = `${sessionKey}:fork`;
220+
const sourceEntry = loadSessionEntry(scope);
221+
if (!sourceEntry) {
222+
throw new Error("expected source session entry");
223+
}
224+
await upsertSessionEntry({ agentId, env, sessionKey: aliasKey }, sourceEntry);
225+
const fullTranscriptLoads = trackFullTranscriptLoads(env);
226+
await listSqliteSessionBranches({ agentId, env, sessionKey });
227+
228+
const result =
229+
mode === "rewind"
230+
? await rewindSessionToMessage({ agentId, env, entryId: "user-2", sessionKey })
231+
: mode === "switch"
232+
? await switchSessionBranch({
233+
agentId,
234+
env,
235+
leafEntryId: "off-path-user",
236+
sessionKey,
237+
})
238+
: await forkSessionAtMessage({
239+
agentId,
240+
env,
241+
entryId: "user-2",
242+
sessionKey,
243+
targetKey,
244+
});
245+
expect(result.status).toBe("created");
246+
247+
const loadsBeforeAliasRead = fullTranscriptLoads();
248+
await listSqliteSessionBranches({ agentId, env, sessionKey: aliasKey });
249+
expect(fullTranscriptLoads()).toBe(loadsBeforeAliasRead + 1);
250+
251+
const listed = await listSqliteSessionBranches({
252+
agentId,
253+
env,
254+
sessionKey: mode === "fork" ? targetKey : sessionKey,
255+
});
256+
expect(listed.status).toBe("ok");
257+
if (listed.status !== "ok") {
258+
throw new Error("expected branch list result");
259+
}
260+
expect(listed.branches.find((branch) => branch.active)).toMatchObject({
261+
leafEntryId: mode === "switch" ? "off-path-user" : "assistant-1",
262+
});
263+
},
264+
);
265+
266+
it("keeps branch summaries isolated between sessions in the same store", async () => {
267+
const { env } = await createSession();
268+
const sibling = await createSiblingSession({
269+
env,
270+
headline: "sibling prompt",
271+
sessionId: "message-cut-sibling",
272+
sessionKey: `${sessionKey}:sibling`,
273+
});
274+
const fullTranscriptLoads = trackFullTranscriptLoads(env);
275+
276+
const source = await listSqliteSessionBranches({ agentId, env, sessionKey });
277+
const other = await listSqliteSessionBranches(sibling);
278+
expect(fullTranscriptLoads()).toBe(2);
279+
expect(source.status).toBe("ok");
280+
if (source.status !== "ok") {
281+
throw new Error("expected source branch list result");
282+
}
283+
expect(source.branches.find((branch) => branch.active)).toMatchObject({
284+
leafEntryId: "assistant-2",
285+
headline: "second answer",
286+
});
287+
expect(other).toEqual({
288+
status: "ok",
289+
branches: [
290+
{
291+
active: true,
292+
headline: "sibling prompt",
293+
leafEntryId: "message-cut-sibling-user",
294+
messageCount: 1,
295+
updatedAt: "2026-07-18T01:00:01.000Z",
296+
},
297+
],
298+
});
299+
await expect(listSqliteSessionBranches({ agentId, env, sessionKey })).resolves.toEqual(source);
300+
expect(fullTranscriptLoads()).toBe(2);
301+
});
302+
130303
it("lists every DAG tip with active state, headline, count, and timestamp", async () => {
131304
const { env } = await createSession({ activeLeafTarget: "assistant-1" });
132305

‎src/config/sessions/session-accessor.sqlite-message-cut.ts‎

Lines changed: 93 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { randomUUID } from "node:crypto";
22
import { asOptionalRecord as asRecord } from "@openclaw/normalization-core/record-coerce";
33
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
4+
import { executeSqliteQueryTakeFirstSync } from "../../infra/kysely-sync.js";
45
import { extractAssistantVisibleText } from "../../shared/chat-message-content.js";
56
import {
67
openOpenClawAgentDatabase,
@@ -18,6 +19,7 @@ import { emitCommittedSessionIdentityDiff } from "./session-accessor.sqlite-iden
1819
import { loadSqliteTranscriptEventsFromDatabase } from "./session-accessor.sqlite-read.js";
1920
import {
2021
formatSqliteSessionMarkerForScope,
22+
getSessionKysely,
2123
normalizeSqliteSessionKey,
2224
resolveSqliteScope,
2325
runExclusiveSqliteSessionWrite,
@@ -62,6 +64,80 @@ type SessionTranscriptMutationResult =
6264
type SessionTranscriptMutationMode = "fork" | "rewind" | "switch";
6365

6466
const BRANCH_HEADLINE_MAX_CHARS = 120;
67+
const SESSION_BRANCH_CACHE_MAX_ENTRIES = 32;
68+
69+
type SessionBranchCacheEntry = {
70+
branches: SessionBranchSummary[];
71+
generation: string | null;
72+
maxSeq: number | null;
73+
};
74+
75+
// Branch listing must not scale with transcript size on every request. Appends advance max(seq),
76+
// while every in-place or replacement path rotates generation; cap the validated LRU at 32 sessions.
77+
const sessionBranchCache = new Map<string, SessionBranchCacheEntry>();
78+
79+
function sessionBranchCacheKey(databasePath: string, sessionId: string): string {
80+
return `${databasePath}\0${sessionId}`;
81+
}
82+
83+
function cloneSessionBranchSummaries(branches: readonly SessionBranchSummary[]) {
84+
return branches.map((branch) => ({ ...branch }));
85+
}
86+
87+
function readSessionBranchWatermark(
88+
database: OpenClawAgentDatabase,
89+
sessionId: string,
90+
): Pick<SessionBranchCacheEntry, "generation" | "maxSeq"> {
91+
const db = getSessionKysely(database.db);
92+
const maxSeq = executeSqliteQueryTakeFirstSync(
93+
database.db,
94+
db
95+
.selectFrom("transcript_events")
96+
.select((eb) => eb.fn.max<number>("seq").as("max_seq"))
97+
.where("session_id", "=", sessionId),
98+
)?.max_seq;
99+
const generation = executeSqliteQueryTakeFirstSync(
100+
database.db,
101+
db
102+
.selectFrom("transcript_rewrite_watermarks")
103+
.select("generation")
104+
.where("session_id", "=", sessionId),
105+
)?.generation;
106+
return { generation: generation ?? null, maxSeq: maxSeq ?? null };
107+
}
108+
109+
function loadSessionBranchSummaries(
110+
database: OpenClawAgentDatabase,
111+
sessionId: string,
112+
): SessionBranchSummary[] {
113+
const cacheKey = sessionBranchCacheKey(database.path, sessionId);
114+
const watermark = readSessionBranchWatermark(database, sessionId);
115+
const cached = sessionBranchCache.get(cacheKey);
116+
if (cached?.generation === watermark.generation && cached.maxSeq === watermark.maxSeq) {
117+
sessionBranchCache.delete(cacheKey);
118+
sessionBranchCache.set(cacheKey, cached);
119+
return cloneSessionBranchSummaries(cached.branches);
120+
}
121+
122+
const branches = summarizeSessionBranches(
123+
loadSqliteTranscriptEventsFromDatabase(database, sessionId),
124+
);
125+
sessionBranchCache.delete(cacheKey);
126+
sessionBranchCache.set(cacheKey, { ...watermark, branches });
127+
if (sessionBranchCache.size > SESSION_BRANCH_CACHE_MAX_ENTRIES) {
128+
const oldestKey = sessionBranchCache.keys().next().value;
129+
if (oldestKey !== undefined) {
130+
sessionBranchCache.delete(oldestKey);
131+
}
132+
}
133+
return cloneSessionBranchSummaries(branches);
134+
}
135+
136+
function invalidateSessionBranchCache(databasePath: string, sessionIds: readonly string[]): void {
137+
for (const sessionId of uniqueStrings(sessionIds)) {
138+
sessionBranchCache.delete(sessionBranchCacheKey(databasePath, sessionId));
139+
}
140+
}
65141

66142
export async function listSqliteSessionBranches(
67143
params: SessionBranchListParams,
@@ -85,8 +161,10 @@ export async function listSqliteSessionBranches(
85161
) {
86162
return { status: "unsupported-storage" };
87163
}
88-
const events = loadSqliteTranscriptEventsFromDatabase(database, currentEntry.sessionId);
89-
return { status: "ok", branches: summarizeSessionBranches(events) };
164+
return {
165+
status: "ok",
166+
branches: loadSessionBranchSummaries(database, currentEntry.sessionId),
167+
};
90168
} catch {
91169
return { status: "failed" };
92170
}
@@ -141,16 +219,17 @@ async function mutateSqliteSessionAtMessage(
141219
...(params.storePath ? { storePath: params.storePath } : {}),
142220
});
143221
return await runExclusiveSqliteSessionWrite(resolved, async () => {
144-
let result: SessionTranscriptMutationResult = { status: "failed" };
145222
let previousIdentity = new Map<string, SessionEntry>();
146223
let currentIdentity = new Map<string, SessionEntry>();
147-
runOpenClawAgentWriteTransaction((database) => {
224+
let databasePath: string | undefined;
225+
const result = runOpenClawAgentWriteTransaction((database) => {
226+
databasePath = database.path;
148227
const identityKeys = uniqueStrings([
149228
...collectSessionEntryLookupKeys(database, sourceKey),
150229
...collectSessionEntryLookupKeys(database, targetKey),
151230
]);
152231
previousIdentity = readSqliteSessionIdentitySnapshot(database, identityKeys);
153-
result = mutateSqliteSessionAtMessageInTransaction(database, resolved, {
232+
const mutationResult = mutateSqliteSessionAtMessageInTransaction(database, resolved, {
154233
entryId: params.entryId,
155234
canonicalSourceKey,
156235
creation: params.creation,
@@ -159,7 +238,16 @@ async function mutateSqliteSessionAtMessage(
159238
targetKey,
160239
});
161240
currentIdentity = readSqliteSessionIdentitySnapshot(database, identityKeys);
241+
return mutationResult;
162242
}, toDatabaseOptions(resolved));
243+
if (result.status === "created" && databasePath) {
244+
invalidateSessionBranchCache(databasePath, [
245+
...[...previousIdentity.values()].flatMap((entry) =>
246+
entry.sessionId ? [entry.sessionId] : [],
247+
),
248+
...(result.entry.sessionId ? [result.entry.sessionId] : []),
249+
]);
250+
}
163251
emitCommittedSessionIdentityDiff(previousIdentity, currentIdentity);
164252
return result;
165253
});

0 commit comments

Comments
 (0)