Skip to content

Commit 348ad76

Browse files
authored
perf(sessions): reuse migration projection facts and doctor statements (#133127)
1 parent 22975b1 commit 348ad76

8 files changed

Lines changed: 314 additions & 221 deletions
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { describe, expect, it } from "vitest";
2+
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
3+
import { ReadOnlySqliteTranscriptReader } from "./doctor-session-sqlite-transcript-readers.js";
4+
5+
describe("read-only SQLite transcript readers", () => {
6+
it.each([
7+
{ stage: "label detection", header: false, failingSeq: 0 },
8+
{ stage: "nested label snapshot", header: false, failingSeq: 1 },
9+
{ stage: "header snapshot", header: true, failingSeq: 1 },
10+
{ stage: "first header row", header: true, failingSeq: 0 },
11+
])("isolates a $stage step failure from the next session", ({ header, failingSeq }) => {
12+
const database = openNodeSqliteDatabase(":memory:");
13+
try {
14+
// json() fails during native stepping. The primary key lets the first row
15+
// reach detection before a later row fails in the complete snapshot.
16+
database.exec(`
17+
CREATE TABLE source_rows (
18+
session_id TEXT,
19+
seq INTEGER,
20+
created_at INTEGER,
21+
event_json TEXT,
22+
PRIMARY KEY (session_id, seq)
23+
);
24+
CREATE VIEW transcript_events AS
25+
SELECT session_id, seq, created_at, json(event_json) AS event_json FROM source_rows;
26+
CREATE TABLE session_windows (session_id TEXT PRIMARY KEY, session_key TEXT);
27+
INSERT INTO session_windows VALUES
28+
('broken', 'agent:main:broken'), ('healthy', 'agent:main:healthy');
29+
`);
30+
const insert = database.prepare("INSERT INTO source_rows VALUES (?, ?, ?, ?)");
31+
insert.run("broken", 0, 10, failingSeq === 0 ? "{" : '{"type":"message","id":"first"}');
32+
if (failingSeq === 1) {
33+
insert.run("broken", 1, 11, "{");
34+
}
35+
const healthyEvents = [
36+
'{"type":"message","id":"healthy-first"}',
37+
'{"type":"message","id":"healthy-second"}',
38+
];
39+
for (const [seq, eventJson] of healthyEvents.entries()) {
40+
insert.run("healthy", seq, 20 + seq, eventJson);
41+
}
42+
43+
const reader = new ReadOnlySqliteTranscriptReader(database);
44+
const read = (sessionId: string) =>
45+
header
46+
? reader.headerlessSnapshot(sessionId)
47+
: reader.repairSnapshot(sessionId, () => true);
48+
expect(read("broken")).toMatchObject({
49+
ok: false,
50+
error: { message: expect.stringMatching(/malformed JSON/iu) },
51+
});
52+
expect(read("healthy")).toEqual({
53+
ok: true,
54+
rows: healthyEvents.map((eventJson, seq) =>
55+
header ? { eventJson, seq, createdAt: 20 + seq } : { eventJson, seq },
56+
),
57+
...(header ? { sessionKey: "agent:main:healthy" } : {}),
58+
});
59+
} finally {
60+
database.close();
61+
}
62+
});
63+
});
Lines changed: 127 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -1,128 +1,154 @@
11
/** Read-only transcript detection; positive repairs retain exact snapshots. */
2-
import type { DatabaseSync } from "node:sqlite";
2+
import type { DatabaseSync, StatementSync } from "node:sqlite";
33
import { isRecord } from "@openclaw/normalization-core/record-coerce";
44
import type { SqliteTranscriptStorageRow } from "../config/sessions/session-accessor.sqlite-read.js";
55
import { tableExists } from "../state/openclaw-state-db-schema-helpers.js";
66

7-
// Schema-tolerant session enumeration for transcript-label migration (avoids post-ship columns).
8-
// Queries transcript_events table (schema-stable) instead of sessions table.
9-
// Returns read-only view of all distinct session IDs with events.
10-
export function readOnlySqliteTranscriptSessionIds(database: DatabaseSync): string[] {
11-
if (!tableExists(database, "transcript_events")) {
12-
return [];
13-
}
14-
const rows = database
15-
.prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC")
16-
.all();
17-
return rows.flatMap((row) => (typeof row.session_id === "string" ? [row.session_id] : []));
18-
}
19-
20-
function iterateTranscriptRows(database: DatabaseSync, sessionId: string, firstRowOnly = false) {
21-
return database
22-
.prepare(
23-
`SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC${firstRowOnly ? " LIMIT 1" : ""}`,
24-
)
25-
.iterate(sessionId);
26-
}
7+
const LABEL_ROWS_SQL =
8+
"SELECT event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC";
279

28-
// Read-only transcript snapshot reader for dry-run detection phase.
29-
// Avoids opening writable database lifecycle (lease/WAL/schema-ensure).
30-
// Returns rows only; migration parses per-row during repair.
3110
type ReadOnlyTranscriptSnapshot =
3211
| {
3312
ok: true;
3413
rows: Array<{ eventJson: string; seq: number }>;
3514
}
3615
| { ok: false; error: unknown };
3716

38-
export function readOnlySqliteTranscriptRepairSnapshot(
39-
database: DatabaseSync,
40-
sessionId: string,
41-
needsRepair: (event: unknown) => boolean,
42-
): ReadOnlyTranscriptSnapshot {
43-
try {
44-
// Unchanged histories retain one payload. Re-read positive candidates in full so
45-
// malformed siblings and exact-snapshot guards still govern the surgical repair.
46-
for (const row of iterateTranscriptRows(database, sessionId)) {
47-
if (typeof row.event_json !== "string" || typeof row.seq !== "number") {
48-
continue;
17+
export class ReadOnlySqliteTranscriptReader {
18+
private labelDetection?: StatementSync;
19+
private labelSnapshot?: StatementSync;
20+
private firstHeaderRow?: StatementSync;
21+
private headerSnapshot?: StatementSync;
22+
private sessionKey?: StatementSync;
23+
24+
// Statements belong to one read-only pass, but no cursor survives a snapshot call.
25+
// Prepare lazily so older databases need only the schema used by that detection path.
26+
constructor(private readonly database: DatabaseSync) {}
27+
28+
sessionIds(): string[] {
29+
if (!tableExists(this.database, "transcript_events")) {
30+
return [];
31+
}
32+
// Enumerate the schema-stable events table, not post-ship sessions columns.
33+
// Materialize IDs so enumeration cannot hold a read transaction across repairs.
34+
const rows = this.database
35+
.prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC")
36+
.all();
37+
return rows.flatMap((row) => (typeof row.session_id === "string" ? [row.session_id] : []));
38+
}
39+
40+
repairSnapshot(
41+
sessionId: string,
42+
needsRepair: (event: unknown) => boolean,
43+
): ReadOnlyTranscriptSnapshot {
44+
let iterator: ReturnType<StatementSync["iterate"]> | undefined;
45+
try {
46+
// Unchanged histories retain one payload. Re-read positive candidates in full so
47+
// malformed siblings and exact-snapshot guards still govern the surgical repair.
48+
this.labelDetection ??= this.database.prepare(LABEL_ROWS_SQL);
49+
iterator = this.labelDetection.iterate(sessionId);
50+
for (const row of iterator) {
51+
if (typeof row.event_json !== "string" || typeof row.seq !== "number") {
52+
continue;
53+
}
54+
let event: unknown;
55+
try {
56+
event = JSON.parse(row.event_json);
57+
} catch {
58+
continue;
59+
}
60+
if (!needsRepair(event)) {
61+
continue;
62+
}
63+
const rows: Array<{ eventJson: string; seq: number }> = [];
64+
// Detection is still iterating: its nested exact snapshot needs a distinct statement.
65+
this.labelSnapshot ??= this.database.prepare(LABEL_ROWS_SQL);
66+
iterator = this.labelSnapshot.iterate(sessionId);
67+
for (const candidate of iterator) {
68+
if (typeof candidate.event_json === "string" && typeof candidate.seq === "number") {
69+
rows.push({ eventJson: candidate.event_json, seq: candidate.seq });
70+
}
71+
}
72+
return { ok: true, rows };
4973
}
50-
let event: unknown;
74+
return { ok: true, rows: [] };
75+
} catch (error) {
76+
// A throwing next() does not close its iterator; reset before the next session.
5177
try {
52-
event = JSON.parse(row.event_json);
78+
iterator?.return?.();
5379
} catch {
54-
continue;
55-
}
56-
if (!needsRepair(event)) {
57-
continue;
58-
}
59-
const rows: Array<{ eventJson: string; seq: number }> = [];
60-
for (const candidate of iterateTranscriptRows(database, sessionId)) {
61-
if (typeof candidate.event_json === "string" && typeof candidate.seq === "number") {
62-
rows.push({ eventJson: candidate.event_json, seq: candidate.seq });
63-
}
80+
// Preserve the original read error if cleanup fails.
6481
}
65-
return { ok: true, rows };
82+
return { ok: false, error };
6683
}
67-
return { ok: true, rows: [] };
68-
} catch (error) {
69-
return { ok: false, error };
7084
}
71-
}
7285

73-
/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */
74-
export function readOnlySqliteHeaderlessTranscriptSnapshot(
75-
database: DatabaseSync,
76-
sessionId: string,
77-
):
78-
| { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string }
79-
| { ok: false; error: unknown } {
80-
try {
81-
// Headers can live at nonzero seq. A current header needs no whole-history read;
82-
// possible headerless repairs still take and validate the complete exact snapshot.
83-
for (const row of iterateTranscriptRows(database, sessionId, true)) {
84-
if (typeof row.event_json !== "string") {
85-
break;
86+
/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */
87+
headerlessSnapshot(
88+
sessionId: string,
89+
):
90+
| { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string }
91+
| { ok: false; error: unknown } {
92+
let iterator: ReturnType<StatementSync["iterate"]> | undefined;
93+
try {
94+
// Headers can live at nonzero seq. A current header needs no whole-history read;
95+
// possible headerless repairs still take and validate the complete exact snapshot.
96+
this.firstHeaderRow ??= this.database.prepare(
97+
"SELECT event_json FROM transcript_events WHERE session_id = ? ORDER BY seq ASC LIMIT 1",
98+
);
99+
const firstRow = this.firstHeaderRow.get(sessionId);
100+
if (typeof firstRow?.event_json === "string") {
101+
let first: unknown;
102+
try {
103+
first = JSON.parse(firstRow.event_json);
104+
} catch {
105+
return { ok: true, rows: [] };
106+
}
107+
if (!isRecord(first) || first.type === "session") {
108+
return { ok: true, rows: [] };
109+
}
110+
}
111+
this.sessionKey ??= this.database.prepare(
112+
"SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1",
113+
);
114+
const sessionKeyRow = this.sessionKey.get(sessionId);
115+
const storageRows: SqliteTranscriptStorageRow[] = [];
116+
this.headerSnapshot ??= this.database.prepare(
117+
"SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC",
118+
);
119+
iterator = this.headerSnapshot.iterate(sessionId);
120+
for (const row of iterator) {
121+
if (
122+
typeof row.created_at !== "number" ||
123+
typeof row.event_json !== "string" ||
124+
typeof row.seq !== "number"
125+
) {
126+
return {
127+
ok: false,
128+
error: new Error(`Invalid transcript row metadata for session ${sessionId}`),
129+
};
130+
}
131+
storageRows.push({
132+
createdAt: row.created_at,
133+
eventJson: row.event_json,
134+
seq: row.seq,
135+
});
86136
}
87-
let first: unknown;
137+
return {
138+
ok: true,
139+
rows: storageRows,
140+
...(typeof sessionKeyRow?.session_key === "string"
141+
? { sessionKey: sessionKeyRow.session_key }
142+
: {}),
143+
};
144+
} catch (error) {
145+
// A throwing next() does not close its iterator; reset before the next session.
88146
try {
89-
first = JSON.parse(row.event_json);
147+
iterator?.return?.();
90148
} catch {
91-
return { ok: true, rows: [] };
92-
}
93-
if (!isRecord(first) || first.type === "session") {
94-
return { ok: true, rows: [] };
95-
}
96-
}
97-
const sessionKeyRow = database
98-
.prepare("SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1")
99-
.get(sessionId);
100-
const storageRows: SqliteTranscriptStorageRow[] = [];
101-
for (const row of iterateTranscriptRows(database, sessionId)) {
102-
if (
103-
typeof row.created_at !== "number" ||
104-
typeof row.event_json !== "string" ||
105-
typeof row.seq !== "number"
106-
) {
107-
return {
108-
ok: false,
109-
error: new Error(`Invalid transcript row metadata for session ${sessionId}`),
110-
};
149+
// Preserve the original read error if cleanup fails.
111150
}
112-
storageRows.push({
113-
createdAt: row.created_at,
114-
eventJson: row.event_json,
115-
seq: row.seq,
116-
});
151+
return { ok: false, error };
117152
}
118-
return {
119-
ok: true,
120-
rows: storageRows,
121-
...(typeof sessionKeyRow?.session_key === "string"
122-
? { sessionKey: sessionKeyRow.session_key }
123-
: {}),
124-
};
125-
} catch (error) {
126-
return { ok: false, error };
127153
}
128154
}

‎src/commands/doctor-session-transcript-headers.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,7 @@ import {
2727
type OpenClawAgentDatabase,
2828
} from "../state/openclaw-agent-db.js";
2929
import { resolveTargetSqliteOptions } from "./doctor-session-sqlite-readers.js";
30-
import {
31-
readOnlySqliteTranscriptSessionIds,
32-
readOnlySqliteHeaderlessTranscriptSnapshot,
33-
} from "./doctor-session-sqlite-transcript-readers.js";
30+
import { ReadOnlySqliteTranscriptReader } from "./doctor-session-sqlite-transcript-readers.js";
3431

3532
const NOTE_TITLE = "Session transcript headers";
3633

@@ -217,8 +214,9 @@ export async function noteSessionTranscriptHeaderHealth(params: {
217214
// Each snapshot exhausts or closes its iterators before repair, so this read-only
218215
// connection holds no read transaction across a guarded writer transaction.
219216
readDatabase = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
220-
for (const sessionId of readOnlySqliteTranscriptSessionIds(readDatabase)) {
221-
const snapshot = readOnlySqliteHeaderlessTranscriptSnapshot(readDatabase, sessionId);
217+
const reader = new ReadOnlySqliteTranscriptReader(readDatabase);
218+
for (const sessionId of reader.sessionIds()) {
219+
const snapshot = reader.headerlessSnapshot(sessionId);
222220
if (!snapshot.ok) {
223221
const detail = formatErrorMessage(snapshot.error).replace(/\s+/g, " ").trim();
224222
note(

‎src/commands/doctor-session-transcript-labels.ts‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,7 @@ import {
1717
runOpenClawAgentWriteTransaction,
1818
} from "../state/openclaw-agent-db.js";
1919
import { resolveTargetSqliteOptions } from "./doctor-session-sqlite-readers.js";
20-
import {
21-
readOnlySqliteTranscriptSessionIds,
22-
readOnlySqliteTranscriptRepairSnapshot,
23-
} from "./doctor-session-sqlite-transcript-readers.js";
20+
import { ReadOnlySqliteTranscriptReader } from "./doctor-session-sqlite-transcript-readers.js";
2421

2522
const NOTE_TITLE = "Session transcript labels";
2623

@@ -214,17 +211,13 @@ export async function noteSessionTranscriptLabelHealth(params: {
214211
let readDatabase: DatabaseSync | undefined;
215212
try {
216213
readDatabase = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
214+
const reader = new ReadOnlySqliteTranscriptReader(readDatabase);
217215
// Detect read-only, then repair each session in its own transaction as it is found, so a large
218216
// store never buffers every plan at once. Enumerate from transcript_events, not sessions: the
219217
// latter gained its columns post-ship and is not safe to assume on old databases.
220-
const sessionIds = readOnlySqliteTranscriptSessionIds(readDatabase);
221-
for (const sessionId of sessionIds) {
218+
for (const sessionId of reader.sessionIds()) {
222219
// Read transcript in read-only mode (detection phase).
223-
const readResult = readOnlySqliteTranscriptRepairSnapshot(
224-
readDatabase,
225-
sessionId,
226-
normalizeLegacyInboundContextLabels,
227-
);
220+
const readResult = reader.repairSnapshot(sessionId, normalizeLegacyInboundContextLabels);
228221
if (!readResult.ok) {
229222
const detail = formatErrorMessage(readResult.error).replace(/\s+/g, " ").trim();
230223
note(

0 commit comments

Comments
 (0)