Skip to content

Commit 279a12c

Browse files
njuboy11obviyus
andauthored
fix(sessions): memoize shared branch summaries (#123541)
Memoize ancestor branch summaries during each cold SQLite transcript scan so long-lived sessions do not repeat the same root-path work for every branch tip. Preserve active-first ordering, missing-parent and cycle behavior, and canonical duplicate-ID results from exact SQLite imports. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 6e63194 commit 279a12c

3 files changed

Lines changed: 142 additions & 23 deletions

File tree

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

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
withOpenClawTestState,
99
type OpenClawTestState,
1010
} from "../../test-utils/openclaw-test-state.js";
11+
import { listSessionBranches } from "./session-accessor.js";
1112
import { loadExactSessionEntry } from "./session-accessor.sqlite-entry.js";
1213
import {
1314
importSqliteSessionRows,
@@ -197,10 +198,16 @@ it("hands off exact SQLite bytes, duplicate IDs, timestamps and owner without ap
197198
await withOpenClawTestState({ label: "import-exact" }, async (state) => {
198199
const params = target(state, "exact");
199200
const owner = { actor: { type: "human" as const, id: "owner" }, assignedAt: 40 };
201+
const firstMessage = { ...message, timestamp: "2026-08-30T00:00:01.000Z" };
202+
const canonicalMessage = {
203+
...message,
204+
timestamp: "2026-08-30T00:00:02.000Z",
205+
message: { role: "user", content: "canonical duplicate" },
206+
};
200207
const rows = [
201208
{ createdAt: 41, eventJson: '{ "type": "session", "id": "exact", "version": 3 }' },
202-
{ createdAt: 43, eventJson: JSON.stringify(message, null, 2) },
203-
{ createdAt: 45, eventJson: JSON.stringify(message) },
209+
{ createdAt: 43, eventJson: JSON.stringify(firstMessage, null, 2) },
210+
{ createdAt: 45, eventJson: JSON.stringify(canonicalMessage) },
204211
];
205212
await importSqliteSessionRows({
206213
...params,
@@ -231,6 +238,16 @@ it("hands off exact SQLite bytes, duplicate IDs, timestamps and owner without ap
231238
}),
232239
).toMatchObject({ skippedExisting: true, transcriptEvents: 0 });
233240
expect(loadTranscriptEventsSync({ ...params, sessionId: "exact" })).toHaveLength(3);
241+
await expect(listSessionBranches(params)).resolves.toEqual({
242+
status: "ok",
243+
branches: Array.from({ length: 2 }, () => ({
244+
leafEntryId: "one",
245+
headline: "canonical duplicate",
246+
messageCount: 1,
247+
updatedAt: canonicalMessage.timestamp,
248+
active: true,
249+
})),
250+
});
234251
});
235252
});
236253

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

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
recordSessionParticipant,
2222
readSessionTranscriptMessageEventPage,
2323
readSessionTranscriptMessageEvents,
24+
replaceTranscriptEvents,
2425
rewindSessionToMessage,
2526
switchSessionBranch,
2627
updateSessionEntry,
@@ -418,6 +419,80 @@ describe("SQLite session message cuts", () => {
418419
});
419420
});
420421

422+
it("summarizes a large shared branch graph without repeated path walks", async () => {
423+
const stateDir = tempDirs.make("openclaw-large-branches-");
424+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
425+
const sessionId = "large-branches-source";
426+
const scope = { agentId, env, sessionId, sessionKey };
427+
await upsertSessionEntryCore(scope, { sessionId, updatedAt: Date.now() });
428+
const events: Parameters<typeof replaceTranscriptEvents>[1] = [
429+
{
430+
type: "session",
431+
id: sessionId,
432+
version: 3,
433+
timestamp: "2026-08-30T00:00:00.000Z",
434+
},
435+
{
436+
type: "message",
437+
id: "orphan-user",
438+
parentId: "missing-ancestor",
439+
timestamp: "2026-08-30T00:00:01.000Z",
440+
message: { role: "user", content: "orphan prompt" },
441+
},
442+
{
443+
type: "message",
444+
id: "orphan-assistant",
445+
parentId: "orphan-user",
446+
timestamp: "2026-08-30T00:00:02.000Z",
447+
message: { role: "assistant", content: "orphan answer" },
448+
},
449+
];
450+
for (let index = 1; index <= 12_554; index += 1) {
451+
events.push({
452+
type: "message",
453+
id: `main-${index}`,
454+
parentId: index === 1 ? null : `main-${index - 1}`,
455+
timestamp: new Date(Date.UTC(2026, 7, 30, 0, 0, index)).toISOString(),
456+
message: { role: index % 2 === 0 ? "assistant" : "user", content: `main ${index}` },
457+
});
458+
}
459+
for (let index = 1; index <= 1_360; index += 1) {
460+
events.push({
461+
type: "message",
462+
id: `side-${index}`,
463+
parentId: "main-5376",
464+
appendMode: "side",
465+
timestamp: new Date(Date.UTC(2026, 7, 30, 1, 0, index)).toISOString(),
466+
message: { role: "assistant", content: `side ${index}` },
467+
});
468+
}
469+
events.push({
470+
type: "leaf",
471+
id: "active-leaf",
472+
parentId: "main-12554",
473+
targetId: "main-12554",
474+
timestamp: "2026-08-30T02:00:02.000Z",
475+
});
476+
await replaceTranscriptEvents(scope, events);
477+
478+
const startedAt = performance.now();
479+
const result = await listSessionBranches({ agentId, env, sessionKey });
480+
const elapsedMs = performance.now() - startedAt;
481+
expect(result.status).toBe("ok");
482+
if (result.status !== "ok") {
483+
throw new Error("expected branch list result");
484+
}
485+
expect(elapsedMs).toBeLessThan(1_000);
486+
expect(result.branches).toHaveLength(1_362);
487+
expect(result.branches.find((branch) => branch.leafEntryId === "orphan-assistant")).toEqual({
488+
leafEntryId: "orphan-assistant",
489+
headline: "orphan answer",
490+
messageCount: 2,
491+
updatedAt: "2026-08-30T00:00:02.000Z",
492+
active: false,
493+
});
494+
}, 15_000);
495+
421496
it("switches to another tip and rebuilds the active-path projection", async () => {
422497
const { env } = await createSession();
423498

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

Lines changed: 48 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ type SessionBranchCacheEntry = {
8181
generation: string | null;
8282
maxSeq: number | null;
8383
};
84+
type SessionBranchPathSummary = Pick<SessionBranchSummary, "headline" | "messageCount">;
8485

8586
// Branch listing must not scale with transcript size on every request. Appends advance max(seq),
8687
// while every in-place or replacement path rotates generation; cap the validated LRU at 32 sessions.
@@ -415,13 +416,17 @@ function validateBranchTip(
415416

416417
function summarizeSessionBranches(events: readonly TranscriptEvent[]): SessionBranchSummary[] {
417418
const tree = scanSessionTranscriptTree(events);
418-
return sessionBranchTipNodes(tree)
419-
.toSorted(
420-
(left, right) =>
421-
Number(right.id === tree.leafId) - Number(left.id === tree.leafId) ||
422-
right.index - left.index,
423-
)
424-
.map((node) => summarizeSessionBranch(tree, node.id));
419+
const pathSummaries = new Map<string, SessionBranchPathSummary>();
420+
return (
421+
sessionBranchTipNodes(tree)
422+
.toSorted(
423+
(left, right) =>
424+
Number(right.id === tree.leafId) - Number(left.id === tree.leafId) ||
425+
right.index - left.index,
426+
)
427+
// SAFETY: scanSessionTranscriptTree inserts every returned node into byId.
428+
.map((node) => summarizeSessionBranch(tree, tree.byId.get(node.id)!, pathSummaries))
429+
);
425430
}
426431

427432
function sessionBranchTipNodes(tree: SessionTranscriptTree<TranscriptEvent>) {
@@ -439,24 +444,46 @@ function sessionBranchTipNodes(tree: SessionTranscriptTree<TranscriptEvent>) {
439444

440445
function summarizeSessionBranch(
441446
tree: SessionTranscriptTree<TranscriptEvent>,
442-
leafEntryId: string,
447+
leaf: SessionTranscriptTree<TranscriptEvent>["nodes"][number],
448+
summaries: Map<string, SessionBranchPathSummary>,
443449
): SessionBranchSummary {
444-
const path = selectSessionTranscriptTreePathNodes(tree, leafEntryId);
445-
const messages = path.flatMap((node) => {
450+
const uncachedPath: typeof tree.nodes = [];
451+
const seen = new Set<string>();
452+
let current = leaf;
453+
// Stop at the first cached ancestor so every shared prefix is summarized once.
454+
// A cycle still produces the empty summary returned by the path selector.
455+
while (!summaries.has(current.id)) {
456+
if (seen.has(current.id)) {
457+
uncachedPath.length = 0;
458+
break;
459+
}
460+
seen.add(current.id);
461+
uncachedPath.push(current);
462+
const parent = current.parentId === null ? undefined : tree.byId.get(current.parentId);
463+
if (!parent) {
464+
break;
465+
}
466+
current = parent;
467+
}
468+
469+
let summary = summaries.get(current.id);
470+
for (const node of uncachedPath.toReversed()) {
446471
const record = asRecord(node.entry);
447-
return record?.type === "message" ? [record] : [];
448-
});
449-
const headline = messages
450-
.toReversed()
451-
.map((record) => extractHeadlineText(record.message))
452-
.find((value): value is string => value !== undefined);
453-
const timestamp = asRecord(tree.byId.get(leafEntryId)?.entry)?.timestamp;
472+
const headline = record?.type === "message" ? extractHeadlineText(record.message) : undefined;
473+
summary = {
474+
headline: headline ?? summary?.headline ?? "",
475+
messageCount: (summary?.messageCount ?? 0) + (record?.type === "message" ? 1 : 0),
476+
};
477+
summaries.set(node.id, summary);
478+
}
479+
480+
const timestamp = asRecord(leaf.entry)?.timestamp;
454481
return {
455-
leafEntryId,
456-
headline: truncateBranchHeadline(headline ?? ""),
457-
messageCount: messages.length,
482+
leafEntryId: leaf.id,
483+
headline: truncateBranchHeadline(summary?.headline ?? ""),
484+
messageCount: summary?.messageCount ?? 0,
458485
...(typeof timestamp === "string" && timestamp.trim() ? { updatedAt: timestamp } : {}),
459-
active: tree.leafId === leafEntryId,
486+
active: tree.leafId === leaf.id,
460487
};
461488
}
462489

0 commit comments

Comments
 (0)