Skip to content

Commit d394da8

Browse files
authored
fix(memory): keep replies responsive during legacy index repair (#135062)
* fix(memory): avoid reply stalls during startup reindex Let the memory manager own legacy provenance repair without awaiting it from automatic project or trigger recall. Keep unclassified candidates excluded until repair completes and preserve retry and teardown ownership. Regression coverage exercises a large legacy index with and without active startup catch-up. Release-note context: restore prompt foreground replies during startup memory repair after upgrades. Thanks @LifeViwer for reporting #134461. * fix(memory): drain detached candidate repair before shutdown Retain the full background repair in existing manager operation admission so optional embedding bootstrap retries finish before close releases storage. Foreground candidate reads remain nonblocking during legacy reindex. Related: #134461; reported by @LifeViwer. * test(memory): avoid returning timer handle from repair gate
1 parent c8393dd commit d394da8

4 files changed

Lines changed: 223 additions & 15 deletions

File tree

‎docs/concepts/memory-builtin.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,10 @@ Full reindexes build a replacement in a temporary database and publish the
119119
memory tables atomically. Concurrent searches and status reads keep using the
120120
published index; a failed rebuild leaves that index intact.
121121

122+
After an upgrade, automatic project and trigger recall may need to repair
123+
legacy provenance. That repair runs in the background. Replies continue while
124+
automatic recall stays empty until the affected sources have been reclassified.
125+
122126
<Info>
123127
You can also index Markdown files outside the workspace with
124128
`memory.search.extraPaths`. See the

‎extensions/memory-core/src/memory/index.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ describe("memory index", () => {
354354
}
355355
});
356356

357-
it("reindexes legacy curated provenance before the first automatic candidate read", async () => {
357+
it("withholds legacy curated candidates until background provenance repair succeeds", async () => {
358358
const projectKey = "github.com/openclaw/openclaw";
359359
await fs.writeFile(
360360
path.join(fixture.paths.workspace, "MEMORY.md"),
@@ -414,6 +414,13 @@ describe("memory index", () => {
414414
upgradedManager as unknown as { runSync: (params?: MemorySyncParams) => Promise<void> },
415415
"runSync",
416416
);
417+
await expect(
418+
Promise.all([
419+
upgradedManager.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }),
420+
upgradedManager.listTriggerCandidates({ activeProjectKeys: [projectKey] }),
421+
]),
422+
).resolves.toEqual([[], []]);
423+
await upgradedManager.sync({ reason: "test-repair-complete" });
417424
const [projectCandidates, triggerCandidates] = await Promise.all([
418425
upgradedManager.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }),
419426
upgradedManager.listTriggerCandidates({ activeProjectKeys: [projectKey] }),
Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import type { DatabaseSync } from "node:sqlite";
4+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
5+
import type { MemorySyncParams } from "openclaw/plugin-sdk/memory-core-host-engine-storage";
6+
import { describe, expect, it, vi } from "vitest";
7+
import { createManagerIndexFixture } from "./manager-index.test-support.js";
8+
import type { MemoryIndexMeta } from "./manager-reindex-state.js";
9+
10+
const { closeAllMemorySearchManagers, getMemorySearchManager } = await import("./index.js");
11+
12+
describe("automatic candidates during provenance repair", () => {
13+
const fixture = createManagerIndexFixture({
14+
getMemorySearchManager,
15+
closeAllMemorySearchManagers,
16+
});
17+
18+
it.each([false, true])(
19+
"returns promptly while a large rebuild is pending (startup catch-up: %s)",
20+
async (startupCatchup) => {
21+
const projectKey = "github.com/example/project";
22+
await fs.writeFile(
23+
path.join(fixture.paths.workspace, "MEMORY.md"),
24+
`- Keep the release local. <!-- trigger: release local --> <!-- project: ${projectKey} -->\n`,
25+
);
26+
await Promise.all(
27+
Array.from({ length: 256 }, (_, index) =>
28+
fs.writeFile(
29+
path.join(fixture.paths.memory, `entry-${index}.md`),
30+
`# Entry ${index}\nSynthetic memory content ${index}.\n`,
31+
),
32+
),
33+
);
34+
const cfg = fixture.createConfig({
35+
provider: "batch-wide-test",
36+
batchEnabled: true,
37+
vectorEnabled: false,
38+
sources: startupCatchup ? ["memory", "sessions"] : ["memory"],
39+
sessionMemory: startupCatchup,
40+
});
41+
if (startupCatchup) {
42+
await fixture.seedSessionTranscript({
43+
sessionId: "legacy-session",
44+
messages: [{ role: "user", timestamp: 1, content: "Remember the release preference." }],
45+
});
46+
}
47+
const initial = await fixture.getFreshManager(cfg, "cli");
48+
await initial.sync({ reason: "cli", force: true });
49+
const db = Reflect.get(initial, "db") as DatabaseSync;
50+
// Older indexes have neither classified provenance nor a chunking version.
51+
db.exec("DELETE FROM memory_index_chunk_provenance; DELETE FROM memory_embedding_cache");
52+
const row = db
53+
.prepare("SELECT value FROM memory_index_meta WHERE key = 'memory_index_meta_v1'")
54+
.get() as { value: string };
55+
const meta = JSON.parse(row.value) as MemoryIndexMeta;
56+
delete meta.provenanceVersion;
57+
delete meta.chunkingVersion;
58+
db.prepare("UPDATE memory_index_meta SET value = ? WHERE key = 'memory_index_meta_v1'").run(
59+
JSON.stringify(meta),
60+
);
61+
await initial.close();
62+
63+
const gate = createDeferred<void>();
64+
fixture.provider.providerRuntimeBatchGate = gate.promise;
65+
const upgraded = await fixture.getFreshManager(cfg);
66+
const candidates: Promise<unknown>[] = [];
67+
try {
68+
expect(upgraded.status().custom?.indexIdentity).toMatchObject({
69+
status: "mismatched",
70+
reason: "index provenance classifier changed",
71+
});
72+
if (startupCatchup) {
73+
await vi.waitFor(() => expect(fixture.provider.providerRuntimeActiveBatchCalls).toBe(1), {
74+
timeout: 10_000,
75+
});
76+
}
77+
let completed = 0;
78+
for (const lookup of [
79+
() => upgraded.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }),
80+
() => upgraded.listTriggerCandidates({ activeProjectKeys: [projectKey] }),
81+
]) {
82+
candidates.push(
83+
lookup().then((results) => {
84+
completed += 1;
85+
return results;
86+
}),
87+
);
88+
}
89+
await vi.waitFor(() => expect(completed).toBe(2));
90+
expect(await Promise.all(candidates)).toEqual([[], []]);
91+
await vi.waitFor(() => expect(fixture.provider.providerRuntimeActiveBatchCalls).toBe(1), {
92+
timeout: 10_000,
93+
});
94+
expect(upgraded.status().dirty).toBe(true);
95+
} finally {
96+
gate.resolve();
97+
await Promise.allSettled(candidates);
98+
}
99+
await upgraded.sync({ reason: "test-repair-complete" });
100+
expect(upgraded.status().dirty).toBe(false);
101+
const expected = [
102+
expect.objectContaining({
103+
projectKey,
104+
triggers: "release local",
105+
provenance: expect.objectContaining({ originClass: "agent" }),
106+
}),
107+
];
108+
expect(
109+
await upgraded.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }),
110+
).toEqual(expected);
111+
expect(await upgraded.listTriggerCandidates({ activeProjectKeys: [projectKey] })).toEqual(
112+
expected,
113+
);
114+
},
115+
);
116+
117+
it("drains admitted candidate repair retries before closing the database", async () => {
118+
const projectKey = "github.com/example/project";
119+
await fs.writeFile(
120+
path.join(fixture.paths.workspace, "MEMORY.md"),
121+
`- Preserve the release preference. <!-- trigger: release local --> <!-- project: ${projectKey} -->\n`,
122+
);
123+
const ftsConfig = fixture.createConfig({ provider: "none", vectorEnabled: false });
124+
const initial = await fixture.getFreshManager(ftsConfig, "cli");
125+
await initial.sync({ reason: "cli", force: true });
126+
// The existing migration will invalidate these sources on the next open.
127+
const initialDb = Reflect.get(initial, "db") as DatabaseSync;
128+
initialDb.exec("DELETE FROM memory_index_chunk_provenance");
129+
await initial.close();
130+
131+
const initialization = createDeferred<void>();
132+
const retryStarted = createDeferred<void>();
133+
const retry = createDeferred<void>();
134+
fixture.provider.providerInitGate = initialization.promise;
135+
fixture.provider.providerCreationFailure = "local";
136+
const upgraded = await fixture.getFreshManager(
137+
fixture.createConfig({ provider: "local", vectorEnabled: false }),
138+
"cli",
139+
);
140+
const owner = upgraded as unknown as {
141+
runSync: (params?: MemorySyncParams) => Promise<void>;
142+
};
143+
const runSync = owner.runSync.bind(upgraded);
144+
let pendingRetry: Promise<void> | undefined;
145+
const retryGate = vi.spyOn(owner, "runSync").mockImplementation((params) => {
146+
retryStarted.resolve();
147+
pendingRetry = retry.promise.then(() => runSync(params));
148+
return pendingRetry;
149+
});
150+
// This is the same public sync admission used by detached startup catch-up.
151+
// Attach rejection handling immediately; its failed initialization is expected.
152+
const startup = upgraded.sync({ reason: "session-startup-catchup" });
153+
const startupOutcome = startup.then(
154+
() => undefined,
155+
(error: unknown) => error,
156+
);
157+
let closing: Promise<void> | undefined;
158+
let closeSettled = false;
159+
try {
160+
await vi.waitFor(() => expect(fixture.provider.providerCalls.at(-1)?.provider).toBe("local"));
161+
await expect(
162+
upgraded.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }),
163+
).resolves.toEqual([]);
164+
closing = upgraded.close().then(() => {
165+
closeSettled = true;
166+
});
167+
// Let close enter its drain before the already-running sync fails. This
168+
// reproduces the original execution order without a timing-based sleep.
169+
await Promise.resolve();
170+
initialization.resolve();
171+
await retryStarted.promise;
172+
// Give teardown a turn to finish while the admitted retry remains gated.
173+
await new Promise<void>((resolve) => {
174+
setImmediate(resolve);
175+
});
176+
expect(closeSettled).toBe(false);
177+
retry.resolve();
178+
await closing;
179+
expect(await startupOutcome).toBeInstanceOf(Error);
180+
181+
// Observable persistence proof: close did not merely cancel or abandon
182+
// the retry; its classified candidates survive a fresh manager open.
183+
const reopened = await fixture.getFreshManager(ftsConfig, "cli");
184+
expect(
185+
await reopened.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }),
186+
).toEqual([
187+
expect.objectContaining({
188+
projectKey,
189+
triggers: "release local",
190+
provenance: expect.objectContaining({ originClass: "agent" }),
191+
}),
192+
]);
193+
} finally {
194+
initialization.resolve();
195+
retry.resolve();
196+
await startupOutcome;
197+
await pendingRetry?.catch(() => undefined);
198+
await closing;
199+
await upgraded.close();
200+
retryGate.mockRestore();
201+
}
202+
});
203+
});

‎extensions/memory-core/src/memory/manager-keyword-retrieval.ts‎

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -115,27 +115,21 @@ export abstract class MemoryKeywordRetrieval extends MemoryProviderLifecycle {
115115
): Promise<MemorySearchResult[]> {
116116
return await this.withManagerOperation(async () => {
117117
if (this.memorySourceProvenanceRepairPending) {
118-
const repairPending = () =>
118+
this.memorySourceProvenanceRepairPending =
119119
this.db
120120
.prepare(
121121
`SELECT 1 FROM memory_index_sources
122122
WHERE source = 'memory' AND hash = '' LIMIT 1`,
123123
)
124124
.get() !== undefined;
125-
try {
126-
// Provenance schema adoption invalidates legacy source hashes. Finish that
127-
// owner-classified reindex before the first automatic candidate read.
128-
if (repairPending()) {
129-
await this.syncAdmitted(
130-
{ reason: "search" },
131-
{ allowEmbeddingBootstrapFallback: true },
132-
);
133-
}
134-
} catch (err) {
135-
log.warn(`memory sync failed (automatic candidates): ${formatErrorMessage(err)}`);
136-
}
137-
this.memorySourceProvenanceRepairPending = repairPending();
138125
if (this.memorySourceProvenanceRepairPending) {
126+
// Automatic recall runs before the model. Keep repair admitted for teardown
127+
// without holding the reply; unclassified sources stay excluded.
128+
void this.withManagerOperation(() =>
129+
this.syncAdmitted({ reason: "search" }, { allowEmbeddingBootstrapFallback: true }),
130+
).catch((err: unknown) => {
131+
log.warn(`memory sync failed (automatic candidates): ${formatErrorMessage(err)}`);
132+
});
139133
return [];
140134
}
141135
}

0 commit comments

Comments
 (0)