Skip to content

Commit c6ebf69

Browse files
committed
perf(sessions): reduce repeated migration and Doctor work
1 parent 5d07c11 commit c6ebf69

8 files changed

Lines changed: 227 additions & 127 deletions

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

Lines changed: 8 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,20 @@
11
/** Read-only transcript detection; positive repairs retain exact snapshots. */
2-
import fs from "node:fs";
32
import type { DatabaseSync } from "node:sqlite";
43
import { isRecord } from "@openclaw/normalization-core/record-coerce";
54
import type { SqliteTranscriptStorageRow } from "../config/sessions/session-accessor.sqlite-read.js";
6-
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
75
import { tableExists } from "../state/openclaw-state-db-schema-helpers.js";
86

97
// Schema-tolerant session enumeration for transcript-label migration (avoids post-ship columns).
108
// Queries transcript_events table (schema-stable) instead of sessions table.
119
// Returns read-only view of all distinct session IDs with events.
12-
export function readOnlySqliteTranscriptSessionIds(sqlitePath: string): string[] {
13-
if (!fs.existsSync(sqlitePath)) {
10+
export function readOnlySqliteTranscriptSessionIds(database: DatabaseSync): string[] {
11+
if (!tableExists(database, "transcript_events")) {
1412
return [];
1513
}
16-
let database: DatabaseSync | undefined;
17-
try {
18-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
19-
if (!tableExists(database, "transcript_events")) {
20-
return [];
21-
}
22-
const rows = database
23-
.prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC")
24-
.all();
25-
return rows.flatMap((row) => (typeof row.session_id === "string" ? [row.session_id] : []));
26-
} finally {
27-
database?.close();
28-
}
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] : []));
2918
}
3019

3120
function iterateTranscriptRows(database: DatabaseSync, sessionId: string, firstRowOnly = false) {
@@ -47,16 +36,11 @@ type ReadOnlyTranscriptSnapshot =
4736
| { ok: false; error: unknown };
4837

4938
export function readOnlySqliteTranscriptRepairSnapshot(
50-
sqlitePath: string,
39+
database: DatabaseSync,
5140
sessionId: string,
5241
needsRepair: (event: unknown) => boolean,
5342
): ReadOnlyTranscriptSnapshot {
54-
if (!fs.existsSync(sqlitePath)) {
55-
return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) };
56-
}
57-
let database: DatabaseSync | undefined;
5843
try {
59-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
6044
// Unchanged histories retain one payload. Re-read positive candidates in full so
6145
// malformed siblings and exact-snapshot guards still govern the surgical repair.
6246
for (const row of iterateTranscriptRows(database, sessionId)) {
@@ -83,24 +67,17 @@ export function readOnlySqliteTranscriptRepairSnapshot(
8367
return { ok: true, rows: [] };
8468
} catch (error) {
8569
return { ok: false, error };
86-
} finally {
87-
database?.close();
8870
}
8971
}
9072

9173
/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */
9274
export function readOnlySqliteHeaderlessTranscriptSnapshot(
93-
sqlitePath: string,
75+
database: DatabaseSync,
9476
sessionId: string,
9577
):
9678
| { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string }
9779
| { ok: false; error: unknown } {
98-
if (!fs.existsSync(sqlitePath)) {
99-
return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) };
100-
}
101-
let database: DatabaseSync | undefined;
10280
try {
103-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
10481
// Headers can live at nonzero seq. A current header needs no whole-history read;
10582
// possible headerless repairs still take and validate the complete exact snapshot.
10683
for (const row of iterateTranscriptRows(database, sessionId, true)) {
@@ -147,7 +124,5 @@ export function readOnlySqliteHeaderlessTranscriptSnapshot(
147124
};
148125
} catch (error) {
149126
return { ok: false, error };
150-
} finally {
151-
database?.close();
152127
}
153128
}

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fs from "node:fs";
2+
import type { DatabaseSync } from "node:sqlite";
23
import { note } from "../../packages/terminal-core/src/note.js";
34
import { resolveAgentWorkspaceDir } from "../agents/agent-scope.js";
45
import { isIndexedSessionEntry } from "../agents/sessions/session-manager-codec.js";
@@ -18,6 +19,7 @@ import {
1819
import type { OpenClawConfig } from "../config/types.openclaw.js";
1920
import { formatErrorMessage } from "../infra/errors.js";
2021
import { executeSqliteQueryTakeFirstSync } from "../infra/kysely-sync.js";
22+
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
2123
import { parseAgentSessionKey } from "../routing/session-key.js";
2224
import {
2325
resolveOpenClawAgentSqlitePath,
@@ -210,9 +212,13 @@ export async function noteSessionTranscriptHeaderHealth(params: {
210212
continue;
211213
}
212214
seenPaths.add(sqlitePath);
215+
let readDatabase: DatabaseSync | undefined;
213216
try {
214-
for (const sessionId of readOnlySqliteTranscriptSessionIds(sqlitePath)) {
215-
const snapshot = readOnlySqliteHeaderlessTranscriptSnapshot(sqlitePath, sessionId);
217+
// Each snapshot exhausts or closes its iterators before repair, so this read-only
218+
// connection holds no read transaction across a guarded writer transaction.
219+
readDatabase = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
220+
for (const sessionId of readOnlySqliteTranscriptSessionIds(readDatabase)) {
221+
const snapshot = readOnlySqliteHeaderlessTranscriptSnapshot(readDatabase, sessionId);
216222
if (!snapshot.ok) {
217223
const detail = formatErrorMessage(snapshot.error).replace(/\s+/g, " ").trim();
218224
note(
@@ -303,6 +309,8 @@ export async function noteSessionTranscriptHeaderHealth(params: {
303309
`- Failed to inspect transcript headers for ${target.agentId} (${sqlitePath}): ${detail}`,
304310
NOTE_TITLE,
305311
);
312+
} finally {
313+
readDatabase?.close();
306314
}
307315
}
308316

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,41 @@ describe("doctor SQLite session transcript label migration", () => {
324324
);
325325
});
326326

327+
it("observes later sessions changed while an earlier session is repaired", async () => {
328+
const databaseOptions = { agentId: AGENT_ID, env: state.env };
329+
const database = seedLegacyLabelTranscript(databaseOptions);
330+
const laterSessionId = "z-later-session";
331+
seedMessageTranscript(databaseOptions, [{ id: "later-user", content: "unchanged" }], {
332+
sessionId: laterSessionId,
333+
sessionKey: `agent:main:${laterSessionId}`,
334+
});
335+
const legacyContent = "Conversation info (untrusted metadata):\n```json\n{}\n```";
336+
const transaction = agentDatabase.runOpenClawAgentWriteTransaction;
337+
vi.spyOn(agentDatabase, "runOpenClawAgentWriteTransaction").mockImplementationOnce(
338+
(write, options, transactionOptions) => {
339+
transaction((db) => {
340+
db.db
341+
.prepare("UPDATE transcript_events SET event_json = ? WHERE session_id = ? AND seq = 1")
342+
.run(
343+
JSON.stringify(createMessageEvent({ id: "later-user", content: legacyContent })),
344+
laterSessionId,
345+
);
346+
}, databaseOptions);
347+
return transaction(write, options, transactionOptions);
348+
},
349+
);
350+
351+
await runTranscriptLabelHealth(state, true);
352+
353+
expect(
354+
findMessageContent(readTranscriptSnapshot(database, laterSessionId).events, "later-user"),
355+
).toContain(`Conversation info: ${INBOUND_CONTEXT_MARKER}`);
356+
expect(note).toHaveBeenCalledWith(
357+
"- Rewrote legacy inbound-context labels in 2 sessions (2 events).",
358+
"Session transcript labels",
359+
);
360+
});
361+
327362
it("preserves the bare Context header when migrating active-memory blocks", async () => {
328363
const databaseOptions = { agentId: AGENT_ID, env: state.env };
329364
const legacyContent = [

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fs from "node:fs";
2+
import type { DatabaseSync } from "node:sqlite";
23
import { note } from "../../packages/terminal-core/src/note.js";
34
import { INBOUND_CONTEXT_MARKER } from "../auto-reply/reply/inbound-context-marker.js";
45
import type { TranscriptEvent } from "../config/sessions/session-accessor.js";
@@ -10,6 +11,7 @@ import { updateSqliteTranscriptEventJsonInTransaction } from "../config/sessions
1011
import { resolveAllAgentSessionStoreTargetsSync } from "../config/sessions/targets.js";
1112
import type { OpenClawConfig } from "../config/types.openclaw.js";
1213
import { formatErrorMessage } from "../infra/errors.js";
14+
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
1315
import {
1416
resolveOpenClawAgentSqlitePath,
1517
runOpenClawAgentWriteTransaction,
@@ -203,15 +205,17 @@ export async function noteSessionTranscriptLabelHealth(params: {
203205
seenPaths.add(sqlitePath);
204206
const { agentId } = target;
205207

208+
let readDatabase: DatabaseSync | undefined;
206209
try {
210+
readDatabase = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
207211
// Detect read-only, then repair each session in its own transaction as it is found, so a large
208212
// store never buffers every plan at once. Enumerate from transcript_events, not sessions: the
209213
// latter gained its columns post-ship and is not safe to assume on old databases.
210-
const sessionIds = readOnlySqliteTranscriptSessionIds(sqlitePath);
214+
const sessionIds = readOnlySqliteTranscriptSessionIds(readDatabase);
211215
for (const sessionId of sessionIds) {
212216
// Read transcript in read-only mode (detection phase).
213217
const readResult = readOnlySqliteTranscriptRepairSnapshot(
214-
sqlitePath,
218+
readDatabase,
215219
sessionId,
216220
normalizeLegacyInboundContextLabels,
217221
);
@@ -285,6 +289,8 @@ export async function noteSessionTranscriptLabelHealth(params: {
285289
`- Failed to inspect or rewrite labels for ${agentId} (${sqlitePath}): ${detail}`,
286290
NOTE_TITLE,
287291
);
292+
} finally {
293+
readDatabase?.close();
288294
}
289295
}
290296

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

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ function observeStages() {
4343
);
4444
}
4545

46-
it.each(["prepare", "commit"])(
46+
it.each(["prepare", "append", "commit"])(
4747
"leaves canonical rows unchanged and removes private staging after %s failure",
4848
async (phase) => {
4949
await withOpenClawTestState({ label: "import-rollback" }, async (state) => {
@@ -60,6 +60,13 @@ it.each(["prepare", "commit"])(
6060
const entriesBefore = database.db.prepare("SELECT * FROM session_nodes").all();
6161
const stages = observeStages();
6262
const exec = database.db.exec.bind(database.db);
63+
if (phase === "append") {
64+
database.db.exec(`
65+
CREATE TRIGGER fail_second_import BEFORE INSERT ON transcript_events
66+
WHEN NEW.session_id = 'second'
67+
BEGIN SELECT RAISE(ABORT, 'injected append failure'); END;
68+
`);
69+
}
6370
if (phase === "commit") {
6471
vi.spyOn(database.db, "exec").mockImplementation((sql) => {
6572
if (sql === "COMMIT") {
@@ -135,37 +142,53 @@ it("deduplicates existing and incoming bytes and identities, preserves aliases,
135142
sessionKey: "agent:main:ALIAS",
136143
preserveExactStoredKey: true,
137144
};
138-
const opaque = { custom: "no identity" };
145+
const first = { ...message, timestamp: 10 };
146+
const second = { ...message, id: "two", parentId: "one", timestamp: 30 };
147+
const opaque = { custom: "no identity", timestamp: 25 };
139148
const readTranscriptEvents = (append: (event: unknown) => void) => {
140149
for (const event of [
141-
message,
142-
message,
143-
{ ...message, message: { role: "user", content: "same id loses" } },
150+
first,
151+
first,
152+
{ ...first, timestamp: 20, message: { role: "user", content: "same id loses" } },
144153
opaque,
145154
opaque,
155+
second,
156+
{ ...second, timestamp: 99 },
146157
]) {
147158
append(event);
148159
}
149160
};
150161
const stages = observeStages();
162+
await importSqliteSessionRows({ ...params, readTranscriptEvents: (append) => append(first) });
163+
const db = openOpenClawAgentDatabase({ agentId: "main", env: state.env }).db;
164+
const generation = db.prepare("SELECT generation FROM transcript_rewrite_watermarks").get();
151165
expect(await importSqliteSessionRows({ ...params, readTranscriptEvents })).toMatchObject({
152166
transcriptEvents: 2,
153167
sessionKey: params.sessionKey,
154168
});
155169
expect(await importSqliteSessionRows({ ...params, readTranscriptEvents })).toMatchObject({
156170
transcriptEvents: 0,
157171
});
158-
const db = openOpenClawAgentDatabase({ agentId: "main", env: state.env }).db;
159172
expect(db.prepare("SELECT session_key FROM session_nodes").all()).toEqual([
160173
{ session_key: params.sessionKey },
161174
]);
162-
expect(db.prepare("SELECT event_json FROM transcript_events ORDER BY seq").all()).toEqual(
163-
[message, opaque].map((event) => ({ event_json: JSON.stringify(event) })),
175+
expect(
176+
db.prepare("SELECT seq, created_at, event_json FROM transcript_events ORDER BY seq").all(),
177+
).toEqual(
178+
[first, opaque, second].map((event, seq) => ({
179+
seq,
180+
created_at: event.timestamp,
181+
event_json: JSON.stringify(event),
182+
})),
164183
);
165-
expect(db.prepare("SELECT event_id FROM transcript_event_identities").all()).toEqual([
166-
{ event_id: "one" },
167-
]);
168-
expect(stages()).toHaveLength(2);
184+
expect(
185+
db.prepare("SELECT event_id FROM transcript_event_identities ORDER BY seq").all(),
186+
).toEqual([{ event_id: "one" }, { event_id: "two" }]);
187+
expect(db.prepare("SELECT updated_at FROM session_windows").get()).toEqual({ updated_at: 99 });
188+
expect(db.prepare("SELECT generation FROM transcript_rewrite_watermarks").get()).toEqual(
189+
generation,
190+
);
191+
expect(stages()).toHaveLength(3);
169192
expect(stages().every((dir) => !fs.existsSync(dir))).toBe(true);
170193
});
171194
});

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

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
ensureTranscriptSessionRoot,
3131
touchTranscriptMutationInTransaction,
3232
} from "./session-accessor.sqlite-transcript-state.js";
33-
import { appendTranscriptEventInTransaction } from "./session-accessor.sqlite-transcript-store.js";
33+
import { appendTranscriptEventsInTransaction } from "./session-accessor.sqlite-transcript-store.js";
3434
import { reconcileSessionTranscriptIndexInTransaction } from "./session-transcript-index.js";
3535
import type { SessionEntry } from "./types.js";
3636

@@ -167,23 +167,23 @@ function importSqliteSessionRowsInTransaction(
167167
)) {
168168
stage.addSeen(row.event_json);
169169
}
170-
for (const row of stage.rows(source)) {
171-
if (stage.hasSeen(row.eventJson)) {
172-
continue;
173-
}
174-
// SAFETY: staging serialized the caller's TranscriptEvent without transforming its contents.
175-
const event = JSON.parse(row.eventJson) as TranscriptEvent;
176-
if (
177-
appendTranscriptEventInTransaction(database, transcriptScope, event, {
178-
allowStoredAlias: true,
179-
scheduleProjectionReconcile: false,
180-
touchMutation: false,
181-
})
182-
) {
183-
stage.addSeen(row.eventJson);
184-
transcriptEvents += 1;
185-
}
186-
}
170+
transcriptEvents = appendTranscriptEventsInTransaction(
171+
database,
172+
transcriptScope,
173+
(function* (): Generator<TranscriptEvent, void, boolean> {
174+
for (const row of stage.rows(source)) {
175+
if (stage.hasSeen(row.eventJson)) {
176+
continue;
177+
}
178+
// SAFETY: staging serialized the caller's TranscriptEvent without transforming its contents.
179+
const inserted = yield JSON.parse(row.eventJson) as TranscriptEvent;
180+
if (inserted) {
181+
stage.addSeen(row.eventJson);
182+
}
183+
}
184+
})(),
185+
{ allowStoredAlias: true, scheduleProjectionReconcile: false, touchMutation: false },
186+
);
187187
// Doctor imports run outside gateway requests and must finish with a complete projection.
188188
reconcileSessionTranscriptIndexInTransaction(database.db, params.entry.sessionId);
189189
publishSessionEntryCacheInvalidation(database);

‎src/config/sessions/session-accessor.sqlite-transcript-state.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,15 @@ export function ensureTranscriptSessionRoot(
181181
);
182182
publishSessionEntryCacheInvalidation(database);
183183
}
184+
upsertTranscriptSessionWindowInTransaction(database, scope, updatedAt);
185+
}
186+
187+
export function upsertTranscriptSessionWindowInTransaction(
188+
database: OpenClawAgentDatabase,
189+
scope: ResolvedTranscriptScope,
190+
updatedAt: number,
191+
): void {
192+
const db = getSessionKysely(database.db);
184193
executeSqliteQuerySync(
185194
database.db,
186195
db

0 commit comments

Comments
 (0)