Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/memory-lock-restore-windows.md
Original file line number Diff line number Diff line change
@@ -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).
110 changes: 110 additions & 0 deletions src/memory/__tests__/file-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,116 @@ 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<void>((resolve) => (thirdRan = resolve));
const third = vi.fn(async () => {
thirdRan();
return "third ran";
});
let thirdOutcome: Promise<unknown> | 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);
});

// 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, "EPERM");
const operation = vi.fn(async () => "ran");

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);
});

it("does not restore a lock its holder released while it was aside", async () => {
await writeStaleLock();
vi.spyOn(console, "error").mockImplementation(() => {});
Expand Down
59 changes: 57 additions & 2 deletions src/memory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,57 @@ 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. 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<void> {
const deadline = guardTakenAt + staleMs / 2;
for (;;) {
try {
await fs.rename(asidePath, lockPath);
return;
} catch (error) {
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 },
);
}
}
}
}

// 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
Expand Down Expand Up @@ -472,8 +523,12 @@ function dropGuard(guardPath: string): void {
async function breakStaleLock(
lockPath: string,
staleMs: number,
retryMs: number,
): Promise<boolean> {
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;
Expand All @@ -490,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 fs.rename(asidePath, lockPath);
await restoreLock(asidePath, lockPath, guardTakenAt, staleMs, retryMs);
return false;
}
console.error(`Breaking stale memory file lock ${lockPath}`);
Expand Down Expand Up @@ -766,7 +821,7 @@ export async function withFileLock<T>(
try {
if (
(await isLockStale(lockPath, staleMs)) &&
(await breakStaleLock(lockPath, staleMs))
(await breakStaleLock(lockPath, staleMs, retryMs))
) {
continue;
}
Expand Down