Skip to content

Commit 32e7ea9

Browse files
committed
fix(memory): reuse targeted session corpus snapshot
1 parent 6922ddd commit 32e7ea9

9 files changed

Lines changed: 148 additions & 81 deletions

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

Lines changed: 28 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ type MemorySessionTranscriptUpdate = {
5050
};
5151

5252
export abstract class MemoryManagerSessionSyncOps extends MemoryManagerWatchOps {
53+
protected listSessionCorpusEntries(): Promise<SessionTranscriptCorpusEntry[]> {
54+
return listSessionTranscriptCorpusEntriesForAgent(this.agentId);
55+
}
56+
5357
protected sessionPathForCorpusEntry(entry: SessionTranscriptCorpusEntry): string {
5458
return entry.transcriptSource === "sqlite"
5559
? sessionPathForSessionIdentity(entry.agentId, entry.sessionId)
@@ -114,7 +118,7 @@ export abstract class MemoryManagerSessionSyncOps extends MemoryManagerWatchOps
114118

115119
private async scheduleCorpusSessionFileDirty(sessionFile: string): Promise<void> {
116120
const resolvedSessionFile = path.resolve(sessionFile);
117-
const corpusEntries = await listSessionTranscriptCorpusEntriesForAgent(this.agentId);
121+
const corpusEntries = await this.listSessionCorpusEntries();
118122
if (corpusEntries.some((entry) => path.resolve(entry.sessionFile) === resolvedSessionFile)) {
119123
this.scheduleSessionDirty(resolvedSessionFile);
120124
}
@@ -133,7 +137,7 @@ export abstract class MemoryManagerSessionSyncOps extends MemoryManagerWatchOps
133137
if (!this.sources.has("sessions") || this.closed) {
134138
return [];
135139
}
136-
const corpusEntries = await listSessionTranscriptCorpusEntriesForAgent(this.agentId);
140+
const corpusEntries = await this.listSessionCorpusEntries();
137141
if (corpusEntries.length === 0 || this.closed) {
138142
return [];
139143
}
@@ -487,30 +491,6 @@ export abstract class MemoryManagerSessionSyncOps extends MemoryManagerWatchOps
487491
return normalized.size > 0 ? normalized : null;
488492
}
489493

490-
private normalizeTargetSessions(
491-
sessions?: MemorySessionSyncTarget[],
492-
): Map<string, MemorySessionSyncTarget> | null {
493-
if (!sessions || sessions.length === 0) {
494-
return null;
495-
}
496-
const normalized = new Map<string, MemorySessionSyncTarget>();
497-
for (const session of sessions) {
498-
const sessionId = session.sessionId.trim();
499-
const agentId = session.agentId?.trim() || this.agentId;
500-
if (!sessionId || normalizeAgentId(agentId) !== normalizeAgentId(this.agentId)) {
501-
continue;
502-
}
503-
const sessionKey = session.sessionKey?.trim();
504-
const target = {
505-
agentId,
506-
sessionId,
507-
...(sessionKey ? { sessionKey } : {}),
508-
};
509-
normalized.set(this.memorySessionSyncTargetKey(target), target);
510-
}
511-
return normalized.size > 0 ? normalized : null;
512-
}
513-
514494
private async resolveArchiveFilesForSyncTargets(
515495
sessions?: Iterable<MemorySessionSyncTarget> | null,
516496
knownCorpusEntries?: readonly SessionTranscriptCorpusEntry[],
@@ -520,27 +500,27 @@ export abstract class MemoryManagerSessionSyncOps extends MemoryManagerWatchOps
520500
if (targets.length === 0) {
521501
return files;
522502
}
523-
const corpusEntries =
524-
knownCorpusEntries ?? (await listSessionTranscriptCorpusEntriesForAgent(this.agentId));
525-
for (const session of targets) {
526-
const sessionKey = session.sessionKey?.trim();
527-
let matchedCorpusEntry = false;
528-
for (const entry of corpusEntries) {
529-
if (normalizeAgentId(entry.agentId) !== normalizeAgentId(this.agentId)) {
530-
continue;
531-
}
532-
if (entry.sessionId !== session.sessionId) {
533-
continue;
534-
}
535-
if (sessionKey && entry.sessionKey !== sessionKey) {
536-
continue;
537-
}
503+
const corpusEntries = knownCorpusEntries ?? (await this.listSessionCorpusEntries());
504+
for (const rawSession of targets) {
505+
const sessionId = rawSession.sessionId.trim();
506+
const agentId = rawSession.agentId?.trim() || this.agentId;
507+
if (!sessionId || normalizeAgentId(agentId) !== normalizeAgentId(this.agentId)) {
508+
continue;
509+
}
510+
const sessionKey = rawSession.sessionKey?.trim();
511+
const session = { agentId, sessionId, ...(sessionKey ? { sessionKey } : {}) };
512+
const matchingEntries = corpusEntries.filter(
513+
(entry) =>
514+
normalizeAgentId(entry.agentId) === normalizeAgentId(this.agentId) &&
515+
entry.sessionId === sessionId &&
516+
(!sessionKey || entry.sessionKey === sessionKey),
517+
);
518+
for (const entry of matchingEntries) {
538519
files.add(
539520
entry.transcriptSource === "sqlite" ? entry.sessionFile : path.resolve(entry.sessionFile),
540521
);
541-
matchedCorpusEntry = true;
542522
}
543-
if (matchedCorpusEntry) {
523+
if (matchingEntries.length > 0) {
544524
continue;
545525
}
546526
const resolved = resolveSessionFileForSyncTarget(session, this.agentId);
@@ -558,22 +538,22 @@ export abstract class MemoryManagerSessionSyncOps extends MemoryManagerWatchOps
558538
return files;
559539
}
560540

561-
protected async combineTargetArchiveFiles(params: {
541+
protected async resolveTargetSessionSyncPlan(params: {
562542
sessions?: MemorySessionSyncTarget[];
563543
archiveFiles?: string[];
564-
}): Promise<Set<string> | null> {
544+
}) {
565545
const files = new Set<string>();
566-
const corpusEntries = await listSessionTranscriptCorpusEntriesForAgent(this.agentId);
546+
const corpusEntries = await this.listSessionCorpusEntries();
567547
for (const file of this.normalizeTargetArchiveFiles(params.archiveFiles, corpusEntries) ?? []) {
568548
files.add(file);
569549
}
570550
for (const file of await this.resolveArchiveFilesForSyncTargets(
571-
this.normalizeTargetSessions(params.sessions)?.values(),
551+
params.sessions,
572552
corpusEntries,
573553
)) {
574554
files.add(file);
575555
}
576-
return files.size > 0 ? files : null;
556+
return files.size > 0 ? { corpusEntries, targetArchiveFiles: files } : null;
577557
}
578558

579559
private memorySessionSyncTargetKey(target: MemorySessionSyncTarget): string {

‎extensions/memory-core/src/memory/manager-source-sync-ops.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import path from "node:path";
33
import { createSubsystemLogger } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
44
import {
55
buildSessionEntry,
6-
listSessionTranscriptCorpusEntriesForAgent,
76
parseSqliteSessionFileMarker,
87
parseUsageCountedSessionIdFromFileName,
98
sessionPathForFile,
@@ -168,6 +167,7 @@ export abstract class MemoryManagerSourceSyncOps extends MemoryManagerSessionSyn
168167
protected override async syncArchiveFiles(params: {
169168
needsFullReindex: boolean;
170169
targetArchiveFiles?: string[];
170+
corpusEntries?: readonly SessionTranscriptCorpusEntry[];
171171
progress?: MemorySyncProgressState;
172172
deferIndex?: boolean;
173173
prefixIndexItems?: MemoryIndexWorkItem[];
@@ -183,7 +183,7 @@ export abstract class MemoryManagerSourceSyncOps extends MemoryManagerSessionSyn
183183
? this.db.prepare(`DELETE FROM ${FTS_TABLE} WHERE path = ? AND source = ?`)
184184
: null;
185185

186-
const corpusEntries = await listSessionTranscriptCorpusEntriesForAgent(this.agentId);
186+
const corpusEntries = params.corpusEntries ?? (await this.listSessionCorpusEntries());
187187
const targetArchiveFiles = params.needsFullReindex
188188
? null
189189
: this.normalizeTargetArchiveFiles(params.targetArchiveFiles, corpusEntries);

‎extensions/memory-core/src/memory/manager-sync-ops.startup-catchup.test.ts‎

Lines changed: 85 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@ import {
99
type ResolvedMemorySearchConfig,
1010
} from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
1111
import { statSessionEntrySync } from "openclaw/plugin-sdk/memory-core-host-engine-qmd";
12-
import type {
13-
MemorySource,
14-
MemorySyncParams,
15-
MemorySyncProgressUpdate,
12+
import {
13+
MEMORY_CHUNKING_VERSION,
14+
type MemorySource,
15+
type MemorySyncParams,
16+
type MemorySyncProgressUpdate,
1617
} from "openclaw/plugin-sdk/memory-core-host-engine-storage";
1718
import {
1819
clearConfigCache,
@@ -25,6 +26,11 @@ import {
2526
formatSqliteSessionFileMarker,
2627
} from "openclaw/plugin-sdk/sqlite-runtime-testing";
2728
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
29+
import {
30+
MEMORY_INDEX_PROVENANCE_VERSION,
31+
resolveConfiguredScopeHash,
32+
type MemoryIndexMeta,
33+
} from "./manager-reindex-state.js";
2834
import { MemoryManagerSyncOps } from "./manager-sync-ops.js";
2935

3036
type MemoryIndexEntry = {
@@ -142,6 +148,8 @@ class SessionStartupCatchupHarness extends MemoryManagerSyncOps {
142148
readonly syncCalls: SyncParams[] = [];
143149
readonly indexedPaths: string[] = [];
144150
readonly indexedContents: string[] = [];
151+
corpusListCalls = 0;
152+
private afterNextCorpusList: (() => Promise<void>) | null = null;
145153
private pendingSyncWork: Promise<void> = Promise.resolve();
146154

147155
constructor(
@@ -202,18 +210,8 @@ class SessionStartupCatchupHarness extends MemoryManagerSyncOps {
202210
await this.pendingSyncWork;
203211
}
204212

205-
async combineTargetArchiveFilesForTest(params: {
206-
sessions?: MemorySyncParams["sessions"];
207-
archiveFiles?: string[];
208-
}): Promise<Set<string> | null> {
209-
return await (
210-
this as unknown as {
211-
combineTargetArchiveFiles: (params: {
212-
sessions?: MemorySyncParams["sessions"];
213-
archiveFiles?: string[];
214-
}) => Promise<Set<string> | null>;
215-
}
216-
).combineTargetArchiveFiles(params);
213+
afterNextCorpusListForTest(callback: () => Promise<void>): void {
214+
this.afterNextCorpusList = callback;
217215
}
218216

219217
isSessionsDirty(): boolean {
@@ -253,6 +251,24 @@ class SessionStartupCatchupHarness extends MemoryManagerSyncOps {
253251
return [];
254252
}
255253

254+
protected override readMeta(): MemoryIndexMeta {
255+
return {
256+
model: "fts-only",
257+
provider: "none",
258+
sources: ["sessions"],
259+
scopeHash: resolveConfiguredScopeHash({
260+
workspaceDir: this.workspaceDir,
261+
extraPaths: this.settings.extraPaths,
262+
multimodal: this.settings.multimodal,
263+
}),
264+
chunkTokens: this.settings.chunking.tokens,
265+
chunkOverlap: this.settings.chunking.overlap,
266+
chunkingVersion: MEMORY_CHUNKING_VERSION,
267+
ftsTokenizer: this.settings.store.fts.tokenizer,
268+
provenanceVersion: MEMORY_INDEX_PROVENANCE_VERSION,
269+
};
270+
}
271+
256272
protected async sync(params?: MemorySyncParams): Promise<void> {
257273
this.syncCalls.push(params ?? {});
258274
this.pendingSyncWork = this.indexSessionUpdates
@@ -273,6 +289,15 @@ class SessionStartupCatchupHarness extends MemoryManagerSyncOps {
273289
return 1;
274290
}
275291

292+
protected override async listSessionCorpusEntries() {
293+
const entries = await super.listSessionCorpusEntries();
294+
this.corpusListCalls += 1;
295+
const callback = this.afterNextCorpusList;
296+
this.afterNextCorpusList = null;
297+
await callback?.();
298+
return entries;
299+
}
300+
276301
protected pruneEmbeddingCacheIfNeeded(): void {}
277302

278303
protected resetProviderInitializationForRetry(): void {}
@@ -599,6 +624,14 @@ describe("session startup catch-up", () => {
599624
expect(harness.indexedPaths).toEqual([]);
600625
});
601626

627+
it("skips corpus preflight when an ordinary sync has no session work", async () => {
628+
const harness = new SessionStartupCatchupHarness([]);
629+
630+
await harness.runSyncForTest({ reason: "session-delta" });
631+
632+
expect(harness.corpusListCalls).toBe(0);
633+
});
634+
602635
it("resolves identity-targeted delta sync through a custom session store", async () => {
603636
const storePath = path.join(stateDir, "custom-sessions", "sessions.json");
604637
const session = await writeSqliteSession({
@@ -626,6 +659,42 @@ describe("session startup catch-up", () => {
626659
expect(harness.syncCalls).toEqual([{ reason: "session-delta" }]);
627660
});
628661

662+
it("keeps targeted indexing on the SQLite store resolved by its corpus snapshot", async () => {
663+
const session = await writeSqliteSession({
664+
storePath: path.join(stateDir, "custom-sessions", "sessions.json"),
665+
sessionId: "snapshot-thread",
666+
sessionKey: "agent:main:chat:snapshot",
667+
content: "original snapshot target",
668+
});
669+
const replacement = await writeSqliteSession({
670+
storePath: path.join(stateDir, "replacement-sessions", "sessions.json"),
671+
sessionId: session.sessionId,
672+
sessionKey: session.sessionKey,
673+
content: "replacement store target",
674+
});
675+
await configureTestSessionStore(session.storePath);
676+
const harness = new SessionStartupCatchupHarness([]);
677+
harness.afterNextCorpusListForTest(async () => {
678+
await configureTestSessionStore(replacement.storePath);
679+
});
680+
681+
await harness.runSyncForTest({
682+
reason: "queued-sessions",
683+
sessions: [
684+
{
685+
agentId: "main",
686+
sessionId: session.sessionId,
687+
sessionKey: session.sessionKey,
688+
},
689+
],
690+
});
691+
692+
expect(harness.corpusListCalls).toBe(1);
693+
expect(harness.indexedPaths).toEqual([session.corpusPath]);
694+
expect(harness.indexedContents[0]).toContain("original snapshot target");
695+
expect(harness.indexedContents[0]).not.toContain("replacement store target");
696+
});
697+
629698
it("preserves generated-session classification during targeted custom-store indexing", async () => {
630699
const storePath = path.join(stateDir, "custom-sessions", "sessions.json");
631700
const session = await writeSqliteSession({

‎extensions/memory-core/src/memory/manager-sync-ops.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,15 @@ export abstract class MemoryManagerSyncOps extends MemoryManagerSourceSyncOps {
174174
// the vector extension before text and FTS indexing can proceed.
175175
const vectorReady = syncProvider ? await this.ensureVectorReady() : false;
176176
const meta = this.readMeta();
177-
const targetArchiveFiles = await this.combineTargetArchiveFiles({
178-
sessions: params?.sessions,
179-
archiveFiles: params?.archiveFiles,
180-
});
177+
// Resolve and index a targeted session against one corpus snapshot. A reset
178+
// between separate enumerations could otherwise replace the chosen identity.
179+
const targetSessionSync = this.hasRequestedTargetSessionSync(params)
180+
? await this.resolveTargetSessionSyncPlan({
181+
sessions: params?.sessions,
182+
archiveFiles: params?.archiveFiles,
183+
})
184+
: null;
185+
const targetArchiveFiles = targetSessionSync?.targetArchiveFiles ?? null;
181186
const hasTargetArchiveFiles = targetArchiveFiles !== null;
182187
if (this.hasRequestedTargetSessionSync(params) && !hasTargetArchiveFiles) {
183188
return;
@@ -272,7 +277,10 @@ export abstract class MemoryManagerSyncOps extends MemoryManagerSourceSyncOps {
272277
sessionsFullRetryDirty: this.sessionsFullRetryDirty,
273278
sessionsDirtyFiles: this.sessionsDirtyFiles,
274279
syncArchiveFiles: async (targetedParams) => {
275-
await this.syncArchiveFiles(targetedParams);
280+
await this.syncArchiveFiles({
281+
...targetedParams,
282+
corpusEntries: targetSessionSync?.corpusEntries,
283+
});
276284
},
277285
shouldFallbackOnError: (err) => this.shouldFallbackOnError(err),
278286
activateFallbackProvider: async (reason) => {

‎extensions/memory-core/src/memory/manager.self-heal-missing-identity.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { resolveOpenClawAgentSqlitePath } from "openclaw/plugin-sdk/sqlite-runti
77
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
88
import { closeAllMemorySearchManagers, getMemorySearchManager } from "./index.js";
99
import type { MemoryIndexManager } from "./manager.js";
10+
import { isolateMemoryManagerTestConfig } from "./test-manager-helpers.js";
1011
import "./test-runtime-mocks.js";
1112

1213
const createEmbeddingProviderMock = vi.hoisted(() =>
@@ -93,7 +94,7 @@ describe("memory manager self-heal missing identity with FTS-only chunks", () =>
9394
params.vectorEnabled === undefined
9495
? undefined
9596
: { vector: { enabled: params.vectorEnabled } };
96-
const cfg = {
97+
const cfg = isolateMemoryManagerTestConfig({
9798
memory: {
9899
backend: "builtin",
99100
search: {
@@ -110,7 +111,7 @@ describe("memory manager self-heal missing identity with FTS-only chunks", () =>
110111
},
111112
list: [{ id: "main", default: true }],
112113
},
113-
} as OpenClawConfig;
114+
} as OpenClawConfig);
114115
const result = await getMemorySearchManager({
115116
cfg,
116117
agentId: "main",

‎extensions/memory-core/src/memory/manager.watcher-config.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ import {
175175
getMemorySearchManager,
176176
type MemoryIndexManager,
177177
} from "./index.js";
178+
import { isolateMemoryManagerTestConfig } from "./test-manager-helpers.js";
178179

179180
describe("memory watcher config", () => {
180181
let manager: MemoryIndexManager | null = null;
@@ -230,7 +231,7 @@ describe("memory watcher config", () => {
230231
const defaults: NonNullable<NonNullable<OpenClawConfig["agents"]>["defaults"]> = {
231232
workspace: workspaceDir,
232233
};
233-
return {
234+
return isolateMemoryManagerTestConfig({
234235
memory: {
235236
backend: "builtin",
236237
search: {
@@ -247,7 +248,7 @@ describe("memory watcher config", () => {
247248
defaults,
248249
list: [{ id: "main", default: true }],
249250
},
250-
} as OpenClawConfig;
251+
} as OpenClawConfig);
251252
}
252253

253254
async function expectWatcherManager(cfg: OpenClawConfig) {

0 commit comments

Comments
 (0)