Skip to content

fix(memory): write memory graph atomically to prevent corruption - #4618

Open
Arnab758 wants to merge 2 commits into
modelcontextprotocol:mainfrom
Arnab758:fix/memory-atomic-write
Open

fix(memory): write memory graph atomically to prevent corruption#4618
Arnab758 wants to merge 2 commits into
modelcontextprotocol:mainfrom
Arnab758:fix/memory-atomic-write

Conversation

@Arnab758

@Arnab758 Arnab758 commented Aug 6, 2026

Copy link
Copy Markdown

What

Fixes #4614.

saveGraph() wrote the memory file directly with fs.writeFile, so an interruption mid-write (process crash, kill, power loss) could leave a truncated or corrupted memory file — permanently losing the agent's long-term memory.

How

Write the graph to a unique temp file, then rename() it into place. Rename is atomic on POSIX and Windows, so the memory file is always either the old complete version or the new complete version — never a half-written one.

  • Random suffix (randomBytes(16)) prevents collisions when saves overlap
  • Temp file is cleaned up on failure so failed saves never leak artifacts

Tests

Added a regression test that simulates an interruption mid-write (partial bytes written, then error) and verifies:

  • The original memory file is untouched
  • No temp files leak

tsc --noEmit passes. Full suite: 51/51 tests pass.

Notes

This complements (not duplicates) #4555, which serializes concurrent graph mutations. #4555 fixes concurrent writes racing each other; this fixes a single write being interrupted mid-write — two different failure modes.

Known limitation: a hard kill between write and rename can still leave a temp file behind (inherent to the temp+rename pattern). The memory file itself is never corrupted.

saveGraph() wrote the memory file directly with fs.writeFile, so an interruption mid-write (crash, kill, power loss) could leave a truncated or corrupted memory file. Write to a unique temp file first, then rename into place — atomic on POSIX and Windows. Clean up the temp file on failure. Includes a regression test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

saveGraph() in src/memory uses non-atomic fs.writeFile — risk of corrupted memory file on interruption

1 participant