Skip to content

Commit f66649f

Browse files
committed
fix(memory-wiki): serialize concurrent apply transactions
1 parent 87a652b commit f66649f

6 files changed

Lines changed: 212 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Docs: https://docs.openclaw.ai
2525

2626
### Fixes
2727

28+
- **Memory Wiki concurrent agent writes:** serialize each vault's `wiki_apply` mutation and compile transaction while allowing separate agent vaults to proceed in parallel, preventing partial-success tool errors and lost metadata during simultaneous agent turns. (#103400)
2829
- **OpenAI-compatible streamed tool calls:** execute complete native tool calls from streams that end with SSE `data: [DONE]` but omit `finish_reason`, while keeping transport EOF and visible-text cases fail-closed. (#98124, #97994) Thanks @SunnyShu0925.
2930
- **Doctor state isolation:** prevent automated update and Gateway watch repair from importing and archiving default-home exec or plugin-binding approvals when `OPENCLAW_STATE_DIR` points elsewhere, keep implicit CLI preflight notice-only, and reserve cross-state imports for direct operator doctor runs. (#103247, #103317)
3031
- **Doctor clean-state guidance:** stop suggesting `openclaw doctor --fix` after a clean run with no config changes while preserving targeted repair hints. (#103233)

‎extensions/memory-wiki/src/apply.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,4 +314,67 @@ keep this note
314314
fs.readFile(path.join(rootDir, "entities", "index.md"), "utf8"),
315315
).resolves.toContain("[Alpha](alpha.md)");
316316
});
317+
318+
it("preserves disjoint metadata updates from concurrent agent turns", async () => {
319+
const { rootDir, config } = await createVault({
320+
prefix: "memory-wiki-apply-concurrent-",
321+
});
322+
const targetPath = path.join(rootDir, "entities", "shared.md");
323+
await fs.mkdir(path.dirname(targetPath), { recursive: true });
324+
await fs.writeFile(
325+
targetPath,
326+
renderWikiMarkdown({
327+
frontmatter: {
328+
pageType: "entity",
329+
id: "entity.shared",
330+
title: "Shared",
331+
},
332+
body: "# Shared\n",
333+
}),
334+
"utf8",
335+
);
336+
337+
await Promise.all([
338+
applyMemoryWikiMutation({
339+
config,
340+
mutation: {
341+
op: "update_metadata",
342+
lookup: "entity.shared",
343+
sourceIds: ["source.concurrent"],
344+
},
345+
}),
346+
applyMemoryWikiMutation({
347+
config,
348+
mutation: {
349+
op: "update_metadata",
350+
lookup: "entity.shared",
351+
questions: ["Which agent owns the next action?"],
352+
},
353+
}),
354+
applyMemoryWikiMutation({
355+
config,
356+
mutation: {
357+
op: "update_metadata",
358+
lookup: "entity.shared",
359+
confidence: 0.9,
360+
},
361+
}),
362+
applyMemoryWikiMutation({
363+
config,
364+
mutation: {
365+
op: "update_metadata",
366+
lookup: "entity.shared",
367+
status: "review",
368+
},
369+
}),
370+
]);
371+
372+
const parsed = parseWikiMarkdown(await fs.readFile(targetPath, "utf8"));
373+
expect(parsed.frontmatter).toMatchObject({
374+
sourceIds: ["source.concurrent"],
375+
questions: ["Which agent owns the next action?"],
376+
confidence: 0.9,
377+
status: "review",
378+
});
379+
});
317380
});

‎extensions/memory-wiki/src/apply.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
normalizeWikiClaims,
1919
type WikiClaim,
2020
} from "./markdown.js";
21+
import { withMemoryWikiVaultMutation } from "./mutation-coordinator.js";
2122
import {
2223
readQueryableWikiPages,
2324
resolveQueryableWikiPageByLookup,
@@ -359,7 +360,7 @@ async function applyUpdateMetadataMutation(params: {
359360
};
360361
}
361362

362-
export async function applyMemoryWikiMutation(params: {
363+
async function applyMemoryWikiMutationUnlocked(params: {
363364
config: ResolvedMemoryWikiConfig;
364365
mutation: ApplyMemoryWikiMutation;
365366
}): Promise<ApplyMemoryWikiMutationResult> {
@@ -383,3 +384,12 @@ export async function applyMemoryWikiMutation(params: {
383384
compile,
384385
};
385386
}
387+
388+
export async function applyMemoryWikiMutation(params: {
389+
config: ResolvedMemoryWikiConfig;
390+
mutation: ApplyMemoryWikiMutation;
391+
}): Promise<ApplyMemoryWikiMutationResult> {
392+
return await withMemoryWikiVaultMutation(params.config.vault.path, () =>
393+
applyMemoryWikiMutationUnlocked(params),
394+
);
395+
}

‎extensions/memory-wiki/src/compile.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
WIKI_RELATED_END_MARKER,
4545
WIKI_RELATED_START_MARKER,
4646
} from "./markdown.js";
47+
import { withMemoryWikiVaultMutation } from "./mutation-coordinator.js";
4748
import { readMemoryWikiSourceSyncState } from "./source-sync-state.js";
4849
import { initializeMemoryWikiVault } from "./vault.js";
4950

@@ -1384,7 +1385,7 @@ async function writeAgentDigestArtifacts(params: {
13841385
return updatedFiles;
13851386
}
13861387

1387-
export async function compileMemoryWikiVault(
1388+
async function compileMemoryWikiVaultUnlocked(
13881389
config: ResolvedMemoryWikiConfig,
13891390
): Promise<CompileMemoryWikiResult> {
13901391
await initializeMemoryWikiVault(config);
@@ -1471,6 +1472,14 @@ export async function compileMemoryWikiVault(
14711472
};
14721473
}
14731474

1475+
export async function compileMemoryWikiVault(
1476+
config: ResolvedMemoryWikiConfig,
1477+
): Promise<CompileMemoryWikiResult> {
1478+
return await withMemoryWikiVaultMutation(config.vault.path, () =>
1479+
compileMemoryWikiVaultUnlocked(config),
1480+
);
1481+
}
1482+
14741483
async function hasMissingWikiIndexes(rootDir: string): Promise<boolean> {
14751484
const required = [
14761485
path.join(rootDir, "index.md"),
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { describe, expect, it } from "vitest";
2+
import { withMemoryWikiVaultMutation } from "./mutation-coordinator.js";
3+
4+
function deferred() {
5+
let resolve!: () => void;
6+
const promise = new Promise<void>((done) => {
7+
resolve = done;
8+
});
9+
return { promise, resolve };
10+
}
11+
12+
describe("withMemoryWikiVaultMutation", () => {
13+
it("serializes mutations for one vault and permits nested work", async () => {
14+
const firstEntered = deferred();
15+
const releaseFirst = deferred();
16+
const order: string[] = [];
17+
18+
const first = withMemoryWikiVaultMutation("/tmp/wiki-a", async () => {
19+
order.push("first:start");
20+
firstEntered.resolve();
21+
await withMemoryWikiVaultMutation("/tmp/wiki-a", async () => {
22+
order.push("first:nested");
23+
});
24+
await releaseFirst.promise;
25+
order.push("first:end");
26+
});
27+
await firstEntered.promise;
28+
29+
const second = withMemoryWikiVaultMutation("/tmp/wiki-a", async () => {
30+
order.push("second");
31+
});
32+
await Promise.resolve();
33+
await Promise.resolve();
34+
expect(order).toEqual(["first:start", "first:nested"]);
35+
36+
releaseFirst.resolve();
37+
await Promise.all([first, second]);
38+
expect(order).toEqual(["first:start", "first:nested", "first:end", "second"]);
39+
});
40+
41+
it("allows distinct agent vaults to mutate in parallel", async () => {
42+
const firstEntered = deferred();
43+
const secondEntered = deferred();
44+
const releaseFirst = deferred();
45+
46+
const first = withMemoryWikiVaultMutation("/tmp/wiki/support", async () => {
47+
firstEntered.resolve();
48+
await releaseFirst.promise;
49+
});
50+
await firstEntered.promise;
51+
const second = withMemoryWikiVaultMutation("/tmp/wiki/marketing", async () => {
52+
secondEntered.resolve();
53+
});
54+
55+
await secondEntered.promise;
56+
releaseFirst.resolve();
57+
await Promise.all([first, second]);
58+
});
59+
60+
it("queues detached work after its inherited transaction has ended", async () => {
61+
const releaseDetached = deferred();
62+
const holderEntered = deferred();
63+
const releaseHolder = deferred();
64+
let detachedEntered = false;
65+
let detached!: Promise<void>;
66+
67+
await withMemoryWikiVaultMutation("/tmp/wiki-detached", async () => {
68+
detached = (async () => {
69+
await releaseDetached.promise;
70+
await withMemoryWikiVaultMutation("/tmp/wiki-detached", async () => {
71+
detachedEntered = true;
72+
});
73+
})();
74+
});
75+
76+
const holder = withMemoryWikiVaultMutation("/tmp/wiki-detached", async () => {
77+
holderEntered.resolve();
78+
await releaseHolder.promise;
79+
});
80+
await holderEntered.promise;
81+
releaseDetached.resolve();
82+
await Promise.resolve();
83+
await Promise.resolve();
84+
expect(detachedEntered).toBe(false);
85+
86+
releaseHolder.resolve();
87+
await Promise.all([holder, detached]);
88+
expect(detachedEntered).toBe(true);
89+
});
90+
});
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Memory Wiki plugin module serializes vault mutation transactions.
2+
import { AsyncLocalStorage } from "node:async_hooks";
3+
import path from "node:path";
4+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
5+
6+
type ActiveVaultMutation = { active: boolean };
7+
8+
const activeVaultMutations = new AsyncLocalStorage<ReadonlyMap<string, ActiveVaultMutation>>();
9+
const vaultMutationQueue = new KeyedAsyncQueue();
10+
11+
/**
12+
* Keep coordinated vault read-modify-write transactions isolated from concurrent work in this process.
13+
* Nested compile calls re-enter; different agent vaults remain parallel.
14+
*/
15+
export async function withMemoryWikiVaultMutation<T>(
16+
vaultPath: string,
17+
mutation: () => Promise<T>,
18+
): Promise<T> {
19+
const key = path.resolve(vaultPath);
20+
const active = activeVaultMutations.getStore();
21+
if (active?.get(key)?.active) {
22+
return await mutation();
23+
}
24+
25+
const lease = { active: true };
26+
const nextActive = new Map(active ?? []);
27+
nextActive.set(key, lease);
28+
return await vaultMutationQueue.enqueue(key, async () => {
29+
try {
30+
return await activeVaultMutations.run(nextActive, mutation);
31+
} finally {
32+
// Detached children inherit this object. Mark it inactive when the
33+
// owner exits so later work queues instead of bypassing serialization.
34+
lease.active = false;
35+
}
36+
});
37+
}

0 commit comments

Comments
 (0)