From af86b99080b0f4af52ca6a8f4f1e043921ec6140 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Wed, 18 Nov 2026 03:34:10 -0500 Subject: [PATCH] fix(memory): release held locks when the Streamable HTTP server stops Over Streamable HTTP, run() never registered the exit hook that removes a lock file the process still holds: only main(), the stdio path, called installLockCleanup(). Closing the listener does not wait for a tool call that is mid-write, so the process.exit() after it left the lock for the next writer to wait out. A second signal took the default action, with no exit event at all. run() now registers the exit hook, and a second SIGINT or SIGTERM exits at once with that signal's status, through the same hook. Closes #5595 Co-Authored-By: Claude Fable 5.2 Signed-off-by: cliffhall --- .changeset/memory-http-lock-cleanup.md | 5 ++ src/memory/__tests__/http.test.ts | 78 +++++++++++++++++++++++++- src/memory/index.ts | 48 ++++++++++++---- 3 files changed, 118 insertions(+), 13 deletions(-) create mode 100644 .changeset/memory-http-lock-cleanup.md diff --git a/.changeset/memory-http-lock-cleanup.md b/.changeset/memory-http-lock-cleanup.md new file mode 100644 index 0000000000..df5c041cce --- /dev/null +++ b/.changeset/memory-http-lock-cleanup.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +Remove the memory file lock when the server is stopped while serving Streamable HTTP: a write still in flight at shutdown no longer leaves its lock behind for the next writer, and a second SIGINT or SIGTERM exits at once instead of waiting for the listener to close. diff --git a/src/memory/__tests__/http.test.ts b/src/memory/__tests__/http.test.ts index c1174ba3e1..70af182f6c 100644 --- a/src/memory/__tests__/http.test.ts +++ b/src/memory/__tests__/http.test.ts @@ -5,7 +5,11 @@ // across requests, and a 2026-07-28 listen stream across clients. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; import { connect as connectTcp } from "node:net"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { Client, StreamableHTTPClientTransport, @@ -18,7 +22,12 @@ import { startHttpServer, type RunningHttpServer, } from "../http.js"; -import { parseTransport, RESOURCE_URI, run } from "../index.js"; +import { + parseTransport, + releaseHeldLocks, + RESOURCE_URI, + run, +} from "../index.js"; import { call, makeTempGraph } from "./helpers.js"; const alice = { name: "Alice", entityType: "person", observations: [] }; @@ -277,6 +286,73 @@ describe("run", () => { await expect(fetch(url)).rejects.toThrow(); }); + it("exits at once on a second signal, with that signal's status (#5595)", async () => { + const running = await run(["--transport=streamable-http"]); + const close = running.close; + // A shutdown that never finishes, as when a request is still in flight. + running.close = vi.fn().mockReturnValue(new Promise(() => {})); + added("SIGINT")[0]("SIGINT"); + expect(process.exit).not.toHaveBeenCalled(); + added("SIGTERM")[0]("SIGTERM"); + expect(process.exit).toHaveBeenLastCalledWith(143); + added("SIGINT")[0]("SIGINT"); + expect(process.exit).toHaveBeenLastCalledWith(130); + expect(running.close).toHaveBeenCalledTimes(1); + await close(); + }); + + it("registers the lock cleanup for the process's exit (#5595)", async () => { + const running = await run(["--transport=streamable-http"]); + expect(process.listeners("exit")).toContain(releaseHeldLocks); + await running.close(); + }); + + // A real signal, sent to a real server process that is serving Streamable + // HTTP and holds the lock mid-write. Windows has no SIGTERM to deliver: + // process.kill() there ends the process outright, so no handler can run. + it.skipIf(process.platform === "win32")( + "removes a lock held mid-write when SIGTERM stops the HTTP server (#5595)", + async () => { + const lockPath = `${graph.filePath}.lock`; + const distIndex = pathToFileURL( + path.join( + path.dirname(fileURLToPath(import.meta.url)), + "..", + "dist", + "index.js", + ), + ).href; + const script = ` + const { run, withFileLock } = await import(${JSON.stringify(distIndex)}); + await run(["--transport", "streamable-http"]); + await withFileLock(${JSON.stringify(lockPath)}, () => { + console.log("held"); + return new Promise(() => {}); + }); + `; + const child = spawn( + process.execPath, + ["--input-type=module", "-e", script], + { stdio: ["ignore", "pipe", "ignore"], env: process.env }, + ); + const exited = new Promise((resolve) => + child.on("exit", (code) => resolve(code)), + ); + await new Promise((resolve, reject) => { + child.stdout.on("data", (data: Buffer) => { + if (data.toString().includes("held")) resolve(); + }); + child.on("exit", () => reject(new Error("exited before holding"))); + }); + expect(existsSync(lockPath)).toBe(true); + + child.kill("SIGTERM"); + + expect(await exited).toBe(0); + expect(existsSync(lockPath)).toBe(false); + }, + ); + it("reports a shutdown that fails and exits non-zero", async () => { const running = await run(["--transport=streamable-http"]); const close = running.close; diff --git a/src/memory/index.ts b/src/memory/index.ts index 70fa8c8d5c..c98d2173ca 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -436,8 +436,22 @@ export function releaseHeldLocks(): void { // signal's number. const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 } as const; +let exitLockCleanupInstalled = false; let lockCleanupInstalled = false; +// Release held locks when the process exits normally or through +// process.exit(), by the `exit` event. Installed once, however the server is +// started. It covers a signal only when something turns that signal into a +// process.exit(): installLockCleanup() does for stdio, and run() does for +// Streamable HTTP, whose signals first close the listener (#5595). +export function installExitLockCleanup(): void { + if (exitLockCleanupInstalled) { + return; + } + exitLockCleanupInstalled = true; + process.on("exit", releaseHeldLocks); +} + // Release held locks however the server process ends (#5485): on a normal // exit or process.exit() through the `exit` event, and on SIGINT or SIGTERM, // whose default action would end the process without emitting `exit`. A @@ -449,7 +463,7 @@ export function installLockCleanup(): void { return; } lockCleanupInstalled = true; - process.on("exit", releaseHeldLocks); + installExitLockCleanup(); for (const [signal, code] of Object.entries(SIGNAL_EXIT_CODES)) { process.on(signal, () => process.exit(code)); } @@ -1781,7 +1795,10 @@ export function parseTransport(args: string[]): TransportName { // Start the server on the transport args names, and hand back how to stop // it. Streamable HTTP listens on HOST:PORT (loopback:3001 by default) and also -// stops, exiting the process, on SIGINT or SIGTERM. +// stops, exiting the process, on SIGINT or SIGTERM. Closing the listener does +// not wait for a tool call that is mid-write, so the exit that follows still +// goes through the lock cleanup (#5595); a second signal does not wait for +// the close either, and exits with the status the signal's default would give. export async function run( args: string[] = process.argv.slice(2), ): Promise<{ close: () => Promise }> { @@ -1799,17 +1816,24 @@ export async function run( console.error( `Knowledge Graph MCP Server running on Streamable HTTP at ${running.url}`, ); - const stop = () => { - running.close().then( - () => process.exit(0), - (error: unknown) => { - console.error("Error shutting down:", error); - process.exit(1); - }, - ); + installExitLockCleanup(); + let stopping = false; + const stop = (signal: keyof typeof SIGNAL_EXIT_CODES) => { + if (stopping) { + process.exit(SIGNAL_EXIT_CODES[signal]); + } else { + stopping = true; + running.close().then( + () => process.exit(0), + (error: unknown) => { + console.error("Error shutting down:", error); + process.exit(1); + }, + ); + } }; - process.once("SIGINT", stop); - process.once("SIGTERM", stop); + process.on("SIGINT", () => stop("SIGINT")); + process.on("SIGTERM", () => stop("SIGTERM")); return running; }