Skip to content

Commit e3887be

Browse files
committed
perf(doctor): bound healthy history checks and import cleanup
Stream unchanged header and label detection while retaining exact snapshots and atomic guards for positive repairs. Reuse one import-finalize operation for handle closure, schema maintenance, and automatic incremental vacuum. Keep full integrity checks, NONE-mode conversion, and explicit full compaction. Verified constrained-heap regressions, real historical upgrades, complete long-history Docker cases, process interruption, source mutation, and temporary-volume exhaustion.
1 parent dc9b252 commit e3887be

16 files changed

Lines changed: 659 additions & 249 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2528,7 +2528,7 @@ src/commands/doctor-session-incognito-key-repair.ts 4
25282528
src/commands/doctor-session-snapshots.ts 5
25292529
src/commands/doctor-session-sqlite-compact.ts 1
25302530
src/commands/doctor-session-sqlite-migration-run.ts 8
2531-
src/commands/doctor-session-sqlite-readers.ts 9
2531+
src/commands/doctor-session-sqlite-readers.ts 5
25322532
src/commands/doctor-session-sqlite-recover-report.ts 3
25332533
src/commands/doctor-session-sqlite.ts 3
25342534
src/commands/doctor-session-state-providers.ts 3

‎docs/cli/doctor.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,11 @@ on the system temporary volume as well as the volume holding OpenClaw state.
306306
Staging is removed when the operation finishes and is never used as a runtime
307307
store or resumed after an interruption; retries use the original sources and
308308
committed session data. Individual transcript records are still parsed in memory.
309+
After import, Doctor checkpoints and incrementally vacuums databases that already
310+
support auto-vacuum, retaining full integrity and foreign-key checks before and
311+
after cleanup. Databases without auto-vacuum still need a full `VACUUM` to enable
312+
it. Incremental cleanup frees unused pages but does not repack partially filled
313+
pages; explicit session and shared-state `compact` modes still run a full `VACUUM`.
309314

310315
The regular `openclaw doctor` pass also reports canonical SQLite transcripts
311316
whose initial session header was never persisted. `openclaw doctor --fix`

‎scripts/check-kysely-guardrails.mts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ const rawSqliteAllowPathGroups = {
111111
"src/commands/doctor-sqlite-compact.ts",
112112
"src/commands/doctor-session-sqlite.ts",
113113
"src/commands/doctor-session-sqlite-readers.ts",
114+
"src/commands/doctor-session-sqlite-transcript-readers.ts",
114115
"src/commands/doctor-session-sqlite-recover-report.ts",
115116
"src/commands/doctor-state-sqlite-compact.ts",
116117
// Disposable import planning only; canonical session tables still use Kysely.

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { compactDoctorSqliteFile } from "./doctor-sqlite-compact.js";
1515
/** Reclaim free pages from one agent session SQLite database. */
1616
export function compactDoctorSessionSqliteTarget(
1717
target: SessionStoreTarget,
18-
options: { env?: NodeJS.ProcessEnv; migrateOlderSchema?: boolean } = {},
18+
options: { env?: NodeJS.ProcessEnv; operation?: "import-finalize" } = {},
1919
): DoctorSessionSqliteCompactReport {
2020
const sqlitePath = resolveTargetSqlitePath(target);
2121
const beforeFileSizes = readSqliteFileSizes(sqlitePath);
@@ -48,7 +48,7 @@ export function compactDoctorSessionSqliteTarget(
4848
);
4949
}
5050
};
51-
if (options.migrateOlderSchema) {
51+
if (options.operation === "import-finalize") {
5252
migrateOpenClawAgentDatabaseForMaintenance({
5353
agentId: target.agentId,
5454
pathname: sqlitePath,
@@ -57,6 +57,7 @@ export function compactDoctorSessionSqliteTarget(
5757
}
5858

5959
const compact = compactDoctorSqliteFile({
60+
operation: options.operation,
6061
afterSuccess: () => {
6162
requireQuarantineCleared();
6263
ensureOpenClawAgentDatabasePermissions(sqlitePath, {

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

Lines changed: 0 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import {
1212
} from "../agents/sessions/session-manager-codec.js";
1313
import type { FileEntry } from "../agents/sessions/session-manager-types.js";
1414
import type { TranscriptEvent } from "../config/sessions/session-accessor.js";
15-
import type { SqliteTranscriptStorageRow } from "../config/sessions/session-accessor.sqlite-read.js";
1615
import { resolveSqliteTargetFromSessionStorePath } from "../config/sessions/session-sqlite-target.js";
1716
import type { SessionStoreTarget as ResolvedSessionStoreTarget } from "../config/sessions/targets.js";
1817
import { resolveAllAgentSessionStoreCandidateTargetsSync } from "../config/sessions/targets.js";
@@ -557,124 +556,3 @@ function sqliteNumber(value: unknown): number {
557556
function parseJsonlLine(line: { text: string }): unknown {
558557
return JSON.parse(line.text);
559558
}
560-
561-
// Schema-tolerant session enumeration for transcript-label migration (avoids post-ship columns).
562-
// Queries transcript_events table (schema-stable) instead of sessions table.
563-
// Returns read-only view of all distinct session IDs with events.
564-
export function readOnlySqliteTranscriptSessionIds(sqlitePath: string): string[] {
565-
if (!fs.existsSync(sqlitePath)) {
566-
return [];
567-
}
568-
let database: DatabaseSync | undefined;
569-
try {
570-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
571-
if (!tableExists(database, "transcript_events")) {
572-
return [];
573-
}
574-
const rows = database
575-
.prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC")
576-
.all() as Array<{ session_id?: unknown }>;
577-
return rows
578-
.filter((row): row is { session_id: string } => typeof row.session_id === "string")
579-
.map((row) => row.session_id);
580-
} finally {
581-
database?.close();
582-
}
583-
}
584-
585-
// Read-only transcript snapshot reader for dry-run detection phase.
586-
// Avoids opening writable database lifecycle (lease/WAL/schema-ensure).
587-
// Returns rows only; migration parses per-row during repair.
588-
type ReadOnlyTranscriptSnapshot =
589-
| {
590-
ok: true;
591-
rows: Array<{ eventJson: string; seq: number }>;
592-
}
593-
| { ok: false; error: unknown };
594-
595-
export function readOnlySqliteTranscriptSnapshot(
596-
sqlitePath: string,
597-
sessionId: string,
598-
): ReadOnlyTranscriptSnapshot {
599-
if (!fs.existsSync(sqlitePath)) {
600-
return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) };
601-
}
602-
let database: DatabaseSync | undefined;
603-
try {
604-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
605-
const rows = database
606-
.prepare(
607-
"SELECT event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC",
608-
)
609-
.all(sessionId) as Array<{ event_json?: string; seq?: number }>;
610-
const validRows = rows.filter(
611-
(row): row is { event_json: string; seq: number } =>
612-
typeof row.event_json === "string" && typeof row.seq === "number",
613-
);
614-
return {
615-
ok: true,
616-
rows: validRows.map((row) => ({ eventJson: row.event_json, seq: row.seq })),
617-
};
618-
} catch (error) {
619-
return { ok: false, error };
620-
} finally {
621-
database?.close();
622-
}
623-
}
624-
625-
/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */
626-
export function readOnlySqliteTranscriptStorageSnapshot(
627-
sqlitePath: string,
628-
sessionId: string,
629-
):
630-
| { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string }
631-
| { ok: false; error: unknown } {
632-
if (!fs.existsSync(sqlitePath)) {
633-
return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) };
634-
}
635-
let database: DatabaseSync | undefined;
636-
try {
637-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
638-
const rows = database
639-
.prepare(
640-
"SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC",
641-
)
642-
.all(sessionId) as Array<{
643-
created_at?: unknown;
644-
event_json?: unknown;
645-
seq?: unknown;
646-
}>;
647-
const sessionKeyRow = database
648-
.prepare("SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1")
649-
.get(sessionId) as { session_key?: unknown } | undefined;
650-
const storageRows: SqliteTranscriptStorageRow[] = [];
651-
for (const row of rows) {
652-
if (
653-
typeof row.created_at !== "number" ||
654-
typeof row.event_json !== "string" ||
655-
typeof row.seq !== "number"
656-
) {
657-
return {
658-
ok: false,
659-
error: new Error(`Invalid transcript row metadata for session ${sessionId}`),
660-
};
661-
}
662-
storageRows.push({
663-
createdAt: row.created_at,
664-
eventJson: row.event_json,
665-
seq: row.seq,
666-
});
667-
}
668-
return {
669-
ok: true,
670-
rows: storageRows,
671-
...(typeof sessionKeyRow?.session_key === "string"
672-
? { sessionKey: sessionKeyRow.session_key }
673-
: {}),
674-
};
675-
} catch (error) {
676-
return { ok: false, error };
677-
} finally {
678-
database?.close();
679-
}
680-
}
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/** Read-only transcript detection; positive repairs retain exact snapshots. */
2+
import fs from "node:fs";
3+
import type { DatabaseSync } from "node:sqlite";
4+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
5+
import type { SqliteTranscriptStorageRow } from "../config/sessions/session-accessor.sqlite-read.js";
6+
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
7+
import { tableExists } from "../state/openclaw-state-db-schema-helpers.js";
8+
9+
// Schema-tolerant session enumeration for transcript-label migration (avoids post-ship columns).
10+
// Queries transcript_events table (schema-stable) instead of sessions table.
11+
// Returns read-only view of all distinct session IDs with events.
12+
export function readOnlySqliteTranscriptSessionIds(sqlitePath: string): string[] {
13+
if (!fs.existsSync(sqlitePath)) {
14+
return [];
15+
}
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+
}
29+
}
30+
31+
function iterateTranscriptRows(database: DatabaseSync, sessionId: string, firstRowOnly = false) {
32+
return database
33+
.prepare(
34+
`SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC${firstRowOnly ? " LIMIT 1" : ""}`,
35+
)
36+
.iterate(sessionId);
37+
}
38+
39+
// Read-only transcript snapshot reader for dry-run detection phase.
40+
// Avoids opening writable database lifecycle (lease/WAL/schema-ensure).
41+
// Returns rows only; migration parses per-row during repair.
42+
type ReadOnlyTranscriptSnapshot =
43+
| {
44+
ok: true;
45+
rows: Array<{ eventJson: string; seq: number }>;
46+
}
47+
| { ok: false; error: unknown };
48+
49+
export function readOnlySqliteTranscriptRepairSnapshot(
50+
sqlitePath: string,
51+
sessionId: string,
52+
needsRepair: (event: unknown) => boolean,
53+
): ReadOnlyTranscriptSnapshot {
54+
if (!fs.existsSync(sqlitePath)) {
55+
return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) };
56+
}
57+
let database: DatabaseSync | undefined;
58+
try {
59+
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
60+
// Unchanged histories retain one payload. Re-read positive candidates in full so
61+
// malformed siblings and exact-snapshot guards still govern the surgical repair.
62+
for (const row of iterateTranscriptRows(database, sessionId)) {
63+
if (typeof row.event_json !== "string" || typeof row.seq !== "number") {
64+
continue;
65+
}
66+
let event: unknown;
67+
try {
68+
event = JSON.parse(row.event_json);
69+
} catch {
70+
continue;
71+
}
72+
if (!needsRepair(event)) {
73+
continue;
74+
}
75+
const rows: Array<{ eventJson: string; seq: number }> = [];
76+
for (const candidate of iterateTranscriptRows(database, sessionId)) {
77+
if (typeof candidate.event_json === "string" && typeof candidate.seq === "number") {
78+
rows.push({ eventJson: candidate.event_json, seq: candidate.seq });
79+
}
80+
}
81+
return { ok: true, rows };
82+
}
83+
return { ok: true, rows: [] };
84+
} catch (error) {
85+
return { ok: false, error };
86+
} finally {
87+
database?.close();
88+
}
89+
}
90+
91+
/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */
92+
export function readOnlySqliteHeaderlessTranscriptSnapshot(
93+
sqlitePath: string,
94+
sessionId: string,
95+
):
96+
| { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string }
97+
| { 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;
102+
try {
103+
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
104+
// Headers can live at nonzero seq. A current header needs no whole-history read;
105+
// possible headerless repairs still take and validate the complete exact snapshot.
106+
for (const row of iterateTranscriptRows(database, sessionId, true)) {
107+
if (typeof row.event_json !== "string") {
108+
break;
109+
}
110+
let first: unknown;
111+
try {
112+
first = JSON.parse(row.event_json);
113+
} catch {
114+
return { ok: true, rows: [] };
115+
}
116+
if (!isRecord(first) || first.type === "session") {
117+
return { ok: true, rows: [] };
118+
}
119+
}
120+
const sessionKeyRow = database
121+
.prepare("SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1")
122+
.get(sessionId);
123+
const storageRows: SqliteTranscriptStorageRow[] = [];
124+
for (const row of iterateTranscriptRows(database, sessionId)) {
125+
if (
126+
typeof row.created_at !== "number" ||
127+
typeof row.event_json !== "string" ||
128+
typeof row.seq !== "number"
129+
) {
130+
return {
131+
ok: false,
132+
error: new Error(`Invalid transcript row metadata for session ${sessionId}`),
133+
};
134+
}
135+
storageRows.push({
136+
createdAt: row.created_at,
137+
eventJson: row.event_json,
138+
seq: row.seq,
139+
});
140+
}
141+
return {
142+
ok: true,
143+
rows: storageRows,
144+
...(typeof sessionKeyRow?.session_key === "string"
145+
? { sessionKey: sessionKeyRow.session_key }
146+
: {}),
147+
};
148+
} catch (error) {
149+
return { ok: false, error };
150+
} finally {
151+
database?.close();
152+
}
153+
}

0 commit comments

Comments
 (0)