Skip to content

Commit 609db0d

Browse files
committed
perf(sessions): avoid redundant legacy transcript planning
1 parent 16421ec commit 609db0d

3 files changed

Lines changed: 149 additions & 37 deletions

File tree

‎src/agents/sessions/session-manager-codec.ts‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,14 @@ export function parseOpaqueLeafEntry(record: unknown):
391391
};
392392
}
393393

394+
export function classifySessionFileEntry(rawEntry: FileEntry, sourceVersion: number) {
395+
const entry = normalizePersistedLegacyHookMessage(rawEntry) as FileEntry;
396+
const recognized =
397+
isIndexedSessionEntry(entry) ||
398+
(sourceVersion < CURRENT_SESSION_VERSION && isReadableLegacySessionEntry(entry));
399+
return { entry, recognized };
400+
}
401+
394402
export function partitionSessionFileEntries(entries: readonly FileEntry[]): {
395403
fileEntries: FileEntry[];
396404
opaqueEntries: Array<{ index: number; record: unknown }>;
@@ -402,20 +410,17 @@ export function partitionSessionFileEntries(entries: readonly FileEntry[]): {
402410
const header = entries.find((entry) => sessionHeaderSchema.safeParse(entry).success) as
403411
| SessionHeader
404412
| undefined;
405-
const acceptsLegacyEntries = (header?.version ?? 1) < CURRENT_SESSION_VERSION;
413+
const sourceVersion = header?.version ?? 1;
406414
let hasHeader = false;
407415
for (const [originalIndex, rawEntry] of entries.entries()) {
408-
const entry = normalizePersistedLegacyHookMessage(rawEntry) as FileEntry;
409-
if (!hasHeader && sessionHeaderSchema.safeParse(entry).success) {
410-
fileEntries.push(entry);
411-
fileEntriesByOriginalIndex[originalIndex] = entry;
416+
if (!hasHeader && sessionHeaderSchema.safeParse(rawEntry).success) {
417+
fileEntries.push(rawEntry);
418+
fileEntriesByOriginalIndex[originalIndex] = rawEntry;
412419
hasHeader = true;
413420
continue;
414421
}
415-
if (
416-
isIndexedSessionEntry(entry) ||
417-
(acceptsLegacyEntries && isReadableLegacySessionEntry(entry))
418-
) {
422+
const { entry, recognized } = classifySessionFileEntry(rawEntry, sourceVersion);
423+
if (recognized) {
419424
fileEntries.push(entry);
420425
fileEntriesByOriginalIndex[originalIndex] = entry;
421426
continue;
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
5+
import { createTranscriptEventReader } from "./doctor-session-sqlite-readers.js";
6+
7+
describe("legacy transcript row classification", () => {
8+
let directory: string;
9+
let transcriptPath: string;
10+
beforeEach(() => {
11+
directory = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-reader-classification-"));
12+
transcriptPath = path.join(directory, "session.jsonl");
13+
});
14+
afterEach(() => fs.rmSync(directory, { recursive: true, force: true }));
15+
16+
it.each([1, 2, 3, 4])("preserves recognized and opaque rows from version %s", (version) => {
17+
const unindexedHook = { type: "message", message: { role: "custom", content: "context" } };
18+
const opaqueRows = [
19+
{ type: "session", id: "later-header", version: 1 },
20+
{ type: "plugin_state", id: "opaque", payload: { keep: "exact" } },
21+
{ type: "message", id: "malformed", message: { role: "user" } },
22+
];
23+
const rows = [
24+
{ type: "session", version, sessionId: "legacy-header" },
25+
{ ...unindexedHook, id: "hook", parentId: null },
26+
unindexedHook,
27+
...opaqueRows,
28+
];
29+
fs.writeFileSync(transcriptPath, rows.map((row) => JSON.stringify(row)).join("\n"));
30+
const events: unknown[] = [];
31+
const validate = createTranscriptEventReader(
32+
transcriptPath,
33+
"target-session",
34+
)((event) => {
35+
events.push(event);
36+
});
37+
validate();
38+
39+
expect(events).toHaveLength(rows.length);
40+
expect(events[0]).toEqual({
41+
type: "session",
42+
id: "target-session",
43+
version: Math.max(version, 3),
44+
timestamp: "",
45+
cwd: "",
46+
});
47+
expect(events[1]).toMatchObject({
48+
id: version === 1 ? expect.stringMatching(/^[a-f0-9]{16}-1$/) : "hook",
49+
message: { role: "custom", customType: "hook", content: "context" },
50+
});
51+
if (version < 3) {
52+
expect(events[2]).toMatchObject({
53+
message: { role: "custom", customType: "hook", content: "context" },
54+
});
55+
} else {
56+
expect(events[2]).toEqual(unindexedHook);
57+
}
58+
expect(events.slice(3)).toEqual(opaqueRows);
59+
});
60+
61+
it.each([1, 3])("enforces the target limit even during v%s prefix recovery", (version) => {
62+
const rows = Array.from({ length: 100_001 }, (_, index) =>
63+
JSON.stringify({
64+
type: "compaction",
65+
id: `c-${index}`,
66+
summary: "kept",
67+
tokensBefore: 0,
68+
firstKeptEntryId: "kept",
69+
firstKeptEntryIndex: index,
70+
}),
71+
);
72+
fs.writeFileSync(
73+
transcriptPath,
74+
`${JSON.stringify({ type: "session", version })}\n${rows.join("\n")}`,
75+
);
76+
expect(() => createTranscriptEventReader(transcriptPath, "target", true)(() => {})).toThrow(
77+
"more than 100000 legacy compaction targets",
78+
);
79+
});
80+
81+
it.each([false, true])("handles malformed tails with prefix recovery %s", (allowPrefix) => {
82+
const rows = [
83+
{ type: "session", version: 3, id: "target" },
84+
{ type: "message", id: "kept", message: { role: "user", content: "x".repeat(70_000) } },
85+
];
86+
fs.writeFileSync(
87+
transcriptPath,
88+
`${rows.map((row) => JSON.stringify(row)).join("\n")}\n{malformed`,
89+
);
90+
const events: unknown[] = [];
91+
const read = () =>
92+
createTranscriptEventReader(
93+
transcriptPath,
94+
"target",
95+
allowPrefix,
96+
)((event) => events.push(event));
97+
if (allowPrefix) {
98+
read()();
99+
expect(events).toHaveLength(2);
100+
expect(events[1]).toEqual(rows[1]);
101+
} else {
102+
expect(read).toThrow();
103+
}
104+
});
105+
});

‎src/commands/doctor-session-sqlite-readers.ts‎

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ import type { DatabaseSync } from "node:sqlite";
55
import { TextDecoder } from "node:util";
66
import { isRecord } from "@openclaw/normalization-core/record-coerce";
77
import {
8+
classifySessionFileEntry,
89
migrateSessionFileEntryToCurrentVersion,
910
normalizeLoadedFileEntry,
10-
partitionSessionFileEntries,
1111
type SessionFileEntryMigrationState,
1212
} from "../agents/sessions/session-manager-codec.js";
1313
import type { FileEntry } from "../agents/sessions/session-manager-types.js";
@@ -112,13 +112,6 @@ function readTranscriptEventsForImport(
112112
// through commit and archive. Fingerprints catch non-cooperating external edits.
113113
const plan = planTranscriptImport(transcriptPath, allowMalformedPrefix);
114114
assertTranscriptFileUnchanged(transcriptPath, sourceFingerprint);
115-
const classificationHeader = {
116-
id: sessionId,
117-
type: "session",
118-
version: plan.sourceVersion,
119-
timestamp: "",
120-
cwd: "",
121-
} satisfies FileEntry;
122115
// V1 compactions refer to original row indexes. Stable index-derived IDs let
123116
// the second pass resolve those links without retaining the transcript.
124117
const idPrefix = createHash("sha256")
@@ -143,6 +136,9 @@ function readTranscriptEventsForImport(
143136
allowMalformedPrefix,
144137
)) {
145138
let event = loadedEvent;
139+
if (plan.sourceVersion >= 2) {
140+
recordLegacyCompactionTarget(event, plan.compactionTargetIndexes);
141+
}
146142
let recognizedEvent: FileEntry | undefined;
147143
if (originalIndex === plan.headerIndex) {
148144
const canonicalHeader = {
@@ -156,15 +152,15 @@ function readTranscriptEventsForImport(
156152
event = canonicalHeader;
157153
recognizedEvent = event;
158154
} else {
159-
// Reuse the runtime partition contract one row at a time. The
160-
// synthetic header carries the source version without being emitted.
161-
recognizedEvent = partitionSessionFileEntries([classificationHeader, event])
162-
.fileEntriesByOriginalIndex[1];
155+
const classified = classifySessionFileEntry(event, plan.sourceVersion);
156+
// Runtime retains normalized opaque rows; import preserves their loaded bytes.
157+
recognizedEvent = classified.recognized ? classified.entry : undefined;
163158
}
164159

165160
if (recognizedEvent) {
166161
migrateSessionFileEntryToCurrentVersion(recognizedEvent, originalIndex, migrationState);
167162
if (
163+
plan.sourceVersion < 2 &&
168164
recognizedEvent.type !== "session" &&
169165
plan.compactionTargetIndexes.has(originalIndex)
170166
) {
@@ -240,28 +236,34 @@ function planTranscriptImport(
240236
if (plan.headerIndex < 0 && isRecord(event) && event.type === "session") {
241237
plan.headerIndex = originalIndex;
242238
plan.sourceVersion = typeof event.version === "number" ? event.version : 1;
243-
}
244-
if (
245-
isRecord(event) &&
246-
event.type === "compaction" &&
247-
Number.isInteger(event.firstKeptEntryIndex) &&
248-
Number(event.firstKeptEntryIndex) >= 0
249-
) {
250-
const targetIndex = Number(event.firstKeptEntryIndex);
251-
if (
252-
!plan.compactionTargetIndexes.has(targetIndex) &&
253-
plan.compactionTargetIndexes.size >= MAX_LEGACY_COMPACTION_TARGETS
254-
) {
255-
throw new TranscriptImportLimitError(
256-
`Transcript has more than ${MAX_LEGACY_COMPACTION_TARGETS} legacy compaction targets`,
257-
);
239+
// Only v1 needs future row indexes before migration. Newer files validate
240+
// the same target limit while streaming, before any canonical write.
241+
if (plan.sourceVersion >= 2) {
242+
return plan;
258243
}
259-
plan.compactionTargetIndexes.add(targetIndex);
260244
}
245+
recordLegacyCompactionTarget(event, plan.compactionTargetIndexes);
261246
}
262247
return plan;
263248
}
264249

250+
function recordLegacyCompactionTarget(event: FileEntry, targets: Set<number>): void {
251+
if (
252+
isRecord(event) &&
253+
event.type === "compaction" &&
254+
Number.isInteger(event.firstKeptEntryIndex) &&
255+
Number(event.firstKeptEntryIndex) >= 0
256+
) {
257+
const targetIndex = Number(event.firstKeptEntryIndex);
258+
if (!targets.has(targetIndex) && targets.size >= MAX_LEGACY_COMPACTION_TARGETS) {
259+
throw new TranscriptImportLimitError(
260+
`Transcript has more than ${MAX_LEGACY_COMPACTION_TARGETS} legacy compaction targets`,
261+
);
262+
}
263+
targets.add(targetIndex);
264+
}
265+
}
266+
265267
function* iterateTranscriptEvents(
266268
transcriptPath: string,
267269
allowMalformedPrefix: boolean,

0 commit comments

Comments
 (0)