Skip to content

Commit 23a292d

Browse files
committed
Merge origin/v2/main into v2/chore/3047-mcp-registry-entries
Catch up before merge: v2/main moved under this PR.
2 parents 9db3591 + 8b63551 commit 23a292d

3 files changed

Lines changed: 172 additions & 2 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+
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).

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

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,116 @@ describe("withFileLock", () => {
606606
expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]);
607607
});
608608

609+
// Stage a successor's live lock in place of the stale one before the
610+
// breaker takes it aside, as onceBeforeRemoval does, and fail the first
611+
// `failures` attempts to put it back with `code`. Returns a count of
612+
// those attempts.
613+
function stageSuccessorAndFailRestore(
614+
failures: number,
615+
code: string,
616+
): () => number {
617+
const realRename = fs.rename;
618+
let staged = false;
619+
let restores = 0;
620+
vi.spyOn(fs, "rename").mockImplementation(async (from, to) => {
621+
if (!staged && from === lockPath) {
622+
staged = true;
623+
await fs.unlink(lockPath);
624+
await fs.writeFile(lockPath, "successor");
625+
}
626+
if (String(from).endsWith(".stale") && to === lockPath) {
627+
restores += 1;
628+
if (restores <= failures) {
629+
throw Object.assign(new Error(code), { code });
630+
}
631+
}
632+
return realRename(from, to);
633+
});
634+
return () => restores;
635+
}
636+
637+
// On Windows a rename over a file that anything holds open fails, and the
638+
// writer that created the lock in the gap keeps opening it while it waits
639+
// out the break. Giving up then left the live lock aside and let that
640+
// writer run beside its holder (#5635).
641+
it("keeps putting a live lock back while Windows refuses to replace the lock created in the gap", async () => {
642+
await writeStaleLock();
643+
vi.spyOn(console, "error").mockImplementation(() => {});
644+
vi.spyOn(process, "platform", "get").mockReturnValue("win32");
645+
const opens = watchOpens();
646+
const restores = stageSuccessorAndFailRestore(2, "EPERM");
647+
let thirdRan!: () => void;
648+
const thirdStarted = new Promise<void>((resolve) => (thirdRan = resolve));
649+
const third = vi.fn(async () => {
650+
thirdRan();
651+
return "third ran";
652+
});
653+
let thirdOutcome: Promise<unknown> | undefined;
654+
onceLockAside(async () => {
655+
const sawBreak = opens.opened(guardPath(), "r");
656+
thirdOutcome = withFileLock(lockPath, third, fast).catch(
657+
(error: unknown) => error,
658+
);
659+
await Promise.race([thirdStarted, sawBreak]);
660+
});
661+
662+
await expect(
663+
withFileLock(lockPath, async () => "breaker ran", fast),
664+
).rejects.toThrow("Timed out");
665+
const outcome = await thirdOutcome;
666+
667+
expect(restores()).toBe(3);
668+
expect(third).not.toHaveBeenCalled();
669+
expect((outcome as Error).message).toContain("Timed out");
670+
expect(await fs.readFile(lockPath, "utf-8")).toBe("successor");
671+
expect(heldLockPaths()).toEqual([]);
672+
expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock"]);
673+
});
674+
675+
it("does not retry a failed put-back off Windows, where the failure lasts", async () => {
676+
await writeStaleLock();
677+
vi.spyOn(console, "error").mockImplementation(() => {});
678+
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
679+
const restores = stageSuccessorAndFailRestore(1, "EPERM");
680+
681+
await expect(
682+
withFileLock(lockPath, async () => "ran", fast),
683+
).rejects.toThrow("EPERM");
684+
685+
expect(restores()).toBe(1);
686+
expect(heldLockPaths()).toEqual([]);
687+
expect(await exists(guardPath())).toBe(false);
688+
});
689+
690+
// Windows' EPERM also means a busy lock to the acquire loop, so a put-back
691+
// that never lands must fail with an error of its own, or the breaker
692+
// would go back to acquiring with the live lock still aside.
693+
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 () => {
694+
await writeStaleLock();
695+
vi.spyOn(console, "error").mockImplementation(() => {});
696+
vi.spyOn(process, "platform", "get").mockReturnValue("win32");
697+
const restores = stageSuccessorAndFailRestore(Infinity, "EPERM");
698+
const operation = vi.fn(async () => "ran");
699+
700+
const error: unknown = await withFileLock(lockPath, operation, {
701+
staleMs: 50,
702+
timeoutMs: 5_000,
703+
retryMs: 5,
704+
}).catch((e: unknown) => e);
705+
706+
expect(error).toBeInstanceOf(Error);
707+
expect((error as Error).message).toContain(
708+
"Could not put back the live memory file lock",
709+
);
710+
expect(((error as Error).cause as NodeJS.ErrnoException).code).toBe(
711+
"EPERM",
712+
);
713+
expect(operation).not.toHaveBeenCalled();
714+
expect(restores()).toBeGreaterThan(1);
715+
expect(heldLockPaths()).toEqual([]);
716+
expect(await exists(guardPath())).toBe(false);
717+
});
718+
609719
it("does not restore a lock its holder released while it was aside", async () => {
610720
await writeStaleLock();
611721
vi.spyOn(console, "error").mockImplementation(() => {});

‎src/memory/index.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,57 @@ function dropGuard(guardPath: string): void {
445445
heldGuards.delete(guardPath);
446446
}
447447

448+
// Whether a rename that replaces a file failed only because the file being
449+
// replaced is open right now. On Windows, renaming over a file that anything
450+
// holds open fails with EPERM (or EACCES, or EBUSY) until that handle closes.
451+
// Elsewhere a rename never fails for that reason, and these codes are lasting.
452+
function isReplaceBusy(error: unknown): boolean {
453+
const code = (error as NodeJS.ErrnoException).code;
454+
return (
455+
process.platform === "win32" &&
456+
(code === "EPERM" || code === "EACCES" || code === "EBUSY")
457+
);
458+
}
459+
460+
// Put a live lock that breakStaleLock took aside by mistake back at lockPath.
461+
// A writer that created the lock in the gap keeps opening its file while it
462+
// waits for the guard to go (confirmLock), so on Windows the rename over that
463+
// file can fail for a moment. Giving up then would drop the guard with the
464+
// live lock still aside, and that writer would run beside its holder (#5635).
465+
// So the rename is retried, still under the guard, until it lands. No attempt
466+
// starts once half of staleMs has passed since the guard was taken: past
467+
// staleMs the guard is taken to be left by a crash and protects nothing, and
468+
// the other half is the margin for the attempt in flight. A put-back that
469+
// cannot be made fails with an error of its own rather than the rename's
470+
// code, which on Windows would read as a busy lock and send this writer back
471+
// to acquiring with the live lock still aside.
472+
async function restoreLock(
473+
asidePath: string,
474+
lockPath: string,
475+
guardTakenAt: number,
476+
staleMs: number,
477+
retryMs: number,
478+
): Promise<void> {
479+
const deadline = guardTakenAt + staleMs / 2;
480+
for (;;) {
481+
try {
482+
await fs.rename(asidePath, lockPath);
483+
return;
484+
} catch (error) {
485+
if (!isReplaceBusy(error)) {
486+
throw error;
487+
}
488+
await pause(retryMs);
489+
if (Date.now() >= deadline) {
490+
throw new Error(
491+
`Could not put back the live memory file lock ${lockPath}, left at ${asidePath}`,
492+
{ cause: error },
493+
);
494+
}
495+
}
496+
}
497+
}
498+
448499
// Remove an abandoned lock, returning whether it did. Breaking happens under
449500
// the guard, so only one waiter breaks at a time and re-checks the lock under
450501
// it: two waiters can never both judge the same abandoned lock stale and one
@@ -472,8 +523,12 @@ function dropGuard(guardPath: string): void {
472523
async function breakStaleLock(
473524
lockPath: string,
474525
staleMs: number,
526+
retryMs: number,
475527
): Promise<boolean> {
476528
const guardPath = guardPathOf(lockPath);
529+
// Read before the guard is created, so it is never later than the time the
530+
// guard's age is counted from.
531+
const guardTakenAt = Date.now();
477532
if (!(await tryTakeGuard(guardPath, staleMs))) {
478533
// Another waiter is breaking the lock, or its holder is releasing it.
479534
return false;
@@ -490,7 +545,7 @@ async function breakStaleLock(
490545
const taken = await fs.stat(asidePath, { bigint: true });
491546
if (taken.dev !== dev || taken.ino !== ino) {
492547
// Not the lock that was judged: a successor's live one. Put it back.
493-
await fs.rename(asidePath, lockPath);
548+
await restoreLock(asidePath, lockPath, guardTakenAt, staleMs, retryMs);
494549
return false;
495550
}
496551
console.error(`Breaking stale memory file lock ${lockPath}`);
@@ -766,7 +821,7 @@ export async function withFileLock<T>(
766821
try {
767822
if (
768823
(await isLockStale(lockPath, staleMs)) &&
769-
(await breakStaleLock(lockPath, staleMs))
824+
(await breakStaleLock(lockPath, staleMs, retryMs))
770825
) {
771826
continue;
772827
}

0 commit comments

Comments
 (0)