fix(memory): persist HNSW metadata atomically and report failures (#5001)

Co-authored-by: wasabihu <973168+wasabihu@users.noreply.github.com>
Co-authored-by: rUv <ruv@ruv.net>
This commit is contained in:
authored and GitHub committed 2026-11-17 11:19:50 -05:00
1 parent 6e1bcc4517
commit e0ad134ce5
2 files changed
+126 -3

No files matched your search

@@ -0,0 +1,119 @@
/** #4739: metadata writes must publish a complete image and report failures. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as fs from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
const state = vi.hoisted(() => ({
failure: undefined as unknown,
swaps: [] as Array<{ previous: string; next: string }>,
}));
// Only the vector engine is stubbed; persistence uses the real atomic helper
// and filesystem, with a failure injected at the final publication boundary.
// vitest.config.ts externalizes @ruvector/*; Vite exposes its dynamic imports
// under /@id/, so mock that external module ID rather than a native addon.
vi.mock('/@id/@ruvector/core', () => ({
default: {
VectorDb: class {
async len() { return 0; }
async insert() {}
},
},
}));
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
return {
...actual,
renameSync: vi.fn((from: string, to: string) => {
if (basename(to) === 'hnsw.metadata.json') {
state.swaps.push({
previous: actual.readFileSync(to, 'utf8'),
next: actual.readFileSync(from, 'utf8'),
});
if (state.failure !== undefined) throw state.failure;
}
actual.renameSync(from, to);
}),
};
});
import * as memory from '../src/memory/memory-initializer.js';
describe('HNSW metadata persistence (#4739)', () => {
let root: string;
let metadataPath: string;
const entry = { id: 'vector-1', key: 'policy', namespace: 'patterns', content: 'memory 世界 🌱' };
const previous = '[]\n' + ' '.repeat(64);
beforeEach(() => {
root = fs.mkdtempSync(join(tmpdir(), 'ruflo-hnsw-4739-'));
metadataPath = join(root, 'hnsw.metadata.json');
fs.writeFileSync(metadataPath, previous);
vi.stubEnv('CLAUDE_FLOW_MEMORY_PATH', root);
vi.stubEnv('CLAUDE_FLOW_DISABLE_BRIDGE', '1');
vi.spyOn(console, 'warn').mockImplementation(() => {});
memory.clearHNSWIndex();
memory._resetMemoryRootCache();
state.failure = undefined;
state.swaps = [];
});
afterEach(() => {
memory.clearHNSWIndex();
memory._resetMemoryRootCache();
vi.restoreAllMocks();
vi.unstubAllEnvs();
fs.rmSync(root, { recursive: true, force: true });
});
it('atomically replaces the old image with complete UTF-8 metadata that reloads', async () => {
expect(await memory.addToHNSWIndex(entry.id, [1, 0, 0], entry)).toBe(true);
const serialized = JSON.stringify([[entry.id, entry]]);
expect(fs.readFileSync(metadataPath, 'utf8')).toBe(serialized);
// Before rename, readers still see the old complete image while the new
// complete image is in a separate sibling file.
expect(state.swaps).toEqual([{ previous, next: serialized }]);
expect(fs.readdirSync(root)).toEqual(['hnsw.metadata.json']);
if (process.platform !== 'win32') {
expect(fs.statSync(metadataPath).mode & 0o777).toBe(0o600);
}
expect(console.warn).not.toHaveBeenCalled();
memory.clearHNSWIndex();
const reloaded = await memory.getHNSWIndex({ dimensions: 3 });
expect(reloaded?.entries.get(entry.id)).toEqual(entry);
});
it.each([
new Error('ENOSPC: no space left on device'),
'EACCES: permission denied',
])('reports a failed atomic swap and preserves the previous image (%s)', async (failure) => {
state.failure = failure;
// Metadata is best-effort: the vector insertion still succeeds in memory.
expect(await memory.addToHNSWIndex(entry.id, [1, 0, 0], entry)).toBe(true);
expect(console.warn).toHaveBeenCalledWith(
'[memory] Failed to save hnsw.metadata.json:',
failure instanceof Error ? failure.message : String(failure),
);
expect(state.swaps).toHaveLength(1);
expect(fs.readFileSync(metadataPath, 'utf8')).toBe(previous);
expect(fs.readdirSync(root)).toEqual(['hnsw.metadata.json']);
expect((await memory.getHNSWIndex())?.entries.get(entry.id)).toEqual(entry);
});
it('reports a missing parent directory without throwing or recreating it', async () => {
expect(await memory.getHNSWIndex({ dimensions: 3 })).not.toBeNull();
fs.rmSync(root, { recursive: true });
expect(await memory.addToHNSWIndex(entry.id, [1, 0, 0], entry)).toBe(true);
expect(console.warn).toHaveBeenCalledWith(
'[memory] Failed to save hnsw.metadata.json:',
expect.stringContaining('ENOENT'),
);
expect(fs.existsSync(root)).toBe(false);
});
});
@@ -795,9 +795,13 @@ function saveHNSWMetadata(): void {
const swarmDir = getMemoryRoot();
const metadataPath = path.join(swarmDir, 'hnsw.metadata.json');
const metadata = Array.from(hnswIndex.entries.entries());
fs.writeFileSync(metadataPath, JSON.stringify(metadata));
} catch {
// Silently fail - metadata save is best-effort
writeFileAtomic(metadataPath, Buffer.from(JSON.stringify(metadata), 'utf-8'));
} catch (error) {
// Metadata is best-effort, but persistence failures must be visible.
console.warn(
'[memory] Failed to save hnsw.metadata.json:',
error instanceof Error ? error.message : String(error),
);
}
}