fix: persist memory across Docker restarts #2

Closed
Barsic Bot wants to merge 21 commits from fix/persistent-memory-docker into master
pull from: fix/persistent-memory-docker
Showing only changes of commit ca647d2298 - Show all commits
+57 -30
View File
@@ -2,6 +2,8 @@
import json
import logging
import os
import tempfile
import uuid
from dataclasses import asdict, dataclass, field
from datetime import datetime
@@ -20,10 +22,14 @@ class MemoryItem:
class GlobalMemory:
"""Persistent global memory store shared across all forum topics."""
"""Persistent global memory store shared across all forum topics.
Writes are atomic: a complete file is fsynced and then renamed into place,
so a container restart cannot leave a truncated JSON file behind.
"""
def __init__(self, storage_path: Path):
self.storage_path = storage_path
self.storage_path = Path(storage_path).expanduser().resolve()
self._items: dict[str, MemoryItem] = {}
self._load()
@@ -31,8 +37,10 @@ class GlobalMemory:
if not self.storage_path.exists():
return
try:
with open(self.storage_path, "r", encoding="utf-8") as f:
with self.storage_path.open("r", encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, list):
raise ValueError("memory file must contain a JSON list")
for item_data in data:
item = MemoryItem(**item_data)
self._items[item.id] = item
@@ -41,70 +49,89 @@ class GlobalMemory:
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
def _save(self) -> None:
try:
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.storage_path, "w", encoding="utf-8") as f:
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
payload = json.dumps(
[asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2
)
fd, tmp_name = tempfile.mkstemp(
prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_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, self.storage_path)
# Persist the directory entry as well (important on abrupt shutdown).
try:
dir_fd = os.open(self.storage_path.parent, os.O_DIRECTORY)
try:
os.fsync(dir_fd)
finally:
os.close(dir_fd)
except OSError:
logger.debug("Directory fsync is unavailable for %s", self.storage_path.parent)
except Exception:
try:
os.unlink(tmp_name)
except OSError:
pass
raise
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
"""Add a new fact or preference to global memory."""
item_id = str(uuid.uuid4())[:8]
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
self._items[item_id] = item
try:
self._save()
except OSError as e:
logger.error("Failed to persist global memory to %s: %s", self.storage_path, e)
raise
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
return item
def remove_fact(self, fact_id: str) -> bool:
"""Remove a fact by its ID."""
if fact_id in self._items:
if fact_id not in self._items:
return False
del self._items[fact_id]
self._save()
return True
return False
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
"""List all facts, optionally filtered by category."""
if category:
cat = category.strip().lower()
return [item for item in self._items.values() if item.category == cat]
return list(self._items.values())
def search(self, query: str) -> list[MemoryItem]:
"""Search memory for keywords in query."""
q = query.lower()
return [
item for item in self._items.values()
if q in item.fact.lower() or q in item.category.lower()
]
return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
def clear(self) -> None:
"""Clear all stored memory."""
self._items.clear()
self._save()
def get_memory_summary(self, max_items: int = 30) -> str:
"""Produce a formatted summary of remembered facts for the system prompt."""
if not self._items:
return ""
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
items = list(self._items.values())[-max_items:]
for item in items:
for item in list(self._items.values())[-max_items:]:
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
return "\n".join(lines)
# Singleton instance container
_global_memory_instance: Optional[GlobalMemory] = None
_global_memory_instances: dict[Path, GlobalMemory] = {}
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
global _global_memory_instance
if _global_memory_instance is None:
"""Return the memory store for the requested persistent path.
The cache is keyed by the resolved path, preventing one process/test/config
from accidentally reusing memory loaded from another DATA_DIR.
"""
if storage_path is None:
storage_path = Path("data") / "global_memory.json"
_global_memory_instance = GlobalMemory(storage_path)
return _global_memory_instance
storage_path = Path(os.getenv("DATA_DIR", "data")) / "global_memory.json"
path = Path(storage_path).expanduser().resolve()
if path not in _global_memory_instances:
_global_memory_instances[path] = GlobalMemory(path)
return _global_memory_instances[path]