From 7e0a6c46853c82158c6cb80f81cfc995cf893c5f Mon Sep 17 00:00:00 2001 From: cliffhall Date: Thu, 19 Nov 2026 10:19:50 -0500 Subject: [PATCH 1/2] fix(memory): keep retrying a lock put-back that Windows refuses for a moment On Windows a rename over a file that anything holds open fails with EPERM. When a stale-lock break took a live lock aside by mistake, the writer that created the lock in the gap kept opening its file while it waited out the break, so putting the live lock back could fail. The failure was swallowed as a busy lock, the guard was dropped with the live lock still aside, and that writer ran beside its holder: the #5565 hand-off window, reopened on Windows. The put-back is now retried under the guard until it lands, for up to staleMs. Closes #5635 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-lock-restore-windows.md | 5 ++ src/memory/__tests__/file-lock.test.ts | 100 ++++++++++++++++++++++ src/memory/index.ts | 45 +++++++++- 3 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 .changeset/memory-lock-restore-windows.md diff --git a/.changeset/memory-lock-restore-windows.md b/.changeset/memory-lock-restore-windows.md new file mode 100644 index 0000000000..4721dca4cb --- /dev/null +++ b/.changeset/memory-lock-restore-windows.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +Keep the memory file lock exclusive on Windows when a stale-lock break takes a live lock aside by mistake: putting it back is retried while Windows briefly refuses to replace the lock another writer created in the gap, instead of giving up and letting that writer run beside the live lock's holder (#5635). diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index a43524064a..308a57e07a 100644 --- a/src/memory/__tests__/file-lock.test.ts +++ b/src/memory/__tests__/file-lock.test.ts @@ -606,6 +606,106 @@ describe("withFileLock", () => { expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]); }); + // Stage a successor's live lock in place of the stale one before the + // breaker takes it aside, as onceBeforeRemoval does, and fail the first + // `failures` attempts to put it back with `code`. Returns a count of + // those attempts. + function stageSuccessorAndFailRestore( + failures: number, + code: string, + ): () => number { + const realRename = fs.rename; + let staged = false; + let restores = 0; + vi.spyOn(fs, "rename").mockImplementation(async (from, to) => { + if (!staged && from === lockPath) { + staged = true; + await fs.unlink(lockPath); + await fs.writeFile(lockPath, "successor"); + } + if (String(from).endsWith(".stale") && to === lockPath) { + restores += 1; + if (restores <= failures) { + throw Object.assign(new Error(code), { code }); + } + } + return realRename(from, to); + }); + return () => restores; + } + + // On Windows a rename over a file that anything holds open fails, and the + // writer that created the lock in the gap keeps opening it while it waits + // out the break. Giving up then left the live lock aside and let that + // writer run beside its holder (#5635). + it("keeps putting a live lock back while Windows refuses to replace the lock created in the gap", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); + const opens = watchOpens(); + const restores = stageSuccessorAndFailRestore(2, "EPERM"); + let thirdRan!: () => void; + const thirdStarted = new Promise((resolve) => (thirdRan = resolve)); + const third = vi.fn(async () => { + thirdRan(); + return "third ran"; + }); + let thirdOutcome: Promise | undefined; + onceLockAside(async () => { + const sawBreak = opens.opened(guardPath(), "r"); + thirdOutcome = withFileLock(lockPath, third, fast).catch( + (error: unknown) => error, + ); + await Promise.race([thirdStarted, sawBreak]); + }); + + await expect( + withFileLock(lockPath, async () => "breaker ran", fast), + ).rejects.toThrow("Timed out"); + const outcome = await thirdOutcome; + + expect(restores()).toBe(3); + expect(third).not.toHaveBeenCalled(); + expect((outcome as Error).message).toContain("Timed out"); + expect(await fs.readFile(lockPath, "utf-8")).toBe("successor"); + expect(heldLockPaths()).toEqual([]); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]); + }); + + it("does not retry a failed put-back off Windows, where the failure lasts", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const restores = stageSuccessorAndFailRestore(1, "EPERM"); + + await expect( + withFileLock(lockPath, async () => "ran", fast), + ).rejects.toThrow("EPERM"); + + expect(restores()).toBe(1); + expect(heldLockPaths()).toEqual([]); + expect(await exists(guardPath())).toBe(false); + }); + + it("stops putting a live lock back on Windows once the guard would be taken for a crash's", async () => { + await writeStaleLock(); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); + const restores = stageSuccessorAndFailRestore(Infinity, "EBUSY"); + + await expect( + withFileLock(lockPath, async () => "ran", { + staleMs: 50, + timeoutMs: 5_000, + retryMs: 5, + }), + ).rejects.toThrow("EBUSY"); + + expect(restores()).toBeGreaterThan(1); + expect(heldLockPaths()).toEqual([]); + expect(await exists(guardPath())).toBe(false); + }); + it("does not restore a lock its holder released while it was aside", async () => { await writeStaleLock(); vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 4eafd60616..f6e3e28922 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -445,6 +445,46 @@ function dropGuard(guardPath: string): void { heldGuards.delete(guardPath); } +// Whether a rename that replaces a file failed only because the file being +// replaced is open right now. On Windows, renaming over a file that anything +// holds open fails with EPERM (or EACCES, or EBUSY) until that handle closes. +// Elsewhere a rename never fails for that reason, and these codes are lasting. +function isReplaceBusy(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException).code; + return ( + process.platform === "win32" && + (code === "EPERM" || code === "EACCES" || code === "EBUSY") + ); +} + +// Put a live lock that breakStaleLock took aside by mistake back at lockPath. +// A writer that created the lock in the gap keeps opening its file while it +// waits for the guard to go (confirmLock), so on Windows the rename over that +// file can fail for a moment. Giving up then would drop the guard with the +// live lock still aside, and that writer would run beside its holder (#5635). +// So the rename is retried, still under the guard, until it lands. It stops +// after staleMs, past which the guard is taken to be left by a crash and +// protects nothing. +async function restoreLock( + asidePath: string, + lockPath: string, + staleMs: number, + retryMs: number, +): Promise { + const deadline = Date.now() + staleMs; + for (;;) { + try { + await fs.rename(asidePath, lockPath); + return; + } catch (error) { + if (!isReplaceBusy(error) || Date.now() >= deadline) { + throw error; + } + } + await pause(retryMs); + } +} + // Remove an abandoned lock, returning whether it did. Breaking happens under // the guard, so only one waiter breaks at a time and re-checks the lock under // it: two waiters can never both judge the same abandoned lock stale and one @@ -472,6 +512,7 @@ function dropGuard(guardPath: string): void { async function breakStaleLock( lockPath: string, staleMs: number, + retryMs: number, ): Promise { const guardPath = guardPathOf(lockPath); if (!(await tryTakeGuard(guardPath, staleMs))) { @@ -490,7 +531,7 @@ async function breakStaleLock( const taken = await fs.stat(asidePath, { bigint: true }); if (taken.dev !== dev || taken.ino !== ino) { // Not the lock that was judged: a successor's live one. Put it back. - await fs.rename(asidePath, lockPath); + await restoreLock(asidePath, lockPath, staleMs, retryMs); return false; } console.error(`Breaking stale memory file lock ${lockPath}`); @@ -766,7 +807,7 @@ export async function withFileLock( try { if ( (await isLockStale(lockPath, staleMs)) && - (await breakStaleLock(lockPath, staleMs)) + (await breakStaleLock(lockPath, staleMs, retryMs)) ) { continue; } From 7a1511cd2e0e6ce1019e259bdef959621492fe26 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Thu, 19 Nov 2026 10:31:36 -0500 Subject: [PATCH 2/2] fix(memory): bound a lock put-back by the guard's age and fail it plainly Review of #5637. The retry deadline counted from the first attempt rather than from when the guard was taken, and was not re-checked after the pause, so a retry could land after the guard went stale and another writer moved on. It now counts from just before the guard is taken, at half of staleMs, and is checked before every retry. A put-back that never lands now fails with an error of its own (the rename's error as its cause): Windows' EPERM would otherwise read as a busy lock and send the breaker back to acquiring with the live lock still aside. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/file-lock.test.ts | 28 +++++++++++++++++--------- src/memory/index.ts | 28 +++++++++++++++++++------- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index 308a57e07a..0ef30288d1 100644 --- a/src/memory/__tests__/file-lock.test.ts +++ b/src/memory/__tests__/file-lock.test.ts @@ -687,20 +687,30 @@ describe("withFileLock", () => { expect(await exists(guardPath())).toBe(false); }); - it("stops putting a live lock back on Windows once the guard would be taken for a crash's", async () => { + // Windows' EPERM also means a busy lock to the acquire loop, so a put-back + // that never lands must fail with an error of its own, or the breaker + // would go back to acquiring with the live lock still aside. + it("fails the acquisition on Windows once a live lock cannot be put back before the guard would be taken for a crash's", async () => { await writeStaleLock(); vi.spyOn(console, "error").mockImplementation(() => {}); vi.spyOn(process, "platform", "get").mockReturnValue("win32"); - const restores = stageSuccessorAndFailRestore(Infinity, "EBUSY"); + const restores = stageSuccessorAndFailRestore(Infinity, "EPERM"); + const operation = vi.fn(async () => "ran"); - await expect( - withFileLock(lockPath, async () => "ran", { - staleMs: 50, - timeoutMs: 5_000, - retryMs: 5, - }), - ).rejects.toThrow("EBUSY"); + const error: unknown = await withFileLock(lockPath, operation, { + staleMs: 50, + timeoutMs: 5_000, + retryMs: 5, + }).catch((e: unknown) => e); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain( + "Could not put back the live memory file lock", + ); + expect(((error as Error).cause as NodeJS.ErrnoException).code).toBe( + "EPERM", + ); + expect(operation).not.toHaveBeenCalled(); expect(restores()).toBeGreaterThan(1); expect(heldLockPaths()).toEqual([]); expect(await exists(guardPath())).toBe(false); diff --git a/src/memory/index.ts b/src/memory/index.ts index f6e3e28922..cd94887230 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -462,26 +462,37 @@ function isReplaceBusy(error: unknown): boolean { // waits for the guard to go (confirmLock), so on Windows the rename over that // file can fail for a moment. Giving up then would drop the guard with the // live lock still aside, and that writer would run beside its holder (#5635). -// So the rename is retried, still under the guard, until it lands. It stops -// after staleMs, past which the guard is taken to be left by a crash and -// protects nothing. +// So the rename is retried, still under the guard, until it lands. No attempt +// starts once half of staleMs has passed since the guard was taken: past +// staleMs the guard is taken to be left by a crash and protects nothing, and +// the other half is the margin for the attempt in flight. A put-back that +// cannot be made fails with an error of its own rather than the rename's +// code, which on Windows would read as a busy lock and send this writer back +// to acquiring with the live lock still aside. async function restoreLock( asidePath: string, lockPath: string, + guardTakenAt: number, staleMs: number, retryMs: number, ): Promise { - const deadline = Date.now() + staleMs; + const deadline = guardTakenAt + staleMs / 2; for (;;) { try { await fs.rename(asidePath, lockPath); return; } catch (error) { - if (!isReplaceBusy(error) || Date.now() >= deadline) { + if (!isReplaceBusy(error)) { throw error; } + await pause(retryMs); + if (Date.now() >= deadline) { + throw new Error( + `Could not put back the live memory file lock ${lockPath}, left at ${asidePath}`, + { cause: error }, + ); + } } - await pause(retryMs); } } @@ -515,6 +526,9 @@ async function breakStaleLock( retryMs: number, ): Promise { const guardPath = guardPathOf(lockPath); + // Read before the guard is created, so it is never later than the time the + // guard's age is counted from. + const guardTakenAt = Date.now(); if (!(await tryTakeGuard(guardPath, staleMs))) { // Another waiter is breaking the lock, or its holder is releasing it. return false; @@ -531,7 +545,7 @@ async function breakStaleLock( const taken = await fs.stat(asidePath, { bigint: true }); if (taken.dev !== dev || taken.ino !== ino) { // Not the lock that was judged: a successor's live one. Put it back. - await restoreLock(asidePath, lockPath, staleMs, retryMs); + await restoreLock(asidePath, lockPath, guardTakenAt, staleMs, retryMs); return false; } console.error(`Breaking stale memory file lock ${lockPath}`);