Skip to content

Commit af86b99

Browse files
cliffhallclaude
andcommitted
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 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent 8e44b8f commit af86b99

3 files changed

Lines changed: 118 additions & 13 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 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.

‎src/memory/__tests__/http.test.ts‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@
55
// across requests, and a 2026-07-28 listen stream across clients.
66

77
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
8+
import { spawn } from "node:child_process";
9+
import { existsSync } from "node:fs";
810
import { connect as connectTcp } from "node:net";
11+
import path from "node:path";
12+
import { fileURLToPath, pathToFileURL } from "node:url";
913
import {
1014
Client,
1115
StreamableHTTPClientTransport,
@@ -18,7 +22,12 @@ import {
1822
startHttpServer,
1923
type RunningHttpServer,
2024
} from "../http.js";
21-
import { parseTransport, RESOURCE_URI, run } from "../index.js";
25+
import {
26+
parseTransport,
27+
releaseHeldLocks,
28+
RESOURCE_URI,
29+
run,
30+
} from "../index.js";
2231
import { call, makeTempGraph } from "./helpers.js";
2332

2433
const alice = { name: "Alice", entityType: "person", observations: [] };
@@ -277,6 +286,73 @@ describe("run", () => {
277286
await expect(fetch(url)).rejects.toThrow();
278287
});
279288

289+
it("exits at once on a second signal, with that signal's status (#5595)", async () => {
290+
const running = await run(["--transport=streamable-http"]);
291+
const close = running.close;
292+
// A shutdown that never finishes, as when a request is still in flight.
293+
running.close = vi.fn().mockReturnValue(new Promise<void>(() => {}));
294+
added("SIGINT")[0]("SIGINT");
295+
expect(process.exit).not.toHaveBeenCalled();
296+
added("SIGTERM")[0]("SIGTERM");
297+
expect(process.exit).toHaveBeenLastCalledWith(143);
298+
added("SIGINT")[0]("SIGINT");
299+
expect(process.exit).toHaveBeenLastCalledWith(130);
300+
expect(running.close).toHaveBeenCalledTimes(1);
301+
await close();
302+
});
303+
304+
it("registers the lock cleanup for the process's exit (#5595)", async () => {
305+
const running = await run(["--transport=streamable-http"]);
306+
expect(process.listeners("exit")).toContain(releaseHeldLocks);
307+
await running.close();
308+
});
309+
310+
// A real signal, sent to a real server process that is serving Streamable
311+
// HTTP and holds the lock mid-write. Windows has no SIGTERM to deliver:
312+
// process.kill() there ends the process outright, so no handler can run.
313+
it.skipIf(process.platform === "win32")(
314+
"removes a lock held mid-write when SIGTERM stops the HTTP server (#5595)",
315+
async () => {
316+
const lockPath = `${graph.filePath}.lock`;
317+
const distIndex = pathToFileURL(
318+
path.join(
319+
path.dirname(fileURLToPath(import.meta.url)),
320+
"..",
321+
"dist",
322+
"index.js",
323+
),
324+
).href;
325+
const script = `
326+
const { run, withFileLock } = await import(${JSON.stringify(distIndex)});
327+
await run(["--transport", "streamable-http"]);
328+
await withFileLock(${JSON.stringify(lockPath)}, () => {
329+
console.log("held");
330+
return new Promise(() => {});
331+
});
332+
`;
333+
const child = spawn(
334+
process.execPath,
335+
["--input-type=module", "-e", script],
336+
{ stdio: ["ignore", "pipe", "ignore"], env: process.env },
337+
);
338+
const exited = new Promise<number | null>((resolve) =>
339+
child.on("exit", (code) => resolve(code)),
340+
);
341+
await new Promise<void>((resolve, reject) => {
342+
child.stdout.on("data", (data: Buffer) => {
343+
if (data.toString().includes("held")) resolve();
344+
});
345+
child.on("exit", () => reject(new Error("exited before holding")));
346+
});
347+
expect(existsSync(lockPath)).toBe(true);
348+
349+
child.kill("SIGTERM");
350+
351+
expect(await exited).toBe(0);
352+
expect(existsSync(lockPath)).toBe(false);
353+
},
354+
);
355+
280356
it("reports a shutdown that fails and exits non-zero", async () => {
281357
const running = await run(["--transport=streamable-http"]);
282358
const close = running.close;

‎src/memory/index.ts‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -436,8 +436,22 @@ export function releaseHeldLocks(): void {
436436
// signal's number.
437437
const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 } as const;
438438

439+
let exitLockCleanupInstalled = false;
439440
let lockCleanupInstalled = false;
440441

442+
// Release held locks when the process exits normally or through
443+
// process.exit(), by the `exit` event. Installed once, however the server is
444+
// started. It covers a signal only when something turns that signal into a
445+
// process.exit(): installLockCleanup() does for stdio, and run() does for
446+
// Streamable HTTP, whose signals first close the listener (#5595).
447+
export function installExitLockCleanup(): void {
448+
if (exitLockCleanupInstalled) {
449+
return;
450+
}
451+
exitLockCleanupInstalled = true;
452+
process.on("exit", releaseHeldLocks);
453+
}
454+
441455
// Release held locks however the server process ends (#5485): on a normal
442456
// exit or process.exit() through the `exit` event, and on SIGINT or SIGTERM,
443457
// whose default action would end the process without emitting `exit`. A
@@ -449,7 +463,7 @@ export function installLockCleanup(): void {
449463
return;
450464
}
451465
lockCleanupInstalled = true;
452-
process.on("exit", releaseHeldLocks);
466+
installExitLockCleanup();
453467
for (const [signal, code] of Object.entries(SIGNAL_EXIT_CODES)) {
454468
process.on(signal, () => process.exit(code));
455469
}
@@ -1781,7 +1795,10 @@ export function parseTransport(args: string[]): TransportName {
17811795

17821796
// Start the server on the transport args names, and hand back how to stop
17831797
// it. Streamable HTTP listens on HOST:PORT (loopback:3001 by default) and also
1784-
// stops, exiting the process, on SIGINT or SIGTERM.
1798+
// stops, exiting the process, on SIGINT or SIGTERM. Closing the listener does
1799+
// not wait for a tool call that is mid-write, so the exit that follows still
1800+
// goes through the lock cleanup (#5595); a second signal does not wait for
1801+
// the close either, and exits with the status the signal's default would give.
17851802
export async function run(
17861803
args: string[] = process.argv.slice(2),
17871804
): Promise<{ close: () => Promise<void> }> {
@@ -1799,17 +1816,24 @@ export async function run(
17991816
console.error(
18001817
`Knowledge Graph MCP Server running on Streamable HTTP at ${running.url}`,
18011818
);
1802-
const stop = () => {
1803-
running.close().then(
1804-
() => process.exit(0),
1805-
(error: unknown) => {
1806-
console.error("Error shutting down:", error);
1807-
process.exit(1);
1808-
},
1809-
);
1819+
installExitLockCleanup();
1820+
let stopping = false;
1821+
const stop = (signal: keyof typeof SIGNAL_EXIT_CODES) => {
1822+
if (stopping) {
1823+
process.exit(SIGNAL_EXIT_CODES[signal]);
1824+
} else {
1825+
stopping = true;
1826+
running.close().then(
1827+
() => process.exit(0),
1828+
(error: unknown) => {
1829+
console.error("Error shutting down:", error);
1830+
process.exit(1);
1831+
},
1832+
);
1833+
}
18101834
};
1811-
process.once("SIGINT", stop);
1812-
process.once("SIGTERM", stop);
1835+
process.on("SIGINT", () => stop("SIGINT"));
1836+
process.on("SIGTERM", () => stop("SIGTERM"));
18131837
return running;
18141838
}
18151839

0 commit comments

Comments
 (0)