Skip to content

Commit b17b76a

Browse files
cliffhallclaude
andcommitted
fix(memory): stop the lock heartbeat refreshing a lock it no longer owns
The heartbeat in withFileLock refreshed the lock file's mtime unconditionally. Once the lock was broken as stale and re-taken by another process, the previous holder kept refreshing the new owner's lock, so a crashed new owner's lock could never go stale. The heartbeat now re-reads the lock token first, as the release path does, and stops the interval on a mismatch. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 281b167 commit b17b76a

3 files changed

Lines changed: 66 additions & 1 deletion

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+
Fix the file lock's heartbeat refreshing a lock file this process no longer owns: once a lock is broken as stale and re-taken by another process, the previous holder stops refreshing it, so a crashed new owner's lock can still go stale and be broken.

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,51 @@ describe("withFileLock", () => {
250250
expect(order).toEqual(["long start", "long end", "waiter"]);
251251
});
252252

253+
it("stops refreshing a lock that was broken and re-taken while it ran (#5418)", async () => {
254+
// Heartbeat every 25 ms; the operation outlives several beats.
255+
const opts = { staleMs: 50, timeoutMs: 5_000, retryMs: 5 };
256+
const old = new Date(Date.now() - 60_000);
257+
const realUtimes = fs.utimes;
258+
let replaced!: () => void;
259+
const replacement = new Promise<void>((resolve) => (replaced = resolve));
260+
// Our first heartbeat refreshes our own lock; right after it, another
261+
// process breaks the lock as stale and re-takes it with its own token.
262+
const utimes = vi
263+
.spyOn(fs, "utimes")
264+
.mockImplementationOnce(async (...args) => {
265+
await realUtimes(...args);
266+
await fs.writeFile(lockPath, "someone else");
267+
await realUtimes(lockPath, old, old);
268+
replaced();
269+
});
270+
const readFile = vi.spyOn(fs, "readFile");
271+
const lockReads = () =>
272+
readFile.mock.calls.filter(([file]) => file === lockPath).length;
273+
274+
await withFileLock(
275+
lockPath,
276+
async () => {
277+
await replacement;
278+
readFile.mockClear();
279+
// Several heartbeats later, only the first one, on our own lock, has
280+
// touched the file: the next one read the new owner's token and stopped
281+
// the interval, so the beats after it do not even read the file.
282+
await new Promise((resolve) => setTimeout(resolve, 100));
283+
expect(utimes).toHaveBeenCalledTimes(1);
284+
const reads = lockReads();
285+
expect(reads).toBeGreaterThan(0);
286+
await new Promise((resolve) => setTimeout(resolve, 150));
287+
expect(lockReads()).toBe(reads);
288+
},
289+
opts,
290+
);
291+
292+
expect(utimes).toHaveBeenCalledTimes(1);
293+
expect(await fs.readFile(lockPath, "utf-8")).toBe("someone else");
294+
const { mtimeMs } = await fs.stat(lockPath);
295+
expect(mtimeMs).toBeLessThan(Date.now() - 30_000);
296+
});
297+
253298
it("removes the lock it created when writing it fails", async () => {
254299
const realOpen = fs.open;
255300
vi.spyOn(fs, "open").mockImplementationOnce(async (...args) => {

‎src/memory/index.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,9 +350,24 @@ export async function withFileLock<T>(
350350

351351
// Keep the lock fresh while the operation runs, so a mutation that outlasts
352352
// staleMs (a large graph, a slow disk) is not mistaken for an abandoned one.
353+
// Refresh only our own lock, as the release below does: once it is broken
354+
// as stale and re-taken, the file belongs to another process, and keeping
355+
// it fresh would stop a crashed new owner's lock from ever going stale.
353356
const heartbeat = setInterval(() => {
354357
const now = new Date();
355-
fs.utimes(lockPath, now, now).catch(ignoreError);
358+
// Not awaited: an interval callback has no caller to await it, and every
359+
// failure (the lock already gone) is caught and ignored here.
360+
void fs
361+
.readFile(lockPath, "utf-8")
362+
.then((current) => {
363+
if (current !== token) {
364+
// The lock changed hands: stop refreshing it, for good.
365+
clearInterval(heartbeat);
366+
return;
367+
}
368+
return fs.utimes(lockPath, now, now);
369+
})
370+
.catch(ignoreError);
356371
}, staleMs / 2);
357372
heartbeat.unref();
358373

0 commit comments

Comments
 (0)