Agent Zero AI framework
Make chat persistence crash-safe
Alessandro811556d24e3c
diff --git a/helpers/persist_chat.py b/helpers/persist_chat.pyindex 199fa3ef5..47479bd35 100644--- a/helpers/persist_chat.py+++ b/helpers/persist_chat.py@@ -1,12 +1,15 @@+import json+import os+import tempfile+import uuidfrom collections import OrderedDictfrom datetime import datetimefrom typing import Any-import uuid+from agent import Agent, AgentConfig, AgentContext, AgentContextTypefrom helpers import files, historyfrom helpers.litellm_transport import delete_stored_response_idsfrom helpers.localization import Localization-import jsonfrom initialize import initialize_agentfrom helpers.log import Log, LogItem@@ -51,10 +54,9 @@ def save_tmp_chat(context: AgentContext):returnpath = _get_chat_file_path(context.id)- files.make_dirs(path)data = _serialize_context(context)js = _safe_json_serialize(data, ensure_ascii=False)- files.write_file(path, js)+ _write_atomic(path, js)mark_chat_saved(context)@@ -94,6 +96,28 @@ def _get_chat_file_path(ctxid: str):return files.get_abs_path(CHATS_FOLDER, ctxid, CHAT_FILE_NAME)+def _write_atomic(path: str, content: str) -> None:+ directory = os.path.dirname(path)+ os.makedirs(directory, exist_ok=True)+ fd, tmp_path = tempfile.mkstemp(+ prefix=f".{os.path.basename(path)}.", suffix=".tmp", dir=directory+ )+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(content.encode("utf-8", "replace").decode("utf-8"))+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(tmp_path, path)+ directory_fd = os.open(directory, os.O_RDONLY)+ try:+ os.fsync(directory_fd)+ finally:+ os.close(directory_fd)+ finally:+ if os.path.exists(tmp_path):+ os.unlink(tmp_path)++def mark_chat_saved(context: AgentContext) -> None:context.data[SAVED_CHAT_CONTEXT_DATA_KEY] = Truediff --git a/helpers/persist_chat.py.dox.md b/helpers/persist_chat.py.dox.mdindex e75fe80d5..09205e7d0 100644--- a/helpers/persist_chat.py.dox.md+++ b/helpers/persist_chat.py.dox.md@@ -45,6 +45,7 @@- Serialized chats store `agent_profile` both at the context level for the main chat and on each serialized agent so subordinate profiles survive server restart.- Deserialization must rebuild each agent with its serialized profile when present, falling back to the context profile for older chat files.- Chat loading skips directories that do not contain `chat.json`; malformed existing chat files still report load errors.+- Chat saves write and fsync a same-directory temporary file, atomically replace `chat.json`, and fsync the directory so an interrupted save cannot truncate the previous chat.- Contexts are marked with private `SAVED_CHAT_CONTEXT_DATA_KEY` only after a successful save or load from disk so snapshot code can detect deleted chat files without hiding fresh unsaved chats.## Key Conceptsdiff --git a/tests/test_persist_chat_log_ids.py b/tests/test_persist_chat_log_ids.pyindex d9c97f3f7..407d1f771 100644--- a/tests/test_persist_chat_log_ids.py+++ b/tests/test_persist_chat_log_ids.py@@ -1,8 +1,11 @@from __future__ import annotationsimport json+from pathlib import Pathfrom types import SimpleNamespace+import pytest+def test_deserialize_log_preserves_item_id() -> None:from helpers.log import Log@@ -53,3 +56,35 @@ def test_load_tmp_chats_skips_directories_without_chat_json(monkeypatch, capsys)assert persist_chat.load_tmp_chats() == ["valid"]assert "Error loading chat" not in capsys.readouterr().out+++def test_save_tmp_chat_preserves_existing_file_until_atomic_replace(+ monkeypatch, tmp_path+) -> None:+ from agent import AgentContextType+ from helpers import persist_chat++ path = tmp_path / "chat.json"+ path.write_text("previous", encoding="utf-8")+ context = SimpleNamespace(id="chat", type=AgentContextType.USER, data={})++ monkeypatch.setattr(persist_chat, "_get_chat_file_path", lambda _ctxid: str(path))+ monkeypatch.setattr(persist_chat, "_serialize_context", lambda _context: {"new": True})+ real_replace = persist_chat.os.replace++ def interrupted_replace(_source: str, destination: str) -> None:+ assert Path(destination).read_text(encoding="utf-8") == "previous"+ raise OSError("simulated interruption")++ monkeypatch.setattr(persist_chat.os, "replace", interrupted_replace)+ with pytest.raises(OSError, match="simulated interruption"):+ persist_chat.save_tmp_chat(context)++ assert path.read_text(encoding="utf-8") == "previous"+ assert list(tmp_path.glob("*.tmp")) == []++ monkeypatch.setattr(persist_chat.os, "replace", real_replace)+ persist_chat.save_tmp_chat(context)++ assert json.loads(path.read_text(encoding="utf-8")) == {"new": True}+ assert context.data[persist_chat.SAVED_CHAT_CONTEXT_DATA_KEY] is True