fix: use atomic write in LocalFileStore to prevent race conditions (#13480)

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: OpenHands Bot <contact@all-hands.dev>
This commit is contained in:
Tim O'Farrell
2026-03-18 16:49:32 -06:00
committed by GitHub
parent abd1f9948f
commit 7edebcbc0c
2 changed files with 67 additions and 2 deletions

View File

@@ -1,5 +1,6 @@
import os
import shutil
import threading
from openhands.core.logger import openhands_logger as logger
from openhands.storage.files import FileStore
@@ -23,8 +24,20 @@ class LocalFileStore(FileStore):
full_path = self.get_full_path(path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
mode = 'w' if isinstance(contents, str) else 'wb'
with open(full_path, mode) as f:
f.write(contents)
# Use atomic write: write to temp file, then rename
# This prevents race conditions where concurrent writes could corrupt the file
temp_path = f'{full_path}.tmp.{os.getpid()}.{threading.get_ident()}'
try:
with open(temp_path, mode) as f:
f.write(contents)
f.flush()
os.fsync(f.fileno())
os.replace(temp_path, full_path)
except Exception:
if os.path.exists(temp_path):
os.remove(temp_path)
raise
def read(self, path: str) -> str:
full_path = self.get_full_path(path)