Skip to content

Commit f91854d

Browse files
ZengWen-DTclaude
andcommitted
fix(memory-wiki): retry transient source-page rewrite race
A concurrent atomic rewrite (write-temp + rename) of a memory-wiki source page by the bridge re-export made fs-safe's opened-fd identity check fail with `path-mismatch`, which the page write rethrew as a fatal "Refusing to write" error and aborted the whole wiki_status / source-sync call. The race is transient and benign: the file is replaced under the open handle and the concurrent writer lands equivalent content. Retry briefly on `path-mismatch` (the rename window closes sub-ms) and rethrow unchanged on exhaustion, so persistent failures (directory collision, not-file) and symlink/path-alias swaps still hard-fail exactly as before. The identity guard is untouched; only the benign rename race is retried, matching the sibling read path that already treats path-mismatch as transient. Extracts the guarded-write logic duplicated by source-page-shared.ts and okf.ts into one writeGuardedVaultPage helper so both write paths get the fix and the copy is removed. Closes #92134 Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 0aa6b8c commit f91854d

4 files changed

Lines changed: 193 additions & 78 deletions

File tree

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

Lines changed: 14 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
WIKI_RELATED_START_MARKER,
2121
} from "./markdown.js";
2222
import { resolveMemoryWikiTimestamp } from "./time.js";
23+
import { isRegularFileStat, writeGuardedVaultPage } from "./vault-page-write.js";
2324
import { initializeMemoryWikiVault } from "./vault.js";
2425

2526
const OKF_RESERVED_FILENAMES = new Set(["index.md", "log.md"]);
@@ -32,11 +33,6 @@ const OKF_RELATED_SECTION_PATTERN = new RegExp(
3233
const OKF_VOLATILE_TIMESTAMP_LINE_PATTERN = /^(?:importedAt|updatedAt): .*\n/gm;
3334
const OKF_HASH_CHARS = 8;
3435

35-
type FileStatLike = {
36-
isFile?: unknown;
37-
nlink?: unknown;
38-
};
39-
4036
type OkfConceptDocument = {
4137
conceptId: string;
4238
relativePath: string;
@@ -88,18 +84,6 @@ function trimMarkdownExtension(value: string): string {
8884
return value.replace(/\.md$/i, "");
8985
}
9086

91-
function isRegularFileStat(value: unknown): value is FileStatLike & { nlink: number } {
92-
if (!value || typeof value !== "object") {
93-
return false;
94-
}
95-
const stat = value as FileStatLike;
96-
const isFile =
97-
typeof stat.isFile === "function"
98-
? (stat.isFile as () => boolean).call(stat)
99-
: stat.isFile === true;
100-
return isFile && typeof stat.nlink === "number";
101-
}
102-
10387
type OkfBundleMetadata = {
10488
key: string;
10589
version?: string;
@@ -344,11 +328,12 @@ function safeDecodeOkfLinkPath(value: string | undefined): string {
344328
function getMarkdownDestinationSuffix(destination: string): string {
345329
const queryIndex = destination.indexOf("?");
346330
const fragmentIndex = destination.indexOf("#");
347-
const suffixIndex = queryIndex === -1
348-
? fragmentIndex
349-
: fragmentIndex === -1
350-
? queryIndex
351-
: Math.min(queryIndex, fragmentIndex);
331+
const suffixIndex =
332+
queryIndex === -1
333+
? fragmentIndex
334+
: fragmentIndex === -1
335+
? queryIndex
336+
: Math.min(queryIndex, fragmentIndex);
352337
return suffixIndex === -1 ? "" : destination.slice(suffixIndex);
353338
}
354339

@@ -481,25 +466,13 @@ async function writeOkfConceptPage(params: {
481466
) {
482467
return { changed: false, created: !pageStat };
483468
}
484-
try {
485-
if (isRegularFileStat(pageStat) && pageStat.nlink > 1) {
486-
await vault.remove(params.pagePath);
487-
}
488-
await vault.write(params.pagePath, params.content);
489-
} catch (error) {
490-
if (error instanceof FsSafeError) {
491-
if (error.code !== "symlink" && error.code !== "path-alias") {
492-
throw new Error(
493-
`Refusing to write OKF concept page (${error.code}): ${params.pagePath}: ${error.message}`,
494-
{ cause: error },
495-
);
496-
}
497-
throw new Error(`Refusing to write OKF concept page through symlink: ${params.pagePath}`, {
498-
cause: error,
499-
});
500-
}
501-
throw error;
502-
}
469+
await writeGuardedVaultPage({
470+
vault,
471+
pagePath: params.pagePath,
472+
content: params.content,
473+
pageStat,
474+
pageLabel: "OKF concept page",
475+
});
503476
return { changed: true, created: !pageStat };
504477
}
505478

‎extensions/memory-wiki/src/source-page-shared.ts‎

Lines changed: 8 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,10 @@ import {
77
shouldSkipImportedSourceWrite,
88
type MemoryWikiImportedSourceGroup,
99
} from "./source-sync-state.js";
10+
import { writeGuardedVaultPage } from "./vault-page-write.js";
1011

1112
type ImportedSourceState = Parameters<typeof shouldSkipImportedSourceWrite>[0]["state"];
1213

13-
type FileStatLike = {
14-
isFile?: unknown;
15-
nlink?: unknown;
16-
};
17-
18-
function isRegularFileStat(value: unknown): value is FileStatLike & { nlink: number } {
19-
if (!value || typeof value !== "object") {
20-
return false;
21-
}
22-
const stat = value as FileStatLike;
23-
const isFile =
24-
typeof stat.isFile === "function"
25-
? (stat.isFile as () => boolean).call(stat)
26-
: stat.isFile === true;
27-
return isFile && typeof stat.nlink === "number";
28-
}
29-
3014
export async function writeImportedSourcePage(params: {
3115
vaultRoot: string;
3216
syncKey: string;
@@ -69,26 +53,13 @@ export async function writeImportedSourcePage(params: {
6953
const rendered = params.buildRendered(raw, updatedAt);
7054
const existing = pageStat ? await vault.readText(params.pagePath).catch(() => "") : "";
7155
if (existing !== rendered) {
72-
try {
73-
if (isRegularFileStat(pageStat) && pageStat.nlink > 1) {
74-
await vault.remove(params.pagePath);
75-
}
76-
await vault.write(params.pagePath, rendered);
77-
} catch (error) {
78-
if (error instanceof FsSafeError) {
79-
if (error.code !== "symlink" && error.code !== "path-alias") {
80-
throw new Error(
81-
`Refusing to write imported source page (${error.code}): ${params.pagePath}: ${error.message}`,
82-
{ cause: error },
83-
);
84-
}
85-
throw new Error(
86-
`Refusing to write imported source page through symlink: ${params.pagePath}`,
87-
{ cause: error },
88-
);
89-
}
90-
throw error;
91-
}
56+
await writeGuardedVaultPage({
57+
vault,
58+
pagePath: params.pagePath,
59+
content: rendered,
60+
pageStat,
61+
pageLabel: "imported source page",
62+
});
9263
}
9364

9465
setImportedSourceEntry({
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// Memory Wiki tests cover the shared guarded vault page write helper.
2+
import { FsSafeError } from "openclaw/plugin-sdk/security-runtime";
3+
import { describe, expect, it, vi } from "vitest";
4+
import { writeGuardedVaultPage } from "./vault-page-write.js";
5+
6+
type FakeVault = Parameters<typeof writeGuardedVaultPage>[0]["vault"];
7+
8+
function fakeVault(write: () => Promise<void>): {
9+
vault: FakeVault;
10+
remove: ReturnType<typeof vi.fn>;
11+
} {
12+
const remove = vi.fn(async () => {});
13+
return { vault: { write: vi.fn(write), remove } as unknown as FakeVault, remove };
14+
}
15+
16+
describe("writeGuardedVaultPage", () => {
17+
it("recovers from a transient concurrent-rewrite path-mismatch by retrying", async () => {
18+
let attempts = 0;
19+
const { vault } = fakeVault(async () => {
20+
attempts += 1;
21+
if (attempts < 3) {
22+
// A concurrent atomic rewrite replaces the page mid-operation.
23+
throw new FsSafeError("path-mismatch", "unable to resolve opened file path");
24+
}
25+
});
26+
27+
await expect(
28+
writeGuardedVaultPage({
29+
vault,
30+
pagePath: "sources/page.md",
31+
content: "body",
32+
pageStat: null,
33+
pageLabel: "imported source page",
34+
}),
35+
).resolves.toBeUndefined();
36+
expect(attempts).toBe(3);
37+
});
38+
39+
it("rethrows a labeled error when the path-mismatch persists across attempts", async () => {
40+
const { vault } = fakeVault(async () => {
41+
throw new FsSafeError("path-mismatch", "unable to resolve opened file path");
42+
});
43+
44+
await expect(
45+
writeGuardedVaultPage({
46+
vault,
47+
pagePath: "sources/page.md",
48+
content: "body",
49+
pageStat: null,
50+
pageLabel: "imported source page",
51+
}),
52+
).rejects.toThrow(
53+
/Refusing to write imported source page \(path-mismatch\): sources\/page\.md/u,
54+
);
55+
});
56+
57+
it("does not retry persistent non-race guard failures and keeps fatal wording", async () => {
58+
const { vault } = fakeVault(async () => {
59+
throw new FsSafeError("not-file", "target is not a regular file");
60+
});
61+
62+
await expect(
63+
writeGuardedVaultPage({
64+
vault,
65+
pagePath: "concepts/page.md",
66+
content: "body",
67+
pageStat: null,
68+
pageLabel: "OKF concept page",
69+
}),
70+
).rejects.toThrow(/Refusing to write OKF concept page \(not-file\): concepts\/page\.md/u);
71+
expect((vault as unknown as { write: ReturnType<typeof vi.fn> }).write).toHaveBeenCalledTimes(
72+
1,
73+
);
74+
});
75+
76+
it("maps symlink and path-alias swaps to the symlink wording without retrying", async () => {
77+
const { vault } = fakeVault(async () => {
78+
throw new FsSafeError("symlink", "page resolved through a symlink");
79+
});
80+
81+
await expect(
82+
writeGuardedVaultPage({
83+
vault,
84+
pagePath: "sources/page.md",
85+
content: "body",
86+
pageStat: null,
87+
pageLabel: "imported source page",
88+
}),
89+
).rejects.toThrow(/Refusing to write imported source page through symlink: sources\/page\.md/u);
90+
expect((vault as unknown as { write: ReturnType<typeof vi.fn> }).write).toHaveBeenCalledTimes(
91+
1,
92+
);
93+
});
94+
});
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Memory Wiki plugin module: shared guarded write for vault pages.
2+
import { retryAsync } from "openclaw/plugin-sdk/retry-runtime";
3+
import { FsSafeError, root as fsRoot } from "openclaw/plugin-sdk/security-runtime";
4+
5+
type VaultRoot = Awaited<ReturnType<typeof fsRoot>>;
6+
7+
export type FileStatLike = {
8+
isFile?: unknown;
9+
nlink?: unknown;
10+
};
11+
12+
export function isRegularFileStat(value: unknown): value is FileStatLike & { nlink: number } {
13+
if (!value || typeof value !== "object") {
14+
return false;
15+
}
16+
const stat = value as FileStatLike;
17+
const isFile =
18+
typeof stat.isFile === "function"
19+
? (stat.isFile as () => boolean).call(stat)
20+
: stat.isFile === true;
21+
return isFile && typeof stat.nlink === "number";
22+
}
23+
24+
// A concurrent atomic rewrite (write-temp + rename) of the same vault page by
25+
// the memory bridge re-export makes fs-safe's opened-fd identity check fail with
26+
// `path-mismatch` (see @openclaw/fs-safe opened-realpath): the file we opened is
27+
// replaced under us mid-operation. It is transient (resolves sub-ms) and benign,
28+
// so a short retry closes the window. Symlink/path-alias swaps and persistent
29+
// guard failures (e.g. a directory collision) carry their own code and still
30+
// hard-fail unchanged below.
31+
const isConcurrentRewriteRace = (error: unknown): boolean =>
32+
error instanceof FsSafeError && error.code === "path-mismatch";
33+
34+
/**
35+
* Write `content` to a vault page, breaking an accidental hardlink first, and map
36+
* fs-safe guard failures to a labeled error. A transient concurrent-rewrite race
37+
* is retried briefly; on exhaustion (or any other guard failure) the error
38+
* propagates so the caller's safety contract is unchanged.
39+
*/
40+
export async function writeGuardedVaultPage(params: {
41+
vault: VaultRoot;
42+
pagePath: string;
43+
content: string;
44+
pageStat: unknown;
45+
pageLabel: string;
46+
}): Promise<void> {
47+
try {
48+
await retryAsync(
49+
async () => {
50+
if (isRegularFileStat(params.pageStat) && params.pageStat.nlink > 1) {
51+
await params.vault.remove(params.pagePath);
52+
}
53+
await params.vault.write(params.pagePath, params.content);
54+
},
55+
{
56+
attempts: 3,
57+
minDelayMs: 25,
58+
maxDelayMs: 50,
59+
label: `memory-wiki write ${params.pageLabel} ${params.pagePath}`,
60+
shouldRetry: isConcurrentRewriteRace,
61+
},
62+
);
63+
} catch (error) {
64+
if (error instanceof FsSafeError) {
65+
if (error.code !== "symlink" && error.code !== "path-alias") {
66+
throw new Error(
67+
`Refusing to write ${params.pageLabel} (${error.code}): ${params.pagePath}: ${error.message}`,
68+
{ cause: error },
69+
);
70+
}
71+
throw new Error(`Refusing to write ${params.pageLabel} through symlink: ${params.pagePath}`, {
72+
cause: error,
73+
});
74+
}
75+
throw error;
76+
}
77+
}

0 commit comments

Comments
 (0)