Skip to content

memory: add tests for the graph file path being a symlink (reads follow it; a write replaces the link, not its target) #5644

Done

Description

@reservoir-cmyk

The README sets MEMORY_FILE_PATH to an absolute path and promises atomic saves by rename, and the file-path tests pin path resolution and migration — but not what happens when the data path itself is a symlink, a routine setup when an operator points the file at another volume or a backup location. Which behaviour holds decides the shape of a "wrote it, but the other side stayed old" incident: does the rename land through the link, or on the link? The documentation is silent on symlinks, so the two cases below pin the current behaviour as characterization. Both pass against the current implementation.

Cases

  1. Reads follow the symlink — a graph written at the link's target is read back through the link path, and the read leaves the link itself in place.
  2. A write replaces the symlink with a regular file, and the former target is left untouched — after creating an entity through the link path, the path is a regular file holding the whole graph (old + new), and the file the link used to point at is byte-for-byte unchanged. The atomic rename lands on the path itself, not through it.

Proposed tests

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

// The physical
// layer lies — here, a symlink standing where the graph file should be.
// The README says to set MEMORY_FILE_PATH to an absolute path and promises
// atomic saves by rename; it is silent on symlinks. These are
// characterization tests pinning what the rename does to a linked path:
// reads follow the link, a write replaces the link itself with a regular
// file, and the link's former target is left byte-for-byte alone.
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 when the graph path is a symlink", () => {
  let testDir: string;
  let targetPath: string;
  let linkPath: string;

  beforeEach(async () => {
    testDir = await fs.mkdtemp(
      path.join(path.dirname(fileURLToPath(import.meta.url)), "wave2-phys-"),
    );
    targetPath = path.join(testDir, "real.jsonl");
    linkPath = path.join(testDir, "memory.jsonl");
    await fs.writeFile(
      targetPath,
      JSON.stringify({
        type: "entity",
        name: "Old",
        entityType: "t",
        observations: [],
      }) + "\n",
    );
    await fs.symlink(targetPath, linkPath);
  });

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

  it("reads the graph through the symlink before any write", async () => {
    const manager = new KnowledgeGraphManager(linkPath);
    const graph = await manager.readGraph();
    expect(graph.entities.map((e) => e.name)).toEqual(["Old"]);
    // A read does not disturb the link.
    expect((await fs.lstat(linkPath)).isSymbolicLink()).toBe(true);
  });

  it("a write replaces the symlink with a regular file and leaves the target untouched", async () => {
    const targetBefore = await fs.readFile(targetPath, "utf-8");
    const manager = new KnowledgeGraphManager(linkPath);
    await manager.createEntities([
      { name: "New", entityType: "t", observations: [] },
    ]);

    // The atomic rename lands on the path itself: the link is gone, the
    // path is now a regular file holding the whole graph (old + new).
    const stat = await fs.lstat(linkPath);
    expect(stat.isSymbolicLink()).toBe(false);
    expect(stat.isFile()).toBe(true);
    const graph = await new KnowledgeGraphManager(linkPath).readGraph();
    expect(graph.entities.map((e) => e.name)).toEqual(["Old", "New"]);

    // The former target was never written through the link.
    expect(await fs.readFile(targetPath, "utf-8")).toBe(targetBefore);
  });
});

Verification

Ran against a byte-identical copy of v2/main @ 6cfff62 (Node 24, vitest 4.1.12): 2 passed. Full memory suite with these included: 275 passed + 1 skipped (25 files). Characterization only: the documentation is silent on symlinks, and no behaviour change is proposed.

Prompt used

"In src/memory's tests, pin what happens when the graph file path is a symlink (the README is silent on symlinks): reads follow the link to the existing graph, and a write's atomic rename replaces the symlink itself with a regular file holding the whole graph, leaving the link's former target byte-for-byte untouched. KnowledgeGraphManager-level tests in the style of the existing memory tests."

Activity

  1. A7mdMe commented on Nov 21, 2026

    @A7mdMe

    Symlink Preservation, Persistent Volume (PV) Mounts & Atomic Renames

    The characterization tests in this issue capture a very common failure mode in containerized and cloud deployments (Docker volumes, Kubernetes PersistentVolumes, or NFS/EFS mounts) where MEMORY_FILE_PATH is symlinked to an external mount or backup target.

    The Operational Impact of Replacing Symlinks

    When atomic writes use standard rename(tempPath, memoryFilePath):

    1. Severing Persistent Storage: In POSIX and Windows filesystem semantics, rename() atomically replaces the inode/entry at memoryFilePath. If memoryFilePath was a symlink, the link is destroyed and replaced with a standalone local file.
    2. The "Silent Desync" Failure Mode: Subsequent reads continue to read the local regular file, while the external mount / backup storage is byte-for-byte frozen in time. Operators only discover that backups stopped updating when a pod restarts or an audit runs.
    3. Cross-Device EXDEV Errors: If the temporary file is created in /tmp (e.g. standard OS temp) while MEMORY_FILE_PATH is a symlink to an external volume mount (e.g. /mnt/data), rename() fails outright with EXDEV: cross-device link not permitted.

    Recommended Architectural Pattern: Canonical Target Staging

    To preserve the symlink while guaranteeing atomic write semantics:

    1. Resolve Canonical Physical Path:
      export function resolveAtomicWriteDestination(filePath: string): string {
        try {
          const lstat = fs.lstatSync(filePath);
          if (lstat.isSymbolicLink()) {
            return fs.realpathSync(filePath);
          }
        } catch {}
        return path.resolve(filePath);
      }
    2. Stage in the Physical Target's Directory:
      Create the .tmp-... staging file in path.dirname(canonicalPath). This guarantees both temp and target are on the exact same physical filesystem, completely preventing EXDEV errors.
    3. Rename Onto Canonical Target:
      Executing fs.renameSync(tempPath, canonicalPath) updates the physical data file. The original symlink at MEMORY_FILE_PATH continues pointing to the freshly updated target without interruption.
    4. Fallback Handling:
      Catch EXDEV and fall back to atomic copy-then-unlink with fsyncSync for multi-volume edge cases.

    Disclosure: I maintain MCP Production Kit, an open-source hardening suite for MCP servers. We implemented and verified this canonical physical staging and symlink preservation pattern in our test suite (Module 31).

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

    @cliffhall
    Member

    Triage: Priority Low (total 3)

    • Severity 2: proposed characterization tests, though the behaviour they pin (a write replaces a symlinked graph file instead of writing through it) may deserve a decision of its own
    • 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