Skip to content

Commit 1e0c7ba

Browse files
authored
Merge pull request #5530 from modelcontextprotocol/v2/fix/5485-memory-lock-cleanup-on-exit
fix(memory): release held lock files on exit and SIGINT/SIGTERM
2 parents 1f8badb + 4efde40 commit 1e0c7ba

5 files changed

Lines changed: 316 additions & 4 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+
Remove the memory file lock the server holds when it is stopped by SIGINT or SIGTERM, or exits, so the next writer does not wait for it to go stale.

‎src/memory/Dockerfile‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,10 @@ WORKDIR /app
7272
# not root, and refuses to start the container under `runAsNonRoot`.
7373
USER 1000:1000
7474

75+
# The server handles SIGTERM itself, removing any lock it holds before it
76+
# exits (#5485). Node running as PID 1 would otherwise ignore `docker stop`'s
77+
# SIGTERM, leaving it to wait out its timeout and SIGKILL the server. SIGINT
78+
# is handled the same way; it is the stop signal everything's image uses.
79+
STOPSIGNAL SIGINT
80+
7581
ENTRYPOINT ["node", "dist/index.js"]

‎src/memory/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ Saves are atomic. Every write tool writes the whole graph to a temporary file in
267267

268268
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).
269269

270+
- 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.
270271
- 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.
271272
- A write that cannot get the lock within 60 seconds fails with a tool error rather than overwriting the file.
272273
- 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.

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

Lines changed: 222 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
// Unit tests for withFileLock, the lock file that orders mutations from
22
// separate server processes sharing one graph file (#4797): mutual exclusion,
3-
// release, breaking an abandoned lock, and giving up on a held one.
3+
// release, breaking an abandoned lock, and giving up on a held one; and the
4+
// exit-time release of the locks this process still holds (#5485).
45
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
56
import { promises as fs } from "fs";
67
import os from "os";
78
import path from "path";
8-
import { spawnSync } from "child_process";
9-
import { KnowledgeGraphManager, withFileLock } from "../index.js";
9+
import { spawn, spawnSync } from "child_process";
10+
import { fileURLToPath, pathToFileURL } from "url";
11+
import {
12+
KnowledgeGraphManager,
13+
heldLockPaths,
14+
installLockCleanup,
15+
releaseHeldLocks,
16+
withFileLock,
17+
} from "../index.js";
1018
import { makeTempGraph } from "./helpers.js";
1119

1220
const fast = { staleMs: 60_000, timeoutMs: 100, retryMs: 5 };
@@ -401,3 +409,214 @@ describe("withFileLock", () => {
401409
expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]);
402410
});
403411
});
412+
413+
describe("releasing held locks on exit (#5485)", () => {
414+
let dir: string;
415+
let cleanup: () => Promise<void>;
416+
417+
beforeEach(async () => {
418+
({ dir, cleanup } = await makeTempGraph());
419+
});
420+
421+
afterEach(async () => {
422+
vi.restoreAllMocks();
423+
await cleanup();
424+
});
425+
426+
async function exists(file: string): Promise<boolean> {
427+
return fs.access(file).then(
428+
() => true,
429+
() => false,
430+
);
431+
}
432+
433+
it("tracks a lock only while it is held", async () => {
434+
const lockPath = path.join(dir, "memory.jsonl.lock");
435+
await withFileLock(lockPath, async () => {
436+
expect(heldLockPaths()).toEqual([lockPath]);
437+
});
438+
expect(heldLockPaths()).toEqual([]);
439+
});
440+
441+
it("removes each lock still held, and only those still ours", async () => {
442+
const ours = path.join(dir, "ours.lock");
443+
const taken = path.join(dir, "taken.lock");
444+
const gone = path.join(dir, "gone.lock");
445+
await withFileLock(ours, () =>
446+
withFileLock(taken, () =>
447+
withFileLock(gone, async () => {
448+
// Another process broke and re-took one lock, and another vanished.
449+
await fs.writeFile(taken, "someone else");
450+
await fs.unlink(gone);
451+
452+
releaseHeldLocks();
453+
454+
expect(heldLockPaths()).toEqual([]);
455+
expect(await exists(ours)).toBe(false);
456+
expect(await fs.readFile(taken, "utf-8")).toBe("someone else");
457+
}),
458+
),
459+
);
460+
expect(await fs.readFile(taken, "utf-8")).toBe("someone else");
461+
});
462+
463+
it("removes a lock whose token was still being written at exit", async () => {
464+
const lockPath = path.join(dir, "memory.jsonl.lock");
465+
const realOpen = fs.open;
466+
let finishWrite!: () => void;
467+
let writing!: () => void;
468+
const writeStarted = new Promise<void>((resolve) => (writing = resolve));
469+
vi.spyOn(fs, "open").mockImplementationOnce(async (...args) => {
470+
const handle = await realOpen(...args);
471+
const realWrite = handle.writeFile.bind(handle);
472+
// Hold the token write open, with nothing written yet.
473+
handle.writeFile = async (data) => {
474+
writing();
475+
await new Promise<void>((resolve) => (finishWrite = resolve));
476+
return realWrite(data);
477+
};
478+
return handle;
479+
});
480+
481+
const held = withFileLock(lockPath, async () => "ran");
482+
await writeStarted;
483+
expect(await fs.readFile(lockPath, "utf-8")).toBe("");
484+
485+
releaseHeldLocks();
486+
487+
expect(await exists(lockPath)).toBe(false);
488+
finishWrite();
489+
expect(await held).toBe("ran");
490+
});
491+
492+
it("leaves another writer's empty replacement of a written lock in place", async () => {
493+
const lockPath = path.join(dir, "memory.jsonl.lock");
494+
await withFileLock(lockPath, async () => {
495+
// Our lock was broken as stale, and a new writer has created its own
496+
// but not yet written its token.
497+
await fs.writeFile(lockPath, "");
498+
499+
releaseHeldLocks();
500+
501+
expect(await exists(lockPath)).toBe(true);
502+
});
503+
});
504+
505+
it("still tracks a lock while its release is in progress", async () => {
506+
const lockPath = path.join(dir, "memory.jsonl.lock");
507+
const realUnlink = fs.unlink;
508+
let trackedDuringRelease: string[] = [];
509+
await withFileLock(lockPath, async () => {
510+
// The release's removal of the lock is the next unlink.
511+
vi.spyOn(fs, "unlink").mockImplementationOnce(async (file) => {
512+
trackedDuringRelease = heldLockPaths();
513+
return realUnlink(file);
514+
});
515+
});
516+
expect(trackedDuringRelease).toEqual([lockPath]);
517+
expect(heldLockPaths()).toEqual([]);
518+
expect(await exists(lockPath)).toBe(false);
519+
});
520+
521+
it("keeps tracking a lock the same process re-took after breaking it", async () => {
522+
const lockPath = path.join(dir, "memory.jsonl.lock");
523+
let releaseFirst!: () => void;
524+
const firstHolds = new Promise<void>((resolve) => (releaseFirst = resolve));
525+
let firstStarted!: () => void;
526+
const started = new Promise<void>((resolve) => (firstStarted = resolve));
527+
vi.spyOn(console, "error").mockImplementation(() => {});
528+
529+
const first = withFileLock(
530+
lockPath,
531+
async () => {
532+
firstStarted();
533+
await firstHolds;
534+
},
535+
{ staleMs: 60_000 },
536+
);
537+
await started;
538+
// Age the first holder's lock past a short staleMs, so a second holder in
539+
// this process breaks it and takes it over.
540+
const old = new Date(Date.now() - 10_000);
541+
await fs.utimes(lockPath, old, old);
542+
await withFileLock(
543+
lockPath,
544+
async () => {
545+
releaseFirst();
546+
await first;
547+
// The first holder's release left the second's lock, and its entry.
548+
expect(heldLockPaths()).toEqual([lockPath]);
549+
expect(await exists(lockPath)).toBe(true);
550+
},
551+
{ staleMs: 1_000, timeoutMs: 1_000, retryMs: 5 },
552+
);
553+
expect(heldLockPaths()).toEqual([]);
554+
});
555+
556+
it("installs an exit hook and SIGINT and SIGTERM handlers, once", () => {
557+
const handlers = new Map<string | symbol, () => void>();
558+
const on = vi.spyOn(process, "on").mockImplementation((event, listener) => {
559+
handlers.set(event, listener as () => void);
560+
return process;
561+
});
562+
const exit = vi
563+
.spyOn(process, "exit")
564+
.mockImplementation((() => undefined) as typeof process.exit);
565+
566+
installLockCleanup();
567+
installLockCleanup();
568+
569+
expect(on).toHaveBeenCalledTimes(3);
570+
expect(handlers.get("exit")).toBe(releaseHeldLocks);
571+
handlers.get("SIGINT")?.();
572+
expect(exit).toHaveBeenLastCalledWith(130);
573+
handlers.get("SIGTERM")?.();
574+
expect(exit).toHaveBeenLastCalledWith(143);
575+
});
576+
577+
// A real signal, sent to a real process holding a lock mid-operation.
578+
// Windows has no SIGTERM to deliver: process.kill() there ends the process
579+
// outright, so no handler can run.
580+
it.skipIf(process.platform === "win32")(
581+
"removes the lock when SIGTERM stops a process mid-mutation",
582+
async () => {
583+
const lockPath = path.join(dir, "memory.jsonl.lock");
584+
const distIndex = pathToFileURL(
585+
path.join(
586+
path.dirname(fileURLToPath(import.meta.url)),
587+
"..",
588+
"dist",
589+
"index.js",
590+
),
591+
).href;
592+
const script = `
593+
const { installLockCleanup, withFileLock } = await import(${JSON.stringify(distIndex)});
594+
installLockCleanup();
595+
await withFileLock(${JSON.stringify(lockPath)}, () => {
596+
console.log("held");
597+
return new Promise(() => setInterval(() => {}, 1000));
598+
});
599+
`;
600+
const child = spawn(
601+
process.execPath,
602+
["--input-type=module", "-e", script],
603+
{ stdio: ["ignore", "pipe", "inherit"] },
604+
);
605+
const exited = new Promise<number | null>((resolve) =>
606+
child.on("exit", (code) => resolve(code)),
607+
);
608+
await new Promise<void>((resolve, reject) => {
609+
child.stdout.on("data", (data: Buffer) => {
610+
if (data.toString().includes("held")) resolve();
611+
});
612+
child.on("exit", () => reject(new Error("exited before holding")));
613+
});
614+
expect(await exists(lockPath)).toBe(true);
615+
616+
child.kill("SIGTERM");
617+
618+
expect(await exited).toBe(143);
619+
expect(await exists(lockPath)).toBe(false);
620+
},
621+
);
622+
});

‎src/memory/index.ts‎

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
import { McpServer } from "@modelcontextprotocol/server";
1616
import type { Transport } from "@modelcontextprotocol/server";
1717
import { z } from "zod";
18-
import { promises as fs, realpathSync } from "fs";
18+
import { promises as fs, readFileSync, realpathSync, unlinkSync } from "fs";
1919
import type { FileHandle } from "fs/promises";
2020
import path from "path";
2121
import os from "os";
@@ -276,6 +276,72 @@ async function breakStaleLock(
276276
}
277277
}
278278

279+
// The lock files this process holds right now, each mapped to the token it
280+
// writes into it and whether that write has finished. withFileLock releases its lock in a `finally`, which never
281+
// runs when a signal ends the process, so the exit hook releaseHeldLocks()
282+
// removes them instead (#5485). Without it, a lock left by a stopped server
283+
// stalls the next writer until it goes stale, which takes the full staleMs
284+
// when that writer is on another host (another container) and cannot see
285+
// that this process has gone.
286+
interface HeldLock {
287+
token: string;
288+
written: boolean;
289+
}
290+
const heldLocks = new Map<string, HeldLock>();
291+
292+
// The lock paths this process holds right now, for tests.
293+
export function heldLockPaths(): string[] {
294+
return [...heldLocks.keys()];
295+
}
296+
297+
// Synchronously remove every lock this process still holds, as the process
298+
// exits: an `exit` listener cannot wait on a promise. As in withFileLock's own
299+
// release, a lock is removed only while it still holds this process's token,
300+
// so a lock broken as stale and re-taken by another process stays in place.
301+
// A lock is tracked from the moment its exclusive create returns, before its
302+
// token is written. Until that write finishes, a file holding only the start
303+
// of the token (or none of it) is ours too: the exit interrupted the write.
304+
// Nothing else can have replaced it by then, since a lock that new, with a
305+
// live owner, is never judged stale. Once the token is written only an exact
306+
// match is ours, so another writer's replacement, empty while its own token
307+
// is being written, is left alone.
308+
export function releaseHeldLocks(): void {
309+
for (const [lockPath, { token, written }] of heldLocks) {
310+
try {
311+
const contents = readFileSync(lockPath, "utf-8");
312+
if (written ? contents === token : token.startsWith(contents)) {
313+
unlinkSync(lockPath);
314+
}
315+
} catch {
316+
// Already gone, or unreadable: there is nothing of ours to remove.
317+
}
318+
}
319+
heldLocks.clear();
320+
}
321+
322+
// The exit codes a shell reports for a process its signal ended: 128 + the
323+
// signal's number.
324+
const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 } as const;
325+
326+
let lockCleanupInstalled = false;
327+
328+
// Release held locks however the server process ends (#5485): on a normal
329+
// exit or process.exit() through the `exit` event, and on SIGINT or SIGTERM,
330+
// whose default action would end the process without emitting `exit`. A
331+
// signal handler replaces that default, so it exits itself, with the status
332+
// the default would have given. Installed once, by main(): only the server
333+
// process should take over its signals, not a test that imports this module.
334+
export function installLockCleanup(): void {
335+
if (lockCleanupInstalled) {
336+
return;
337+
}
338+
lockCleanupInstalled = true;
339+
process.on("exit", releaseHeldLocks);
340+
for (const [signal, code] of Object.entries(SIGNAL_EXIT_CODES)) {
341+
process.on(signal, () => process.exit(code));
342+
}
343+
}
344+
279345
// Run operation while holding an exclusive lock file at lockPath, so that
280346
// mutations from separate server processes sharing one graph file take turns
281347
// and each one loads the graph the previous one saved (#4797). The lock is a
@@ -305,14 +371,21 @@ export async function withFileLock<T>(
305371
}
306372
}
307373
if (handle) {
374+
// Track the lock before anything else is awaited: a signal is handled
375+
// only between tasks, never between the open's completion and this
376+
// line, so from here on the exit hook can remove it (#5485).
377+
const held: HeldLock = { token, written: false };
378+
heldLocks.set(lockPath, held);
308379
try {
309380
await handle.writeFile(token);
381+
held.written = true;
310382
await handle.close();
311383
} catch (error) {
312384
// The lock was created but not written: remove it rather than leave
313385
// every other writer waiting for it to go stale.
314386
await handle.close().catch(ignoreError);
315387
await fs.unlink(lockPath).catch(ignoreError);
388+
heldLocks.delete(lockPath);
316389
throw error;
317390
}
318391
break;
@@ -381,6 +454,13 @@ export async function withFileLock<T>(
381454
if (current === token) {
382455
await fs.unlink(lockPath).catch(ignoreError);
383456
}
457+
// Stop tracking the lock only once the release is done, so an exit during
458+
// it still removes the lock. A lock this same process broke as stale and
459+
// re-took in another withFileLock call carries that call's token, and
460+
// stays tracked for it.
461+
if (heldLocks.get(lockPath)?.token === token) {
462+
heldLocks.delete(lockPath);
463+
}
384464
}
385465
}
386466

@@ -1435,6 +1515,7 @@ export async function main(transport?: Transport): Promise<StdioServerHandle> {
14351515
if (locationWarning) {
14361516
console.error(locationWarning);
14371517
}
1518+
installLockCleanup();
14381519
const handle = serveStdio(({ era }) => createServer(memoryFilePath, era), {
14391520
transport,
14401521
// serveStdio reports a transport that fails, including one that cannot

0 commit comments

Comments
 (0)