Skip to content

Commit 1c0c732

Browse files
committed
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.
1 parent d5d2167 commit 1c0c732

12 files changed

Lines changed: 736 additions & 177 deletions

‎docs/cli/doctor.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,13 @@ 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+
303310
The regular `openclaw doctor` pass also reports canonical SQLite transcripts
304311
whose initial session header was never persisted. `openclaw doctor --fix`
305312
prepends a current header and rebuilds the transcript indexes in one

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

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ export function createTranscriptEventReader(
8484
sessionId: string,
8585
allowMalformedPrefix = false,
8686
sourceFingerprint = readTranscriptFingerprint(transcriptPath),
87-
): (append: (event: TranscriptEvent) => void) => void {
87+
): (append: (event: TranscriptEvent) => void) => () => void {
8888
return (append) => {
8989
for (const event of readTranscriptEventsForImport(
9090
transcriptPath,
@@ -94,6 +94,7 @@ export function createTranscriptEventReader(
9494
)) {
9595
append(event as TranscriptEvent);
9696
}
97+
return () => assertTranscriptFileUnchanged(transcriptPath, sourceFingerprint);
9798
};
9899
}
99100

@@ -511,27 +512,28 @@ function* iterateJsonlLinesSync(filePath: string): Generator<{ lineNumber: numbe
511512
const fd = fs.openSync(filePath, "r");
512513
const decoder = new TextDecoder("utf-8", { fatal: true });
513514
const buffer = Buffer.allocUnsafe(JSONL_READ_CHUNK_BYTES);
514-
let carry = "";
515+
let fragments: string[] = [];
515516
let lineNumber = 0;
516517
try {
517518
while (true) {
518519
const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
519520
if (bytesRead === 0) {
520521
break;
521522
}
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) {
523+
const parts = decoder.decode(buffer.subarray(0, bytesRead), { stream: true }).split("\n");
524+
for (let index = 0; index < parts.length - 1; index++) {
525+
fragments.push(parts[index]!);
526526
lineNumber += 1;
527-
const text = part.trim();
527+
const text = fragments.join("").trim();
528+
fragments = [];
528529
if (text) {
529530
yield { lineNumber, text };
530531
}
531532
}
533+
fragments.push(parts.at(-1)!);
532534
}
533-
carry += decoder.decode();
534-
const text = carry.trim();
535+
fragments.push(decoder.decode());
536+
const text = fragments.join("").trim();
535537
if (text) {
536538
yield { lineNumber: lineNumber + 1, text };
537539
}
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import assert from "node:assert/strict";
2+
import { createHash } from "node:crypto";
3+
import fs from "node:fs";
4+
import path from "node:path";
5+
import { pathToFileURL } from "node:url";
6+
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
7+
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
8+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
9+
import { resolveTargetSqlitePath } from "./doctor-session-sqlite-readers.js";
10+
import { runDoctorSessionSqlite } from "./doctor-session-sqlite.js";
11+
12+
export const sqliteImportMemorySupportUrl = import.meta.url;
13+
14+
async function main() {
15+
const [stateDir, scenario] = process.argv.slice(2);
16+
assert(stateDir && scenario);
17+
process.env.OPENCLAW_STATE_DIR = stateDir;
18+
process.env.OPENCLAW_CONFIG_PATH = path.join(stateDir, "openclaw.json");
19+
const sessionCount = scenario === "batch" ? 256 : 1;
20+
const eventCount = scenario === "deep" ? 100_000 : scenario === "batch" ? 64 : 8;
21+
const payloadBytes = scenario === "deep" ? 4096 : scenario === "batch" ? 32768 : 256;
22+
const sessionsDir = path.join(stateDir, "agents/main/sessions");
23+
const storePath = path.join(sessionsDir, "sessions.json");
24+
fs.mkdirSync(sessionsDir, { recursive: true });
25+
const store: Record<string, { sessionId: string; updatedAt: number; sessionFile: string }> = {};
26+
const expected = new Map<string, string>();
27+
const timestamp = 1_800_000_000_000;
28+
for (let session = 0; session < sessionCount; session++) {
29+
const sessionId = `memory-${session}`;
30+
const transcriptPath = path.join(sessionsDir, `${sessionId}.jsonl`);
31+
store[`agent:main:memory-${session}`] = {
32+
sessionId,
33+
updatedAt: timestamp,
34+
sessionFile: transcriptPath,
35+
};
36+
const fd = fs.openSync(transcriptPath, "wx", 0o600);
37+
const hash = createHash("sha256");
38+
const write = (event: unknown) => {
39+
const json = JSON.stringify(event);
40+
hash.update(json).update("\n");
41+
fs.writeSync(fd, `${json}\n`);
42+
};
43+
try {
44+
write({
45+
type: "session",
46+
version: 3,
47+
id: sessionId,
48+
timestamp: new Date(timestamp).toISOString(),
49+
cwd: "/fixture",
50+
});
51+
for (let index = 0; index < eventCount; index++) {
52+
write({
53+
type: "message",
54+
id: `e-${index}`,
55+
parentId: index === 0 ? null : `e-${index - 1}`,
56+
timestamp,
57+
message: {
58+
role: "toolResult",
59+
toolCallId: `call-${index}`,
60+
toolName: "exec",
61+
isError: false,
62+
content: [{ type: "text", text: `${session}:${index}:é🦞${"x".repeat(payloadBytes)}` }],
63+
timestamp,
64+
},
65+
});
66+
}
67+
// Force the full projection owner, including a deep selected ancestry.
68+
write({
69+
type: "leaf",
70+
id: "selected-leaf",
71+
parentId: `e-${eventCount - 1}`,
72+
targetId: `e-${eventCount - 2}`,
73+
});
74+
} finally {
75+
fs.closeSync(fd);
76+
}
77+
expected.set(sessionId, hash.digest("hex"));
78+
}
79+
fs.writeFileSync(storePath, JSON.stringify(store));
80+
process.stderr.write(`seeded ${sessionCount} sessions x ${eventCount} events; importing\n`);
81+
const started = performance.now();
82+
const report = await runDoctorSessionSqlite({
83+
mode: "import",
84+
store: storePath,
85+
env: process.env,
86+
});
87+
assert.equal(report.totals.issues, 0, JSON.stringify(report.targets.map((t) => t.issues)));
88+
assert.equal(report.totals.importedEntries, sessionCount);
89+
assert.equal(report.totals.importedTranscriptEvents, sessionCount * (eventCount + 2));
90+
const db = openNodeSqliteDatabase(resolveTargetSqlitePath({ agentId: "main", storePath }), {
91+
readOnly: true,
92+
});
93+
try {
94+
const read = db.prepare(
95+
"SELECT event_json FROM transcript_events WHERE session_id = ? ORDER BY seq",
96+
);
97+
for (const [sessionId, digest] of expected) {
98+
const hash = createHash("sha256");
99+
for (const row of read.iterate(sessionId)) {
100+
hash.update(String(row.event_json)).update("\n");
101+
}
102+
assert.equal(hash.digest("hex"), digest);
103+
assert.deepEqual(
104+
{
105+
...db
106+
.prepare(
107+
"SELECT active_event_count, active_message_count, leaf_event_id, needs_rebuild FROM session_transcript_index_state WHERE session_id = ?",
108+
)
109+
.get(sessionId),
110+
},
111+
{
112+
active_event_count: eventCount - 1,
113+
active_message_count: eventCount - 1,
114+
leaf_event_id: `e-${eventCount - 2}`,
115+
needs_rebuild: 0,
116+
},
117+
);
118+
}
119+
} finally {
120+
db.close();
121+
}
122+
const rerun = await runDoctorSessionSqlite({
123+
mode: "import",
124+
store: storePath,
125+
env: process.env,
126+
});
127+
assert.equal(rerun.totals.importedEntries, 0);
128+
closeOpenClawAgentDatabasesForTest();
129+
closeOpenClawStateDatabaseForTest();
130+
process.stdout.write(
131+
JSON.stringify({
132+
scenario,
133+
sessionCount,
134+
eventCount,
135+
elapsedMs: performance.now() - started,
136+
maxRssKiB: process.resourceUsage().maxRSS,
137+
}),
138+
);
139+
}
140+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
141+
void main().catch((error: unknown) => {
142+
console.error(error);
143+
process.exitCode = 1;
144+
});
145+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { execFile } from "node:child_process";
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import { fileURLToPath } from "node:url";
5+
import { promisify } from "node:util";
6+
import { build as esbuild } from "esbuild";
7+
import { afterAll, beforeAll, expect, it } from "vitest";
8+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
9+
import { sqliteImportMemorySupportUrl } from "./doctor-session-sqlite.memory.test-support.js";
10+
11+
const execFileAsync = promisify(execFile);
12+
let bundleDir: string;
13+
let childPath: string;
14+
15+
beforeAll(async () => {
16+
fs.mkdirSync(path.join(process.cwd(), "node_modules/.cache"), { recursive: true });
17+
bundleDir = fs.mkdtempSync(path.join(process.cwd(), "node_modules/.cache/import-memory-"));
18+
childPath = path.join(bundleDir, "child.mjs");
19+
for (const schema of ["openclaw-agent-schema.sql", "openclaw-state-schema.sql"]) {
20+
fs.copyFileSync(path.join(process.cwd(), "src/state", schema), path.join(bundleDir, schema));
21+
}
22+
await esbuild({
23+
bundle: true,
24+
entryPoints: [fileURLToPath(sqliteImportMemorySupportUrl)],
25+
format: "esm",
26+
outfile: childPath,
27+
packages: "external",
28+
platform: "node",
29+
target: "node22",
30+
});
31+
});
32+
afterAll(() => {
33+
if (bundleDir) {
34+
fs.rmSync(bundleDir, { force: true, recursive: true });
35+
}
36+
});
37+
38+
it.each(["batch", "deep"])(
39+
"imports %s transcripts and completes branch projections under a 256 MiB heap",
40+
async (scenario) => {
41+
await withOpenClawTestState({ applyEnv: false, label: "import-memory" }, async (state) => {
42+
const { stdout } = await execFileAsync(
43+
process.execPath,
44+
["--max-old-space-size=256", childPath, state.stateDir, scenario],
45+
{
46+
cwd: process.cwd(),
47+
env: state.env,
48+
encoding: "utf8",
49+
maxBuffer: 1024 * 1024,
50+
timeout: 180_000,
51+
},
52+
);
53+
expect(JSON.parse(stdout)).toMatchObject({ scenario });
54+
});
55+
},
56+
180_000,
57+
);
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Disposable migration spool: never registered, resumed, or read by the runtime.
2+
import { createHash } from "node:crypto";
3+
import fs from "node:fs";
4+
import os from "node:os";
5+
import path from "node:path";
6+
import type { DatabaseSync } from "node:sqlite";
7+
import { openNodeSqliteDatabase } from "../../infra/node-sqlite.js";
8+
import { createPrivateSqliteTempDirectorySync } from "../../infra/sqlite-private-directory.js";
9+
10+
type StagedTranscriptRow = { seq: number; eventJson: string; createdAt: number | null };
11+
12+
export function withSqliteSessionImportStage<T>(run: (stage: SqliteSessionImportStage) => T): T {
13+
const directory = createPrivateSqliteTempDirectorySync(os.tmpdir(), "openclaw-session-import-");
14+
let database: DatabaseSync | undefined;
15+
try {
16+
const filename = path.join(directory, "transcripts.sqlite");
17+
fs.closeSync(fs.openSync(filename, "wx", 0o600));
18+
database = openNodeSqliteDatabase(filename);
19+
// The spool is discarded even on failure. Keep SQLite's page cache and temporary
20+
// work on disk; transcript bytes must not move from a JS array to a native heap.
21+
database.exec(`
22+
PRAGMA cache_size = -2048;
23+
PRAGMA temp_store = FILE;
24+
CREATE TABLE rows (
25+
source INTEGER NOT NULL, seq INTEGER NOT NULL, event_json TEXT NOT NULL,
26+
created_at INTEGER, PRIMARY KEY (source, seq)
27+
) WITHOUT ROWID;
28+
CREATE TABLE seen (hash BLOB NOT NULL, event_json TEXT NOT NULL);
29+
CREATE INDEX seen_hash ON seen(hash);
30+
BEGIN;
31+
`);
32+
return run(new SqliteSessionImportStage(database));
33+
} finally {
34+
try {
35+
database?.close();
36+
} finally {
37+
fs.rmSync(directory, { recursive: true, force: true });
38+
}
39+
}
40+
}
41+
42+
export class SqliteSessionImportStage {
43+
private readonly insert;
44+
private readonly read;
45+
private readonly findSeen;
46+
private readonly insertSeen;
47+
48+
constructor(private readonly database: DatabaseSync) {
49+
this.insert = database.prepare("INSERT INTO rows VALUES (?, ?, ?, ?)");
50+
this.read = database.prepare(
51+
"SELECT seq, event_json AS eventJson, created_at AS createdAt FROM rows WHERE source = ? ORDER BY seq",
52+
);
53+
this.findSeen = database.prepare(
54+
"SELECT 1 FROM seen WHERE hash = ? AND event_json = ? LIMIT 1",
55+
);
56+
this.insertSeen = database.prepare("INSERT INTO seen VALUES (?, ?)");
57+
}
58+
59+
append(source: number, seq: number, eventJson: string, createdAt: number | null): void {
60+
this.insert.run(source, seq, eventJson, createdAt);
61+
}
62+
63+
rows(source: number): Iterable<StagedTranscriptRow> {
64+
// SAFETY: this private table is written only by append; the projection preserves its row types.
65+
return this.read.iterate(source) as Iterable<StagedTranscriptRow>;
66+
}
67+
68+
resetSeen(): void {
69+
this.database.exec("DELETE FROM seen");
70+
}
71+
72+
hasSeen(eventJson: string): boolean {
73+
// Hash narrows the lookup; exact bytes decide equality even under a hash collision.
74+
return (
75+
this.findSeen.get(createHash("sha256").update(eventJson).digest(), eventJson) !== undefined
76+
);
77+
}
78+
79+
addSeen(eventJson: string): void {
80+
this.insertSeen.run(createHash("sha256").update(eventJson).digest(), eventJson);
81+
}
82+
}

0 commit comments

Comments
 (0)