Skip to content

Commit af175c8

Browse files
authored
fix: prevent large session migrations from stalling (#104737)
* fix: scale session SQLite migration manifests * chore: leave release notes to release workflow
1 parent 8a4463e commit af175c8

3 files changed

Lines changed: 160 additions & 54 deletions

File tree

‎src/commands/doctor-session-sqlite-migration-run.ts‎

Lines changed: 51 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import fs from "node:fs";
44
import path from "node:path";
55
import { isRecord } from "@openclaw/normalization-core/record-coerce";
66
import { resolveStateDir } from "../config/paths.js";
7+
import * as replaceFile from "../infra/replace-file.js";
78
import { VERSION } from "../version.js";
89
import type {
910
DoctorSessionSqliteIssue,
@@ -100,8 +101,12 @@ export function writeSessionSqliteMigrationManifest(
100101
activeRun: ActiveSessionSqliteMigrationRun,
101102
): void {
102103
fs.mkdirSync(path.dirname(activeRun.manifestPath), { recursive: true, mode: 0o700 });
103-
fs.writeFileSync(activeRun.manifestPath, `${JSON.stringify(activeRun.manifest, null, 2)}\n`, {
104+
replaceFile.replaceFileAtomicSync({
105+
filePath: activeRun.manifestPath,
106+
content: `${JSON.stringify(activeRun.manifest, null, 2)}\n`,
107+
dirMode: 0o700,
104108
mode: 0o600,
109+
tempPrefix: path.basename(activeRun.manifestPath),
105110
});
106111
}
107112

@@ -129,29 +134,62 @@ export function recordPlannedMigrationMove(
129134
target: SessionSqliteMigrationTargetInput,
130135
move: SessionSqliteMigrationMove,
131136
): void {
132-
const manifestTarget = findMigrationManifestTarget(activeRun, target);
133-
if (!activeRun || !manifestTarget) {
134-
return;
135-
}
136-
if (!manifestTarget.plannedMoves.some((item) => movesMatch(item, move))) {
137-
manifestTarget.plannedMoves.push(move);
138-
}
139-
writeSessionSqliteMigrationManifest(activeRun);
137+
recordPlannedMigrationMoves(activeRun, target, [move]);
138+
}
139+
140+
export function recordPlannedMigrationMoves(
141+
activeRun: ActiveSessionSqliteMigrationRun | undefined,
142+
target: SessionSqliteMigrationTargetInput,
143+
moves: readonly SessionSqliteMigrationMove[],
144+
): void {
145+
recordMigrationMoves(activeRun, target, "plannedMoves", moves);
140146
}
141147

142148
export function recordCompletedMigrationMove(
143149
activeRun: ActiveSessionSqliteMigrationRun | undefined,
144150
target: SessionSqliteMigrationTargetInput,
145151
move: SessionSqliteMigrationMove,
152+
): void {
153+
recordCompletedMigrationMoves(activeRun, target, [move]);
154+
}
155+
156+
export function recordCompletedMigrationMoves(
157+
activeRun: ActiveSessionSqliteMigrationRun | undefined,
158+
target: SessionSqliteMigrationTargetInput,
159+
moves: readonly SessionSqliteMigrationMove[],
160+
): void {
161+
recordMigrationMoves(activeRun, target, "completedMoves", moves);
162+
}
163+
164+
function recordMigrationMoves(
165+
activeRun: ActiveSessionSqliteMigrationRun | undefined,
166+
target: SessionSqliteMigrationTargetInput,
167+
listKey: "completedMoves" | "plannedMoves",
168+
moves: readonly SessionSqliteMigrationMove[],
146169
): void {
147170
const manifestTarget = findMigrationManifestTarget(activeRun, target);
148-
if (!activeRun || !manifestTarget) {
171+
if (!activeRun || !manifestTarget || moves.length === 0) {
149172
return;
150173
}
151-
if (!manifestTarget.completedMoves.some((item) => movesMatch(item, move))) {
152-
manifestTarget.completedMoves.push(move);
174+
const targetMoves = manifestTarget[listKey];
175+
const knownMoves = new Set(targetMoves.map(migrationMoveKey));
176+
let changed = false;
177+
for (const move of moves) {
178+
const key = migrationMoveKey(move);
179+
if (knownMoves.has(key)) {
180+
continue;
181+
}
182+
knownMoves.add(key);
183+
targetMoves.push(move);
184+
changed = true;
185+
}
186+
if (changed) {
187+
writeSessionSqliteMigrationManifest(activeRun);
153188
}
154-
writeSessionSqliteMigrationManifest(activeRun);
189+
}
190+
191+
function migrationMoveKey(move: SessionSqliteMigrationMove): string {
192+
return `${move.sourcePath}\u0000${move.archivePath}`;
155193
}
156194

157195
export function restoreSessionSqliteMigrationRuns(params: {
@@ -333,10 +371,6 @@ function findMigrationManifestTarget(
333371
);
334372
}
335373

336-
function movesMatch(left: SessionSqliteMigrationMove, right: SessionSqliteMigrationMove): boolean {
337-
return left.sourcePath === right.sourcePath && left.archivePath === right.archivePath;
338-
}
339-
340374
function emptyRestoreReport(): DoctorSessionSqliteRestoreReport {
341375
return {
342376
conflicts: [],

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

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
import fs from "node:fs";
33
import os from "node:os";
44
import path from "node:path";
5-
import { afterEach, beforeEach, describe, expect, it } from "vitest";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import {
77
loadExactSqliteSessionEntry,
88
loadSqliteTranscriptEventsSync,
99
upsertSqliteSessionEntry,
1010
} from "../config/sessions/session-accessor.sqlite.js";
1111
import { requireNodeSqlite } from "../infra/node-sqlite.js";
12+
import * as replaceFile from "../infra/replace-file.js";
1213
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
1314
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
1415
import type { SessionSqliteMigrationManifest } from "./doctor-session-sqlite-migration-run.js";
@@ -391,6 +392,53 @@ describe("runDoctorSessionSqlite", () => {
391392
]);
392393
});
393394

395+
it("checkpoints bulk unreferenced archive moves without per-file manifest rewrites", async () => {
396+
const store = createLegacyStore();
397+
for (let index = 0; index < 64; index += 1) {
398+
fs.writeFileSync(path.join(store.sessionDir, `orphan-${index}.jsonl`), "{}\n", {
399+
mode: 0o600,
400+
});
401+
}
402+
fs.writeFileSync(path.join(store.sessionDir, "orphan collision.jsonl"), "{}\n", {
403+
mode: 0o600,
404+
});
405+
fs.writeFileSync(path.join(store.sessionDir, "orphan_collision.jsonl"), "{}\n", {
406+
mode: 0o600,
407+
});
408+
const replaceFileAtomicSync = vi.spyOn(replaceFile, "replaceFileAtomicSync");
409+
410+
try {
411+
const report = await runDoctorSessionSqlite({
412+
env: store.env,
413+
mode: "import",
414+
store: store.storePath,
415+
});
416+
const manifest = readMigrationManifest(report.migrationRun?.manifestPath);
417+
const manifestWrites = replaceFileAtomicSync.mock.calls.filter(([options]) =>
418+
options.filePath.includes("session-sqlite-migration-runs"),
419+
).length;
420+
const plannedUnreferencedMoves =
421+
manifest.targets[0]?.plannedMoves.filter((move) => move.kind === "unreferenced-jsonl") ??
422+
[];
423+
424+
expect(plannedUnreferencedMoves).toHaveLength(67);
425+
expect(new Set(plannedUnreferencedMoves.map((move) => move.archivePath)).size).toBe(67);
426+
expect(
427+
manifest.targets[0]?.completedMoves.filter((move) => move.kind === "unreferenced-jsonl"),
428+
).toHaveLength(67);
429+
expect(manifestWrites).toBeLessThan(20);
430+
expect(replaceFileAtomicSync).toHaveBeenCalledWith(
431+
expect.objectContaining({
432+
filePath: report.migrationRun?.manifestPath,
433+
mode: 0o600,
434+
tempPrefix: path.basename(report.migrationRun?.manifestPath ?? ""),
435+
}),
436+
);
437+
} finally {
438+
replaceFileAtomicSync.mockRestore();
439+
}
440+
});
441+
394442
it("archives legacy trajectory pointer files with imported transcripts", async () => {
395443
const store = createLegacyStore();
396444
const pointerPath = path.join(store.sessionDir, "session-1.trajectory-path.json");

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

Lines changed: 60 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,14 @@ import { compactDoctorSessionSqliteTarget } from "./doctor-session-sqlite-compac
2525
import {
2626
createSessionSqliteMigrationRun,
2727
recordCompletedMigrationMove,
28+
recordCompletedMigrationMoves,
2829
recordPlannedMigrationMove,
30+
recordPlannedMigrationMoves,
2931
updateMigrationManifestTarget,
3032
writeSessionSqliteMigrationFailureReports,
3133
writeSessionSqliteMigrationManifest,
3234
type ActiveSessionSqliteMigrationRun,
35+
type SessionSqliteMigrationMove,
3336
type SessionSqliteMigrationMoveKind,
3437
type SessionSqliteMigrationTargetInput,
3538
} from "./doctor-session-sqlite-migration-run.js";
@@ -627,25 +630,46 @@ function archiveUnreferencedJsonlFiles(
627630
referencedPaths: readonly string[],
628631
activeRun: ActiveSessionSqliteMigrationRun | undefined,
629632
): void {
630-
for (const sourcePath of listUnreferencedJsonlFiles(target.storePath, referencedPaths)) {
631-
try {
632-
report.archivedUnreferencedJsonlFiles.push(
633-
moveSessionJsonlToArchive({
634-
activeRun,
633+
const reservedArchivePaths = new Set<string>();
634+
const plannedMoves = listUnreferencedJsonlFiles(target.storePath, referencedPaths).flatMap(
635+
(sourcePath) => {
636+
try {
637+
const move = planSessionJsonlArchiveMove({
635638
archiveKey: "archive-tier",
636639
baseNameRaw: path.basename(sourcePath),
637640
kind: "unreferenced-jsonl",
641+
reservedArchivePaths,
638642
sourcePathRaw: sourcePath,
639643
target,
640-
}),
641-
);
644+
});
645+
reservedArchivePaths.add(move.archivePath);
646+
return [move];
647+
} catch (err) {
648+
report.issues.push({
649+
code: "unreferenced_jsonl_archive_failed",
650+
message: `${sourcePath}: ${String(err)}`,
651+
});
652+
return [];
653+
}
654+
},
655+
);
656+
// Persist every source/destination before the first rename. A crash can then
657+
// restore moved files even when the completion checkpoint was never written.
658+
recordPlannedMigrationMoves(activeRun, createMigrationTargetInput(target), plannedMoves);
659+
const completedMoves: SessionSqliteMigrationMove[] = [];
660+
for (const move of plannedMoves) {
661+
try {
662+
fs.renameSync(move.sourcePath, move.archivePath);
663+
report.archivedUnreferencedJsonlFiles.push(move.archivePath);
664+
completedMoves.push(move);
642665
} catch (err) {
643666
report.issues.push({
644667
code: "unreferenced_jsonl_archive_failed",
645-
message: `${sourcePath}: ${String(err)}`,
668+
message: `${move.sourcePath}: ${String(err)}`,
646669
});
647670
}
648671
}
672+
recordCompletedMigrationMoves(activeRun, createMigrationTargetInput(target), completedMoves);
649673
}
650674

651675
function archiveImportedLegacySessionStores(
@@ -1035,48 +1059,48 @@ function moveSessionJsonlToArchive(params: {
10351059
sourcePathRaw: string;
10361060
target: SessionStoreTarget;
10371061
}): string {
1038-
const { archiveKey, baseNameRaw, sourcePathRaw } = params;
1039-
const sourcePath = path.resolve(sourcePathRaw);
1062+
const move = planSessionJsonlArchiveMove(params);
1063+
recordPlannedMigrationMove(params.activeRun, createMigrationTargetInput(params.target), move);
1064+
fs.renameSync(move.sourcePath, move.archivePath);
1065+
recordCompletedMigrationMove(params.activeRun, createMigrationTargetInput(params.target), move);
1066+
return move.archivePath;
1067+
}
1068+
1069+
function planSessionJsonlArchiveMove(params: {
1070+
archiveKey: string;
1071+
baseNameRaw: string;
1072+
kind: SessionSqliteMigrationMoveKind;
1073+
reservedArchivePaths?: ReadonlySet<string>;
1074+
sessionKey?: string;
1075+
sourcePathRaw: string;
1076+
target: SessionStoreTarget;
1077+
}): SessionSqliteMigrationMove {
1078+
const sourcePath = path.resolve(params.sourcePathRaw);
10401079
const stat = fs.statSync(sourcePath);
10411080
if (!stat.isFile()) {
10421081
throw new Error("source is not a regular file");
10431082
}
10441083
const archiveDir = resolveImportedTranscriptArchiveDir(params.target.storePath);
10451084
fs.mkdirSync(archiveDir, { recursive: true });
1046-
const baseName = baseNameRaw.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 160) || "artifact";
1047-
const keySlug = archiveKey.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 120) || "session";
1085+
const baseName = params.baseNameRaw.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 160) || "artifact";
1086+
const keySlug = params.archiveKey.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 120) || "session";
10481087
for (let attempt = 0; attempt < 100; attempt += 1) {
10491088
const suffix = attempt === 0 ? "" : `.${attempt}`;
10501089
const archivePath = path.join(
10511090
archiveDir,
10521091
`${keySlug}.${baseName}.imported-${Date.now()}${suffix}`,
10531092
);
1054-
if (fs.existsSync(archivePath)) {
1093+
if (fs.existsSync(archivePath) || params.reservedArchivePaths?.has(archivePath)) {
10551094
continue;
10561095
}
1057-
try {
1058-
const move = {
1059-
archivePath,
1060-
kind: params.kind,
1061-
...(params.sessionKey ? { sessionKey: params.sessionKey } : {}),
1062-
sourcePath,
1063-
};
1064-
recordPlannedMigrationMove(params.activeRun, createMigrationTargetInput(params.target), move);
1065-
fs.renameSync(sourcePath, archivePath);
1066-
recordCompletedMigrationMove(
1067-
params.activeRun,
1068-
createMigrationTargetInput(params.target),
1069-
move,
1070-
);
1071-
return archivePath;
1072-
} catch (err) {
1073-
if ((err as { code?: unknown })?.code === "EEXIST") {
1074-
continue;
1075-
}
1076-
throw err;
1077-
}
1078-
}
1079-
throw new Error(`Could not archive ${baseName} for ${archiveKey}`);
1096+
return {
1097+
archivePath,
1098+
kind: params.kind,
1099+
...(params.sessionKey ? { sessionKey: params.sessionKey } : {}),
1100+
sourcePath,
1101+
};
1102+
}
1103+
throw new Error(`Could not archive ${baseName} for ${params.archiveKey}`);
10801104
}
10811105

10821106
function resolveImportedTranscriptArchiveDir(storePath: string): string {

0 commit comments

Comments
 (0)