Skip to content

Commit 8af2af2

Browse files
authored
fix(memory): catch up stale sessions on startup (#82341)
* fix(memory): catch up stale sessions on startup Add a startup catch-up scan for memory session source files so clean gateway restarts compare on-disk transcripts against persisted index file state and mark only missing/newer/resized session files dirty for a normal incremental sync. * fix(memory): catch up sessions for cli indexing Ensure one-shot memory index managers also compare session transcripts against persisted source state before no-force CLI syncs, so openclaw memory index can recover stale session rows without requiring --force. * chore: refresh CI after main repairs
1 parent 845da0e commit 8af2af2

7 files changed

Lines changed: 359 additions & 7 deletions

‎extensions/memory-core/src/memory/manager-session-sync-state.test.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { describe, expect, it } from "vitest";
2-
import { resolveMemorySessionSyncPlan } from "./manager-session-sync-state.js";
2+
import {
3+
resolveMemorySessionStartupDirtyFiles,
4+
resolveMemorySessionSyncPlan,
5+
} from "./manager-session-sync-state.js";
36

47
describe("memory session sync state", () => {
58
it("tracks active paths and bulk hashes for full scans", () => {
@@ -61,4 +64,46 @@ describe("memory session sync state", () => {
6164
expect(plan.indexAll).toBe(false);
6265
expect(plan.activePaths).toEqual(new Set(["sessions/incremental.jsonl"]));
6366
});
67+
68+
it("marks missing and changed startup session files dirty", () => {
69+
const dirtyFiles = resolveMemorySessionStartupDirtyFiles({
70+
files: [
71+
{
72+
absPath: "/tmp/sessions/unchanged.jsonl",
73+
path: "sessions/unchanged.jsonl",
74+
mtimeMs: 100,
75+
size: 10,
76+
},
77+
{
78+
absPath: "/tmp/sessions/newer.jsonl",
79+
path: "sessions/newer.jsonl",
80+
mtimeMs: 250,
81+
size: 20,
82+
},
83+
{
84+
absPath: "/tmp/sessions/resized.jsonl",
85+
path: "sessions/resized.jsonl",
86+
mtimeMs: 300,
87+
size: 31,
88+
},
89+
{
90+
absPath: "/tmp/sessions/missing.jsonl",
91+
path: "sessions/missing.jsonl",
92+
mtimeMs: 400,
93+
size: 40,
94+
},
95+
],
96+
existingRows: [
97+
{ path: "sessions/unchanged.jsonl", hash: "hash-unchanged", mtime: 100, size: 10 },
98+
{ path: "sessions/newer.jsonl", hash: "hash-newer", mtime: 200, size: 20 },
99+
{ path: "sessions/resized.jsonl", hash: "hash-resized", mtime: 300, size: 30 },
100+
],
101+
});
102+
103+
expect(dirtyFiles).toEqual([
104+
"/tmp/sessions/newer.jsonl",
105+
"/tmp/sessions/resized.jsonl",
106+
"/tmp/sessions/missing.jsonl",
107+
]);
108+
});
64109
});

‎extensions/memory-core/src/memory/manager-session-sync-state.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,37 @@
11
import { type MemorySourceFileStateRow } from "./manager-source-state.js";
22

3+
export type MemorySessionStartupFileState = {
4+
absPath: string;
5+
path: string;
6+
mtimeMs: number;
7+
size: number;
8+
};
9+
10+
export function resolveMemorySessionStartupDirtyFiles(params: {
11+
files: MemorySessionStartupFileState[];
12+
existingRows?: MemorySourceFileStateRow[] | null;
13+
}): string[] {
14+
const indexedRows = new Map((params.existingRows ?? []).map((row) => [row.path, row]));
15+
const dirtyFiles: string[] = [];
16+
for (const file of params.files) {
17+
const existing = indexedRows.get(file.path);
18+
if (!existing) {
19+
dirtyFiles.push(file.absPath);
20+
continue;
21+
}
22+
const indexedMtimeMs = Number(existing.mtime);
23+
const indexedSize = Number(existing.size);
24+
if (!Number.isFinite(indexedMtimeMs) || !Number.isFinite(indexedSize)) {
25+
dirtyFiles.push(file.absPath);
26+
continue;
27+
}
28+
if (file.size !== indexedSize || file.mtimeMs > indexedMtimeMs) {
29+
dirtyFiles.push(file.absPath);
30+
}
31+
}
32+
return dirtyFiles;
33+
}
34+
335
export function resolveMemorySessionSyncPlan(params: {
436
needsFullReindex: boolean;
537
files: string[];

‎extensions/memory-core/src/memory/manager-source-state.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ describe("memory source state", () => {
1515
all: (...args) => {
1616
calls.push({ sql, args });
1717
return [
18-
{ path: "memory/one.md", hash: "hash-1" },
19-
{ path: "memory/two.md", hash: "hash-2" },
18+
{ path: "memory/one.md", hash: "hash-1", mtime: 100, size: 10 },
19+
{ path: "memory/two.md", hash: "hash-2", mtime: 200, size: 20 },
2020
];
2121
},
2222
get: () => undefined,
@@ -27,8 +27,8 @@ describe("memory source state", () => {
2727

2828
expect(calls).toEqual([{ sql: MEMORY_SOURCE_FILE_STATE_SQL, args: ["memory"] }]);
2929
expect(state.rows).toEqual([
30-
{ path: "memory/one.md", hash: "hash-1" },
31-
{ path: "memory/two.md", hash: "hash-2" },
30+
{ path: "memory/one.md", hash: "hash-1", mtime: 100, size: 10 },
31+
{ path: "memory/two.md", hash: "hash-2", mtime: 200, size: 20 },
3232
]);
3333
expect(state.hashes).toEqual(
3434
new Map([

‎extensions/memory-core/src/memory/manager-source-state.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import type { MemorySource } from "openclaw/plugin-sdk/memory-core-host-engine-s
44
export type MemorySourceFileStateRow = {
55
path: string;
66
hash: string;
7+
mtime?: number;
8+
size?: number;
79
};
810

911
type MemorySourceStateDb = {
@@ -13,7 +15,7 @@ type MemorySourceStateDb = {
1315
};
1416
};
1517

16-
export const MEMORY_SOURCE_FILE_STATE_SQL = `SELECT path, hash FROM files WHERE source = ?`;
18+
export const MEMORY_SOURCE_FILE_STATE_SQL = `SELECT path, hash, mtime, size FROM files WHERE source = ?`;
1719
export const MEMORY_SOURCE_FILE_HASH_SQL = `SELECT hash FROM files WHERE path = ? AND source = ?`;
1820

1921
export function loadMemorySourceFileState(params: {
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import type { DatabaseSync } from "node:sqlite";
5+
import {
6+
resolveSessionTranscriptsDirForAgent,
7+
type OpenClawConfig,
8+
type ResolvedMemorySearchConfig,
9+
} from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
10+
import type {
11+
MemorySource,
12+
MemorySyncProgressUpdate,
13+
} from "openclaw/plugin-sdk/memory-core-host-engine-storage";
14+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
15+
import { MemoryManagerSyncOps } from "./manager-sync-ops.js";
16+
17+
type MemoryIndexEntry = {
18+
path: string;
19+
absPath: string;
20+
mtimeMs: number;
21+
size: number;
22+
hash: string;
23+
content?: string;
24+
};
25+
26+
type SyncParams = {
27+
reason?: string;
28+
force?: boolean;
29+
sessionFiles?: string[];
30+
progress?: (update: MemorySyncProgressUpdate) => void;
31+
};
32+
33+
type SourceStateRow = { path: string; hash: string; mtime: number; size: number };
34+
35+
class SessionStartupCatchupHarness extends MemoryManagerSyncOps {
36+
protected readonly cfg = {} as OpenClawConfig;
37+
protected readonly agentId = "main";
38+
protected readonly workspaceDir = "/tmp/openclaw-test-workspace";
39+
protected readonly settings = {
40+
sync: {
41+
sessions: {
42+
deltaBytes: 100_000,
43+
deltaMessages: 50,
44+
postCompactionForce: true,
45+
},
46+
},
47+
} as ResolvedMemorySearchConfig;
48+
protected readonly batch = {
49+
enabled: false,
50+
wait: false,
51+
concurrency: 1,
52+
pollIntervalMs: 0,
53+
timeoutMs: 0,
54+
};
55+
protected readonly vector = { enabled: false, available: false };
56+
protected readonly cache = { enabled: false };
57+
protected db: DatabaseSync;
58+
59+
readonly syncCalls: SyncParams[] = [];
60+
61+
constructor(sourceRows: SourceStateRow[]) {
62+
super();
63+
this.sources.add("sessions");
64+
this.db = {
65+
prepare: () => ({
66+
all: () => sourceRows,
67+
get: () => undefined,
68+
run: () => undefined,
69+
}),
70+
} as unknown as DatabaseSync;
71+
}
72+
73+
async catchUp(): Promise<string[]> {
74+
return await this.runSessionStartupCatchup();
75+
}
76+
77+
async markStartupDirtyFiles(): Promise<string[]> {
78+
return await this.markSessionStartupCatchupDirtyFiles();
79+
}
80+
81+
getDirtySessionFiles(): string[] {
82+
return Array.from(this.sessionsDirtyFiles);
83+
}
84+
85+
isSessionsDirty(): boolean {
86+
return this.sessionsDirty;
87+
}
88+
89+
protected computeProviderKey(): string {
90+
return "test";
91+
}
92+
93+
protected async sync(params?: SyncParams): Promise<void> {
94+
this.syncCalls.push(params ?? {});
95+
}
96+
97+
protected async withTimeout<T>(
98+
promise: Promise<T>,
99+
_timeoutMs: number,
100+
_message: string,
101+
): Promise<T> {
102+
return await promise;
103+
}
104+
105+
protected getIndexConcurrency(): number {
106+
return 1;
107+
}
108+
109+
protected pruneEmbeddingCacheIfNeeded(): void {}
110+
111+
protected async indexFile(
112+
_entry: MemoryIndexEntry,
113+
_options: { source: MemorySource; content?: string },
114+
): Promise<void> {}
115+
}
116+
117+
describe("session startup catch-up", () => {
118+
let stateDir = "";
119+
120+
beforeEach(async () => {
121+
stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-startup-"));
122+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
123+
});
124+
125+
afterEach(async () => {
126+
vi.unstubAllEnvs();
127+
await fs.rm(stateDir, { recursive: true, force: true });
128+
});
129+
130+
async function writeSessionFile(
131+
name: string,
132+
): Promise<{ filePath: string; size: number; mtimeMs: number }> {
133+
const sessionsDir = resolveSessionTranscriptsDirForAgent("main");
134+
await fs.mkdir(sessionsDir, { recursive: true });
135+
const filePath = path.join(sessionsDir, name);
136+
await fs.writeFile(
137+
filePath,
138+
JSON.stringify({ type: "message", message: { role: "user", content: "startup catchup" } }) +
139+
"\n",
140+
"utf-8",
141+
);
142+
const stat = await fs.stat(filePath);
143+
return { filePath, size: stat.size, mtimeMs: stat.mtimeMs };
144+
}
145+
146+
it("marks stale indexed session files dirty and schedules catch-up sync", async () => {
147+
const session = await writeSessionFile("thread.jsonl");
148+
const harness = new SessionStartupCatchupHarness([
149+
{
150+
path: "sessions/main/thread.jsonl",
151+
hash: "old-hash",
152+
mtime: session.mtimeMs - 1000,
153+
size: session.size,
154+
},
155+
]);
156+
157+
await expect(harness.catchUp()).resolves.toEqual([session.filePath]);
158+
expect(harness.getDirtySessionFiles()).toEqual([session.filePath]);
159+
expect(harness.isSessionsDirty()).toBe(true);
160+
expect(harness.syncCalls).toEqual([{ reason: "session-startup-catchup" }]);
161+
});
162+
163+
it("can mark startup catch-up files without scheduling background sync", async () => {
164+
const session = await writeSessionFile("thread.jsonl");
165+
const harness = new SessionStartupCatchupHarness([
166+
{
167+
path: "sessions/main/thread.jsonl",
168+
hash: "old-hash",
169+
mtime: session.mtimeMs - 1000,
170+
size: session.size,
171+
},
172+
]);
173+
174+
await expect(harness.markStartupDirtyFiles()).resolves.toEqual([session.filePath]);
175+
expect(harness.getDirtySessionFiles()).toEqual([session.filePath]);
176+
expect(harness.isSessionsDirty()).toBe(true);
177+
expect(harness.syncCalls).toEqual([]);
178+
});
179+
180+
it("leaves unchanged indexed session files clean", async () => {
181+
const session = await writeSessionFile("thread.jsonl");
182+
const harness = new SessionStartupCatchupHarness([
183+
{
184+
path: "sessions/main/thread.jsonl",
185+
hash: "current-hash",
186+
mtime: session.mtimeMs,
187+
size: session.size,
188+
},
189+
]);
190+
191+
await expect(harness.catchUp()).resolves.toEqual([]);
192+
expect(harness.getDirtySessionFiles()).toEqual([]);
193+
expect(harness.isSessionsDirty()).toBe(false);
194+
expect(harness.syncCalls).toEqual([]);
195+
});
196+
});

0 commit comments

Comments
 (0)