Skip to content

Commit 1d4699c

Browse files
committed
fix(memory): coordinate shared graph writes with directory leases
Protect each read-modify-write transaction with a generation-marked directory lease while retaining the manager-local FIFO and atomic JSONL replacement. Use Node built-ins only. Propagate MCP cancellation and a shared 30-second request budget. Distinguish definitely uncommitted writes from uncertain rename outcomes, preserve safe errno diagnostics, and bound admitted mutations. Cover cross-process writes, lease recovery and ownership races, cancellation, outcome reporting, and resource notifications.
1 parent f46d957 commit 1d4699c

8 files changed

Lines changed: 1445 additions & 83 deletions

File tree

‎src/memory/__tests__/atomic-save.test.ts‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,10 @@ describe('KnowledgeGraphManager persistence durability', () => {
6666
expect(before).toContain('Alice');
6767

6868
// Simulate the process being interrupted while persisting the next write.
69-
vi.spyOn(fs, 'writeFile').mockImplementationOnce(async () => {
70-
throw new Error('ENOSPC: simulated interruption');
69+
const writeFile = fs.writeFile;
70+
vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
71+
if (String(args[0]).endsWith('.tmp')) throw new Error('ENOSPC: simulated interruption');
72+
return writeFile(...args);
7173
});
7274

7375
await expect(
@@ -100,8 +102,10 @@ describe('KnowledgeGraphManager persistence durability', () => {
100102
{ name: 'Alice', entityType: 'person', observations: ['works at Acme Corp'] },
101103
]);
102104

103-
vi.spyOn(fs, 'rename').mockImplementationOnce(async () => {
104-
throw new Error('EXDEV: simulated rename failure');
105+
const rename = fs.rename;
106+
vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
107+
if (to === testFilePath) throw new Error('EXDEV: simulated rename failure');
108+
return rename(from, to);
105109
});
106110

107111
await expect(
@@ -114,6 +118,43 @@ describe('KnowledgeGraphManager persistence durability', () => {
114118
expect(await fs.readdir(testDir)).toEqual(['memory.jsonl']);
115119
});
116120

121+
it('does not publish after losing its lease and can process a later mutation', async () => {
122+
const manager = new KnowledgeGraphManager(testFilePath);
123+
await manager.createEntities([
124+
{ name: 'Alice', entityType: 'person', observations: [] },
125+
]);
126+
const before = await fs.readFile(testFilePath, 'utf8');
127+
const lockPath = `${testFilePath}.lock`;
128+
const writeFile = fs.writeFile;
129+
vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
130+
await writeFile(...args);
131+
if (!String(args[0]).endsWith('.tmp')) return;
132+
// Replace the lease between preparation and publication of the graph.
133+
await fs.rm(lockPath, { recursive: true });
134+
await fs.mkdir(lockPath);
135+
const replacementTime = new Date(Date.now() + 10000);
136+
await fs.utimes(lockPath, replacementTime, replacementTime);
137+
});
138+
139+
// Lease loss detected before the rename is NOT_COMMITTED: the graph file
140+
// was definitely not replaced, so a retry is safe.
141+
await expect(manager.createEntities([
142+
{ name: 'Bob', entityType: 'person', observations: [] },
143+
])).rejects.toMatchObject({ name: 'MemoryRequestError', state: 'NOT_COMMITTED' });
144+
expect(await fs.readFile(testFilePath, 'utf8')).toBe(before);
145+
expect((await fs.stat(lockPath)).isDirectory()).toBe(true);
146+
expect((await fs.readdir(testDir)).sort()).toEqual(['memory.jsonl', 'memory.jsonl.lock']);
147+
148+
// The replacement owner releases its own lease; the failed request must
149+
// not leave the manager's in-process mutation queue permanently rejected.
150+
vi.restoreAllMocks();
151+
await fs.rmdir(lockPath);
152+
await manager.createEntities([
153+
{ name: 'Carol', entityType: 'person', observations: [] },
154+
]);
155+
expect((await manager.readGraph()).entities.map(entity => entity.name)).toEqual(['Alice', 'Carol']);
156+
});
157+
117158
it('still persists graph contents correctly across reloads', async () => {
118159
const manager = new KnowledgeGraphManager(testFilePath);
119160
await manager.createEntities([
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2+
import { promises as fs } from 'node:fs';
3+
import os from 'node:os';
4+
import path from 'node:path';
5+
import { setTimeout as sleep } from 'node:timers/promises';
6+
import { withDirectoryLock } from '../file-lock.js';
7+
8+
let directory: string;
9+
let file: string;
10+
11+
beforeEach(async () => {
12+
directory = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-memory-lease-'));
13+
file = path.join(directory, 'memory.jsonl');
14+
});
15+
16+
afterEach(async () => {
17+
vi.restoreAllMocks();
18+
await fs.rm(directory, { recursive: true, force: true });
19+
});
20+
21+
// Obtain the fixture through the public lease API so it follows the on-disk
22+
// protocol, then model a holder that disappeared without releasing it. The
23+
// operation itself resolves (it parks the lease); the loss surfaces only at
24+
// release, where a resolved operation is final and the lease stays parked.
25+
async function abandonLease(): Promise<void> {
26+
const lockPath = `${file}.lock`;
27+
const parked = `${file}.abandoned`;
28+
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
29+
await withDirectoryLock(file, () => fs.rename(lockPath, parked), { timeoutMs: 1000 });
30+
errors.mockRestore();
31+
await fs.rename(parked, lockPath);
32+
const old = new Date(Date.now() - 10000);
33+
await fs.utimes(lockPath, old, old);
34+
for (const entry of await fs.readdir(lockPath)) {
35+
await fs.utimes(path.join(lockPath, entry), old, old);
36+
}
37+
}
38+
39+
describe('memory directory leases', () => {
40+
it('does not let a delayed stale remover delete a newly acquired lease', async () => {
41+
await abandonLease();
42+
const lockPath = `${file}.lock`;
43+
const rmdir = fs.rmdir;
44+
const timing = { staleMs: 500, updateMs: 50, timeoutMs: 2000 };
45+
let replacement: Promise<void> | undefined;
46+
let entered!: () => void;
47+
const ready = new Promise<void>(resolve => { entered = resolve; });
48+
let intercepted = false;
49+
let active = false;
50+
let overlapped = false;
51+
52+
vi.spyOn(fs, 'rmdir').mockImplementation(async (target, options) => {
53+
if (String(target) === lockPath && !intercepted) {
54+
intercepted = true;
55+
// A peer removes the old generation and acquires a replacement before
56+
// this contender's already-authorized rmdir reaches the filesystem.
57+
await rmdir(target, options);
58+
replacement = withDirectoryLock(file, async () => {
59+
active = true;
60+
entered();
61+
await sleep(150);
62+
active = false;
63+
}, timing);
64+
await ready;
65+
}
66+
return rmdir(target, options);
67+
});
68+
69+
const first = await Promise.allSettled([
70+
withDirectoryLock(file, async () => { overlapped = active; }, timing),
71+
]);
72+
const second = await Promise.allSettled([replacement]);
73+
expect(intercepted).toBe(true);
74+
expect(overlapped).toBe(false);
75+
expect(first[0].status).toBe('fulfilled');
76+
expect(second[0].status).toBe('fulfilled');
77+
});
78+
79+
it('does not adopt a replacement installed before acquisition finishes', async () => {
80+
const lockPath = `${file}.lock`;
81+
const mkdir = fs.mkdir;
82+
const rename = fs.rename;
83+
let replaced = false;
84+
let entered = false;
85+
const replace = async () => {
86+
replaced = true;
87+
await fs.rm(lockPath, { recursive: true });
88+
await mkdir(lockPath);
89+
};
90+
vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
91+
await rename(from, to);
92+
if (String(to) === lockPath && !replaced) await replace();
93+
});
94+
await expect(withDirectoryLock(file, async () => { entered = true; }, { timeoutMs: 1000 }))
95+
.rejects.toThrow('Memory file lock lost');
96+
expect(entered).toBe(false);
97+
expect((await fs.stat(lockPath)).isDirectory()).toBe(true);
98+
});
99+
100+
it('times out without entering another holder\'s critical section', async () => {
101+
const timing = { staleMs: 1000, updateMs: 100, timeoutMs: 1000 };
102+
await withDirectoryLock(file, async () => {
103+
await expect(withDirectoryLock(file, () => fs.writeFile(file, 'must not be written'), {
104+
...timing,
105+
timeoutMs: 25,
106+
})).rejects.toThrow('Timed out waiting');
107+
await expect(fs.stat(file)).rejects.toMatchObject({ code: 'ENOENT' });
108+
expect((await fs.stat(`${file}.lock`)).isDirectory()).toBe(true);
109+
}, timing);
110+
});
111+
112+
it('accepts the timestamp precision actually stored by the filesystem', async () => {
113+
const utimes = fs.utimes;
114+
let holding = false;
115+
let updated!: () => void;
116+
const heartbeat = new Promise<void>(resolve => { updated = resolve; });
117+
vi.spyOn(fs, 'utimes').mockImplementation(async (target, atime, mtime) => {
118+
const seconds = mtime instanceof Date ? mtime.getTime() / 1000 : Number(mtime);
119+
await utimes(target, atime, Math.floor(seconds));
120+
if (holding) updated();
121+
});
122+
await expect(withDirectoryLock(file, async assertOwned => {
123+
holding = true;
124+
await heartbeat;
125+
await assertOwned();
126+
return 'still owned';
127+
}, { staleMs: 3000, updateMs: 20, timeoutMs: 100 })).resolves.toBe('still owned');
128+
});
129+
130+
it('stops renewing and leaves a replacement lease untouched', async () => {
131+
let replacementMtime = 0;
132+
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
133+
await expect(withDirectoryLock(file, async () => {
134+
await fs.rm(`${file}.lock`, { recursive: true });
135+
await fs.mkdir(`${file}.lock`);
136+
const replacementTime = new Date(Date.now() + 10000);
137+
await fs.utimes(`${file}.lock`, replacementTime, replacementTime);
138+
replacementMtime = (await fs.stat(`${file}.lock`)).mtimeMs;
139+
await sleep(80);
140+
}, { staleMs: 1000, updateMs: 20, timeoutMs: 100 })).resolves.toBeUndefined();
141+
errors.mockRestore();
142+
expect((await fs.stat(`${file}.lock`)).mtimeMs).toBe(replacementMtime);
143+
});
144+
145+
it('does not mask an operation error when releasing its directory also fails', async () => {
146+
const failure = new Error('operation failed');
147+
vi.spyOn(fs, 'rmdir').mockRejectedValueOnce(new Error('release failed'));
148+
vi.spyOn(console, 'error').mockImplementation(() => {});
149+
await expect(withDirectoryLock(file, async () => { throw failure; }, { timeoutMs: 1000 })).rejects.toBe(failure);
150+
});
151+
152+
it('keeps a live holder exclusive for longer than the stale interval', async () => {
153+
let entered!: () => void;
154+
const ready = new Promise<void>(resolve => { entered = resolve; });
155+
const timing = { staleMs: 100, updateMs: 20, timeoutMs: 1000 };
156+
let active = false;
157+
let overlapped = false;
158+
const first = withDirectoryLock(file, async () => {
159+
active = true;
160+
entered();
161+
await sleep(350);
162+
active = false;
163+
}, timing);
164+
await ready;
165+
const second = withDirectoryLock(file, async () => { overlapped = active; }, timing);
166+
await Promise.all([first, second]);
167+
expect(overlapped).toBe(false);
168+
});
169+
170+
it('recovers an abandoned lease without requiring the data file to exist', async () => {
171+
await abandonLease();
172+
173+
await expect(withDirectoryLock(file, async () => 'recovered', {
174+
staleMs: 500,
175+
updateMs: 50,
176+
timeoutMs: 100,
177+
})).resolves.toBe('recovered');
178+
await expect(fs.stat(`${file}.lock`)).rejects.toMatchObject({ code: 'ENOENT' });
179+
});
180+
});

0 commit comments

Comments
 (0)