From d104316e8e3b70402c60a395d076097a6aed8551 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:22 -0500 Subject: [PATCH 01/16] test(memory): pin what a save does when the graph file path is a symlink Reads follow the link to its target; a save's atomic rename replaces the link itself with a regular file holding the whole graph, and the link's former target is left byte-for-byte unchanged. Characterization only, no behavior change. POSIX only, like the other symlink tests in the suite. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .../__tests__/graph-path-symlink.test.ts | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/memory/__tests__/graph-path-symlink.test.ts diff --git a/src/memory/__tests__/graph-path-symlink.test.ts b/src/memory/__tests__/graph-path-symlink.test.ts new file mode 100644 index 0000000000..37391e0730 --- /dev/null +++ b/src/memory/__tests__/graph-path-symlink.test.ts @@ -0,0 +1,87 @@ +// Characterization tests for a graph file path that is itself a symlink +// (#5644), a routine setup when an operator points MEMORY_FILE_PATH at another +// volume or a backup location. The README promises atomic saves by rename and +// is silent on symlinks, so these pin what the server does today, driven +// through an SDK Client over an in-memory transport: reads follow the link to +// its target, and a save's rename lands on the path itself, replacing the link +// with a regular file that holds the whole graph and leaving the link's former +// target byte-for-byte unchanged. They pin current behavior and do not endorse +// it; whether a save should write through the link is a separate decision. +// POSIX only: creating a symlink on Windows needs privileges, as in +// persistence.test.ts. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { promises as fs } from "fs"; +import path from "path"; +import { call, connect, makeTempGraph, readFileText } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +const old = { name: "Old", entityType: "t", observations: [] }; +const added = { name: "New", entityType: "t", observations: [] }; + +describe.skipIf(process.platform === "win32")( + "memory server when the graph file path is a symlink", + () => { + let linkPath: string; + let targetPath: string; + let cleanup: () => Promise; + let conn: Connection | undefined; + + beforeEach(async () => { + let dir: string; + ({ dir, filePath: linkPath, cleanup } = await makeTempGraph()); + conn = undefined; + targetPath = path.join(dir, "real.jsonl"); + await fs.writeFile( + targetPath, + JSON.stringify({ type: "entity", ...old }) + "\n", + ); + await fs.symlink(targetPath, linkPath); + }); + + afterEach(async () => { + await conn?.close(); + await cleanup(); + }); + + async function entityNames(connection: Connection): Promise { + const { structuredContent } = await call(connection.client, "read_graph"); + const { entities } = structuredContent as { + entities: { name: string }[]; + }; + return entities.map((e) => e.name); + } + + it("reads the graph through the symlink and leaves the link in place", async () => { + conn = await connect(linkPath); + + expect(await entityNames(conn)).toEqual(["Old"]); + expect((await fs.lstat(linkPath)).isSymbolicLink()).toBe(true); + expect(await fs.readlink(linkPath)).toBe(targetPath); + }); + + it("replaces the symlink with a regular file on write and leaves the target untouched", async () => { + const targetBefore = await readFileText(targetPath); + conn = await connect(linkPath); + + const result = await call(conn.client, "create_entities", { + entities: [added], + }); + expect(result.isError).toBeFalsy(); + + // The rename lands on the path itself: the link is gone, and the path + // is a regular file holding the whole graph, old and new. + const stat = await fs.lstat(linkPath); + expect(stat.isSymbolicLink()).toBe(false); + expect(stat.isFile()).toBe(true); + expect(await entityNames(conn)).toEqual(["Old", "New"]); + + // A fresh server over the same path reads the same graph back. + await conn.close(); + conn = await connect(linkPath); + expect(await entityNames(conn)).toEqual(["Old", "New"]); + + // The link's former target was never written through it. + expect(await readFileText(targetPath)).toBe(targetBefore); + }); + }, +); From 9ff9867d58b54cde658149e754c32f9c04b9c343 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:37 -0500 Subject: [PATCH 02/16] docs(memory): say what happens to lines of the memory file the server cannot read Which line shapes are skipped, which of them log to stderr and which do not, that every save keeps them and they count toward MEMORY_MAX_FILE_BYTES, that no tool reaches them, and that the fix is a hand edit with the clients stopped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..2d32338f11 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -318,6 +318,17 @@ By default nothing caps the graph. Set `MEMORY_MAX_ENTITIES`, `MEMORY_MAX_RELATI - The delete tools are never refused, so a graph over a limit (one that grew before the limit was set, or lowered) can always be shrunk. While it is over, calls that would grow it further on that dimension are refused. - `MEMORY_MAX_FILE_BYTES` counts the bytes of the file as it would be saved, unreadable lines included, so it bounds the cost of each write directly. The counts are easier to reason about but do not bound how long each entity's observations grow. +#### Lines the server cannot read + +Each line of the memory file is expected to be one JSON object with `"type": "entity"` or `"type": "relation"` and the fields described under [Core Concepts](#core-concepts). The server reads the whole file on every tool call, and leaves any other non-blank line out of the graph it loads: a line that is not JSON, a JSON value that is not an object (a number, a string, `null`), a JSON array, an object whose `type` is missing or is neither `entity` nor `relation`, and an entity or relation that fails its schema (an entity with no `entityType`, an observation that is not a string, a relation with no `relationType`, say). + +- **Most skipped lines are logged to stderr, not all.** A line that is not JSON logs `Skipping malformed line in memory file`, a non-object value logs `Skipping non-object line in memory file`, and an entity or relation that fails its schema logs `Skipping invalid entity in memory file:` or `Skipping invalid relation in memory file:` followed by the fields at fault. A JSON array, and an object whose `type` is missing or unknown, are skipped without a message. The messages repeat each time the file is read, so on every tool call. +- **Skipped lines are kept.** Every save writes them back unchanged, after the graph's own lines, so a write never drops data the server could not read. Blank lines are not kept: a save removes them. +- **Skipped lines count toward `MEMORY_MAX_FILE_BYTES`**, since they are part of the file each save writes. +- **No tool can reach a skipped line.** `read_graph`, `search_nodes` and `open_nodes` do not show it. `delete_entities` and `delete_observations` report its name as not found, and `add_observations` and `create_relations` refuse it as an entity that does not exist. `create_entities` under the same name stores a second record beside the skipped line rather than replacing it. A skipped relation matches no `delete_relations` call, and stays in the file after the entities it names are deleted. + +**The only fix is to edit the file by hand.** Quit every MCP client using the memory file, so that no server writes it while you work, then correct or delete the line in a text editor and start the clients again. A stderr line from the list above, or a `not found` for an entity you can see in the file, is the sign to look. + # VS Code Installation Instructions For quick installation, use one of the one-click installation buttons below: From c26881969a089cef0489c4e9180228cb44f24c2a Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:41 -0500 Subject: [PATCH 03/16] test(memory): pin the neighbouring faces of three pinned invariants Adds protocol-level characterization tests for the sibling faces of rules already pinned elsewhere: delete_relations' exact match also rejects a space-padded relation type; entity identity is case-sensitive while search_nodes is case-insensitive; and observationCount agrees with delete_observations on the next read. Each request names every item once. Test-only; no behavior change. Proposed by @reservoir-cmyk in #5645. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/sibling-faces.test.ts | 115 +++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 src/memory/__tests__/sibling-faces.test.ts diff --git a/src/memory/__tests__/sibling-faces.test.ts b/src/memory/__tests__/sibling-faces.test.ts new file mode 100644 index 0000000000..f1b7842287 --- /dev/null +++ b/src/memory/__tests__/sibling-faces.test.ts @@ -0,0 +1,115 @@ +// Characterization tests for the neighbouring faces of invariants the memory +// server already pins on one face (#5645), driven through an SDK Client over +// an in-memory transport. Each case re-measures a pinned rule on its sibling: +// - delete_relations' exact-match rule is pinned for a different type +// (tools.test.ts); here it is a type padded with a space, which is not the +// same type, so nothing is deleted and the relation survives. +// - search_nodes' case-insensitivity is pinned on the read face +// (knowledge-graph.test.ts); here the write face's identity is shown to be +// case-sensitive, so "Test" and "test" coexist and one search finds both. +// The docs are silent on this asymmetry: it is characterization. +// - observationCount is computed at read time; here it is read right after +// delete_observations, so a stale total would show. +// Every request names each item once, so these hold whatever the server does +// with repeated items in one request. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import type { Client } from "@modelcontextprotocol/client"; +import { call, connect, makeTempGraph } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +describe("neighbouring faces of pinned invariants (#5645)", () => { + let conn: Connection; + let client: Client; + let cleanup: () => Promise; + + beforeEach(async () => { + const graph = await makeTempGraph(); + cleanup = graph.cleanup; + conn = await connect(graph.filePath); + client = conn.client; + }); + + afterEach(async () => { + await conn.close(); + await cleanup(); + }); + + // The structured result of a call that must succeed. + async function structured(name: string, args: Record = {}) { + const result = await call(client, name, args); + expect(result.isError).toBeFalsy(); + return result.structuredContent; + } + + it("delete_relations deletes nothing for a relation type padded with a space", async () => { + const a = { name: "A", entityType: "t", observations: [] }; + const b = { name: "B", entityType: "t", observations: [] }; + const knows = { from: "A", to: "B", relationType: "knows" }; + await structured("create_entities", { entities: [a, b] }); + await structured("create_relations", { relations: [knows] }); + + for (const padded of ["knows ", " knows"]) { + expect( + await structured("delete_relations", { + relations: [{ ...knows, relationType: padded }], + }), + ).toEqual({ + success: true, + message: "Deleted 0 of 1 relations. The rest matched nothing.", + }); + expect(await structured("read_graph")).toEqual({ + entities: [a, b], + relations: [knows], + }); + } + + expect( + await structured("delete_relations", { relations: [knows] }), + ).toEqual({ success: true, message: "Relations deleted successfully" }); + expect(await structured("read_graph")).toEqual({ + entities: [a, b], + relations: [], + }); + }); + + it("keeps 'Test' and 'test' as distinct entities, and a search in either case finds both", async () => { + const upper = { name: "Test", entityType: "T", observations: [] }; + const lower = { name: "test", entityType: "T", observations: [] }; + await structured("create_entities", { entities: [upper, lower] }); + + expect(await structured("read_graph")).toEqual({ + entities: [upper, lower], + relations: [], + }); + for (const query of ["test", "TEST"]) { + expect(await structured("search_nodes", { query })).toEqual({ + entities: [upper, lower], + relations: [], + }); + } + }); + + it("observationCount agrees with delete_observations on the next read", async () => { + await structured("create_entities", { + entities: [ + { name: "E", entityType: "t", observations: ["O1", "O2", "O3"] }, + ], + }); + expect( + await structured("delete_observations", { + deletions: [{ entityName: "E", observations: ["O1"] }], + }), + ).toEqual({ success: true, message: "Observations deleted successfully" }); + + expect(await structured("read_graph", { observationLimit: 0 })).toEqual({ + entities: [ + { name: "E", entityType: "t", observations: [], observationCount: 2 }, + ], + relations: [], + }); + expect(await structured("read_graph")).toEqual({ + entities: [{ name: "E", entityType: "t", observations: ["O2", "O3"] }], + relations: [], + }); + }); +}); From 9167dc56c9e68c355c6cf79e1eca48e120e9fb6f Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:23:51 -0500 Subject: [PATCH 04/16] fix(memory): store a repeated observation once in create_entities create_entities pushed the requested entities unchanged, so a string repeated within one entity's observations was stored twice, unlike add_observations (#5201), and delete_observations then reported deleting more than it was asked to. Dedupe each new entity's observations in place: skippedEntityNames tells created entities apart by identity, so mapped copies would report every entity as skipped. Closes #5653 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- ...y-create-entities-repeated-observations.md | 5 ++ src/memory/README.md | 1 + .../create-repeated-observations.test.ts | 72 +++++++++++++++++++ src/memory/index.ts | 6 ++ 4 files changed, 84 insertions(+) create mode 100644 .changeset/memory-create-entities-repeated-observations.md create mode 100644 src/memory/__tests__/create-repeated-observations.test.ts diff --git a/.changeset/memory-create-entities-repeated-observations.md b/.changeset/memory-create-entities-repeated-observations.md new file mode 100644 index 0000000000..91a0223528 --- /dev/null +++ b/.changeset/memory-create-entities-repeated-observations.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +`create_entities` now stores a string repeated within one entity's observations once, as `add_observations` does, so a later `delete_observations` reports the count it was asked for. diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..56c4876829 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -71,6 +71,7 @@ Example: - `name` (string): Entity identifier - `entityType` (string): Type classification - `observations` (string[]): Associated observations + - A string repeated within one entity's `observations` is stored once, as `add_observations` does - Ignores entities with existing names (and repeats of a name earlier in the same call); their observations are not added - Returns the created entities. When any were skipped, the structured result also lists their names in `skipped`, and a second text item says which were skipped (use `add_observations` to extend an existing entity) diff --git a/src/memory/__tests__/create-repeated-observations.test.ts b/src/memory/__tests__/create-repeated-observations.test.ts new file mode 100644 index 0000000000..700096cad7 --- /dev/null +++ b/src/memory/__tests__/create-repeated-observations.test.ts @@ -0,0 +1,72 @@ +// Regression tests for #5653, driven through an SDK Client over an in-memory +// transport: create_entities stores a string repeated within one entity's +// observations once, as add_observations does since #5201. A stored repeat +// would otherwise make delete_observations report deleting more than it was +// asked to. The fix dedupes in place, so these tests also check that the +// skip report, which tells created entities apart by identity, still holds. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { call, connect, makeTempGraph, textOf } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +describe("create_entities with repeated observations (#5653)", () => { + let cleanup: () => Promise; + let conn: Connection; + + beforeEach(async () => { + const graph = await makeTempGraph(); + cleanup = graph.cleanup; + conn = await connect(graph.filePath); + }); + + afterEach(async () => { + await conn.close(); + await cleanup(); + }); + + async function observationsOf(name: string): Promise { + const result = await call(conn.client, "open_nodes", { names: [name] }); + const { entities } = result.structuredContent as { + entities: { observations: string[] }[]; + }; + return entities[0].observations; + } + + it("stores and returns an observation repeated in one entity once", async () => { + const result = await call(conn.client, "create_entities", { + entities: [ + { name: "A", entityType: "thing", observations: ["x", "y", "x"] }, + ], + }); + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual({ + entities: [{ name: "A", entityType: "thing", observations: ["x", "y"] }], + }); + expect(await observationsOf("A")).toEqual(["x", "y"]); + }); + + it("lets delete_observations report the count it was asked for", async () => { + await call(conn.client, "create_entities", { + entities: [{ name: "A", entityType: "thing", observations: ["x", "x"] }], + }); + const result = await call(conn.client, "delete_observations", { + deletions: [{ entityName: "A", observations: ["x"] }], + }); + expect(result.isError).toBeUndefined(); + expect(textOf(result)).toBe("Observations deleted successfully"); + expect(await observationsOf("A")).toEqual([]); + }); + + it("still reports a skipped entity alongside a deduped one", async () => { + const result = await call(conn.client, "create_entities", { + entities: [ + { name: "A", entityType: "thing", observations: ["x", "x"] }, + { name: "A", entityType: "thing", observations: ["z"] }, + ], + }); + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual({ + entities: [{ name: "A", entityType: "thing", observations: ["x"] }], + skipped: ["A"], + }); + }); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..ae0c3edee1 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -1198,6 +1198,12 @@ export class KnowledgeGraphManager { // Also skip duplicates appearing earlier in this same batch !entities.slice(0, index).some((earlier) => earlier.name === e.name), ); + // A string repeated within one entity's observations is stored once, as + // add_observations does (#5201, #5653). In place, not mapped copies: + // skippedEntityNames tells created entities apart by identity. + for (const e of newEntities) { + e.observations = [...new Set(e.observations)]; + } graph.entities.push(...newEntities); // Only a call that adds something is held to the limits: re-saving can // grow an existing file that was not written in this exact form. From edb349e3cf443893df273538957cc504810ed940 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:24:42 -0500 Subject: [PATCH 05/16] fix(memory): report relations create_relations skipped create_relations returned a bare empty list for a relation that already exists, so an agent could not tell "already there" from "nothing happened". Mirror create_entities: list the skipped relations (existing, or repeated earlier in the same call) in an optional `skipped` field of structuredContent, add a text notice naming them, and say so in the tool description and README. Closes #5654 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-create-relations-skipped.md | 5 ++ src/memory/README.md | 3 +- src/memory/__tests__/tools.test.ts | 41 ++++++++++++++-- src/memory/__tests__/write-limits.test.ts | 5 +- src/memory/index.ts | 48 +++++++++++++++++-- 5 files changed, 92 insertions(+), 10 deletions(-) create mode 100644 .changeset/memory-create-relations-skipped.md diff --git a/.changeset/memory-create-relations-skipped.md b/.changeset/memory-create-relations-skipped.md new file mode 100644 index 0000000000..21e2c5f301 --- /dev/null +++ b/.changeset/memory-create-relations-skipped.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +`create_relations` now reports the relations it skipped because they already exist (or repeat an earlier relation in the same call): the structured result lists them in a new optional `skipped` array, a second text item names them, and the tool description says so. Skipped relations are still not added again ([#5654](https://github.com/modelcontextprotocol/servers/issues/5654)). diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..df5e96abda 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -81,7 +81,8 @@ Example: - `from` (string): Source entity name - `to` (string): Target entity name - `relationType` (string): Relationship type in active voice - - Skips duplicate relations + - Skips relations that already exist (and repeats of a relation earlier in the same call) + - Returns the created relations. When any were skipped, the structured result also lists them in `skipped`, and a second text item says which were skipped - Fails if either the source or target entity doesn't exist - **add_observations** diff --git a/src/memory/__tests__/tools.test.ts b/src/memory/__tests__/tools.test.ts index 8fc5cfeaff..725dbb4100 100644 --- a/src/memory/__tests__/tools.test.ts +++ b/src/memory/__tests__/tools.test.ts @@ -162,7 +162,7 @@ const expectedTools = [ name: "create_relations", title: "Create Relations", description: - "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice", + "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice. A relation already in the graph, or that repeats an earlier relation in the same call, is skipped; the result lists the skipped relations in `skipped`.", inputSchema: { type: "object", properties: { @@ -178,7 +178,10 @@ const expectedTools = [ }, outputSchema: { type: "object", - properties: { relations: { type: "array", items: relationItem(true) } }, + properties: { + relations: { type: "array", items: relationItem(true) }, + skipped: { type: "array", items: relationItem(true) }, + }, required: ["relations"], $schema: JSON_SCHEMA_2020_12, additionalProperties: false, @@ -653,20 +656,52 @@ describe("memory tools over the protocol", () => { ); }); - it("skips relations that already exist or repeat within the batch", async () => { + it("skips relations that already exist or repeat within the batch, and reports them (#5654)", async () => { await call(client, "create_relations", { relations: [aliceKnowsBob] }); const result = await call(client, "create_relations", { relations: [aliceKnowsBob, aliceWorksAtAcme, aliceWorksAtAcme], }); + expect(result.isError).toBeUndefined(); expect(result.structuredContent).toEqual({ relations: [aliceWorksAtAcme], + skipped: [aliceKnowsBob, aliceWorksAtAcme], }); + expect(result.content).toEqual([ + { type: "text", text: JSON.stringify([aliceWorksAtAcme], null, 2) }, + { + type: "text", + text: `Skipped 2 relations that already exist: Alice -[${aliceKnowsBob.relationType}]-> Bob, Alice -[${aliceWorksAtAcme.relationType}]-> ${aliceWorksAtAcme.to}. They are already in the graph, so nothing was added for them.`, + }, + ]); expect(await readGraph()).toEqual({ entities: [alice, bob, acme], relations: [aliceKnowsBob, aliceWorksAtAcme], }); }); + it("reports a repeated call's relation as skipped rather than returning a bare empty list (#5654)", async () => { + await call(client, "create_relations", { relations: [aliceKnowsBob] }); + const result = await call(client, "create_relations", { + relations: [aliceKnowsBob], + }); + expect(result.isError).toBeUndefined(); + expect(result.structuredContent).toEqual({ + relations: [], + skipped: [aliceKnowsBob], + }); + expect(result.content).toEqual([ + { type: "text", text: "[]" }, + { + type: "text", + text: `Skipped 1 relation that already exists: Alice -[${aliceKnowsBob.relationType}]-> Bob. It is already in the graph, so nothing was added for it.`, + }, + ]); + expect(await readGraph()).toEqual({ + entities: [alice, bob, acme], + relations: [aliceKnowsBob], + }); + }); + it("treats a different relation type between the same pair as new", async () => { const aliceManagesBob = { ...aliceKnowsBob, relationType: "manages" }; await call(client, "create_relations", { relations: [aliceKnowsBob] }); diff --git a/src/memory/__tests__/write-limits.test.ts b/src/memory/__tests__/write-limits.test.ts index 4e81d934a8..a9ea86705d 100644 --- a/src/memory/__tests__/write-limits.test.ts +++ b/src/memory/__tests__/write-limits.test.ts @@ -220,7 +220,10 @@ describe("write limits", () => { relations: [{ from: "A", to: "B", relationType: "knows" }], }); expect(repeat.isError).toBeUndefined(); - expect(repeat.structuredContent).toEqual({ relations: [] }); + expect(repeat.structuredContent).toEqual({ + relations: [], + skipped: [{ from: "A", to: "B", relationType: "knows" }], + }); }); }); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..90d1996275 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -180,6 +180,29 @@ export function skippedEntitiesNotice(skipped: string[]): string { ); } +// Requested relations that createRelations did not create: the relation +// already existed, or repeated an earlier one in the same batch (#5654). +// createRelations returns the requested relation objects themselves, so +// identity tells them apart, as it does for skippedEntityNames. +export function skippedRelations( + requested: Relation[], + created: Relation[], +): Relation[] { + return requested.filter((r) => !created.includes(r)); +} + +// Text telling the agent which relations create_relations skipped. +export function skippedRelationsNotice(skipped: Relation[]): string { + const one = skipped.length === 1; + const listed = skipped + .map((r) => `${r.from} -[${r.relationType}]-> ${r.to}`) + .join(", "); + return ( + `Skipped ${skipped.length} ${one ? "relation that already exists" : "relations that already exist"}: ` + + `${listed}. ${one ? "It is" : "They are"} already in the graph, so nothing was added for ${one ? "it" : "them"}.` + ); +} + // Opt-in ceilings on how large the write tools may grow the graph (#5525). // Every mutation reads the whole graph file and writes it back under the // cross-process lock, so its cost, and how long it holds the lock, grow @@ -1646,7 +1669,7 @@ export function createServer( { title: "Create Relations", description: - "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice", + "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice. A relation already in the graph, or that repeats an earlier relation in the same call, is skipped; the result lists the skipped relations in `skipped`.", inputSchema: z.object({ relations: z .array(RelationSchema) @@ -1656,6 +1679,8 @@ export function createServer( }), outputSchema: z.object({ relations: z.array(RelationSchema), + // Present only when at least one requested relation was skipped. + skipped: z.array(RelationSchema).optional(), }), annotations: { readOnlyHint: false, @@ -1667,11 +1692,24 @@ export function createServer( async ({ relations }) => { const result = await knowledgeGraphManager.createRelations(relations); notifyGraphUpdated(); + // Existing relations are ignored. Say so, as create_entities does: + // otherwise an empty result reads as nothing having happened (#5654). + const skipped = skippedRelations(relations, result); + const content = [ + { type: "text" as const, text: JSON.stringify(result, null, 2) }, + ]; + if (skipped.length > 0) { + content.push({ + type: "text" as const, + text: skippedRelationsNotice(skipped), + }); + } return { - content: [ - { type: "text" as const, text: JSON.stringify(result, null, 2) }, - ], - structuredContent: { relations: result }, + content, + structuredContent: + skipped.length > 0 + ? { relations: result, skipped } + : { relations: result }, }; }, ); From 2b64c89517c87398d61723a3e896c3b1022ae137 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:24:58 -0500 Subject: [PATCH 06/16] fix(memory): count a repeated delete request item once delete_relations and delete_observations compared the number of stored records removed with the raw request length, so a relation or observation listed twice reported "Deleted 1 of 2 ... The rest matched nothing" although both items matched the same record. Both now count distinct requested items: (from, to, relationType) for relations, keyed collision-free by JSON-encoding the three fields, and (entityName, observation) pairs for observations. The methods count distinct requested items that matched rather than records removed, so a requested item stored twice counts once and the message can never read "Deleted 2 of 1". The response shape and wording are unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-delete-repeated-items.md | 5 + src/memory/README.md | 4 +- src/memory/__tests__/tools.test.ts | 142 +++++++++++++++++++++ src/memory/index.ts | 65 ++++++++-- 4 files changed, 204 insertions(+), 12 deletions(-) create mode 100644 .changeset/memory-delete-repeated-items.md diff --git a/.changeset/memory-delete-repeated-items.md b/.changeset/memory-delete-repeated-items.md new file mode 100644 index 0000000000..a48f98e3a7 --- /dev/null +++ b/.changeset/memory-delete-repeated-items.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +`delete_relations` and `delete_observations` count a request item listed more than once as one item, so a repeated relation or observation no longer reports "Deleted 1 of 2" as if part of the deletion missed. A requested observation or relation stored more than once also counts once. diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..e1ba22400f 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -106,7 +106,7 @@ Example: - Each object contains: - `entityName` (string): Target entity - `observations` (string[]): Observations to remove - - No error if an observation doesn't exist; the response reports how many were deleted + - No error if an observation doesn't exist; the response reports how many of the requested observations were deleted, counting an observation listed more than once for the same entity as one - **delete_relations** - Remove specific relations from the graph, keeping the entities they connect (to remove an entity itself, use `delete_entities`) @@ -116,7 +116,7 @@ Example: - `to` (string): Target entity name - `relationType` (string): Relationship type - A relation is deleted only when `from`, `to` and `relationType` all match a stored one exactly; read the stored `relationType` with `open_nodes` (or `search_nodes`) first if unsure - - No error if a relation doesn't exist; the response reports how many were deleted + - No error if a relation doesn't exist; the response reports how many of the requested relations were deleted, counting a relation listed more than once as one - **read_graph** - Read the entire knowledge graph diff --git a/src/memory/__tests__/tools.test.ts b/src/memory/__tests__/tools.test.ts index 8fc5cfeaff..c150b2264c 100644 --- a/src/memory/__tests__/tools.test.ts +++ b/src/memory/__tests__/tools.test.ts @@ -3,6 +3,7 @@ // sees today: the advertised tool list, each tool's text and // structured results, and the error results. A test that pins a known bug // cites its issue, so the PR that fixes it has a test to change. +import { promises as fs } from "fs"; import { describe, it, expect, beforeEach, afterEach } from "vitest"; import type { Client } from "@modelcontextprotocol/client"; import { call, connect, makeTempGraph, textOf } from "./helpers.js"; @@ -424,10 +425,12 @@ describe("memory tools over the protocol", () => { let conn: Connection; let client: Client; let cleanup: () => Promise; + let filePath: string; beforeEach(async () => { const graph = await makeTempGraph(); cleanup = graph.cleanup; + filePath = graph.filePath; conn = await connect(graph.filePath); client = conn.client; }); @@ -449,6 +452,24 @@ describe("memory tools over the protocol", () => { return (await call(client, "read_graph")).structuredContent; } + // Write the graph file directly, one JSON record per line, for stored + // states the tools themselves do not produce (duplicate records, say). + async function writeGraphFile(records: object[]) { + await fs.writeFile( + filePath, + records.map((r) => JSON.stringify(r)).join("\n") + "\n", + ); + } + + // The result every delete tool returns: the message as text and as + // structured content. + function deleteResult(message: string) { + return { + content: [{ type: "text", text: message }], + structuredContent: { success: true, message }, + }; + } + describe("server identity and tool list", () => { it("reports its name, the package version and its capabilities", async () => { expect(client.getServerVersion()).toEqual({ @@ -873,6 +894,69 @@ describe("memory tools over the protocol", () => { structuredContent: { success: true, message }, }); }); + + // #5655: a repeated request item matches the same stored observation, so + // it is one item, not a miss. + it("counts an observation repeated in one entry once", async () => { + const result = await call(client, "delete_observations", { + deletions: [ + { entityName: "Alice", observations: ["likes tea", "likes tea"] }, + ], + }); + expect(result).toEqual(deleteResult("Observations deleted successfully")); + expect(await call(client, "open_nodes", { names: ["Alice"] })).toEqual( + expect.objectContaining({ + structuredContent: { + entities: [{ ...alice, observations: ["works at Acme Corp"] }], + relations: [aliceKnowsBob, aliceWorksAtAcme], + }, + }), + ); + }); + + it("counts an observation repeated across entries for one entity once", async () => { + const result = await call(client, "delete_observations", { + deletions: [ + { entityName: "Alice", observations: ["likes tea"] }, + { entityName: "Alice", observations: ["likes tea"] }, + ], + }); + expect(result).toEqual(deleteResult("Observations deleted successfully")); + }); + + it("counts a repeated observation once next to one that is not there", async () => { + const result = await call(client, "delete_observations", { + deletions: [ + { + entityName: "Alice", + observations: ["likes tea", "likes tea", "never said"], + }, + ], + }); + expect(result).toEqual(deleteResult("Deleted 1 of 2 observations.")); + }); + + it("counts a requested observation stored twice once", async () => { + await writeGraphFile([ + { + type: "entity", + name: "Alice", + entityType: "person", + observations: ["likes tea", "likes tea", "works at Acme Corp"], + }, + ]); + expect( + await call(client, "delete_observations", { + deletions: [ + { entityName: "Alice", observations: ["likes tea", "never said"] }, + ], + }), + ).toEqual(deleteResult("Deleted 1 of 2 observations.")); + expect(await readGraph()).toEqual({ + entities: [{ ...alice, observations: ["works at Acme Corp"] }], + relations: [], + }); + }); }); describe("delete_relations", () => { @@ -918,6 +1002,64 @@ describe("memory tools over the protocol", () => { structuredContent: { success: true, message }, }); }); + + // #5655: a repeated request item matches the same stored relation, so it + // is one item, not a miss. + it("counts a relation repeated in the request once", async () => { + const result = await call(client, "delete_relations", { + relations: [aliceKnowsBob, { ...aliceKnowsBob }], + }); + expect(result).toEqual(deleteResult("Relations deleted successfully")); + expect(await readGraph()).toEqual({ + entities: [alice, bob, acme], + relations: [aliceWorksAtAcme], + }); + }); + + it("counts a repeated relation once next to one that matched nothing", async () => { + const result = await call(client, "delete_relations", { + relations: [ + aliceKnowsBob, + aliceKnowsBob, + { ...aliceKnowsBob, relationType: "likes" }, + ], + }); + expect(result).toEqual( + deleteResult("Deleted 1 of 2 relations. The rest matched nothing."), + ); + }); + + it("counts a requested relation stored twice once", async () => { + await writeGraphFile([ + { type: "entity", ...alice }, + { type: "entity", ...bob }, + { type: "relation", ...aliceKnowsBob }, + { type: "relation", ...aliceKnowsBob }, + ]); + expect( + await call(client, "delete_relations", { relations: [aliceKnowsBob] }), + ).toEqual(deleteResult("Relations deleted successfully")); + expect(await readGraph()).toEqual({ + entities: [alice, bob], + relations: [], + }); + }); + + it("tells relations apart whose fields would join to the same string", async () => { + const stored = { from: "x|y", to: "z", relationType: "t" }; + await writeGraphFile([ + { type: "entity", name: "x|y", entityType: "e", observations: [] }, + { type: "entity", name: "z", entityType: "e", observations: [] }, + { type: "relation", ...stored }, + ]); + expect( + await call(client, "delete_relations", { + relations: [stored, { from: "x", to: "y|z", relationType: "t" }], + }), + ).toEqual( + deleteResult("Deleted 1 of 2 relations. The rest matched nothing."), + ); + }); }); describe("read_graph", () => { diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..d605e4a8a5 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -1291,6 +1291,11 @@ export class KnowledgeGraphManager { }); } + // deletedCount is how many distinct requested (entityName, observation) + // pairs matched a stored observation, not how many stored records went: + // a pair repeated in the request counts once, and so does a pair that + // matched a stored duplicate (#5655). It never exceeds + // countDistinctObservations(deletions), which the tool compares it with. async deleteObservations( deletions: { entityName: string; observations: string[] }[], ): Promise<{ deletedCount: number; missingEntities: string[] }> { @@ -1301,11 +1306,14 @@ export class KnowledgeGraphManager { deletions.forEach((d) => { const entity = graph.entities.find((e) => e.name === d.entityName); if (entity) { - const before = entity.observations.length; + // A pair an earlier entry already removed is no longer stored, so + // it is not counted twice. + deletedCount += [...new Set(d.observations)].filter((o) => + entity.observations.includes(o), + ).length; entity.observations = entity.observations.filter( (o) => !d.observations.includes(o), ); - deletedCount += before - entity.observations.length; } else { missingEntities.push(d.entityName); } @@ -1315,12 +1323,20 @@ export class KnowledgeGraphManager { }); } + // deletedCount is how many distinct requested relations matched a stored + // one, not how many stored records went: a relation repeated in the + // request counts once, and so does one that matched a stored duplicate + // (#5655). It never exceeds countDistinctRelations(relations), which the + // tool compares it with. async deleteRelations( relations: Relation[], ): Promise<{ deletedCount: number }> { return this.withLock(async () => { const { graph, unreadable } = await this.loadGraphWithUnreadable(); - const before = graph.relations.length; + const stored = new Set(graph.relations.map(relationKey)); + const deletedCount = [...new Set(relations.map(relationKey))].filter( + (key) => stored.has(key), + ).length; graph.relations = graph.relations.filter( (r) => !relations.some( @@ -1331,7 +1347,7 @@ export class KnowledgeGraphManager { ), ); await this.saveGraph(graph, unreadable); - return { deletedCount: before - graph.relations.length }; + return { deletedCount }; }); } @@ -1470,6 +1486,37 @@ function limitObservations( })); } +// A relation's identity as one string, for Set lookups. JSON-encoding the +// three fields as an array cannot collide, whatever the names hold; joining +// them with a separator could ("a|b" + "c" against "a" + "b|c"). +function relationKey(r: Relation): string { + return JSON.stringify([r.from, r.to, r.relationType]); +} + +// How many distinct relations a delete_relations request names: the same +// relation listed twice is one request item, so it can match only once +// (#5655). +function countDistinctRelations(relations: Relation[]): number { + return new Set(relations.map(relationKey)).size; +} + +// How many distinct (entityName, observation) pairs a delete_observations +// request names, whether repeated inside one entry or across entries for the +// same entity (#5655). +function countDistinctObservations( + deletions: { entityName: string; observations: string[] }[], +): number { + const byEntity = new Map>(); + for (const d of deletions) { + const observations = byEntity.get(d.entityName) ?? new Set(); + d.observations.forEach((o) => observations.add(o)); + byEntity.set(d.entityName, observations); + } + let total = 0; + byEntity.forEach((observations) => (total += observations.size)); + return total; +} + // Zod schemas for entities and relations const EntitySchema = z.object({ name: z.string().describe("The name of the entity"), @@ -1802,10 +1849,7 @@ export function createServer( const { deletedCount, missingEntities } = await knowledgeGraphManager.deleteObservations(deletions); notifyGraphUpdated(); - const requested = deletions.reduce( - (total, d) => total + d.observations.length, - 0, - ); + const requested = countDistinctObservations(deletions); const message = deletedCount === requested ? "Observations deleted successfully" @@ -1847,10 +1891,11 @@ export function createServer( const { deletedCount } = await knowledgeGraphManager.deleteRelations(relations); notifyGraphUpdated(); + const requested = countDistinctRelations(relations); const message = - deletedCount === relations.length + deletedCount === requested ? "Relations deleted successfully" - : `Deleted ${deletedCount} of ${relations.length} relations. The rest matched nothing.`; + : `Deleted ${deletedCount} of ${requested} relations. The rest matched nothing.`; return { content: [{ type: "text" as const, text: message }], structuredContent: { success: true, message }, From 90e20f77340eb9dcc1c1239128d91457b67d4e1a Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:25:50 -0500 Subject: [PATCH 07/16] fix(memory): fail every tool with an actionable error when the memory file's directory is missing When the directory holding MEMORY_FILE_PATH did not exist, reads reported an empty graph while every write failed with a raw ENOENT naming the internal .lock file. The README already promises that the server creates the memory file but not the directories above it, so keep that and make reads and writes agree: both now fail with one error naming the memory file and its directory, and pointing at MEMORY_FILE_PATH. A missing file in an existing directory is still an empty graph. Closes #5689 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-missing-directory-error.md | 5 + src/memory/README.md | 2 +- .../__tests__/missing-directory.test.ts | 158 ++++++++++++++++++ src/memory/index.ts | 44 ++++- 4 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 .changeset/memory-missing-directory-error.md create mode 100644 src/memory/__tests__/missing-directory.test.ts diff --git a/.changeset/memory-missing-directory-error.md b/.changeset/memory-missing-directory-error.md new file mode 100644 index 0000000000..fc59eb1baa --- /dev/null +++ b/.changeset/memory-missing-directory-error.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +When the directory holding `MEMORY_FILE_PATH` does not exist, every tool now fails with an error naming the memory file and its directory, instead of reads returning an empty graph while writes failed with a raw `ENOENT` on the internal `.lock` file. diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..9c5a30b1a7 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -291,7 +291,7 @@ When `MEMORY_FILE_PATH` is not set and the server directory still holds a legacy **Set `MEMORY_FILE_PATH` to an absolute path you own**, such as `~/memory.jsonl`, as in the configuration above. The default `memory.jsonl` sits in the server's own directory, next to its code. Under `npx` or an npm install, that directory is inside a `node_modules` tree, which npm manages as its own: reinstalling or updating the server, or clearing the npx cache, can delete the file and the knowledge graph in it. A relative `MEMORY_FILE_PATH` resolves against that same directory, so it has the same problem. - When the memory file it resolves is inside a `node_modules` directory, the server prints a warning on stderr at startup naming the file; most clients show a server's stderr in its log. Move the file to the new path when you set the variable, or the server starts on an empty graph. -- The directory must already exist: the server creates the memory file, not the directories above it. +- The directory must already exist: the server creates the memory file, not the directories above it. While it is missing, every tool, read or write, and the `memory://knowledge-graph` resource fail with an error naming the memory file and its directory, rather than reads reporting an empty graph that no write could save to. Create the directory (no restart is needed) or point `MEMORY_FILE_PATH` at one that exists. A missing memory file in an existing directory is an empty graph, and the first write creates it. - The default stays where it is so that existing graphs keep loading. The [Docker](#docker) setup above keeps it in a named volume mounted over `/app/dist`, so the graph there survives restarts and draws no warning. Saves are atomic. Every write tool writes the whole graph to a temporary file in the same directory and renames it over the memory file, so a server stopped or killed mid-save leaves the previous graph intact rather than a half-written file. The file's permission bits are kept across the rename. The temporary file is always newly created by the save. Writes from several processes are serialized by a lock, described next. diff --git a/src/memory/__tests__/missing-directory.test.ts b/src/memory/__tests__/missing-directory.test.ts new file mode 100644 index 0000000000..5a179e1b3b --- /dev/null +++ b/src/memory/__tests__/missing-directory.test.ts @@ -0,0 +1,158 @@ +// Tests for a memory file whose directory does not exist (#5689). The server +// creates the memory file but never the directories above it, as its README +// says, so every tool, read or write, fails with the same actionable error +// naming MEMORY_FILE_PATH. Before, reads reported an empty graph while every +// write failed with a raw ENOENT naming the internal .lock file. Driven +// through an MCP client over an in-memory transport, so each test asserts on +// what a client sees. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { promises as fs } from "fs"; +import path from "path"; +import { call, connect, makeTempGraph, textOf } from "./helpers.js"; +import type { Connection } from "./helpers.js"; + +const alice = { name: "Alice", entityType: "person", observations: ["hi"] }; + +// Every tool, with arguments it accepts. A read and a write both have to fail +// the same way, so the whole list is checked rather than one of each. +const TOOLS: ReadonlyArray]> = [ + ["read_graph", {}], + ["search_nodes", { query: "Alice" }], + ["open_nodes", { names: ["Alice"] }], + ["create_entities", { entities: [alice] }], + [ + "create_relations", + { relations: [{ from: "Alice", to: "Bob", relationType: "knows" }] }, + ], + [ + "add_observations", + { observations: [{ entityName: "Alice", contents: ["x"] }] }, + ], + ["delete_entities", { entityNames: ["Alice"] }], + [ + "delete_observations", + { deletions: [{ entityName: "Alice", observations: ["hi"] }] }, + ], + [ + "delete_relations", + { relations: [{ from: "Alice", to: "Bob", relationType: "knows" }] }, + ], +]; + +describe("a memory file whose directory does not exist", () => { + let dir: string; + let cleanup: () => Promise; + let connection: Connection | undefined; + + beforeEach(async () => { + ({ dir, cleanup } = await makeTempGraph()); + }); + + afterEach(async () => { + await connection?.close(); + connection = undefined; + await cleanup(); + }); + + function expectedError(filePath: string): string { + return ( + `The directory for the memory file ${filePath} does not exist: ${path.dirname(filePath)}. ` + + "The server creates the memory file but not the directories above it. " + + "Create that directory, or set MEMORY_FILE_PATH to a file in a directory that exists." + ); + } + + it("fails every read and write tool with an error naming MEMORY_FILE_PATH", async () => { + const filePath = path.join(dir, "missing", "memory.jsonl"); + connection = await connect(filePath); + + for (const [name, args] of TOOLS) { + const result = await call(connection.client, name, args); + expect({ name, result }).toEqual({ + name, + result: { + content: [{ type: "text", text: expectedError(filePath) }], + isError: true, + }, + }); + expect(textOf(result)).not.toContain(".lock"); + } + // Nothing was created: not the directory, and not a lock file in it. + expect(await fs.readdir(dir)).toEqual([]); + }); + + it("fails the knowledge-graph resource the same way", async () => { + const filePath = path.join(dir, "missing", "memory.jsonl"); + connection = await connect(filePath); + + await expect( + connection.client.readResource({ uri: "memory://knowledge-graph" }), + ).rejects.toThrow(expectedError(filePath)); + }); + + it("treats a file where the directory should be as a missing directory", async () => { + await fs.writeFile(path.join(dir, "not-a-dir"), ""); + const filePath = path.join(dir, "not-a-dir", "memory.jsonl"); + connection = await connect(filePath); + + const result = await call(connection.client, "create_entities", { + entities: [alice], + }); + expect(result).toEqual({ + content: [{ type: "text", text: expectedError(filePath) }], + isError: true, + }); + }); + + it("serves the graph once the directory is created, with no restart", async () => { + const filePath = path.join(dir, "later", "memory.jsonl"); + connection = await connect(filePath); + expect( + (await call(connection.client, "create_entities", { entities: [alice] })) + .isError, + ).toBe(true); + + await fs.mkdir(path.dirname(filePath)); + + expect( + (await call(connection.client, "create_entities", { entities: [alice] })) + .isError, + ).toBeUndefined(); + const graph = await call(connection.client, "read_graph"); + expect(graph.isError).toBeUndefined(); + expect(JSON.parse(textOf(graph))).toEqual({ + entities: [alice], + relations: [], + }); + }); + + it("still reads a missing file in an existing directory as an empty graph", async () => { + connection = await connect(path.join(dir, "memory.jsonl")); + + const result = await call(connection.client, "read_graph"); + expect(result.isError).toBeUndefined(); + expect(JSON.parse(textOf(result))).toEqual({ entities: [], relations: [] }); + }); + + // A directory that cannot be examined is not reported as missing: the + // stat error (EACCES here) reaches the client unchanged. Root reads through + // a mode-000 directory, so the case cannot be produced there. + it.skipIf(process.getuid?.() === 0)( + "passes through an error other than a missing directory", + async () => { + const locked = path.join(dir, "locked"); + await fs.mkdir(path.join(locked, "inner"), { recursive: true }); + await fs.chmod(locked, 0o000); + try { + connection = await connect(path.join(locked, "inner", "memory.jsonl")); + const result = await call(connection.client, "create_entities", { + entities: [alice], + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(/^EACCES/); + } finally { + await fs.chmod(locked, 0o700); + } + }, + ); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..051dc411c0 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -912,8 +912,17 @@ export class KnowledgeGraphManager { private extraFields = new WeakMap>(); private async withLock(operation: () => Promise): Promise { - const locked = () => - withFileLock(`${this.memoryFilePath}.lock`, operation, this.lockOptions); + // The directory is checked before the lock is taken, since the lock file + // is created in it: a missing one would otherwise fail as a raw ENOENT + // naming the internal .lock path (#5689). + const locked = async () => { + await this.requireMemoryDirectory(); + return withFileLock( + `${this.memoryFilePath}.lock`, + operation, + this.lockOptions, + ); + }; const result = this.mutationQueue.then(locked, locked); // Always resolve the queue itself, even if this operation failed, so a // single failed mutation doesn't permanently wedge every call after it. @@ -925,6 +934,34 @@ export class KnowledgeGraphManager { return result; } + // Throw an actionable error when the directory that holds the memory file + // does not exist (#5689). The server creates the memory file, never the + // directories above it: a missing directory is far more often a mistyped + // MEMORY_FILE_PATH or an unmounted volume than a request to create one, and + // creating it would put the graph somewhere the user did not mean. Reads and + // writes both call this, so a read no longer reports an empty graph for a + // store that no write can ever reach. + private async requireMemoryDirectory(): Promise { + const directory = path.dirname(this.memoryFilePath); + let isDirectory: boolean; + try { + isDirectory = (await fs.stat(directory)).isDirectory(); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== "ENOENT" && code !== "ENOTDIR") { + throw error; + } + isDirectory = false; + } + if (!isDirectory) { + throw new Error( + `The directory for the memory file ${this.memoryFilePath} does not exist: ${directory}. ` + + "The server creates the memory file but not the directories above it. " + + "Create that directory, or set MEMORY_FILE_PATH to a file in a directory that exists.", + ); + } + } + private async loadGraph(): Promise { return (await this.loadGraphWithUnreadable()).graph; } @@ -1009,6 +1046,9 @@ export class KnowledgeGraphManager { "code" in error && error.code === "ENOENT" ) { + // A missing file is an empty graph, but only in a directory a write + // can create it in (see requireMemoryDirectory). + await this.requireMemoryDirectory(); return { graph: { entities: [], relations: [] }, unreadable: [], From b076e507fddcd0b1635fd4fe2d218ef2541940e7 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:26:34 -0500 Subject: [PATCH 08/16] fix(memory): clear a crash-left lock guard by rename-aside, not by path Two processes clearing the same crash-left guard could remove a live guard a third took in between. The clearer now renames the guard aside, compares it with the file it judged (whose handle stays open, so its inode cannot be reused), and links a live guard back exclusively. The comment above guardPathOf() states the gap that remains. Closes #5624 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-guard-clear-race.md | 5 + src/memory/README.md | 2 +- src/memory/__tests__/guard-clearing.test.ts | 124 ++++++++++++++++++++ src/memory/index.ts | 61 +++++++++- 4 files changed, 185 insertions(+), 7 deletions(-) create mode 100644 .changeset/memory-guard-clear-race.md create mode 100644 src/memory/__tests__/guard-clearing.test.ts diff --git a/.changeset/memory-guard-clear-race.md b/.changeset/memory-guard-clear-race.md new file mode 100644 index 0000000000..78f38c70b7 --- /dev/null +++ b/.changeset/memory-guard-clear-race.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +Clearing a lock guard (`.lock.break`) left by a crash no longer deletes it by path. It is renamed aside and checked to be the file judged stale, so when two servers clear the same crash-left guard at once, the second no longer removes a live guard a third server took in between (#5624). diff --git a/src/memory/README.md b/src/memory/README.md index b119225f86..16c6ecb92d 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -302,7 +302,7 @@ Each MCP client starts its own server process, so two clients using the same `ME - 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. - 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 `.lock.break` file. It never deletes the lock where it stands: it renames it aside to a momentary `.lock..stale` file, checks that what it took is the very file it judged stale, and only then deletes it. A live lock that replaced the stale one in between is put straight back, untouched, and the breaker goes on waiting. -- The same momentary `.lock.break` file orders every hand-off of the lock, not only the breaking of a stale one. A server takes it to release its lock, and a server that has just created the lock waits until no `.lock.break` file is there, then checks the lock is still its own, before it writes. So a lock cannot be broken and taken over halfway through its holder's release, and a writer cannot start in the moment a live lock spends moved aside. A `.lock.break` file left by a crash is cleared once it is 30 seconds old, so it delays the next write by at most that long. This holds as long as no server stalls for 30 seconds in the middle of a hand-off. +- The same momentary `.lock.break` file orders every hand-off of the lock, not only the breaking of a stale one. A server takes it to release its lock, and a server that has just created the lock waits until no `.lock.break` file is there, then checks the lock is still its own, before it writes. So a lock cannot be broken and taken over halfway through its holder's release, and a writer cannot start in the moment a live lock spends moved aside. A `.lock.break` file left by a crash is cleared once it is 30 seconds old, so it delays the next write by at most that long. It is cleared the way a stale lock is broken: renamed aside to a momentary `.lock.break..stale` file and checked to be the very file judged stale, so a live `.lock.break` file another server took in its place is put back rather than deleted. This holds as long as no server stalls for 30 seconds in the middle of a hand-off. - Servers of different versions can share a memory file: the lock file, what it holds and the `.lock.break` file are the same in every version. A server at 2.2.1 or earlier takes the `.lock.break` file only to break a stale lock, so its own releases and acquisitions are not ordered this way, and the gaps described above stay open for that server (each needs a lock to go stale first). Upgrade every server sharing a file to close them. - A write that cannot get the lock within 60 seconds fails with a tool error rather than overwriting the file. - 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. diff --git a/src/memory/__tests__/guard-clearing.test.ts b/src/memory/__tests__/guard-clearing.test.ts new file mode 100644 index 0000000000..983ff42829 --- /dev/null +++ b/src/memory/__tests__/guard-clearing.test.ts @@ -0,0 +1,124 @@ +// Tests for clearing a lock guard (`.break`) left by a crash (#5624). +// Two processes can find the same crash-left guard stale at once; the one +// that clears it second must not remove a live guard a third process took in +// between. Each interleaving is staged deterministically: the clearers run in +// turn, and the other processes' steps are made from inside fs spies, at the +// exact call where they would have to land: the second clearer's removal of +// the guard path (whether it renames or unlinks it), or its put-back. Kept apart +// from file-lock.test.ts so the guard-clearing cases change independently of +// the lock's own. +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { promises as fs } from "fs"; +import path from "path"; +import { isGuardHeld } from "../index.js"; +import { makeTempGraph } from "./helpers.js"; + +const staleMs = 60_000; + +describe("clearing a guard left by a crash (#5624)", () => { + let dir: string; + let guardPath: string; + let cleanup: () => Promise; + + beforeEach(async () => { + ({ dir, cleanup } = await makeTempGraph()); + guardPath = path.join(dir, "memory.jsonl.lock.break"); + // The guard a crashed holder left behind: empty, as every guard is, and + // older than staleMs. + await fs.writeFile(guardPath, ""); + const longAgo = new Date(Date.now() - 2 * staleMs); + await fs.utimes(guardPath, longAgo, longAgo); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await cleanup(); + }); + + // Run stage once, just before the first call that removes the file at the + // guard path, by renaming it or by unlinking it: the moment a clearer that + // has judged the guard stale acts on that judgement. Returns whether it ran. + function beforeFirstRemoval(stage: () => Promise): () => boolean { + let staged = false; + const once = async (file: unknown): Promise => { + if (file === guardPath && !staged) { + staged = true; + await stage(); + } + }; + const realRename = fs.rename; + vi.spyOn(fs, "rename").mockImplementation(async (from, to) => { + await once(from); + return realRename(from, to); + }); + const realUnlink = fs.unlink; + vi.spyOn(fs, "unlink").mockImplementation(async (file) => { + await once(file); + return realUnlink(file); + }); + return () => staged; + } + + // Another process takes the guard, as tryTakeGuard does: an exclusive + // create. Its contents mark it, so the test can tell it from the stale one. + function takeGuard(owner: string): Promise { + return fs.writeFile(guardPath, owner, { flag: "wx" }); + } + + it("leaves a guard taken between two clearers' removals in place", async () => { + const staged = beforeFirstRemoval(async () => { + // Clearer B has judged the guard stale and is about to remove it. + // Before it does, clearer A, which judged the same guard, clears it, + // and process C takes a fresh guard at the same path. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + await expect(fs.access(guardPath)).rejects.toThrow(); + await takeGuard("C"); + }); + + // Clearer B. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + + expect(staged()).toBe(true); + expect(await fs.readFile(guardPath, "utf-8")).toBe("C"); + // C's guard is back under its own name, with no aside file left behind. + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock.break"]); + // And it is still judged live, so nobody clears it in its turn. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + expect(await fs.readFile(guardPath, "utf-8")).toBe("C"); + }); + + it("removes the stale guard once when two clearers find it at once", async () => { + const staged = beforeFirstRemoval(async () => { + // Clearer A gets there first; nobody takes the guard after it. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + }); + + // Clearer B finds the path empty and leaves it so. + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + + expect(staged()).toBe(true); + expect(await fs.readdir(dir)).toEqual([]); + expect(await isGuardHeld(guardPath, staleMs)).toBe(false); + }); + + it("never puts a live guard back over one created while it was aside", async () => { + beforeFirstRemoval(async () => { + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + await takeGuard("C"); + }); + const realLink = fs.link; + vi.spyOn(fs, "link").mockImplementation(async (existing, target) => { + // Clearer B has taken C's guard aside by mistake. Process D takes the + // free path before B can put C's guard back. This is the gap the + // comment above guardPathOf() leaves: C's guard cannot go back without + // replacing D's, so D's is the one kept. + await takeGuard("D"); + return realLink(existing, target); + }); + + expect(await isGuardHeld(guardPath, staleMs)).toBe(true); + + expect(await fs.readFile(guardPath, "utf-8")).toBe("D"); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl.lock.break"]); + }); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..5a1da14104 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -352,9 +352,19 @@ async function isLockStale( // holder that stops refreshing it for staleMs is presumed dead. A lock // file can go no further without a lock the kernel releases itself, which // Node offers only through a native dependency. -// - A guard left by a crash is cleared by path. Two processes clearing the -// same one at once can remove a guard a third took in between, which -// leaves that third process unguarded for its few calls (#5624). +// - A guard left by a crash is never deleted where it stands +// (clearCrashLeftGuard): it is renamed aside and compared with the file +// judged stale, as a stale lock is, so two processes clearing the same one +// at once cannot remove a guard a third took in between (#5624). A live +// guard taken aside that way is put back with an exclusive link, which +// never replaces a guard a fourth process created at the path in that +// moment. That is the gap left: should a fourth create one there between +// the rename and the link, the third's guard cannot go back without +// replacing the fourth's, so it is dropped, and the third and fourth each +// run believing they hold the guard. It takes a crash inside a guarded +// section, two clearers of that guard at once, a third process taking it +// between them, and a fourth within the two calls after. A server from +// before #5624 still clears a guard by path, with the wider gap that had. // - A server older than this change takes the guard only to break a lock. It // releases without the guard and runs as soon as it has created the lock. // Sharing a memory file with one is safe in every way it was before (same @@ -381,7 +391,8 @@ function pause(retryMs: number): Promise { // Whether a guard stands at guardPath. One left by a crash (older than // staleMs) is cleared on the way, and still reported: the caller looks again. -async function isGuardHeld( +// Exported for tests, which drive two clearers of one guard in turn. +export async function isGuardHeld( guardPath: string, staleMs: number, ): Promise { @@ -399,15 +410,53 @@ async function isGuardHeld( throw error; } try { - if ((await judgeLock(handle, staleMs)).stale) { - await fs.unlink(guardPath).catch(ignoreError); + const judged = await judgeLock(handle, staleMs); + if (judged.stale) { + await clearCrashLeftGuard(guardPath, judged); } } finally { + // Closed only once the clearing is done: while the judged guard is open + // its inode number cannot be reused by a guard created after it, so the + // comparison in clearCrashLeftGuard cannot mistake one for the other. await handle.close(); } return true; } +// Remove the guard judged stale (left by a crash) from guardPath, without +// removing a guard that replaced it there. Another process clearing the same +// guard can have removed it already, and a third can have taken the guard +// since, so a removal by path could delete that live guard (#5624). Instead +// the file at guardPath is renamed aside to a name nobody else uses, which +// is atomic and takes whichever file stands there at that instant, and what +// was taken is compared with the file that was judged. A live guard taken by +// mistake is linked back to guardPath before its aside name is removed: a +// link is created exclusively, so it never replaces a guard created at the +// path in the meantime. What that leaves is described above guardPathOf(). +async function clearCrashLeftGuard( + guardPath: string, + judged: LockJudgement, +): Promise { + const asidePath = `${guardPath}.${randomBytes(8).toString("hex")}.stale`; + try { + await fs.rename(guardPath, asidePath); + } catch { + // Gone already (another process cleared it, or its holder dropped it), + // or it cannot be moved: either way the caller looks again. + return; + } + try { + const taken = await fs.stat(asidePath, { bigint: true }); + if (taken.dev !== judged.dev || taken.ino !== judged.ino) { + // Not the guard that was judged: one taken since. Put it back. + await fs.link(asidePath, guardPath).catch(ignoreError); + } + } finally { + // The aside name only: a guard put back keeps its name at guardPath. + await fs.unlink(asidePath).catch(ignoreError); + } +} + // Take the guard if it is free, returning whether it was taken. A guard that // is held is left to its holder, unless a crash left it: that one is cleared, // for the next attempt. From f7adcea5f00cbbc2d1fb67f10b5f54c7845a3339 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:27:06 -0500 Subject: [PATCH 09/16] perf(memory): index the write methods' lookups with Set and Map The six KnowledgeGraphManager write methods matched each requested item against the loaded graph (and against earlier items in the same batch) by linear scan. They now build a Set or Map once per call: relation keys are JSON.stringify of the (from, to, relationType) tuple, which no separator in an entity name can collide, and name lookups keep the first entity of a name, as Array.prototype.find did. Behavior is unchanged. A new test checks a seeded run of 300 random writes, step by step, against a reference model holding the old scanning code, and pins separator-bearing relation keys, a hand-edited file with two same-named entities, and create_entities' skipped report. Refs #5693 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .changeset/memory-write-lookups.md | 5 + src/memory/__tests__/write-lookups.test.ts | 422 +++++++++++++++++++++ src/memory/index.ts | 101 +++-- 3 files changed, 493 insertions(+), 35 deletions(-) create mode 100644 .changeset/memory-write-lookups.md create mode 100644 src/memory/__tests__/write-lookups.test.ts diff --git a/.changeset/memory-write-lookups.md b/.changeset/memory-write-lookups.md new file mode 100644 index 0000000000..e0225e38fc --- /dev/null +++ b/.changeset/memory-write-lookups.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +The write tools (`create_entities`, `create_relations`, `add_observations`, `delete_entities`, `delete_observations`, `delete_relations`) match requested items against the graph through Set and Map lookups instead of a scan per item, so large graphs and batches write much faster and hold the file lock for less time. Results, their order and every message are unchanged. diff --git a/src/memory/__tests__/write-lookups.test.ts b/src/memory/__tests__/write-lookups.test.ts new file mode 100644 index 0000000000..ed069edffa --- /dev/null +++ b/src/memory/__tests__/write-lookups.test.ts @@ -0,0 +1,422 @@ +// Pins that the write methods' Set/Map lookups (#5693) behave exactly as the +// linear scans they replaced: same results, same order, same messages, same +// graph afterwards. A seeded run of random writes is checked step by step +// against a reference model that keeps the old scanning code, and targeted +// protocol-level cases cover what the indexes could plausibly get wrong: +// relation keys whose fields contain a separator, a hand-edited file holding +// two entities with one name (only the first was ever matched), and +// create_entities telling skipped from created by object identity. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { promises as fs } from "fs"; +import { + KnowledgeGraphManager, + type Entity, + type KnowledgeGraph, + type Relation, +} from "../index.js"; +import { call, connect, makeTempGraph, type Connection } from "./helpers.js"; + +// The write methods as they were before #5693, over an in-memory graph. +class ScanningModel { + constructor(public graph: KnowledgeGraph) {} + + createEntities(entities: Entity[]): Entity[] { + const newEntities = entities.filter( + (e, index) => + !this.graph.entities.some((x) => x.name === e.name) && + !entities.slice(0, index).some((earlier) => earlier.name === e.name), + ); + this.graph.entities.push(...newEntities); + return newEntities; + } + + createRelations(relations: Relation[]): Relation[] { + const names = new Set(this.graph.entities.map((e) => e.name)); + relations.forEach((r) => { + if (!names.has(r.from)) { + throw new Error(`Entity with name ${r.from} not found`); + } + if (!names.has(r.to)) { + throw new Error(`Entity with name ${r.to} not found`); + } + }); + const same = (a: Relation, b: Relation) => + a.from === b.from && a.to === b.to && a.relationType === b.relationType; + const newRelations = relations.filter( + (r, index) => + !this.graph.relations.some((x) => same(x, r)) && + !relations.slice(0, index).some((earlier) => same(earlier, r)), + ); + this.graph.relations.push(...newRelations); + return newRelations; + } + + addObservations( + observations: { entityName: string; contents: string[] }[], + ): { entityName: string; addedObservations: string[] }[] { + return observations.map((o) => { + const entity = this.graph.entities.find((e) => e.name === o.entityName); + if (!entity) { + throw new Error(`Entity with name ${o.entityName} not found`); + } + const newObservations = [...new Set(o.contents)].filter( + (content) => !entity.observations.includes(content), + ); + entity.observations.push(...newObservations); + return { entityName: o.entityName, addedObservations: newObservations }; + }); + } + + deleteEntities(entityNames: string[]): { + deleted: string[]; + notFound: string[]; + } { + const present = new Set(this.graph.entities.map((e) => e.name)); + const deleted = entityNames.filter((name) => present.has(name)); + const notFound = entityNames.filter((name) => !present.has(name)); + this.graph.entities = this.graph.entities.filter( + (e) => !entityNames.includes(e.name), + ); + this.graph.relations = this.graph.relations.filter( + (r) => !entityNames.includes(r.from) && !entityNames.includes(r.to), + ); + return { deleted, notFound }; + } + + deleteObservations( + deletions: { entityName: string; observations: string[] }[], + ): { deletedCount: number; missingEntities: string[] } { + let deletedCount = 0; + const missingEntities: string[] = []; + deletions.forEach((d) => { + const entity = this.graph.entities.find((e) => e.name === d.entityName); + if (entity) { + const before = entity.observations.length; + entity.observations = entity.observations.filter( + (o) => !d.observations.includes(o), + ); + deletedCount += before - entity.observations.length; + } else { + missingEntities.push(d.entityName); + } + }); + return { deletedCount, missingEntities }; + } + + deleteRelations(relations: Relation[]): { deletedCount: number } { + const before = this.graph.relations.length; + this.graph.relations = this.graph.relations.filter( + (r) => + !relations.some( + (d) => + r.from === d.from && + r.to === d.to && + r.relationType === d.relationType, + ), + ); + return { deletedCount: before - this.graph.relations.length }; + } +} + +// mulberry32: a small seeded generator, so a failure replays exactly. +function seeded(seed: number): () => number { + let a = seed; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +// A small pool, so repeats within a batch and against the graph are common. +// The separator-bearing names would collide under a joined-string key. +const NAMES = ["a", "b", "a|b", "b|c", "c", "a\u0000b", ""]; +const TYPES = ["knows", "knows|a", "b"]; +const OBSERVATIONS = ["o1", "o2", "o3", "o1|o2"]; + +type Outcome = { value: unknown } | { error: string }; + +async function outcome(run: () => unknown): Promise { + try { + return { value: await run() }; + } catch (error) { + return { error: (error as Error).message }; + } +} + +function jsonl(graph: KnowledgeGraph): string { + return ( + [ + ...graph.entities.map((e) => JSON.stringify({ type: "entity", ...e })), + ...graph.relations.map((r) => JSON.stringify({ type: "relation", ...r })), + ].join("\n") + "\n" + ); +} + +// A hand-edited starting graph: "a" appears twice, and one relation is stored +// twice, neither of which the tools themselves would ever write. +function startingGraph(): KnowledgeGraph { + return { + entities: [ + { name: "a", entityType: "first", observations: ["o1", "o1"] }, + { name: "b", entityType: "t", observations: [] }, + { name: "a", entityType: "second", observations: ["o2"] }, + { name: "a|b", entityType: "t", observations: ["o3"] }, + ], + relations: [ + { from: "a", to: "b", relationType: "knows" }, + { from: "a", to: "b", relationType: "knows" }, + { from: "a|b", to: "b", relationType: "knows" }, + ], + }; +} + +describe("write lookups (#5693)", () => { + let tmp: Awaited>; + + beforeEach(async () => { + tmp = await makeTempGraph(); + }); + + afterEach(async () => { + await tmp.cleanup(); + }); + + it("matches the scanning implementation over a seeded run of writes", async () => { + await fs.writeFile(tmp.filePath, jsonl(startingGraph())); + const manager = new KnowledgeGraphManager(tmp.filePath); + const model = new ScanningModel(startingGraph()); + const random = seeded(5693); + const pick = (items: T[]): T => + items[Math.floor(random() * items.length)]; + const some = (make: () => T): T[] => + Array.from({ length: Math.floor(random() * 5) }, make); + // Distinct items only, where a repeat within one request is what #5653 + // and #5655 change: this test pins the lookups, not those behaviors. + const distinct = (make: () => T): T[] => { + const items = some(make); + return items.filter( + (item, i) => + items.findIndex( + (other) => JSON.stringify(other) === JSON.stringify(item), + ) === i, + ); + }; + const relation = (): Relation => ({ + from: pick(NAMES), + to: pick(NAMES), + relationType: pick(TYPES), + }); + + // What the run reached, so a change to the generator cannot quietly turn + // it into 300 no-ops. + const reached = new Set(); + for (let step = 0; step < 300; step++) { + const op = Math.floor(random() * 6); + // A call that throws saves nothing, so the model rolls back with it. + const snapshot = structuredClone(model.graph); + let ours: Outcome; + let theirs: Outcome; + if (op === 0) { + const batch = some(() => ({ + name: pick(NAMES), + entityType: pick(TYPES), + observations: distinct(() => pick(OBSERVATIONS)), + })); + const created = await manager.createEntities(batch); + // The result holds the requested objects themselves, in order. + for (const e of created) { + expect(batch).toContain(e); + } + ours = { value: created }; + theirs = await outcome(() => + model.createEntities(structuredClone(batch)), + ); + } else if (op === 1) { + // Repeats are kept here: skipping them is the dedup under test. + const batch = some(relation); + ours = await outcome(() => manager.createRelations(batch)); + theirs = await outcome(() => + model.createRelations(structuredClone(batch)), + ); + } else if (op === 2) { + const batch = some(() => ({ + entityName: pick(NAMES), + contents: some(() => pick(OBSERVATIONS)), + })); + ours = await outcome(() => manager.addObservations(batch)); + theirs = await outcome(() => + model.addObservations(structuredClone(batch)), + ); + } else if (op === 3) { + // Rarely, so the graph does not empty out early. + const batch = random() < 0.3 ? distinct(() => pick(NAMES)) : []; + ours = await outcome(() => manager.deleteEntities(batch)); + theirs = await outcome(() => + model.deleteEntities(structuredClone(batch)), + ); + } else if (op === 4) { + const batch = some(() => ({ + entityName: pick(NAMES), + observations: distinct(() => pick(OBSERVATIONS)), + })); + ours = await outcome(() => manager.deleteObservations(batch)); + theirs = await outcome(() => + model.deleteObservations(structuredClone(batch)), + ); + } else { + const batch = distinct(relation); + ours = await outcome(() => manager.deleteRelations(batch)); + theirs = await outcome(() => + model.deleteRelations(structuredClone(batch)), + ); + } + if ("error" in theirs) { + model.graph = snapshot; + reached.add(`${op}:error`); + } else if (JSON.stringify(model.graph) !== JSON.stringify(snapshot)) { + reached.add(`${op}:changed`); + } + expect(ours, `step ${step}, op ${op}`).toEqual(theirs); + expect(await manager.readGraph(), `step ${step}, op ${op}`).toEqual( + model.graph, + ); + } + expect([...reached].sort()).toEqual([ + "0:changed", + "1:changed", + "1:error", + "2:changed", + "2:error", + "3:changed", + "4:changed", + "5:changed", + ]); + }); + + describe("over the protocol", () => { + let conn: Connection; + + beforeEach(async () => { + await fs.writeFile(tmp.filePath, jsonl(startingGraph())); + conn = await connect(tmp.filePath); + }); + + afterEach(async () => { + await conn.close(); + }); + + async function graph(): Promise { + return (await call(conn.client, "read_graph")).structuredContent; + } + + it("keeps relations whose fields contain a separator apart", async () => { + await call(conn.client, "create_entities", { + entities: [ + { name: "b|c", entityType: "t", observations: [] }, + { name: "c", entityType: "t", observations: [] }, + ], + }); + // Joined with "|", the second would read as a repeat of the first. + const created = await call(conn.client, "create_relations", { + relations: [ + { from: "a|b", to: "c", relationType: "knows" }, + { from: "a", to: "b|c", relationType: "knows" }, + { from: "a|b", to: "c", relationType: "knows" }, + ], + }); + expect(created.structuredContent).toEqual({ + relations: [ + { from: "a|b", to: "c", relationType: "knows" }, + { from: "a", to: "b|c", relationType: "knows" }, + ], + }); + + const deleted = await call(conn.client, "delete_relations", { + relations: [{ from: "a", to: "b|c", relationType: "knows" }], + }); + expect(deleted.isError).toBeFalsy(); + expect(await graph()).toMatchObject({ + relations: [ + { from: "a", to: "b", relationType: "knows" }, + { from: "a", to: "b", relationType: "knows" }, + { from: "a|b", to: "b", relationType: "knows" }, + { from: "a|b", to: "c", relationType: "knows" }, + ], + }); + }); + + it("deletes every stored copy of a relation, in stored order", async () => { + await call(conn.client, "delete_relations", { + relations: [{ from: "a", to: "b", relationType: "knows" }], + }); + expect(await graph()).toMatchObject({ + relations: [{ from: "a|b", to: "b", relationType: "knows" }], + }); + }); + + it("adds and deletes observations on the first of two same-named entities", async () => { + await call(conn.client, "add_observations", { + observations: [ + { entityName: "a", contents: ["o2", "o1"] }, + // A second entry for the same entity sees what the first added. + { entityName: "a", contents: ["o2", "o3"] }, + ], + }); + expect(await graph()).toMatchObject({ + entities: [ + { + name: "a", + entityType: "first", + observations: ["o1", "o1", "o2", "o3"], + }, + { name: "b" }, + { name: "a", entityType: "second", observations: ["o2"] }, + { name: "a|b" }, + ], + }); + + await call(conn.client, "delete_observations", { + deletions: [{ entityName: "a", observations: ["o1", "o3"] }], + }); + expect(await graph()).toMatchObject({ + entities: [ + { name: "a", entityType: "first", observations: ["o2"] }, + { name: "b" }, + { name: "a", entityType: "second", observations: ["o2"] }, + { name: "a|b" }, + ], + }); + }); + + it("deletes every same-named entity and every relation touching one", async () => { + await call(conn.client, "delete_entities", { entityNames: ["a"] }); + expect(await graph()).toEqual({ + entities: [ + { name: "b", entityType: "t", observations: [] }, + { name: "a|b", entityType: "t", observations: ["o3"] }, + ], + relations: [{ from: "a|b", to: "b", relationType: "knows" }], + }); + }); + + it("reports stored names and in-batch repeats as skipped, in request order", async () => { + const result = await call(conn.client, "create_entities", { + entities: [ + { name: "c", entityType: "t", observations: ["kept"] }, + { name: "a", entityType: "t", observations: ["dropped"] }, + { name: "c", entityType: "t", observations: ["dropped"] }, + { name: "d", entityType: "t", observations: [] }, + ], + }); + expect(result.structuredContent).toEqual({ + entities: [ + { name: "c", entityType: "t", observations: ["kept"] }, + { name: "d", entityType: "t", observations: [] }, + ], + skipped: ["a", "c"], + }); + }); + }); +}); diff --git a/src/memory/index.ts b/src/memory/index.ts index 6df277c4fb..b80ef76f14 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -170,6 +170,29 @@ export function skippedEntityNames( return requested.filter((e) => !created.includes(e)).map((e) => e.name); } +// The write methods match against the loaded graph through these indexes +// rather than scanning it once per requested item (#5693). + +// A relation's identity as one string. JSON.stringify of the tuple is +// collision-free: entity names are arbitrary strings, so joining the three +// fields with any separator could make two different relations share a key. +function relationKey(r: Relation): string { + return JSON.stringify([r.from, r.to, r.relationType]); +} + +// Each name's FIRST entity, the one Array.prototype.find would return. A +// hand-edited file can hold two entities with one name, and only the first +// is ever matched by name. +function firstEntityByName(entities: Entity[]): Map { + const byName = new Map(); + for (const entity of entities) { + if (!byName.has(entity.name)) { + byName.set(entity.name, entity); + } + } + return byName; +} + // Text telling the agent which entities create_entities skipped. export function skippedEntitiesNotice(skipped: string[]): string { const one = skipped.length === 1; @@ -1190,14 +1213,18 @@ export class KnowledgeGraphManager { async createEntities(entities: Entity[]): Promise { return this.withLock(async () => { const { graph, unreadable, size } = await this.loadGraphWithUnreadable(); - const newEntities = entities.filter( - (e, index) => - !graph.entities.some( - (existingEntity) => existingEntity.name === e.name, - ) && - // Also skip duplicates appearing earlier in this same batch - !entities.slice(0, index).some((earlier) => earlier.name === e.name), - ); + // Seeded with the stored names, and grown as the batch is read, so a + // name repeating an earlier one in this same batch is skipped too. The + // filter keeps the requested objects themselves: skippedEntityNames + // tells created from skipped by identity. + const seen = new Set(graph.entities.map((e) => e.name)); + const newEntities = entities.filter((e) => { + if (seen.has(e.name)) { + return false; + } + seen.add(e.name); + return true; + }); graph.entities.push(...newEntities); // Only a call that adds something is held to the limits: re-saving can // grow an existing file that was not written in this exact form. @@ -1224,18 +1251,17 @@ export class KnowledgeGraphManager { } }); - const isSameRelation = (a: Relation, b: Relation) => - a.from === b.from && a.to === b.to && a.relationType === b.relationType; - const newRelations = relations.filter( - (r, index) => - !graph.relations.some((existingRelation) => - isSameRelation(existingRelation, r), - ) && - // Also skip duplicates appearing earlier in this same batch - !relations - .slice(0, index) - .some((earlier) => isSameRelation(earlier, r)), - ); + // As in createEntities: stored relations, then earlier ones in this + // same batch, are skipped. + const seen = new Set(graph.relations.map(relationKey)); + const newRelations = relations.filter((r) => { + const key = relationKey(r); + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; + }); graph.relations.push(...newRelations); // Held to the limits only when it adds something (see createEntities). await this.saveGraph( @@ -1252,17 +1278,26 @@ export class KnowledgeGraphManager { ): Promise<{ entityName: string; addedObservations: string[] }[]> { return this.withLock(async () => { const { graph, unreadable, size } = await this.loadGraphWithUnreadable(); + const entityByName = firstEntityByName(graph.entities); + // Each touched entity's observations as a Set, built on first use and + // kept in step with what is pushed, so a later entry for the same + // entity sees what an earlier one added. + const storedByName = new Map>(); const results = observations.map((o) => { - const entity = graph.entities.find((e) => e.name === o.entityName); + const entity = entityByName.get(o.entityName); if (!entity) { throw new Error(`Entity with name ${o.entityName} not found`); } + const known = + storedByName.get(o.entityName) ?? new Set(entity.observations); + storedByName.set(o.entityName, known); // A Set keeps the first occurrence of each string, so a repeat within // one call is stored and reported once (#5201). const newObservations = [...new Set(o.contents)].filter( - (content) => !entity.observations.includes(content), + (content) => !known.has(content), ); entity.observations.push(...newObservations); + newObservations.forEach((content) => known.add(content)); return { entityName: o.entityName, addedObservations: newObservations }; }); // Held to the limits only when it adds something (see createEntities). @@ -1280,11 +1315,10 @@ export class KnowledgeGraphManager { const present = new Set(graph.entities.map((e) => e.name)); const deleted = entityNames.filter((name) => present.has(name)); const notFound = entityNames.filter((name) => !present.has(name)); - graph.entities = graph.entities.filter( - (e) => !entityNames.includes(e.name), - ); + const toDelete = new Set(entityNames); + graph.entities = graph.entities.filter((e) => !toDelete.has(e.name)); graph.relations = graph.relations.filter( - (r) => !entityNames.includes(r.from) && !entityNames.includes(r.to), + (r) => !toDelete.has(r.from) && !toDelete.has(r.to), ); await this.saveGraph(graph, unreadable); return { deleted, notFound }; @@ -1298,12 +1332,14 @@ export class KnowledgeGraphManager { const { graph, unreadable } = await this.loadGraphWithUnreadable(); let deletedCount = 0; const missingEntities: string[] = []; + const entityByName = firstEntityByName(graph.entities); deletions.forEach((d) => { - const entity = graph.entities.find((e) => e.name === d.entityName); + const entity = entityByName.get(d.entityName); if (entity) { const before = entity.observations.length; + const toDelete = new Set(d.observations); entity.observations = entity.observations.filter( - (o) => !d.observations.includes(o), + (o) => !toDelete.has(o), ); deletedCount += before - entity.observations.length; } else { @@ -1321,14 +1357,9 @@ export class KnowledgeGraphManager { return this.withLock(async () => { const { graph, unreadable } = await this.loadGraphWithUnreadable(); const before = graph.relations.length; + const toDelete = new Set(relations.map(relationKey)); graph.relations = graph.relations.filter( - (r) => - !relations.some( - (delRelation) => - r.from === delRelation.from && - r.to === delRelation.to && - r.relationType === delRelation.relationType, - ), + (r) => !toDelete.has(relationKey(r)), ); await this.saveGraph(graph, unreadable); return { deletedCount: before - graph.relations.length }; From 2b02c2f91c0c9979578c8b0562700556900715a6 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:30:48 -0500 Subject: [PATCH 10/16] test(memory): drive the clock in the heartbeat freshness test instead of racing it "keeps a lock held longer than staleMs fresh" held a lock for 400 ms with staleMs 100, so the heartbeat refreshed it every 50 ms, and a waiter judged its age against the real clock. When a refresh landed more than 50 ms late (a slow runner's disk or scheduler), the waiter saw a live lock older than staleMs and broke it. Delaying each heartbeat utimes by 120 ms reproduces the CI order [long start, waiter, long end] every time. The heartbeat itself is sound: production keeps a 15 s margin (staleMs 30 s, a beat every 15 s). The test now fakes Date and the heartbeat's interval only. It advances the clock one beat at a time, waits for that beat's refresh to land and for the waiter to look at the lock again, and holds the lock for four times staleMs before releasing it. Timeouts stay real, so the waiter retries on its own. Closes #5680 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/file-lock.test.ts | 112 ++++++++++++++++++++----- 1 file changed, 89 insertions(+), 23 deletions(-) diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index 63b5fc719a..259680493a 100644 --- a/src/memory/__tests__/file-lock.test.ts +++ b/src/memory/__tests__/file-lock.test.ts @@ -315,30 +315,96 @@ describe("withFileLock", () => { }); it("keeps a lock held longer than staleMs fresh, so it is not broken", async () => { - const opts = { staleMs: 100, timeoutMs: 5_000, retryMs: 5 }; - const order: string[] = []; - const long = withFileLock( - lockPath, - async () => { - order.push("long start"); - await new Promise((resolve) => setTimeout(resolve, 400)); - order.push("long end"); - }, - opts, - ); - // Let the long holder take the lock before the waiter starts. - await new Promise((resolve) => setTimeout(resolve, 20)); - const waiter = withFileLock( - lockPath, - async () => { - order.push("waiter"); - }, - opts, - ); + // The lock's age is judged against the clock, so the test drives the + // clock rather than racing it (#5680). With real time, a waiter that ran + // while a loaded runner held the next heartbeat back by more than + // staleMs / 2 judged the live lock stale and broke it. Here Date and the + // heartbeat's interval are fake and move only when the test advances + // them; timeouts stay real, so the waiter keeps retrying on its own. Each + // step waits for the refresh it fires to land and for the waiter to look + // at the lock again, so a slow runner only makes the test take longer. A + // heartbeat that stops refreshing the lock fails it on its timeout. + const opts = { staleMs: 100, timeoutMs: 60_000, retryMs: 5 }; + vi.useFakeTimers({ + now: Date.now(), + toFake: ["Date", "setInterval", "clearInterval"], + }); + try { + const realOpen = fs.open; + let judgments = 0; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === lockPath && args[1] === "r") { + judgments++; + } + return realOpen(...args); + }) as typeof fs.open); + const realUtimes = fs.utimes; + let refreshLanded: (() => void) | undefined; + vi.spyOn(fs, "utimes").mockImplementation(async (...args) => { + await realUtimes(...args); + if (args[0] === lockPath) { + refreshLanded?.(); + } + }); + const until = async (done: () => boolean): Promise => { + while (!done()) { + await new Promise((resolve) => setTimeout(resolve, 1)); + } + }; + // Two more opens than were seen means one whole judgment of the lock + // started and finished, and the waiter came back for another. + const waiterLooksAgain = () => { + const seen = judgments; + return until(() => judgments >= seen + 2); + }; - await Promise.all([long, waiter]); - expect(order).toEqual(["long start", "long end", "waiter"]); - }); + const order: string[] = []; + let started!: () => void; + const holding = new Promise((resolve) => (started = resolve)); + let finish!: () => void; + const finished = new Promise((resolve) => (finish = resolve)); + const long = withFileLock( + lockPath, + async () => { + order.push("long start"); + started(); + await finished; + order.push("long end"); + }, + opts, + ); + await holding; + const waiter = withFileLock( + lockPath, + async () => { + order.push("waiter"); + }, + opts, + ); + await waiterLooksAgain(); + + // Hold the lock for four times staleMs, one heartbeat at a time. + const start = Date.now(); + for (let beat = 0; beat < 8; beat++) { + const refreshed = new Promise( + (resolve) => (refreshLanded = resolve), + ); + vi.advanceTimersByTime(opts.staleMs / 2); + await refreshed; + await waiterLooksAgain(); + } + expect(Date.now() - start).toBe(4 * opts.staleMs); + expect(order).toEqual(["long start"]); + + finish(); + await Promise.all([long, waiter]); + expect(order).toEqual(["long start", "long end", "waiter"]); + } finally { + vi.useRealTimers(); + } + }, 30_000); it("stops refreshing a lock that was broken and re-taken while it ran (#5418)", async () => { // Heartbeat every 100 ms, wide enough that the replacement below finishes From f0e16a0a21faba9bc171a515986c6512e4565fad Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 02:00:42 -0500 Subject: [PATCH 11/16] docs(memory): separate an unreachable line from a reachable namesake, and stop HTTP servers before a hand edit Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/memory/README.md b/src/memory/README.md index 2d32338f11..585a5a190e 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -325,9 +325,9 @@ Each line of the memory file is expected to be one JSON object with `"type": "en - **Most skipped lines are logged to stderr, not all.** A line that is not JSON logs `Skipping malformed line in memory file`, a non-object value logs `Skipping non-object line in memory file`, and an entity or relation that fails its schema logs `Skipping invalid entity in memory file:` or `Skipping invalid relation in memory file:` followed by the fields at fault. A JSON array, and an object whose `type` is missing or unknown, are skipped without a message. The messages repeat each time the file is read, so on every tool call. - **Skipped lines are kept.** Every save writes them back unchanged, after the graph's own lines, so a write never drops data the server could not read. Blank lines are not kept: a save removes them. - **Skipped lines count toward `MEMORY_MAX_FILE_BYTES`**, since they are part of the file each save writes. -- **No tool can reach a skipped line.** `read_graph`, `search_nodes` and `open_nodes` do not show it. `delete_entities` and `delete_observations` report its name as not found, and `add_observations` and `create_relations` refuse it as an entity that does not exist. `create_entities` under the same name stores a second record beside the skipped line rather than replacing it. A skipped relation matches no `delete_relations` call, and stays in the file after the entities it names are deleted. +- **No tool can reach a skipped line.** `read_graph`, `search_nodes` and `open_nodes` do not show it. While no readable entity has its name, `delete_entities` and `delete_observations` report the name as not found, and `add_observations` and `create_relations` refuse it as an entity that does not exist. `create_entities` under the same name stores a second, readable record beside the skipped line rather than replacing it; from then on every tool acts on that new record, and deleting it removes only the new record, never the skipped line. A skipped relation matches no `delete_relations` call, and stays in the file after the entities it names are deleted. -**The only fix is to edit the file by hand.** Quit every MCP client using the memory file, so that no server writes it while you work, then correct or delete the line in a text editor and start the clients again. A stderr line from the list above, or a `not found` for an entity you can see in the file, is the sign to look. +**The only fix is to edit the file by hand.** Stop every server process using the memory file and wait for each to exit, so that none can save over your edit: quitting a client stops the stdio server it started, but a [Streamable HTTP](#streamable-http) server runs on its own and must be stopped itself. Then correct or delete the line in a text editor and start the servers and clients again. A stderr line from the list above, or a `not found` for an entity you can see in the file, is the sign to look. # VS Code Installation Instructions From 0875cae8dfe6c5ddc37d1fbbb2f16c7692b02d61 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 02:58:41 -0500 Subject: [PATCH 12/16] fix(memory): give reads the missing-directory error for ENOTDIR too A path component that is a file made writes report the missing directory, but reads still returned Node's raw ENOTDIR. Reads now run the same directory check on ENOTDIR, and keep the original error if it passes. The tests cover every tool for that case. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .../__tests__/missing-directory.test.ts | 29 ++++++++++++++++--- src/memory/index.ts | 14 +++++---- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/memory/__tests__/missing-directory.test.ts b/src/memory/__tests__/missing-directory.test.ts index 5a179e1b3b..681b915808 100644 --- a/src/memory/__tests__/missing-directory.test.ts +++ b/src/memory/__tests__/missing-directory.test.ts @@ -5,7 +5,7 @@ // write failed with a raw ENOENT naming the internal .lock file. Driven // through an MCP client over an in-memory transport, so each test asserts on // what a client sees. -import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { promises as fs } from "fs"; import path from "path"; import { call, connect, makeTempGraph, textOf } from "./helpers.js"; @@ -49,6 +49,7 @@ describe("a memory file whose directory does not exist", () => { }); afterEach(async () => { + vi.restoreAllMocks(); await connection?.close(); connection = undefined; await cleanup(); @@ -95,11 +96,31 @@ describe("a memory file whose directory does not exist", () => { const filePath = path.join(dir, "not-a-dir", "memory.jsonl"); connection = await connect(filePath); - const result = await call(connection.client, "create_entities", { - entities: [alice], + for (const [name, args] of TOOLS) { + const result = await call(connection.client, name, args); + expect({ name, result }).toEqual({ + name, + result: { + content: [{ type: "text", text: expectedError(filePath) }], + isError: true, + }, + }); + } + }); + + // ENOTDIR from a read whose directory checks out is not an empty graph: + // the read's own error reaches the client. A real filesystem cannot produce + // that combination, so the read is made to fail. + it("passes through an ENOTDIR read in a directory that exists", async () => { + connection = await connect(path.join(dir, "memory.jsonl")); + const notDir = Object.assign(new Error("ENOTDIR: simulated"), { + code: "ENOTDIR", }); + vi.spyOn(fs, "readFile").mockRejectedValueOnce(notDir); + + const result = await call(connection.client, "read_graph"); expect(result).toEqual({ - content: [{ type: "text", text: expectedError(filePath) }], + content: [{ type: "text", text: "ENOTDIR: simulated" }], isError: true, }); }); diff --git a/src/memory/index.ts b/src/memory/index.ts index 051dc411c0..44ad6e1dd8 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -1041,11 +1041,15 @@ export class KnowledgeGraphManager { }; return { graph, unreadable, size }; } catch (error) { - if ( - error instanceof Error && - "code" in error && - error.code === "ENOENT" - ) { + const code = (error as NodeJS.ErrnoException | null)?.code; + // A path component that is a file (ENOTDIR) is a missing directory too, + // and gets the same error; should the directory check still pass, the + // original error stands rather than reading as an empty graph. + if (code === "ENOTDIR") { + await this.requireMemoryDirectory(); + throw error; + } + if (code === "ENOENT") { // A missing file is an empty graph, but only in a directory a write // can create it in (see requireMemoryDirectory). await this.requireMemoryDirectory(); From d8715927988d122dffda10d395e5f638435bad6c Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 03:13:33 -0500 Subject: [PATCH 13/16] test(memory): bound the heartbeat test's waits and clean up on a failure Review of #5715: a heartbeat that stopped refreshing left the test waiting until Vitest's timeout, which skips the test's finally, so the fake timers and the blocked lock holder outlived it. Each wait now gives up after 10 s of real time with an error that names what it waited for. The finally releases the holder and settles both lock operations, and afterEach restores real timers for a test that times out anyway. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/file-lock.test.ts | 76 ++++++++++++++++---------- 1 file changed, 48 insertions(+), 28 deletions(-) diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index 259680493a..72a1b58a31 100644 --- a/src/memory/__tests__/file-lock.test.ts +++ b/src/memory/__tests__/file-lock.test.ts @@ -33,6 +33,8 @@ describe("withFileLock", () => { }); afterEach(async () => { + // Also runs when a test times out, which skips the test's own finally. + vi.useRealTimers(); vi.restoreAllMocks(); await cleanup(); }); @@ -322,13 +324,18 @@ describe("withFileLock", () => { // heartbeat's interval are fake and move only when the test advances // them; timeouts stay real, so the waiter keeps retrying on its own. Each // step waits for the refresh it fires to land and for the waiter to look - // at the lock again, so a slow runner only makes the test take longer. A - // heartbeat that stops refreshing the lock fails it on its timeout. + // at the lock again, so a slow runner only makes the test take longer. + // Each wait gives up after 10 s of real time, well inside the test's + // timeout, so a heartbeat that stops refreshing the lock fails the test + // by name and the cleanup below still runs. const opts = { staleMs: 100, timeoutMs: 60_000, retryMs: 5 }; vi.useFakeTimers({ now: Date.now(), toFake: ["Date", "setInterval", "clearInterval"], }); + const order: string[] = []; + let finish = () => {}; + const running: Promise[] = []; try { const realOpen = fs.open; let judgments = 0; @@ -341,15 +348,20 @@ describe("withFileLock", () => { return realOpen(...args); }) as typeof fs.open); const realUtimes = fs.utimes; - let refreshLanded: (() => void) | undefined; + let refreshes = 0; vi.spyOn(fs, "utimes").mockImplementation(async (...args) => { await realUtimes(...args); if (args[0] === lockPath) { - refreshLanded?.(); + refreshes++; } }); - const until = async (done: () => boolean): Promise => { + const until = async (what: string, done: () => boolean) => { + // performance.now is not faked, so this bound is real time. + const giveUpAt = performance.now() + 10_000; while (!done()) { + if (performance.now() > giveUpAt) { + throw new Error(`Gave up waiting for ${what}`); + } await new Promise((resolve) => setTimeout(resolve, 1)); } }; @@ -357,52 +369,60 @@ describe("withFileLock", () => { // started and finished, and the waiter came back for another. const waiterLooksAgain = () => { const seen = judgments; - return until(() => judgments >= seen + 2); + return until("the waiter to judge the lock again", () => { + return judgments >= seen + 2; + }); }; - const order: string[] = []; let started!: () => void; const holding = new Promise((resolve) => (started = resolve)); - let finish!: () => void; const finished = new Promise((resolve) => (finish = resolve)); - const long = withFileLock( - lockPath, - async () => { - order.push("long start"); - started(); - await finished; - order.push("long end"); - }, - opts, + running.push( + withFileLock( + lockPath, + async () => { + order.push("long start"); + started(); + await finished; + order.push("long end"); + }, + opts, + ), ); await holding; - const waiter = withFileLock( - lockPath, - async () => { - order.push("waiter"); - }, - opts, + running.push( + withFileLock( + lockPath, + async () => { + order.push("waiter"); + }, + opts, + ), ); await waiterLooksAgain(); // Hold the lock for four times staleMs, one heartbeat at a time. const start = Date.now(); for (let beat = 0; beat < 8; beat++) { - const refreshed = new Promise( - (resolve) => (refreshLanded = resolve), - ); + const seen = refreshes; vi.advanceTimersByTime(opts.staleMs / 2); - await refreshed; + await until(`heartbeat ${beat + 1} to refresh the lock`, () => { + return refreshes > seen; + }); await waiterLooksAgain(); } expect(Date.now() - start).toBe(4 * opts.staleMs); expect(order).toEqual(["long start"]); finish(); - await Promise.all([long, waiter]); + await Promise.all(running); expect(order).toEqual(["long start", "long end", "waiter"]); } finally { + // On a failure, let both lock operations finish before the lock + // directory is removed, so neither outlives the test. vi.useRealTimers(); + finish(); + await Promise.allSettled(running); } }, 30_000); From 157c06c61ec9bdf745c1685134ad770c37ec16dd Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 03:40:42 -0500 Subject: [PATCH 14/16] docs(memory): name every gap the guard put-back leaves Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/index.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/memory/index.ts b/src/memory/index.ts index 5a1da14104..3ed4d88eb0 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -358,13 +358,22 @@ async function isLockStale( // at once cannot remove a guard a third took in between (#5624). A live // guard taken aside that way is put back with an exclusive link, which // never replaces a guard a fourth process created at the path in that -// moment. That is the gap left: should a fourth create one there between -// the rename and the link, the third's guard cannot go back without -// replacing the fourth's, so it is dropped, and the third and fourth each -// run believing they hold the guard. It takes a crash inside a guarded -// section, two clearers of that guard at once, a third process taking it -// between them, and a fourth within the two calls after. A server from -// before #5624 still clears a guard by path, with the wider gap that had. +// moment. What is left, each needing a crash inside a guarded section, +// two clearers of that guard at once and a third process taking it +// between them, and then one more event within the two calls between the +// rename and the link: +// - A fourth process creates a guard at the path. The third's guard cannot +// go back without replacing the fourth's, so it is dropped, and the third +// and fourth each run believing they hold the guard. +// - The link fails for another reason (a filesystem without hard links, +// say). The third's guard is dropped, as the removal by path dropped it +// before. +// - The third finishes and drops its guard, finding the path empty. The +// link then puts back a guard nobody holds, and writers wait for it to +// go stale as for one left by a crash: a delay of at most staleMs, never +// two writers at once. +// A server from before #5624 still clears a guard by path, with the wider +// gap that had. // - A server older than this change takes the guard only to break a lock. It // releases without the guard and runs as soon as it has created the lock. // Sharing a memory file with one is safe in every way it was before (same From f3f9f9754c278bd9b761571282ddf2a4a119965a Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 04:28:13 -0500 Subject: [PATCH 15/16] test(memory): simulate the stat failure rather than rely on a mode-000 directory Windows ignores POSIX mode bits, so the passthrough test saw no EACCES there and failed on the Windows CI leg. Make fs.stat reject instead, which holds on every platform and needs no skip for root. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- .../__tests__/missing-directory.test.ts | 39 +++++++++---------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/src/memory/__tests__/missing-directory.test.ts b/src/memory/__tests__/missing-directory.test.ts index 681b915808..40628c0153 100644 --- a/src/memory/__tests__/missing-directory.test.ts +++ b/src/memory/__tests__/missing-directory.test.ts @@ -155,25 +155,22 @@ describe("a memory file whose directory does not exist", () => { expect(JSON.parse(textOf(result))).toEqual({ entities: [], relations: [] }); }); - // A directory that cannot be examined is not reported as missing: the - // stat error (EACCES here) reaches the client unchanged. Root reads through - // a mode-000 directory, so the case cannot be produced there. - it.skipIf(process.getuid?.() === 0)( - "passes through an error other than a missing directory", - async () => { - const locked = path.join(dir, "locked"); - await fs.mkdir(path.join(locked, "inner"), { recursive: true }); - await fs.chmod(locked, 0o000); - try { - connection = await connect(path.join(locked, "inner", "memory.jsonl")); - const result = await call(connection.client, "create_entities", { - entities: [alice], - }); - expect(result.isError).toBe(true); - expect(textOf(result)).toMatch(/^EACCES/); - } finally { - await fs.chmod(locked, 0o700); - } - }, - ); + // A directory that cannot be examined is not reported as missing: the stat + // error reaches the client unchanged. The stat is made to fail, because a + // mode-000 directory denies nothing on Windows or to root. + it("passes through an error other than a missing directory", async () => { + connection = await connect(path.join(dir, "memory.jsonl")); + const denied = Object.assign(new Error("EACCES: simulated"), { + code: "EACCES", + }); + vi.spyOn(fs, "stat").mockRejectedValueOnce(denied); + + const result = await call(connection.client, "create_entities", { + entities: [alice], + }); + expect(result).toEqual({ + content: [{ type: "text", text: "EACCES: simulated" }], + isError: true, + }); + }); }); From 79b9f023b1f0bdf281987184eeb77ccc9290f47c Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 05:23:58 -0500 Subject: [PATCH 16/16] test(memory): assert the created relations without pinning create_relations' skipped report The separator test compared the whole structuredContent, so it failed once #5654 reports the in-batch repeat as skipped. The lookup is what it tests. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/write-lookups.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/memory/__tests__/write-lookups.test.ts b/src/memory/__tests__/write-lookups.test.ts index ed069edffa..a43b2da1f6 100644 --- a/src/memory/__tests__/write-lookups.test.ts +++ b/src/memory/__tests__/write-lookups.test.ts @@ -326,7 +326,9 @@ describe("write lookups (#5693)", () => { { from: "a|b", to: "c", relationType: "knows" }, ], }); - expect(created.structuredContent).toEqual({ + // toMatchObject, not toEqual: whether the repeat is also reported as + // skipped is create_relations' reporting (#5654), not this lookup. + expect(created.structuredContent).toMatchObject({ relations: [ { from: "a|b", to: "c", relationType: "knows" }, { from: "a", to: "b|c", relationType: "knows" },