Skip to content

Commit cd7b282

Browse files
authored
fix(sessions): migrate long histories without exhausting heap (#131276)
* fix(sessions): bound legacy transcript import memory Stage transcript payloads and deduplication in private temporary SQLite storage before the existing atomic import. Rebuild projections from navigation metadata and stream payload reads rather than retaining entire histories. Preserve exact handoffs, source validation, and archive recovery.\n\nFixes #127468. * build: register doctor transcript staging SQL boundary * 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 d83a53d commit cd7b282

26 files changed

Lines changed: 1397 additions & 426 deletions

‎config/assertion-safety-baseline.txt‎

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

‎docs/cli/doctor.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,18 @@ imported and archived out of the active sessions directory after successful
300300
import; archive-tier JSONL files remain support artifacts, not runtime
301301
fallbacks.
302302

303+
The import stages transcript payloads in a private, temporary SQLite database
304+
instead of retaining complete batches of histories in memory. Keep free space
305+
on the system temporary volume as well as the volume holding OpenClaw state.
306+
Staging is removed when the operation finishes and is never used as a runtime
307+
store or resumed after an interruption; retries use the original sources and
308+
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`.
314+
303315
The regular `openclaw doctor` pass also reports canonical SQLite transcripts
304316
whose initial session header was never persisted. `openclaw doctor --fix`
305317
prepends a current header and rebuilds the transcript indexes in one

‎scripts/check-kysely-guardrails.mts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,11 @@ 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",
117+
// Disposable import planning only; canonical session tables still use Kysely.
118+
"src/config/sessions/session-accessor.sqlite-import-stage.ts",
116119
"src/infra/state-migrations.task-sidecar-rows.ts",
117120
"src/infra/state-migrations.storage.ts",
118121
"src/infra/state-migrations.cron-run-logs.ts",

‎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: 11 additions & 131 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";
@@ -84,7 +83,7 @@ export function createTranscriptEventReader(
8483
sessionId: string,
8584
allowMalformedPrefix = false,
8685
sourceFingerprint = readTranscriptFingerprint(transcriptPath),
87-
): (append: (event: TranscriptEvent) => void) => void {
86+
): (append: (event: TranscriptEvent) => void) => () => void {
8887
return (append) => {
8988
for (const event of readTranscriptEventsForImport(
9089
transcriptPath,
@@ -94,6 +93,7 @@ export function createTranscriptEventReader(
9493
)) {
9594
append(event as TranscriptEvent);
9695
}
96+
return () => assertTranscriptFileUnchanged(transcriptPath, sourceFingerprint);
9797
};
9898
}
9999

@@ -511,27 +511,28 @@ function* iterateJsonlLinesSync(filePath: string): Generator<{ lineNumber: numbe
511511
const fd = fs.openSync(filePath, "r");
512512
const decoder = new TextDecoder("utf-8", { fatal: true });
513513
const buffer = Buffer.allocUnsafe(JSONL_READ_CHUNK_BYTES);
514-
let carry = "";
514+
let fragments: string[] = [];
515515
let lineNumber = 0;
516516
try {
517517
while (true) {
518518
const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
519519
if (bytesRead === 0) {
520520
break;
521521
}
522-
carry += decoder.decode(buffer.subarray(0, bytesRead), { stream: true });
523-
const parts = carry.split(/\r?\n/);
524-
carry = parts.pop() ?? "";
525-
for (const part of parts) {
522+
const parts = decoder.decode(buffer.subarray(0, bytesRead), { stream: true }).split("\n");
523+
for (let index = 0; index < parts.length - 1; index++) {
524+
fragments.push(parts[index]!);
526525
lineNumber += 1;
527-
const text = part.trim();
526+
const text = fragments.join("").trim();
527+
fragments = [];
528528
if (text) {
529529
yield { lineNumber, text };
530530
}
531531
}
532+
fragments.push(parts.at(-1)!);
532533
}
533-
carry += decoder.decode();
534-
const text = carry.trim();
534+
fragments.push(decoder.decode());
535+
const text = fragments.join("").trim();
535536
if (text) {
536537
yield { lineNumber: lineNumber + 1, text };
537538
}
@@ -555,124 +556,3 @@ function sqliteNumber(value: unknown): number {
555556
function parseJsonlLine(line: { text: string }): unknown {
556557
return JSON.parse(line.text);
557558
}
558-
559-
// Schema-tolerant session enumeration for transcript-label migration (avoids post-ship columns).
560-
// Queries transcript_events table (schema-stable) instead of sessions table.
561-
// Returns read-only view of all distinct session IDs with events.
562-
export function readOnlySqliteTranscriptSessionIds(sqlitePath: string): string[] {
563-
if (!fs.existsSync(sqlitePath)) {
564-
return [];
565-
}
566-
let database: DatabaseSync | undefined;
567-
try {
568-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
569-
if (!tableExists(database, "transcript_events")) {
570-
return [];
571-
}
572-
const rows = database
573-
.prepare("SELECT DISTINCT session_id FROM transcript_events ORDER BY session_id ASC")
574-
.all() as Array<{ session_id?: unknown }>;
575-
return rows
576-
.filter((row): row is { session_id: string } => typeof row.session_id === "string")
577-
.map((row) => row.session_id);
578-
} finally {
579-
database?.close();
580-
}
581-
}
582-
583-
// Read-only transcript snapshot reader for dry-run detection phase.
584-
// Avoids opening writable database lifecycle (lease/WAL/schema-ensure).
585-
// Returns rows only; migration parses per-row during repair.
586-
type ReadOnlyTranscriptSnapshot =
587-
| {
588-
ok: true;
589-
rows: Array<{ eventJson: string; seq: number }>;
590-
}
591-
| { ok: false; error: unknown };
592-
593-
export function readOnlySqliteTranscriptSnapshot(
594-
sqlitePath: string,
595-
sessionId: string,
596-
): ReadOnlyTranscriptSnapshot {
597-
if (!fs.existsSync(sqlitePath)) {
598-
return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) };
599-
}
600-
let database: DatabaseSync | undefined;
601-
try {
602-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
603-
const rows = database
604-
.prepare(
605-
"SELECT event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC",
606-
)
607-
.all(sessionId) as Array<{ event_json?: string; seq?: number }>;
608-
const validRows = rows.filter(
609-
(row): row is { event_json: string; seq: number } =>
610-
typeof row.event_json === "string" && typeof row.seq === "number",
611-
);
612-
return {
613-
ok: true,
614-
rows: validRows.map((row) => ({ eventJson: row.event_json, seq: row.seq })),
615-
};
616-
} catch (error) {
617-
return { ok: false, error };
618-
} finally {
619-
database?.close();
620-
}
621-
}
622-
623-
/** Reads exact row metadata for a guarded transcript replacement without opening a writer. */
624-
export function readOnlySqliteTranscriptStorageSnapshot(
625-
sqlitePath: string,
626-
sessionId: string,
627-
):
628-
| { ok: true; rows: SqliteTranscriptStorageRow[]; sessionKey?: string }
629-
| { ok: false; error: unknown } {
630-
if (!fs.existsSync(sqlitePath)) {
631-
return { ok: false, error: new Error(`SQLite database not found: ${sqlitePath}`) };
632-
}
633-
let database: DatabaseSync | undefined;
634-
try {
635-
database = openNodeSqliteDatabase(sqlitePath, { readOnly: true });
636-
const rows = database
637-
.prepare(
638-
"SELECT created_at, event_json, seq FROM transcript_events WHERE session_id = ? ORDER BY seq ASC",
639-
)
640-
.all(sessionId) as Array<{
641-
created_at?: unknown;
642-
event_json?: unknown;
643-
seq?: unknown;
644-
}>;
645-
const sessionKeyRow = database
646-
.prepare("SELECT session_key FROM session_windows WHERE session_id = ? LIMIT 1")
647-
.get(sessionId) as { session_key?: unknown } | undefined;
648-
const storageRows: SqliteTranscriptStorageRow[] = [];
649-
for (const row of rows) {
650-
if (
651-
typeof row.created_at !== "number" ||
652-
typeof row.event_json !== "string" ||
653-
typeof row.seq !== "number"
654-
) {
655-
return {
656-
ok: false,
657-
error: new Error(`Invalid transcript row metadata for session ${sessionId}`),
658-
};
659-
}
660-
storageRows.push({
661-
createdAt: row.created_at,
662-
eventJson: row.event_json,
663-
seq: row.seq,
664-
});
665-
}
666-
return {
667-
ok: true,
668-
rows: storageRows,
669-
...(typeof sessionKeyRow?.session_key === "string"
670-
? { sessionKey: sessionKeyRow.session_key }
671-
: {}),
672-
};
673-
} catch (error) {
674-
return { ok: false, error };
675-
} finally {
676-
database?.close();
677-
}
678-
}

0 commit comments

Comments
 (0)