Skip to content

Commit 03ddb97

Browse files
claude[bot]olaservo
andcommitted
fix(memory): implement atomic writes to prevent race condition
Fixes race condition vulnerability where concurrent operations could corrupt memory.json file by writing incomplete or malformed data. Changes: - Add atomic write operations using temporary files and rename - Import crypto.randomBytes for generating unique temp file names - Add proper error handling and cleanup for temp files - Use same pattern as filesystem server for consistency This resolves JSON parsing errors like 'Unexpected non-whitespace character after JSON' that occurred when multiple processes attempted simultaneous file writes. Fixes #2579 Co-authored-by: Ola Hungerford <[email protected]>
1 parent 338d8af commit 03ddb97

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

‎src/memory/index.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
import { promises as fs } from 'fs';
1010
import path from 'path';
1111
import { fileURLToPath } from 'url';
12+
import { randomBytes } from 'crypto';
1213

1314
// Define memory file path using environment variable with fallback
1415
const defaultMemoryPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'memory.json');
@@ -63,7 +64,22 @@ class KnowledgeGraphManager {
6364
...graph.entities.map(e => JSON.stringify({ type: "entity", ...e })),
6465
...graph.relations.map(r => JSON.stringify({ type: "relation", ...r })),
6566
];
66-
await fs.writeFile(MEMORY_FILE_PATH, lines.join("\n"));
67+
68+
// Use atomic rename to prevent race conditions where concurrent writes
69+
// could corrupt the file. Rename operations are atomic on all filesystems.
70+
const tempPath = `${MEMORY_FILE_PATH}.${randomBytes(16).toString('hex')}.tmp`;
71+
try {
72+
await fs.writeFile(tempPath, lines.join("\n"), 'utf-8');
73+
await fs.rename(tempPath, MEMORY_FILE_PATH);
74+
} catch (error) {
75+
// Clean up temp file on failure
76+
try {
77+
await fs.unlink(tempPath);
78+
} catch (unlinkError) {
79+
// Ignore unlink errors - temp file might not exist or already cleaned up
80+
}
81+
throw error;
82+
}
6783
}
6884

6985
async createEntities(entities: Entity[]): Promise<Entity[]> {

0 commit comments

Comments
 (0)