Skip to content

Commit b9a69dc

Browse files
authored
Merge pull request #5563 from modelcontextprotocol/v2/fix/5560-memory-stale-lock-race
fix(memory): never delete a successor's live lock when breaking a stale one
2 parents b4e4a6a + d57917b commit b9a69dc

4 files changed

Lines changed: 154 additions & 13 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-memory": patch
3+
---
4+
5+
Stop a server breaking a stale memory file lock from deleting a live lock that replaced it in the meantime, which let two writers change the memory file at once and lose a write. The stale lock is now moved aside, checked to be the file that was judged stale, and only then deleted.

‎src/memory/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ Saves are atomic. Every write tool writes the whole graph to a temporary file in
301301
Each MCP client starts its own server process, so two clients using the same `MEMORY_FILE_PATH` (or both using the default) are two processes writing one file. Every write tool takes an exclusive lock file, `<memory file>.lock`, next to the memory file while it reads, changes and saves the graph, so writes from different processes take turns and none is lost. The lock file exists only while a write is in progress, so the directory holding the memory file must be writable (it already must be, for the atomic save).
302302

303303
- A server stopped mid-write by `SIGINT` or `SIGTERM` (Ctrl-C, `docker stop`, a client shutting it down), or exiting normally, removes the lock it holds before it exits, so the next writer does not wait on it.
304-
- A lock left behind by a server that crashed mid-write is removed automatically: at once if its process is known to have exited on the same machine, otherwise once it has gone 30 seconds without being refreshed (a server holding the lock refreshes it every 15 seconds while it works). Only one waiting server breaks a stale lock at a time, guarded by a momentary `<memory file>.lock.break` file.
304+
- A lock left behind by a server that crashed mid-write is removed automatically: at once if its process is known to have exited on the same machine, otherwise once it has gone 30 seconds without being refreshed (a server holding the lock refreshes it every 15 seconds while it works). Only one waiting server breaks a stale lock at a time, guarded by a momentary `<memory file>.lock.break` file. It never deletes the lock where it stands: it renames it aside to a momentary `<memory file>.lock.<random>.stale` file, checks that what it took is the very file it judged stale, and only then deletes it. A live lock that replaced the stale one in between is put straight back, untouched, and the breaker goes on waiting.
305305
- A write that cannot get the lock within 60 seconds fails with a tool error rather than overwriting the file.
306306
- The lock relies on exclusive file creation, which local filesystems provide; a network filesystem that does not honour it cannot be shared safely this way.
307307

‎src/memory/__tests__/file-lock.test.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,85 @@ describe("withFileLock", () => {
184184
expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]);
185185
});
186186

187+
// Run hook once, just before the breaker moves the lock it judged stale
188+
// aside: after its staleness re-check, before the removal (#5560).
189+
function onceBeforeRemoval(hook: () => Promise<void>): void {
190+
const realRename = fs.rename;
191+
let fired = false;
192+
vi.spyOn(fs, "rename").mockImplementation(async (from, to) => {
193+
if (!fired && from === lockPath) {
194+
fired = true;
195+
await hook();
196+
}
197+
return realRename(from, to);
198+
});
199+
}
200+
201+
it("keeps a successor's lock placed between the staleness re-check and the removal (#5560)", async () => {
202+
await writeStaleLock();
203+
vi.spyOn(console, "error").mockImplementation(() => {});
204+
let successor: { ino: bigint; mtimeMs: bigint } | undefined;
205+
// The stale lock's holder comes back and releases it, and a successor
206+
// takes a live lock at the same path, after the breaker's re-check under
207+
// its guard and before the breaker removes what it judged.
208+
onceBeforeRemoval(async () => {
209+
await fs.unlink(lockPath);
210+
await fs.writeFile(lockPath, "successor");
211+
successor = await fs.stat(lockPath, { bigint: true });
212+
});
213+
const operation = vi.fn(async () => "ran");
214+
215+
await expect(withFileLock(lockPath, operation, fast)).rejects.toThrow(
216+
"Timed out",
217+
);
218+
219+
// The breaker did not acquire the lock, and broke nothing.
220+
expect(operation).not.toHaveBeenCalled();
221+
expect(console.error).not.toHaveBeenCalled();
222+
// The successor's lock is the same file, untouched: not a copy, and not
223+
// refreshed or aged by its trip aside.
224+
expect(successor).toBeDefined();
225+
expect(await fs.readFile(lockPath, "utf-8")).toBe("successor");
226+
const kept = await fs.stat(lockPath, { bigint: true });
227+
expect(kept.ino).toBe(successor?.ino);
228+
expect(kept.mtimeMs).toBe(successor?.mtimeMs);
229+
// Neither the breaking guard nor the aside file is left behind.
230+
expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]);
231+
});
232+
233+
it("acquires the lock at once when its holder releases it between the re-check and the removal", async () => {
234+
await writeStaleLock();
235+
const error = vi.spyOn(console, "error").mockImplementation(() => {});
236+
onceBeforeRemoval(() => fs.unlink(lockPath));
237+
238+
expect(await withFileLock(lockPath, async () => "ran", fast)).toBe("ran");
239+
// Nothing was broken: the lock was gone before the breaker could take it.
240+
expect(error).not.toHaveBeenCalled();
241+
expect(await fs.readdir(dir)).toEqual([]);
242+
});
243+
244+
it("removes the stale lock itself, leaving no aside file", async () => {
245+
await writeStaleLock();
246+
vi.spyOn(console, "error").mockImplementation(() => {});
247+
const unlink = vi.spyOn(fs, "unlink");
248+
249+
await withFileLock(
250+
lockPath,
251+
async () => {
252+
// The lock path was never unlinked while the stale lock stood there:
253+
// the stale file was moved aside and deleted under its own name.
254+
const removed = unlink.mock.calls.map(([file]) => String(file));
255+
expect(removed).not.toContain(lockPath);
256+
expect(
257+
removed.filter((file) => /\.lock\.[0-9a-f]{16}\.stale$/.test(file)),
258+
).toHaveLength(1);
259+
expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]);
260+
},
261+
fast,
262+
);
263+
expect(await fs.readdir(dir)).toEqual([]);
264+
});
265+
187266
it("leaves a stale lock to the waiter already breaking it", async () => {
188267
await writeStaleLock();
189268
await fs.writeFile(`${lockPath}.break`, "");

‎src/memory/index.ts‎

Lines changed: 69 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -275,20 +275,44 @@ function isLockOwnerDead(contents: string): boolean {
275275
}
276276
}
277277

278-
// Whether the lock at lockPath is abandoned. Its owner and its mtime are read
279-
// through one open handle, so both describe the same lock file even if it is
278+
// What a waiter learns from one look at a lock file: whether it is abandoned,
279+
// and which file it looked at. The device and inode numbers identify the file
280+
// itself rather than its path, so a later check can tell that file from one
281+
// that has replaced it at the same path. They are read as bigints because a
282+
// Windows file id does not fit in a double.
283+
interface LockJudgement {
284+
stale: boolean;
285+
dev: bigint;
286+
ino: bigint;
287+
}
288+
289+
// Judge the lock file open at handle. Its owner and its mtime are read
290+
// through that one handle, so both describe the same lock file even if it is
280291
// replaced meanwhile.
292+
async function judgeLock(
293+
handle: FileHandle,
294+
staleMs: number,
295+
): Promise<LockJudgement> {
296+
const [contents, stats] = await Promise.all([
297+
handle.readFile("utf-8"),
298+
handle.stat({ bigint: true }),
299+
]);
300+
return {
301+
stale:
302+
isLockOwnerDead(contents) || Date.now() - Number(stats.mtimeMs) > staleMs,
303+
dev: stats.dev,
304+
ino: stats.ino,
305+
};
306+
}
307+
308+
// Whether the lock at lockPath is abandoned.
281309
async function isLockStale(
282310
lockPath: string,
283311
staleMs: number,
284312
): Promise<boolean> {
285313
const handle = await fs.open(lockPath, "r");
286314
try {
287-
const [contents, stats] = await Promise.all([
288-
handle.readFile("utf-8"),
289-
handle.stat(),
290-
]);
291-
return isLockOwnerDead(contents) || Date.now() - stats.mtimeMs > staleMs;
315+
return (await judgeLock(handle, staleMs)).stale;
292316
} finally {
293317
await handle.close();
294318
}
@@ -299,6 +323,25 @@ async function isLockStale(
299323
// re-checks the lock under that guard: two waiters can never both judge the
300324
// same abandoned lock stale and one then remove the lock the other has just
301325
// taken in its place.
326+
//
327+
// The guard orders breakers only. The lock's own holder can still release it,
328+
// and a breaker that stalls past staleMs loses its guard to another, so the
329+
// file at lockPath can be replaced by a successor's live lock after the
330+
// re-check has judged it stale. Removing by path would then delete that live
331+
// lock and let a third writer in beside its holder (#5560). So the lock is
332+
// never deleted where it stands. It is renamed aside to a name nobody else
333+
// uses, which is atomic and takes whichever file is at lockPath at that
334+
// instant, and what was taken is then compared with the file that was judged:
335+
// the judged file is deleted, and anything else is a live lock and is renamed
336+
// straight back. The handle the judgement was read through stays open until
337+
// then, so the judged file's inode number cannot be reused by a successor's
338+
// file and the comparison cannot be fooled.
339+
//
340+
// What remains is the moment a live lock spends aside before it is put back:
341+
// a writer that creates the lock in exactly that moment is overwritten by the
342+
// restored one and runs beside its holder. Reaching it takes a replacement
343+
// between the judgement and the rename, then a create between the two
344+
// renames; a lock file cannot close that without the kernel's help.
302345
async function breakStaleLock(
303346
lockPath: string,
304347
staleMs: number,
@@ -321,12 +364,26 @@ async function breakStaleLock(
321364
}
322365
try {
323366
await breaker.close();
324-
if (!(await isLockStale(lockPath, staleMs))) {
325-
return false;
367+
const judged = await fs.open(lockPath, "r");
368+
try {
369+
const { stale, dev, ino } = await judgeLock(judged, staleMs);
370+
if (!stale) {
371+
return false;
372+
}
373+
const asidePath = `${lockPath}.${randomBytes(8).toString("hex")}.stale`;
374+
await fs.rename(lockPath, asidePath);
375+
const taken = await fs.stat(asidePath, { bigint: true });
376+
if (taken.dev !== dev || taken.ino !== ino) {
377+
// Not the lock that was judged: a successor's live one. Put it back.
378+
await fs.rename(asidePath, lockPath);
379+
return false;
380+
}
381+
console.error(`Breaking stale memory file lock ${lockPath}`);
382+
await fs.unlink(asidePath);
383+
return true;
384+
} finally {
385+
await judged.close();
326386
}
327-
console.error(`Breaking stale memory file lock ${lockPath}`);
328-
await fs.unlink(lockPath);
329-
return true;
330387
} finally {
331388
await fs.unlink(breakerPath).catch(ignoreError);
332389
}

0 commit comments

Comments
 (0)