Skip to content

memory: add tests for the neighbouring faces of pinned invariants (exact-match delete vs. whitespace, case asymmetry, observationCount) #5645

Done

Description

@reservoir-cmyk

Several invariants of the memory server are pinned on one face and unpinned on the neighbouring face, where the same shape of accident could recur. Exact-match deletion is pinned for the case variant but not for whitespace; search's case-insensitivity is pinned, but whether write-face identity shares it is not; observationCount is computed at read time, but not checked immediately after a delete. The three cases below re-measure each pinned invariant on its sibling face. All three pass against the current implementation.

Cases

  1. delete_relations' exact-match rule also rejects a space-padded type — deleting with "knows " or " knows" removes nothing (deletedCount 0, the relation survives); the exact type deletes it. The documentation states that delete_relations deletes only an exact match; the case variant of that rule is already pinned in the search tests, the whitespace variant was not.
  2. Identity is case-sensitive while search is case-insensitive — "Test" and "test" coexist as distinct entities, and a search for either spelling returns both (the read face's case-insensitivity is pinned at knowledge-graph.test.ts:418). The asymmetry itself is the contract being pinned; the documentation is silent, so this case is characterization.
  3. observationCount agrees with delete_observations on the next read — after deleting one of three observations, a read with observationLimit: 0 reports observationCount 2 alongside an empty observations list, and an unlimited read returns the two remaining observations. The documentation promises each entity's total is added as observationCount; this pins that the total does not go stale across a delete.

Proposed tests

As a new file in src/memory/__tests__/, driving KnowledgeGraphManager against a temp directory:

// Sibling
// accidents — the shape of a bug fixed on one face of this server,
// checked on the neighbouring face. delete_relations states an
// exact-match rule: a relation type padded with a space is not the same
// type. Identity is
// case-sensitive on the write face while search is case-insensitive on
// the read face, so "Test" and "test" coexist and one search finds both.
// And observationCount, computed on the read face, must agree with what
// delete_observations did on the write face. Docs anchors: the
// exact-match rule for delete_relations, and "add each entity's total as
// observationCount"; the case asymmetry is docs-silent characterization.
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { KnowledgeGraphManager } from "../index.js";

describe("KnowledgeGraphManager sibling faces", () => {
  let testDir: string;
  let manager: KnowledgeGraphManager;

  beforeEach(async () => {
    testDir = await fs.mkdtemp(
      path.join(path.dirname(fileURLToPath(import.meta.url)), "wave2-sib-"),
    );
    manager = new KnowledgeGraphManager(path.join(testDir, "memory.jsonl"));
  });

  afterEach(async () => {
    await fs.rm(testDir, { recursive: true, force: true });
  });

  it("deleteRelations is exact-match: a space-padded type deletes nothing", async () => {
    await manager.createEntities([
      { name: "A", entityType: "t", observations: [] },
      { name: "B", entityType: "t", observations: [] },
    ]);
    await manager.createRelations([
      { from: "A", to: "B", relationType: "knows" },
    ]);
    for (const padded of ["knows ", " knows"]) {
      const result = await manager.deleteRelations([
        { from: "A", to: "B", relationType: padded },
      ]);
      expect(result.deletedCount).toBe(0);
    }
    expect((await manager.readGraph()).relations).toHaveLength(1);
    const exact = await manager.deleteRelations([
      { from: "A", to: "B", relationType: "knows" },
    ]);
    expect(exact.deletedCount).toBe(1);
    expect((await manager.readGraph()).relations).toEqual([]);
  });

  it("keeps 'Test' and 'test' as distinct entities, and one case-insensitive search finds both", async () => {
    await manager.createEntities([
      { name: "Test", entityType: "T", observations: [] },
      { name: "test", entityType: "T", observations: [] },
    ]);
    const graph = await manager.readGraph();
    expect(graph.entities.map((e) => e.name)).toEqual(["Test", "test"]);
    const found = await manager.searchNodes("test");
    expect(found.entities.map((e) => e.name)).toEqual(["Test", "test"]);
    const foundUpper = await manager.searchNodes("TEST");
    expect(foundUpper.entities.map((e) => e.name)).toEqual(["Test", "test"]);
  });

  it("observationCount agrees with delete_observations on the next read", async () => {
    await manager.createEntities([
      { name: "E", entityType: "t", observations: ["O1", "O2", "O3"] },
    ]);
    await manager.deleteObservations([
      { entityName: "E", observations: ["O1"] },
    ]);
    const overview = await manager.readGraph({ observationLimit: 0 });
    expect(overview.entities[0].observationCount).toBe(2);
    expect(overview.entities[0].observations).toEqual([]);
    const full = await manager.readGraph();
    expect(full.entities[0].observations).toEqual(["O2", "O3"]);
  });
});

Verification

Ran against a byte-identical copy of v2/main @ 6cfff62 (Node 24, vitest 4.1.12): 3 passed. Full memory suite with these included: 275 passed + 1 skipped (25 files). No behaviour change is proposed.

Prompt used

"In src/memory's tests, check the neighbouring faces of already-pinned invariants: delete_relations' exact-match rule also rejects a relation type padded with a leading or trailing space; entity identity is case-sensitive — 'Test' and 'test' coexist — while search stays case-insensitive and finds both; and observationCount read right after delete_observations agrees with the observations actually left. Style follows the existing memory tests."

Activity

  1. A7mdMe commented on Nov 22, 2026

    @A7mdMe

    Great characterization tests by @reservoir-cmyk on pinning the sibling faces of these memory invariants.

    In production multi-agent environments (where LLMs autonomously issue create_entities, create_relations, and delete_relations), these three specific invariants have direct operational consequences:

    1. Whitespace Sensitivity & Silent Zombie Relations

    When an LLM generates a tool call to delete relations, prompt formatting or string tokenization frequently introduces trailing or leading whitespace (e.g. relationType: "worksWith " or " knows"):

    • With the exact-match rule pinned, delete_relations returns { deletedCount: 0 }.
    • Because agents rarely inspect the zero-count return when an error isn't thrown, the relation is never actually removed from storage. Over long multi-turn sessions, this leads to accumulated "zombie" relations that degrade graph traversal and retrieval precision.
    • In production architectures, servers often benefit from pairing exact-match deletion with an optional trimmed matching mode or diagnostic warning when whitespace-padded candidates exist.

    2. Case Asymmetry & Split-Brain Entity Graphs

    The asymmetry between case-sensitive write identity ("Test" vs "test") and case-insensitive search (search_nodes) can trigger split-brain knowledge models:

    • An agent creates "Service" with infrastructure observations, and in a later turn creates "service" with deployment observations.
    • Both entities coexist independently, but when searching or updating, the agent receives mixed or ambiguous node lists, frequently leading to duplicate relations or updates attaching to the wrong variant.
    • Supporting either canonical case folding or a case-preserving alias mapping prevents graph fragmentation across long-running agent threads.

    3. Atomic observationCount Synchronization

    Pinning that observationCount immediately decrements upon delete_observations (even when observationLimit: 0 is passed) is essential for agent token efficiency. Many agent frameworks query overview graphs with observationLimit: 0 to discover available entities and their observation density before fetching full payloads; stale counters cause incorrect pagination and token budget overruns.

    We codified automated test suites verifying all three sibling invariants—exact space-padded deletion rejection, case-sensitive write vs case-insensitive search coexistence, and atomic observationCount synchronization across overview reads—in A7mdMe/mcp-production-kit (commit 36c4b01). Happy to share further benchmark cases if helpful!

    (Disclosure: Project maintainer at mcp-production-kit)

  2. added
    chore
    server-memory
    on Nov 30, 2026
  3. cliffhall commented on Nov 30, 2026

    @cliffhall
    Member

    Triage: Priority Low (total 2)

    • Severity 1: proposed characterization tests; all cases pass on the current code
    • Urgency 1: no time pressure
    • Bonuses: none

    Board: Servers V2 (#43), Status Incoming, awaiting maintainer review (no milestone yet).

  4. added this to the v2.7.0 milestone on Nov 30, 2026
  5. self-assigned this
    on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

choreserver-memoryv2

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions