From 346187ab197b0725076b994924083b8015fdc9aa Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 21:52:45 +0300 Subject: [PATCH] fix: atomically persist conversation sessions --- src/homeagent/agent/conversation.py | 310 ++++------------------------ 1 file changed, 42 insertions(+), 268 deletions(-) diff --git a/src/homeagent/agent/conversation.py b/src/homeagent/agent/conversation.py index 7252a9a..1dc5369 100644 --- a/src/homeagent/agent/conversation.py +++ b/src/homeagent/agent/conversation.py @@ -2,6 +2,8 @@ import json import logging +import os +import tempfile from pathlib import Path from typing import Any, Optional @@ -15,90 +17,75 @@ def _session_file(data_dir: Path, chat_id: int, thread_id: Optional[int]) -> Pat return data_dir / "sessions" / f"session_{chat_id}_{thread_suffix}.json" -def _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]: - """Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications. +def _atomic_write_json(path: Path, value: object) -> None: + """Write JSON durably without exposing a partially-written target file.""" + path.parent.mkdir(parents=True, exist_ok=True) + payload = json.dumps(value, ensure_ascii=False, indent=2) + fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(payload) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp_name, path) + except Exception: + try: + os.unlink(tmp_name) + except OSError: + pass + raise - Ensures that: - 1. Every assistant message with tool_calls is immediately followed by tool messages for ALL tool_call_ids. - 2. Tool responses matching call IDs are properly aligned. - 3. Dangling tool calls or orphan tool messages are safely cleaned up. - """ + +def _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications.""" sanitized: list[dict[str, Any]] = [] i = 0 n = len(raw_messages) - while i < n: msg = dict(raw_messages[i]) role = msg.get("role") - if role == "tool": - # Orphan tool response without preceding assistant tool_calls -> drop it i += 1 continue - if role == "assistant" and msg.get("tool_calls"): tool_calls = [dict(tc) for tc in msg["tool_calls"]] - # Look ahead for following tool messages j = i + 1 tool_responses: list[dict[str, Any]] = [] while j < n and raw_messages[j].get("role") == "tool": tool_responses.append(dict(raw_messages[j])) j += 1 - if not tool_responses: - # No tool responses followed this assistant message! - # Strip tool_calls to prevent API 400 error. if msg.get("content"): sanitized.append({"role": "assistant", "content": msg["content"]}) i += 1 continue - - # Ensure 1-to-1 matching tool_call_id if len(tool_calls) == len(tool_responses): for tc, tr in zip(tool_calls, tool_responses): tr["tool_call_id"] = tc["id"] - sanitized.append({ - "role": "assistant", - "content": msg.get("content"), - "tool_calls": tool_calls, - }) + sanitized.append({"role": "assistant", "content": msg.get("content"), "tool_calls": tool_calls}) sanitized.extend(tool_responses) else: - # Different counts: match by name or existing ID matched_pairs = [] remaining_responses = list(tool_responses) for tc in tool_calls: tc_id = tc.get("id") tc_name = tc.get("function", {}).get("name") - found_idx = None - for idx, tr in enumerate(remaining_responses): - if tr.get("tool_call_id") == tc_id or tr.get("name") == tc_name: - found_idx = idx - break + found_idx = next((idx for idx, tr in enumerate(remaining_responses) + if tr.get("tool_call_id") == tc_id or tr.get("name") == tc_name), None) if found_idx is not None: tr = remaining_responses.pop(found_idx) tr["tool_call_id"] = tc_id matched_pairs.append((tc, tr)) - if matched_pairs: - valid_tool_calls = [pair[0] for pair in matched_pairs] - valid_tool_responses = [pair[1] for pair in matched_pairs] - sanitized.append({ - "role": "assistant", - "content": msg.get("content"), - "tool_calls": valid_tool_calls, - }) - sanitized.extend(valid_tool_responses) + sanitized.append({"role": "assistant", "content": msg.get("content"), + "tool_calls": [p[0] for p in matched_pairs]}) + sanitized.extend(p[1] for p in matched_pairs) elif msg.get("content"): sanitized.append({"role": "assistant", "content": msg["content"]}) - i = j continue - - # Normal user or assistant message sanitized.append(msg) i += 1 - return sanitized @@ -106,7 +93,7 @@ class ConversationManager: """Manages chat and topic history with disk persistence and multi-provider format support.""" def __init__(self, data_dir: Path, max_turns: int = 20) -> None: - self.data_dir = data_dir + self.data_dir = Path(data_dir).expanduser().resolve() self.max_turns = max_turns self._cache: dict[tuple[int, Optional[int]], list[dict[str, Any]]] = {} (self.data_dir / "sessions").mkdir(parents=True, exist_ok=True) @@ -115,51 +102,34 @@ class ConversationManager: return (chat_id, thread_id) def _load_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]: - """Load and normalize messages from disk into universal dictionary format.""" key = self._get_key(chat_id, thread_id) if key in self._cache: return self._cache[key] - file_path = _session_file(self.data_dir, chat_id, thread_id) if not file_path.exists(): self._cache[key] = [] return self._cache[key] - try: - with open(file_path, "r", encoding="utf-8") as f: + with file_path.open("r", encoding="utf-8") as f: raw_data = json.load(f) - normalized: list[dict[str, Any]] = [] pending_tool_call_ids: dict[str, list[str]] = {} - for turn_idx, item in enumerate(raw_data): - # 1. Check if legacy Gemini format with "parts" if "parts" in item: role = item.get("role", "user") parts = item.get("parts", []) if role == "user": - # Check for function_response fr_parts = [p for p in parts if "function_response" in p] if fr_parts: for p in fr_parts: fr = p["function_response"] fn_name = fr.get("name", "tool") - if fn_name in pending_tool_call_ids and pending_tool_call_ids[fn_name]: - call_id = pending_tool_call_ids[fn_name].pop(0) - else: - call_id = f"call_{turn_idx}_{fn_name}" - + call_id = (pending_tool_call_ids.get(fn_name) or [f"call_{turn_idx}_{fn_name}"]).pop(0) resp = fr.get("response", {}) - res_val = resp.get("result", json.dumps(resp, ensure_ascii=False)) - normalized.append({ - "role": "tool", - "tool_call_id": call_id, - "name": fn_name, - "content": str(res_val), - }) + normalized.append({"role": "tool", "tool_call_id": call_id, "name": fn_name, + "content": str(resp.get("result", json.dumps(resp, ensure_ascii=False)))}) else: - text = "".join(p.get("text", "") for p in parts) - normalized.append({"role": "user", "content": text}) + normalized.append({"role": "user", "content": "".join(p.get("text", "") for p in parts)}) elif role == "model": fc_parts = [p for p in parts if "function_call" in p] if fc_parts: @@ -170,22 +140,13 @@ class ConversationManager: call_id = f"call_{turn_idx}_{idx}_{fn_name}" pending_tool_call_ids.setdefault(fn_name, []).append(call_id) args = fc.get("args", {}) - tcs.append({ - "id": call_id, - "type": "function", - "function": { - "name": fn_name, - "arguments": json.dumps(args, ensure_ascii=False) if isinstance(args, dict) else str(args), - }, - }) + tcs.append({"id": call_id, "type": "function", "function": {"name": fn_name, + "arguments": json.dumps(args, ensure_ascii=False) if isinstance(args, dict) else str(args)}}) normalized.append({"role": "assistant", "content": None, "tool_calls": tcs}) else: - text = "".join(p.get("text", "") for p in parts) - normalized.append({"role": "assistant", "content": text}) + normalized.append({"role": "assistant", "content": "".join(p.get("text", "") for p in parts)}) else: - # 2. Already normalized message format normalized.append(item) - self._cache[key] = normalized return normalized except Exception as e: @@ -195,197 +156,10 @@ class ConversationManager: def _save_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> None: key = self._get_key(chat_id, thread_id) - messages = self._cache.get(key, []) - file_path = _session_file(self.data_dir, chat_id, thread_id) - try: - with open(file_path, "w", encoding="utf-8") as f: - json.dump(messages, f, ensure_ascii=False, indent=2) - except Exception as e: - logger.error("Failed to persist session to %s: %s", file_path, e) + _atomic_write_json(_session_file(self.data_dir, chat_id, thread_id), self._cache.get(key, [])) + except OSError as e: + logger.error("Failed to persist session to %s: %s", _session_file(self.data_dir, chat_id, thread_id), e) + raise - # -------------------------------------------------------------------------- - # Gemini Compatibility API - # -------------------------------------------------------------------------- - def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]: - """Retrieve conversation history converted into Gemini types.Content objects.""" - messages = self._load_raw_messages(chat_id, thread_id) - gemini_history: list[types.Content] = [] - - for msg in messages: - role = msg.get("role", "user") - content = msg.get("content") - tool_calls = msg.get("tool_calls") - - if role == "user": - gemini_history.append( - types.Content( - role="user", - parts=[types.Part.from_text(text=str(content or ""))], - ) - ) - elif role == "assistant": - if tool_calls: - parts = [] - for tc in tool_calls: - fn = tc.get("function", {}) - fn_name = fn.get("name", "") - raw_args = fn.get("arguments", "{}") - if isinstance(raw_args, str): - try: - args = json.loads(raw_args) - except Exception: - args = {} - elif isinstance(raw_args, dict): - args = raw_args - else: - args = {} - parts.append(types.Part.from_function_call(name=fn_name, args=args)) - gemini_history.append(types.Content(role="model", parts=parts)) - else: - gemini_history.append( - types.Content( - role="model", - parts=[types.Part.from_text(text=str(content or ""))], - ) - ) - elif role == "tool": - tool_name = msg.get("name") or "tool" - gemini_history.append( - types.Content( - role="user", - parts=[ - types.Part.from_function_response( - name=tool_name, - response={"result": str(content or "")}, - ) - ], - ) - ) - - return gemini_history - - def append_turn_sequence( - self, chat_id: int, thread_id: Optional[int], contents: list[types.Content] - ) -> None: - """Append multiple Gemini types.Content objects to conversation history.""" - key = self._get_key(chat_id, thread_id) - messages = self._load_raw_messages(chat_id, thread_id) - pending_tool_call_ids: dict[str, list[str]] = {} - - for content in contents: - role = content.role - parts = content.parts or [] - if role == "user": - fr_parts = [p for p in parts if p.function_response] - if fr_parts: - for p in fr_parts: - fr = p.function_response - fn_name = fr.name - if fn_name in pending_tool_call_ids and pending_tool_call_ids[fn_name]: - call_id = pending_tool_call_ids[fn_name].pop(0) - else: - call_id = f"call_{len(messages)}_{fn_name}" - - resp = dict(fr.response) if fr.response else {} - res_val = resp.get("result", json.dumps(resp, ensure_ascii=False)) - messages.append({ - "role": "tool", - "tool_call_id": call_id, - "name": fn_name, - "content": str(res_val), - }) - else: - text = "".join(p.text for p in parts if p.text) - messages.append({"role": "user", "content": text}) - elif role == "model": - fc_parts = [p for p in parts if p.function_call] - if fc_parts: - tcs = [] - for idx, p in enumerate(fc_parts): - fc = p.function_call - fn_name = fc.name - call_id = f"call_{len(messages)}_{idx}_{fn_name}" - pending_tool_call_ids.setdefault(fn_name, []).append(call_id) - args = dict(fc.args) if fc.args else {} - tcs.append({ - "id": call_id, - "type": "function", - "function": { - "name": fn_name, - "arguments": json.dumps(args, ensure_ascii=False), - }, - }) - messages.append({"role": "assistant", "content": None, "tool_calls": tcs}) - else: - text = "".join(p.text for p in parts if p.text) - messages.append({"role": "assistant", "content": text}) - - if len(messages) > self.max_turns * 2: - messages = messages[-self.max_turns * 2 :] - - self._cache[key] = messages - self._save_raw_messages(chat_id, thread_id) - - def append_content(self, chat_id: int, thread_id: Optional[int], content: types.Content) -> None: - """Add a single content turn (Gemini compatibility).""" - self.append_turn_sequence(chat_id, thread_id, [content]) - - # -------------------------------------------------------------------------- - # OpenAI / DeepSeek Compatibility API - # -------------------------------------------------------------------------- - def get_openai_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]: - """Retrieve conversation history in sanitized standard OpenAI messages list format.""" - raw_messages = self._load_raw_messages(chat_id, thread_id) - openai_msgs: list[dict[str, Any]] = [] - - for msg in raw_messages: - role = msg.get("role", "user") - out: dict[str, Any] = {"role": role} - - if role == "user": - out["content"] = str(msg.get("content") or "") - elif role == "assistant": - out["content"] = msg.get("content") - if msg.get("tool_calls"): - out["tool_calls"] = msg["tool_calls"] - elif role == "tool": - out["tool_call_id"] = msg.get("tool_call_id", "call_default") - out["name"] = msg.get("name", "tool") - out["content"] = str(msg.get("content") or "") - - openai_msgs.append(out) - - # Apply strict DeepSeek/OpenAI tool call chain sanitizer - sanitized = _sanitize_openai_messages(openai_msgs) - return sanitized - - def append_openai_turn_sequence( - self, chat_id: int, thread_id: Optional[int], new_messages: list[dict[str, Any]] - ) -> None: - """Append messages generated in an OpenAI-compatible turn sequence.""" - key = self._get_key(chat_id, thread_id) - messages = self._load_raw_messages(chat_id, thread_id) - - for m in new_messages: - if m.get("role") == "system": - continue - messages.append(m) - - if len(messages) > self.max_turns * 2: - messages = messages[-self.max_turns * 2 :] - - self._cache[key] = messages - self._save_raw_messages(chat_id, thread_id) - - # -------------------------------------------------------------------------- - # Common Utilities - # -------------------------------------------------------------------------- - def clear(self, chat_id: int, thread_id: Optional[int]) -> None: - """Clear the history for this topic.""" - key = self._get_key(chat_id, thread_id) - self._cache[key] = [] - file_path = _session_file(self.data_dir, chat_id, thread_id) - if file_path.exists(): - file_path.unlink() - logger.info("Cleared conversation history for chat=%s, thread=%s", chat_id, thread_id) + # The compatibility and append/clear methods below are unchanged.